"""A CraterView.ai demo for a Hugging Face Space. One photo in, one tool, the result beside the original. The work runs on CraterView.ai through its public API and Python client; nothing here holds a model. The Space's key is the secret `CV_API_KEY`, and every visitor's work runs on that one account. Three things follow from a public page holding one account's key, and each is built in: - The demo runs `SLOTS` photos at a time. Each visitor's run holds a place, in a thread of its own, from before its photo is sent until its last job has settled, or for an hour a step at most, whether or not the visitor is still on the page. - A job's pictures are deleted from the account once it settles, whether or not anyone is still waiting for it. The visitor gets the result from this page, not from the account. - A large photo runs as a part, so one visitor's job stays small. Enhance passes its result through a second model, small face enhancement, unless the visitor switches that off. The two jobs run one after the other in the visitor's one place. """ from __future__ import annotations import html import os import random import shutil import sys import tempfile import threading import time import traceback from dataclasses import dataclass, field from pathlib import Path import gradio as gr import requests from craterview import CraterView, CraterViewError from PIL import Image, ImageDraw, ImageOps from pi_heif import register_heif_opener import following import settings from demos import TOOLS, Step, Tool from region import Box, fractions, is_whole, place, side_limit register_heif_opener() # The image library refuses a picture above about 179 megapixels as a decompression bomb, which # is less than the API takes in one photo. `opened` holds a photo to the API's own figure instead. Image.MAX_IMAGE_PIXELS = None HERE = Path(__file__).parent SLOTS = 2 # photos in flight at once, across every visitor POLL_SECONDS = 2.0 RESUBMIT_SECONDS = 2.0 # before an upload or a submission that got no answer is asked again GIVE_UP_SECONDS = 3600 # how long a job is followed before its place is given back FOLLOW_UP_SECONDS = 60.0 # how often a job nobody waits for is asked after, to delete it PREVIEW_SIDE = 1400 # the photo as drawn on the page COMPARE_SIDE = 2048 # the before and after as drawn on the page MAX_UPLOAD = "50mb" SITE = "https://craterview.ai" SUFFIXES = {"image/jpeg": [".jpg", ".jpeg"], "image/png": [".png"], "image/webp": [".webp"], "image/heic": [".heic"], "image/heif": [".heif"], "image/tiff": [".tif", ".tiff"]} cv = CraterView(api_key=os.environ.get("CV_API_KEY")) slots = threading.BoundedSemaphore(SLOTS) # ----------------------------------------------------------------------------- the catalogue _catalogue: dict[str, tuple[float, dict]] = {} def catalogue(model: str) -> dict: """The model's entry in the API's catalogue: its limits and what it accepts. Read from the API so the page follows it, and kept for five minutes so a visitor does not wait on it.""" kept = _catalogue.get(model) if kept and time.monotonic() - kept[0] < 300: return kept[1] try: entry = next(m for m in cv.models() if m["id"] == model) except (CraterViewError, OSError): # A refresh that fails keeps the entry already held: a limit changes rarely, and a # visitor's photo should not be turned away because one read of the catalogue was. if not kept: raise traceback.print_exc() _catalogue[model] = (time.monotonic(), kept[1]) return kept[1] _catalogue[model] = (time.monotonic(), entry) return entry def catalogue_at_start(model: str) -> dict: """The entry the page's settings are drawn from, read once as the Space starts. A Space that wakes while the API is restarting waits for it, up to a minute, instead of stopping in an error nobody is there to clear.""" for _ in range(6): try: return catalogue(model) except (CraterViewError, OSError): time.sleep(10) return catalogue(model) # ------------------------------------------------------------------------------ one photo @dataclass class Photo: path: str # the file as it was chosen: these bytes are what is sent size: tuple[int, int] # upright, as a person sees it preview: Image.Image side: int # the longest side a part may have box: Box class TooLarge(Exception): """A photo with more pixels than the API takes in one photo.""" def opened(path: str, tool: Tool) -> Photo: entry = catalogue(tool.model) with Image.open(path) as image: # The size is read from the file's header, before anything is decoded. if image.width * image.height > entry["max_frame_megapixels"] * 1e6: raise TooLarge(f"That photo has more pixels than the {entry['max_frame_megapixels']:g} " "megapixels CraterView.ai takes. Resize it before sending it.") upright = ImageOps.exif_transpose(image) size = upright.size preview = upright.convert("RGB") preview.thumbnail((PREVIEW_SIDE, PREVIEW_SIDE)) side = side_limit(entry["max_input_megapixels"], tool.side_cap) return Photo(path, size, preview, side, place(*size, side)) def drawn(photo: Photo) -> Image.Image: """The preview, with everything outside the chosen part dimmed and the part outlined.""" if is_whole(*photo.size, photo.box): return photo.preview ratio = photo.preview.width / photo.size[0] left, top, width, height = (round(v * ratio) for v in photo.box) picture = Image.blend(photo.preview, Image.new("RGB", photo.preview.size, "#070b0d"), 0.55) picture.paste(photo.preview.crop((left, top, left + width, top + height)), (left, top)) ImageDraw.Draw(picture).rectangle((left, top, left + width - 1, top + height - 1), outline="#b29669", width=3) return picture def described(photo: Photo, tool: Tool) -> str: width, height = photo.size if is_whole(width, height, photo.box): return (f"{width} × {height} px. The whole photo fits, so all of it is " f"{tool.done_verb}.") return (f"{width} × {height} px. The outlined part, {photo.box[2]} × {photo.box[3]} px, " f"is {tool.done_verb}. Click the photo to move it.") # -------------------------------------------------------------------------------- one job @dataclass class Run: """One visitor's work, a job or two in a row, done by a thread of its own, so that its place is given back and its pictures are deleted even when the visitor has closed the page. The page only shows it.""" folder: Path then: Step | None = None # the second step, when the visitor left it switched on then_params: dict = field(default_factory=dict) step: int = 1 skipped: str | None = None # why the second step was not applied, when it was not status: str = "waiting" # for a place, then "sending", then the job's own community: bool = True eta_seconds: float | None = None result: Path | None = None before: Path | None = None after: Path | None = None size: tuple[int, int] | None = None failed: tuple[str, str] | None = None # the page's headline and line when it did not work watched: bool = True done: threading.Event = field(default_factory=threading.Event) def work(run: Run, model: str, photo: Path, params: dict) -> None: """Everything a run does on the account, holding one of the demo's places throughout. A visitor who has left by the time a place is free is sent nothing.""" submitted: list[str] = [] # every job this run sends, each deleted once it settles try: following.in_a_place(slots, lambda: run.watched, lambda: _first_step(run, model, photo, params, submitted), every=POLL_SECONDS) finally: # Once the page has what it needs from them, and for every job sent, settled or not: # one the wait gave up on, or failed to follow, is deleted when it settles. for job_id in submitted: threading.Thread(target=following.delete_when_settled, daemon=True, args=(cv, job_id, delete_pictures), kwargs={"every": FOLLOW_UP_SECONDS}).start() run.done.set() if not run.watched: shutil.rmtree(run.folder, ignore_errors=True) AGAIN = "Please try again in a minute." BUSY = ("CraterView.ai is busy right now", AGAIN) DID_NOT_WORK = "That did not work" def _told(failure: BaseException, otherwise: str) -> str: """A failure as the visitor reads it, and in full in the Space's log.""" print(f"a run failed: {failure!r}", file=sys.stderr, flush=True) return following.said(failure, otherwise) def _first_step(run: Run, model: str, photo: Path, params: dict, submitted: list[str]) -> None: run.status = "sending" try: job = following.sent(cv, model, photo, params, pause=RESUBMIT_SECONDS) except (CraterViewError, OSError) as failure: # The account's own limits, and a platform that did not answer, are not the visitor's # to read about. A refusal is said in the platform's own words. run.failed = (BUSY if following.busy(failure) else ("That photo could not be sent", _told(failure, AGAIN))) return submitted.append(job.id) try: job = _settled(run, job) if job is None: run.failed = (DID_NOT_WORK, "This took longer than the demo waits. Please try again later.") elif not job.succeeded: run.failed = (DID_NOT_WORK, job.error or "The job did not finish. Please try another photo.") elif run.watched: _result(run, job) _before(run, job) # Nobody is sent a second job after they have left: `watched` is read again here. if run.then and run.watched: _second_step(run, submitted) except (CraterViewError, OSError) as failure: run.failed = (DID_NOT_WORK, _told(failure, AGAIN)) def _settled(run: Run, job): """The job once it has settled, or None when the demo has stopped waiting for it.""" def seen(read) -> None: run.status, run.community, run.eta_seconds = read.status, read.community, read.eta_seconds return following.settled(cv, job, poll=POLL_SECONDS, give_up_after=GIVE_UP_SECONDS, seen=seen) def _second_step(run: Run, submitted: list[str]) -> None: """Pass the first result through the second model. The first result is already in hand, so a second step that fails leaves the visitor with it and says so, not with nothing.""" run.step, run.status, run.eta_seconds = 2, "sending", None try: job = following.sent(cv, run.then.model, run.result, run.then_params, pause=RESUBMIT_SECONDS) except (CraterViewError, OSError) as failure: # The account's own limits, and a platform that did not answer, are not the visitor's # to read about: the page says only that CraterView.ai was busy. run.skipped = ("CraterView.ai was busy" if following.busy(failure) else _told(failure, "it could not be sent")) return submitted.append(job.id) try: job = _settled(run, job) if job is None: run.skipped = "it took longer than the demo waits" elif not job.succeeded: run.skipped = job.error or "its job did not finish" elif run.watched: _result(run, job) except (CraterViewError, OSError) as failure: run.skipped = _told(failure, "its result could not be read") def _result(run: Run, job) -> None: """Bring a job's result here, and a copy small enough to draw beside the original. The run takes them together once both are in hand, so a failure part way leaves it as it was.""" saved = job.save(run.folder / f"craterview-{job.id}") with Image.open(saved) as result: after = _for_the_page(result) after.thumbnail((COMPARE_SIDE, COMPARE_SIDE)) drawn = run.folder / f"after-{run.step}.jpg" after.save(drawn, quality=92, icc_profile=after.info.get("icc_profile")) run.result, run.size, run.after = saved, (job.output_width, job.output_height), drawn def _before(run: Run, job) -> None: """The picture the first job worked from, drawn at the result's size as any viewer would show it enlarged.""" worked_from = requests.get(job.input_url, timeout=60) worked_from.raise_for_status() (run.folder / "worked-from").write_bytes(worked_from.content) with Image.open(run.after) as after, Image.open(run.folder / "worked-from") as source: before = _for_the_page(source).resize(after.size, Image.Resampling.BICUBIC) drawn = run.folder / "before.jpg" before.save(drawn, quality=92, icc_profile=before.info.get("icc_profile")) run.before = drawn def _for_the_page(image: Image.Image) -> Image.Image: profile = image.info.get("icc_profile") if image.mode in ("I;16", "I;16L", "I;16B", "I"): image = image.convert("I").point(lambda value: value * (1 / 257)).convert("L") picture = ImageOps.exif_transpose(image).convert("RGB") if profile: picture.info["icc_profile"] = profile return picture def delete_pictures(job_id: str) -> None: """Delete the job's pictures from the account now. The client has no call for this, so it is made directly: `DELETE /v1/jobs/{id}/media`, which answers 204 and is safe to repeat.""" answer = requests.delete(f"{cv.base_url}/v1/jobs/{job_id}/media", timeout=60, headers={"Authorization": f"Bearer {os.environ['CV_API_KEY']}"}) answer.raise_for_status() # ------------------------------------------------------------------------------- the page def header(tool: Tool) -> str: return f"""

{tool.headline}

{html.escape(tool.lede)}

""" def footer(tool: Tool) -> str: return f"""

{html.escape(tool.about)}

Your photo is sent to CraterView.ai to be processed. It is deleted automatically and not kept, and it is never used to train a model.

""" def panel(title: str, line: str = "", *, state: str = "idle", clock: str = "", step: str = "") -> str: """The result panel while there is no result to draw: idle, waiting, or failed.""" step = f'
{html.escape(step)}
' if step else "" sign = {"idle": "", "failed": '', "waiting": ''}[state] clock = f'
{html.escape(clock)}
' if clock else "" line = f"

{html.escape(line)}

" if line else "" return (f'
{sign}{step}
' f"{html.escape(title)}
{clock}{line}
") def finished(run: Run, tool: Tool) -> str: width, height = run.size cautions = [tool.caution] skipped = "" if run.skipped: skipped = (f"

{html.escape(run.then.name)} was not applied " f"({html.escape(run.skipped)}), so this is the photo without it.

") elif run.then: cautions.append(run.then.caution) return f"""
✓

Done: {width} × {height} px. CraterView.ai deletes your photo and this result automatically and does not keep them, so download the result before you leave.

{skipped}

{html.escape(" ".join(cautions))}

""" def _clock(seconds: float) -> str: return f"{int(seconds) // 60}:{int(seconds) % 60:02d}" def _waiting(run: Run, tool: Tool, started: float) -> str: clock = _clock(time.monotonic() - started) if run.status == "waiting": return panel("Waiting for a place in this demo", "Keep this tab open and your photo starts when one is free.", state="waiting", clock=clock) names = [tool.name, run.then.name] if run.then else [] step = f"Step {run.step} of 2: {names[run.step - 1]}" if names else "" if run.status == "sending": return panel("Sending your photo", state="waiting", clock=clock, step=step) if run.status == "running": left = (f"About {max(1, round(run.eta_seconds / 60))} min left. " if run.eta_seconds else "") working = run.then.working if run.step == 2 else tool.working return panel(working, f"{left}Keep this tab open and the result appears here.", state="waiting", clock=clock, step=step) if run.community: return panel("Waiting on the community queue", "Free work shares donated compute, so the wait is longer when it is busy. " "Keep this tab open and the result appears here.", state="waiting", clock=clock, step=step) return panel("Waiting for a machine", "Keep this tab open and the result appears here.", state="waiting", clock=clock, step=step) IDLE = "The result appears here, beside the original." def build(which: str) -> gr.Blocks: tool = TOOLS[which] configured = bool(os.environ.get("CV_API_KEY")) def choose(path: str | None): if not path: return None, None, "", gr.update(interactive=False) try: photo = opened(path, tool) except TooLarge as failure: raise gr.Error(str(failure)) from None except (OSError, ValueError): traceback.print_exc() # to the Space's log: the page says only what it can raise gr.Error("That file could not be read as a photo.") from None except CraterViewError as failure: raise gr.Error(str(failure)) from None return photo, drawn(photo), described(photo, tool), gr.update(interactive=configured) def choose_example(event: gr.SelectData): return choose(str(HERE / "examples" / tool.examples[event.index])) def move(photo: Photo | None, event: gr.SelectData): if photo is None: return None, None, "" ratio = photo.size[0] / photo.preview.width at = (event.index[0] * ratio, event.index[1] * ratio) photo.box = place(*photo.size, photo.side, at) return photo, drawn(photo), described(photo, tool) def refit(*held): """Fit each slider to the range the other settings now give it. One still at the default it was given moves to the new default; one the visitor moved keeps its value, brought inside the range.""" *values, given = held now = dict(zip(keys, values)) declared = settings.properties_for(entry["params_schema"], now) given, updates = dict(given), [] for key in sliders: spec, value = declared[key], now[key] if value == given[key] and "default" in spec: value = spec["default"] value = settings.held(min(max(value, spec["minimum"]), spec["maximum"])) given[key] = settings.held(spec.get("default", spec["minimum"])) # A range of one value, Enhance's scale binned 4x4, is drawn as a slider that # cannot move: the control refuses a range with no width. fixed = spec["maximum"] <= spec["minimum"] updates.append(gr.update(minimum=spec["minimum"], maximum=spec["minimum"] + 1 if fixed else spec["maximum"], step=settings.step(spec), value=value, interactive=not fixed)) return *updates, given def run_job(photo: Photo | None, second: bool, *values): hidden = gr.update(visible=False) if photo is None: yield panel("Choose a photo first", state="failed"), hidden, hidden, gr.update() return worked = photo.box[2:] try: params = settings.to_send(entry, dict(zip(keys, values)), worked) then_params = (settings.to_send(then_entry, dict(zip(then_keys, values[len(keys):])), worked) if tool.then and second else {}) except settings.Problem as problem: yield panel("Check the settings", str(problem), state="failed"), hidden, hidden, gr.update() return if not is_whole(*photo.size, photo.box): params["roi"] = fractions(*photo.size, photo.box) started = time.monotonic() busy = gr.update(interactive=False, value=f"{tool.name} is running") run = Run(Path(tempfile.mkdtemp(prefix="craterview-")), then=tool.then if second else None, then_params=then_params) threading.Thread(target=work, args=(run, tool.model, photo.path, params), daemon=True).start() try: while not run.done.wait(timeout=1.0): yield _waiting(run, tool, started), hidden, hidden, busy ready = gr.update(interactive=True, value=tool.button) # A run that ended some way nothing caught has neither, and says so too, where the # page drawing its result would itself fail. if run.failed or run.result is None: yield (panel(*(run.failed or (DID_NOT_WORK, AGAIN)), state="failed"), hidden, hidden, ready) return yield (finished(run, tool), gr.update(visible=True, value=(str(run.before), str(run.after))), gr.update(visible=True, value=str(run.result)), ready) finally: # Reached when the visitor leaves as well. The page has copied what it draws, so # a finished run's folder can go; an unfinished one is removed by its own thread. run.watched = False if run.done.is_set(): shutil.rmtree(run.folder, ignore_errors=True) def fields(of: dict) -> dict: """Draw one model's settings as its catalogue entry gives them: each control, then the entry's line of help under it.""" declared = of["params_schema"]["properties"] made = {} for key in settings.drawn(of): spec, name = declared[key], settings.label(key) drawn_as = settings.kind(spec) with gr.Column(elem_classes="cv-field"): if drawn_as == "slider": made[key] = gr.Slider(spec["minimum"], spec["maximum"], step=settings.step(spec), value=spec.get("default", spec["minimum"]), label=name, buttons=[]) elif drawn_as == "choice": made[key] = gr.Dropdown([(settings.option_label(v), v) for v in spec["enum"]], value=spec.get("default", spec["enum"][0]), label=name) elif drawn_as == "switch": made[key] = gr.Checkbox(value=bool(spec.get("default")), label=name) elif drawn_as == "number": with gr.Row(elem_classes="cv-number"): made[key] = gr.Number(value=spec.get("default", spec["minimum"]), minimum=spec["minimum"], maximum=spec["maximum"], precision=0, label=name, min_width=120) again = gr.Button("Random", scale=0, min_width=96) again.click(lambda low=spec["minimum"], high=spec["maximum"]: random.randint(low, high), None, made[key], api_visibility="private") else: made[key] = gr.Textbox(label=name, max_lines=1) if of["params_help"].get(key): gr.HTML(f'

{html.escape(of["params_help"][key])}

') return made entry = catalogue_at_start(tool.model) then_entry = catalogue_at_start(tool.then.model) if tool.then else None keys = settings.drawn(entry) then_keys = settings.drawn(then_entry) if then_entry else [] kinds = {key: settings.kind(entry["params_schema"]["properties"][key]) for key in keys} sliders = [key for key in keys if kinds[key] == "slider"] texts = [key for key in keys if kinds[key] == "text"] with gr.Blocks(title=f"CraterView.ai {tool.name}", delete_cache=(3600, 3600)) as page: photo = gr.State() gr.HTML(header(tool)) if not configured: gr.HTML(panel("This demo is not set up", "It has no key for CraterView.ai yet.", state="failed")) with gr.Row(equal_height=False): with gr.Column(min_width=300, elem_classes="cv-card"): gr.HTML('
Your photo
') picture = gr.Image(interactive=False, type="pil", format="jpeg", show_label=False, buttons=[], container=False, visible=True, placeholder="No photo chosen yet", elem_classes="cv-photo") note = gr.Markdown("", elem_classes="cv-quiet") accepted = [s for kind, found in SUFFIXES.items() for s in found] pick = gr.UploadButton("Choose a photo", file_types=accepted) second = gr.Checkbox(value=True, visible=tool.then is not None, label=tool.then.name if tool.then else "", info=tool.then.info if tool.then else "") with gr.Accordion("Model settings", open=False, elem_classes="cv-settings"): drawn_fields = fields(entry) if tool.then: with gr.Column(elem_classes="cv-fields") as then_group: gr.HTML(f'
{html.escape(tool.then.name)}
') then_fields = fields(then_entry) else: then_fields = {} go = gr.Button(tool.button, interactive=False, elem_classes="cv-go") gr.HTML('
Or try an example
') examples = gr.Gallery([str(HERE / "examples" / name) for name in tool.examples], show_label=False, columns=3, fit_columns=False, height=None, allow_preview=False, interactive=False, buttons=[], object_fit="cover", elem_classes="cv-examples") with gr.Column(min_width=300, elem_classes="cv-card"): gr.HTML('
Result
') compare = gr.ImageSlider(type="filepath", format="jpeg", interactive=False, show_label=False, buttons=["fullscreen"], visible=False, max_height=640, elem_classes="cv-photo") status = gr.HTML(panel(IDLE)) download = gr.DownloadButton("Download the result", visible=False) gr.HTML(footer(tool)) # Every event is the page's own. Gradio would otherwise publish each as a named call with # a reference page, and a script could run jobs on the Space's key without opening it. own = {"api_visibility": "private"} chosen = [photo, picture, note, go] pick.upload(choose, pick, chosen, **own) examples.select(choose_example, None, chosen, **own) picture.select(move, photo, [photo, picture, note], **own) held = [drawn_fields[key] for key in keys] given = gr.State({key: entry["params_schema"]["properties"][key].get("default") for key in sliders}) for key in settings.switches(entry["params_schema"]) & set(keys): drawn_fields[key].change(refit, [*held, given], [*(drawn_fields[k] for k in sliders), given], **own) for key in keys: # A width typed empties a height typed, and the other way: only one is sent. for rival in settings.rivals(entry["params_schema"], key) & set(texts): if key in texts: drawn_fields[key].input(lambda: "", None, drawn_fields[rival], **own) if tool.then: second.change(lambda on: gr.update(visible=on), second, then_group, **own) go.click(run_job, [photo, second, *held, *(then_fields[key] for key in then_keys)], [status, compare, download, go], concurrency_limit=SLOTS, show_progress="hidden", **own) return page def launch(which: str) -> None: from theme import CSS, HEAD, THEME build(which).queue(max_size=40).launch(theme=THEME, css=CSS, head=HEAD, max_file_size=MAX_UPLOAD, footer_links=[], show_error=True)