File size: 8,572 Bytes
ad959cf
 
 
affeece
 
 
ec0d954
affeece
0d9b756
ec0d954
 
 
 
3154e18
 
affeece
 
 
 
 
 
 
 
 
 
 
 
dabe70f
ec0d954
 
 
 
affeece
 
30b7b8c
 
ad959cf
dabe70f
affeece
30b7b8c
 
 
 
 
 
 
 
 
ec0d954
ad959cf
 
30b7b8c
ad959cf
ec0d954
 
dabe70f
 
ec0d954
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3154e18
 
 
 
 
 
 
 
 
 
 
 
 
ec0d954
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df440d2
 
 
 
ec0d954
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df440d2
 
ec0d954
 
 
 
 
 
0d9b756
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0d954
 
affeece
 
 
ec0d954
3154e18
0d9b756
ec0d954
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import base64
import os

import cv2
import gradio as gr
import numpy as np
import stripe

import accounts
import enhance
import jobs
import payments
from colorize import apply_ab, ensure_ddcolor, predict_ab
from fill import ensure_lama, fill
from glare import deglare
from setup_models import ensure_models

try:  # ZeroGPU Spaces refuse to start unless at least one function asks for the GPU
    import spaces

    @spaces.GPU
    def _gpu_placeholder():
        pass
except ImportError:
    pass

ensure_models()
ensure_lama()
ensure_ddcolor()
import threading  # noqa: E402
import colorize as _colorize  # noqa: E402
threading.Thread(target=_colorize._model, daemon=True).start()  # load the 1 GB model before the first user needs it
from restore import restore  # noqa: E402

def to_data_url(bgr, quality=92):
    ok, buf = cv2.imencode(".jpg", bgr, [cv2.IMWRITE_JPEG_QUALITY, quality])
    return "data:image/jpeg;base64," + base64.b64encode(buf).decode()


def from_data_url(url, flags=cv2.IMREAD_COLOR):
    if not url or "," not in url:
        raise gr.Error("Missing image.")
    img = cv2.imdecode(np.frombuffer(base64.b64decode(url.split(",", 1)[1]), np.uint8), flags)
    if img is None:
        raise gr.Error("Couldn't read that image.")
    return img


def _mask_for(img, mask_url):
    if not mask_url or "," not in mask_url:
        raise gr.Error("Paint over the area you want fixed first.")
    painted = from_data_url(mask_url)
    mask = (painted.max(axis=2) > 40).astype(np.uint8) * 255
    # the brush is painted on the preview, so scale it up to the full-quality image
    mask = cv2.resize(mask, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_NEAREST)
    if not mask.any():
        raise gr.Error("Paint over the area you want fixed first.")
    return mask


def _load(job_id):
    try:
        return jobs.load(job_id)
    except (KeyError, OSError):
        raise gr.Error("This photo has expired. Please restore it again.")


def _pay(fn, *args):
    try:
        return fn(*args)
    except payments.PaymentError as e:
        raise gr.Error(str(e))
    except stripe.StripeError as e:
        print("stripe error:", e)
        raise gr.Error("The payment service had a problem. Please try again.")


# Endpoints for the PicRest website and phone app. Images travel as data URLs. Restoring and
# touching up are free but only return a small watermarked preview; the full-quality image stays
# on the server under a job id until it is downloaded for a credit.
def app_restore(image: str) -> dict:
    return _restored(*restore(from_data_url(image)))


def app_restore_glare(image: str, others: list) -> dict:
    """The same print photographed from two or three angles, so glare can be taken out using the
    shot where each part is darkest. 'fused' says how many extra shots lined up."""
    if not isinstance(others, list) or not 1 <= len(others) <= 3:
        raise gr.Error("Add one or two more photos of the same print.")
    out, info = restore(from_data_url(image), [from_data_url(o) for o in others])
    return {**_restored(out, info), "fused": int(info["fused"])}


def _restored(out, info):
    return {"job": jobs.create(out, before=info["prepped"]), "image": to_data_url(jobs.preview(out), 88),
            "before": to_data_url(jobs.shrink(info["prepped"]), 88),
            "print_found": bool(info["print_found"]), "damaged": round(float(info["damaged"]), 4),
            **enhance.analyse(out)}  # monochrome -> offer Colourize, faded -> offer Fix colours


def app_touch_up(job: str, mask: str, tool: str = "fill", strength: float = 1.0) -> dict:
    if job.startswith("data:"):  # version 1.0 of the app sends the photo itself and gets it back
        img = from_data_url(job)
        m = _mask_for(img, mask)
        out = fill(img, m) if tool == "fill" else deglare(img, m, float(strength))
        return {"image": to_data_url(out, 95)}
    img = _load(job)
    m = _mask_for(img, mask)
    out = fill(img, m) if tool == "fill" else deglare(img, m, float(strength))
    return {"job": jobs.create(out, root=jobs.root(job)), "image": to_data_url(jobs.preview(out), 88)}


def app_enhance(job: str, opts: dict) -> dict:
    """Colourize, fix faded colours and adjust. `job` is the photo before any enhancing, and opts
    holds every setting (see enhance.DEFAULTS), so each call starts afresh from the same photo."""
    img = _load(job)
    o = enhance.clean_opts(opts)

    def cached_colorize(src, strength):
        # the model's colour depends only on the photo (and grain setting), not on the strength,
        # so it is worked out once per photo and reused while the user moves the slider
        path = jobs.cache_file(job, f"ab_{o['grain']:.2f}.npy")
        try:
            ab = np.load(path).astype(np.float32)
            if ab.shape[:2] != src.shape[:2]:
                raise ValueError
        except (OSError, ValueError):
            ab = predict_ab(src)
            np.save(path, ab.astype(np.float16))
        return apply_ab(src, ab, strength)

    out = enhance.enhance(img, o, cached_colorize)
    return {"job": jobs.create(out, root=jobs.root(job)), "image": to_data_url(jobs.preview(out), 88)}


def app_balance(token: str) -> dict:
    if not payments.enabled():
        return {"credits": 0, "packs": {}, "free": True}
    return {"credits": _pay(payments.balance, token), "packs": {
        k: {"credits": c, "price": p, "currency": payments.CURRENCY,
            "prices": {cur: table[k] for cur, table in payments.PRICES.items()}}
        for k, (c, p) in payments.PACKS.items()},
        "zero_decimal": sorted(payments.ZERO_DECIMAL)}


def app_download(job: str, token: str, layout: str = "photo") -> dict:
    """The full-quality image. Costs one credit the first time for each photo; touch-ups of a
    photo that was already downloaded are free. layout "compare" gives before and after side by side."""
    img = _load(job)
    if not payments.enabled():  # until the Stripe key is added as a Space secret, downloads are free
        left = 0
    elif jobs.is_unlocked(job):
        left = _pay(payments.balance, token)
    else:
        try:
            left = payments.spend(token)
        except payments.PaymentError:
            return {"need_credits": True, "credits": _pay(payments.balance, token)}
        except stripe.StripeError as e:
            print("stripe error:", e)
            raise gr.Error("The payment service had a problem. Please try again.")
        jobs.unlock(job)
    if layout == "compare":
        before = jobs.load_before(job)
        if before is None:
            raise gr.Error("The before photo isn't available for this one. Please restore it again.")
        img = enhance.side_by_side(before, img)
    return {"image": to_data_url(img, 95), "credits": left, "free": not payments.enabled()}


def app_checkout(token: str, pack: str, return_url: str, currency: str = "usd") -> dict:
    return {"url": _pay(payments.checkout, token, pack, return_url, currency)}


def app_claim(token: str, session_id: str) -> dict:
    return {"credits": _pay(payments.claim_stripe, token, session_id)}


# Accounts: email + password, so credits bought on the website also work in the app.
def app_signup(email: str, password: str, device: str = "") -> dict:
    return _pay(accounts.signup, email, password, device)


def app_login(email: str, password: str, device: str = "") -> dict:
    return _pay(accounts.login, email, password, device)


def app_me(session: str) -> dict:
    return _pay(accounts.me, session)


def app_reset_request(email: str) -> dict:
    return _pay(accounts.request_reset, email)


def app_reset(token: str, password: str) -> dict:
    return _pay(accounts.reset_password, token, password)


def app_export(session: str) -> dict:
    return _pay(accounts.export, session)


def app_delete_account(session: str, password: str) -> dict:
    return _pay(accounts.delete, session, password)


def app_play_claim(token: str, purchase_token: str, product_id: str) -> dict:
    return {"credits": _pay(payments.claim_play, token, purchase_token, product_id)}


with gr.Blocks(title="PicRest") as demo:
    gr.Markdown("# PicRest\nThis is the restoration server behind the PicRest website and Android app.")
    for fn in (app_restore, app_restore_glare, app_touch_up, app_enhance, app_balance, app_download, app_checkout, app_claim, app_play_claim,
               app_signup, app_login, app_me, app_reset_request, app_reset, app_export, app_delete_account):
        gr.api(fn, api_name=fn.__name__)

demo.queue(max_size=8).launch()