Spaces:
Running on Zero
Running on Zero
Download app.py from concisewebsesign/picrest: direct link, hf CLI and curl.
- Browser
- Download file 8.57 kB
-
https://huggingface.co/spaces/concisewebsesign/picrest/resolve/main/app.py
- Command line
-
hf download hf://spaces/concisewebsesign/picrest/app.py
-
curl -L -o app.py https://huggingface.co/spaces/concisewebsesign/picrest/resolve/main/app.py
8.57 kB
| 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 | |
| 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() | |