Spaces:
Running on Zero
Running on Zero
Download app.py from linlinlinlinsdada/Jeveration: direct link, hf CLI and curl.
- Browser
- Download file 26.8 kB
-
https://huggingface.co/spaces/linlinlinlinsdada/Jeveration/resolve/main/app.py
- Command line
-
hf download hf://spaces/linlinlinlinsdada/Jeveration/app.py
-
curl -L -o app.py https://huggingface.co/spaces/linlinlinlinsdada/Jeveration/resolve/main/app.py
26.8 kB
| """Jeveration Studio — project-page-inspired gr.Server studio + gr.Workflow canvas. | |
| One loaded pipeline: text-to-image, image-to-image and dense prediction, available through | |
| gr.Server API endpoints at / and a chainable gr.Workflow canvas at /workflow. | |
| python app.py # weights from the Hugging Face Hub, studio on port 7860 | |
| """ | |
| import base64 | |
| import io | |
| import json | |
| import os | |
| import tempfile | |
| import threading | |
| import time | |
| from urllib.parse import unquote, urlparse | |
| import numpy as np | |
| import torch | |
| from PIL import Image, ImageOps | |
| try: | |
| import spaces # Hugging Face ZeroGPU: a GPU is attached only while a decorated function runs | |
| except ImportError: | |
| spaces = None | |
| import gradio as gr | |
| from fastapi.responses import FileResponse, HTMLResponse | |
| from gradio.context import LocalContext | |
| from gradio.utils import get_upload_folder | |
| from gradio_client import utils as client_utils | |
| from starlette.requests import Request as StarletteRequest | |
| from jeveration import config | |
| from jeveration.dense import depth_view, normal_view, seg_view | |
| WEIGHTS_REPO = "linlinlinlinsdada/Jeveration" | |
| APP_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| EXAMPLES_DIR = os.path.join(APP_DIR, "examples") | |
| MAX_SEED = 2**31 - 1 | |
| I2I_TASKS = list(config.I2I_TASKS) | |
| I2I_HELP = { | |
| "hed": "Input: a soft edge map (white edges on black), or a photo with the switch below on. Add a caption.", | |
| "depth": "Input: a depth map (bright = near), or a photo with the switch below on. Add a caption.", | |
| "colorize": "Input: a photo. It is read as a grey picture and colorized.", | |
| "anime": "Input: a photo.", "ghibli": "Input: a photo.", "watercolor": "Input: a photo.", | |
| } | |
| T2I_EXAMPLES = [ # each looks good at every seed tried | |
| "An oil painting of sunflowers in a blue ceramic vase, thick brush strokes.", | |
| "An owl with bright yellow eyes perched on a mossy branch at twilight, warm golden backlight, detailed feathers.", | |
| "An impressionist oil painting of a bouquet of peonies in a vase.", | |
| "A stone cottage with a thatched roof and a flower garden in the countryside.", | |
| "A watercolor painting of a sailboat on a calm sea at sunset.", | |
| "A lone pine tree on a small island in a calm lake at dawn.", | |
| "A watercolor painting of a snowy village at dusk with warm lit windows.", | |
| "A burger with melted cheese, lettuce and tomato on a wooden board, close-up.", | |
| "A painting in the style of Van Gogh of a starry night over a quiet village with a swirling sky.", | |
| "A small white chapel on a green alpine meadow with snowy peaks behind.", | |
| "A spirit fox made of glowing blue flames sitting in a dark forest, magical atmosphere.", | |
| "A river winding through a green valley with snowy mountains in the distance.", | |
| "An oil painting of a mountain lake in autumn with golden trees, visible brush strokes.", | |
| "A bouquet of tulips in a glass vase on a windowsill, soft morning light.", | |
| "A lion's face with a golden mane at sunset, savanna grass, cinematic lighting.", | |
| "A waterfall cascading into an emerald pool in a tropical jungle, sun rays through the mist.", | |
| "A Chinese ink wash painting of misty mountains and a lone boat on a river.", | |
| "A stack of fluffy pancakes with blueberries and maple syrup dripping down, butter on top, morning light.", | |
| "A snowy mountain cabin with warm glowing windows at blue hour, surrounded by pine trees.", | |
| "A close-up portrait of a woman wearing a flower crown in a meadow, dreamy pastel tones.", | |
| ] | |
| I2I_EXAMPLES = [ # (file in examples/, task, caption, the file is a photo) | |
| ("hed_puppy.png", "hed", "A fluffy white Samoyed puppy smiling in a field of yellow flowers on a sunny afternoon.", False), | |
| ("hed_tulips.png", "hed", "A bouquet of tulips in a glass vase on a windowsill, soft morning light.", False), | |
| ("photo_owl.jpg", "hed", "An owl with bright yellow eyes perched on a mossy branch at twilight, warm golden backlight, " | |
| "detailed feathers.", True), | |
| ("depth_pancakes.png", "depth", | |
| "A stack of fluffy pancakes with blueberries and maple syrup dripping down, butter on top, morning light.", False), | |
| ("photo_croissant.jpg", "depth", "A golden croissant on a marble table next to a cup of coffee, soft morning light.", True), | |
| ("gray_burger.jpg", "colorize", "", False), ("gray_pancakes.jpg", "colorize", "", False), | |
| ("photo_boathouse.jpg", "anime", "", False), ("photo_waterfall.jpg", "anime", "", False), | |
| ("photo_pine.jpg", "ghibli", "", False), ("photo_valley.jpg", "ghibli", "", False), | |
| ("photo_chapel.jpg", "watercolor", "", False), ("photo_snowcabin.jpg", "watercolor", "", False), | |
| ] | |
| DENSE_EXAMPLES = ["room_1.png", "room_2.png", "room_3.png", "room_4.png"] | |
| KNOWN_EXAMPLE_FILES = {name for name, *_ in I2I_EXAMPLES} | set(DENSE_EXAMPLES) | |
| def _load_pipeline(): | |
| from huggingface_hub import hf_hub_download | |
| from jeveration import JeverationPipeline | |
| paths = {name: hf_hub_download(WEIGHTS_REPO, name) | |
| for name in ("jeveration.pt", "decoder512.pt", "source_decoder512.pt")} | |
| return JeverationPipeline(paths["jeveration.pt"], decoder=paths["decoder512.pt"], | |
| source_decoder=paths["source_decoder512.pt"], device="cuda") | |
| PIPE = _load_pipeline() | |
| def _timed(call): | |
| """run call() -> (its result, 'NN ms on <device name>')""" | |
| cuda = PIPE.device.type == "cuda" | |
| if cuda: | |
| torch.cuda.synchronize(PIPE.device) | |
| t = time.perf_counter() | |
| out = call() | |
| if cuda: | |
| torch.cuda.synchronize(PIPE.device) | |
| ms = (time.perf_counter() - t) * 1000 | |
| return out, f"{ms:.0f} ms on {torch.cuda.get_device_name(PIPE.device) if cuda else 'the CPU'}" | |
| def _gpu(fn): | |
| # ZeroGPU checks the reserved seconds against the visitor's remaining quota; a request needs 1 to 7 s, the | |
| # first one from a photo also loads its edge or depth model. | |
| return spaces.GPU(duration=60)(fn) if spaces else fn | |
| def _generate_run(prompt, seed): | |
| """-> (uint8 [512, 512, 3], time note)""" | |
| prompt = (prompt or "").strip() | |
| if not prompt: | |
| raise ValueError("Write a prompt first.") | |
| images, note = _timed(lambda: PIPE.text_to_image([prompt], PIPE.generator(int(seed)))) | |
| return images[0], note | |
| def _edit_run(image, task, caption, from_photo, seed): | |
| """image: a PIL image -> (the prepared 512-px input, the result, time note), both uint8 [512, 512, 3]""" | |
| from jeveration.images import load_square, to_gray | |
| if image is None: | |
| raise ValueError("Upload an image first.") | |
| if task not in I2I_TASKS: | |
| raise ValueError(f"Task must be one of: {', '.join(I2I_TASKS)}.") | |
| source = load_square(image, config.IMAGE_SIZE) | |
| if task == "colorize": | |
| source = to_gray(source) | |
| elif from_photo and task in ("hed", "depth"): | |
| from jeveration.annotators import structure_map | |
| source = structure_map(source, task, PIPE.device) | |
| images, note = _timed(lambda: PIPE.image_to_image(source[None], task, [(caption or "").strip()], 0, | |
| PIPE.generator(int(seed)))) | |
| return source, images[0], note | |
| def _dense_run(image): | |
| """image: a PIL image -> (segmentation in colour, depth view with nearer brighter, normals as RGB, note)""" | |
| if image is None: | |
| raise ValueError("Upload a picture first.") | |
| picture = np.asarray(image.convert("RGB"), dtype=np.uint8) | |
| pred, note = _timed(lambda: PIPE.dense_predict(picture[None])) | |
| pred = {t: v[0].cpu().numpy() for t, v in pred.items()} | |
| seg = pred["seg"].astype(np.uint8) | |
| d = pred["depth"].astype(np.float32) | |
| classes = ", ".join(config.NYU13[i] for i in np.unique(seg)) | |
| return (seg_view(seg, picture), depth_view(d), normal_view(pred["normal"].astype(np.float32)), | |
| f"{note}; depth {d.min():.2f} to {d.max():.2f} m; classes: {classes}") | |
| # --------------------------------------------------------------------------- helpers | |
| def _resolve_seed(seed, randomize) -> int: | |
| import random | |
| return random.randint(0, MAX_SEED) if randomize else min(max(int(float(seed)), 0), MAX_SEED) | |
| def _check_choice(value, choices, name): | |
| if value not in choices: | |
| raise gr.Error(f"{name} must be one of: {', '.join(choices)}.") | |
| return value | |
| def _to_png_uri(pixels) -> str: | |
| """A uint8 [H, W, 3] array as a PNG data URI, so the studio page never needs a file route.""" | |
| handle = io.BytesIO() | |
| Image.fromarray(np.asarray(pixels, dtype=np.uint8)).save(handle, format="PNG") | |
| return "data:image/png;base64," + base64.b64encode(handle.getvalue()).decode("ascii") | |
| def _requested_path(value) -> str: | |
| """Turn whatever the studio/API client sends into a path.""" | |
| if isinstance(value, str): | |
| return value | |
| if not isinstance(value, dict): | |
| raise gr.Error(f"Expected an image, got {type(value).__name__}") | |
| if path := value.get("path"): | |
| return path | |
| url = value.get("url") or "" | |
| if "/gradio_api/file=" in url: | |
| return unquote(url.split("/gradio_api/file=", 1)[1]) | |
| if url.startswith(("http://", "https://")): | |
| raise gr.Error("Upload the image instead of passing a URL.") | |
| return unquote(urlparse(url).path) | |
| def _local_path(value) -> str: | |
| """A path this process may open: only files inside gradio's upload folder, | |
| where /gradio_api/upload puts uploads.""" | |
| path = os.path.realpath(_requested_path(value)) | |
| folder = os.path.realpath(get_upload_folder()) | |
| if os.path.commonpath([path, folder]) != folder: | |
| raise gr.Error("Upload the image first.") | |
| return path | |
| def _open_rgb(value): | |
| return ImageOps.exif_transpose(Image.open(_local_path(value))).convert("RGB") | |
| def _publish(pixels) -> str: | |
| """Write a result into Gradio's upload folder so the workflow canvas can display and chain it.""" | |
| folder = get_upload_folder() | |
| os.makedirs(folder, exist_ok=True) | |
| path = os.path.join(folder, f"jeveration_{os.urandom(8).hex()}.png") | |
| Image.fromarray(np.asarray(pixels, dtype=np.uint8)).save(path, format="PNG") | |
| return path | |
| def _as_media(path: str) -> dict: | |
| """The media shape used by gr.Workflow image inputs and outputs.""" | |
| return { | |
| "path": path, | |
| "url": f"/gradio_api/file={client_utils.encode_file_path(path)}", | |
| "is_file": True, | |
| } | |
| def _run(fn, *args): | |
| """One GPU call with the studio's error surface: messages, not stack traces.""" | |
| try: | |
| return fn(*args) | |
| except (RuntimeError, ValueError) as error: | |
| message = str(error).split("\n")[0] | |
| if "ZeroGPU" in message and ("limit" in message or "quota" in message): | |
| message += (" The run was billed anonymously: open the Space from its huggingface.co page " | |
| "while signed in, so it uses your own ZeroGPU quota — the anonymous allowance " | |
| "is tiny and shared.") | |
| raise gr.Error(message) | |
| def _generate(prompt, seed): | |
| return _generate_run(prompt, seed) | |
| def _edit(image, task, caption, from_photo, seed): | |
| return _edit_run(image, task, caption, from_photo, seed) | |
| def _dense(image): | |
| return _dense_run(image) | |
| # ---- ZeroGPU quota on the workflow canvas ----------------------------------- | |
| # The canvas is nested inside the studio iframe, so gradio's postMessage handshake with | |
| # huggingface.co — which would attach the visitor's x-ip-token to the canvas's requests — | |
| # never completes, and its @spaces.GPU calls bill the Space's anonymous allowance. The | |
| # studio page's own @gradio/client calls do carry the header, so every studio API call | |
| # stashes it per client IP, and workflow runs from the same IP re-attach it here. | |
| # Pattern from akhaliq/idol-studio. | |
| _TOKEN_TTL = 1800 # seconds | |
| _tokens: dict[str, tuple[str, float]] = {} | |
| _tokens_lock = threading.Lock() | |
| def _token_claims(token: str) -> dict: | |
| """The unverified JWT payload, to tell user-attributed tokens from anonymous ones.""" | |
| try: | |
| payload = token.split(".")[1] | |
| return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) | |
| except Exception: # noqa: BLE001 - not a JWT | |
| return {} | |
| def _client_ip(request) -> str: | |
| forwarded = (request.headers.get("x-forwarded-for") or "").split(",")[0].strip() | |
| return forwarded or (request.client.host if request.client else "") | |
| def _is_user_token(token: str) -> bool: | |
| return bool(_token_claims(token).get("user")) | |
| def _is_fresh_user_token(token: str) -> bool: | |
| """User-attributed and not expiring in the next few seconds (proxy tokens live ~2-4 min).""" | |
| claims = _token_claims(token) | |
| return bool(claims.get("user")) and claims.get("exp", 0) > time.time() + 5 | |
| def _remember_token(request) -> None: | |
| if request is None: | |
| return | |
| token = request.headers.get("x-ip-token") | |
| if not token: | |
| return | |
| ip = _client_ip(request) | |
| with _tokens_lock: | |
| now = time.time() | |
| for stale in [stale for stale, (_, at) in _tokens.items() if now - at > _TOKEN_TTL]: | |
| del _tokens[stale] | |
| existing = _tokens.get(ip) | |
| # never downgrade: an anonymous edge token must not replace a usable user-attributed one | |
| if existing and _is_fresh_user_token(existing[0]) and not _is_user_token(token): | |
| return | |
| _tokens[ip] = (token, now) | |
| def _fake_starlette_request(token_or_headers) -> StarletteRequest: | |
| """A real starlette request carrying just an x-ip-token (or a full header dict), so the | |
| gradio Request built on top of it behaves like one served over HTTP.""" | |
| if isinstance(token_or_headers, str): | |
| headers = {"x-ip-token": token_or_headers} | |
| else: | |
| headers = token_or_headers | |
| scope = { | |
| "type": "http", | |
| "method": "GET", | |
| "path": "/", | |
| "scheme": "https", | |
| "query_string": b"", | |
| "headers": [(k.lower().encode("ascii"), str(v).encode("latin-1")) | |
| for k, v in headers.items() if v is not None], | |
| } | |
| return StarletteRequest(scope) | |
| def _as_gradio_request(request): | |
| """A gradio Request with a live underlying starlette request — the shape spaces' ZeroGPU | |
| hook expects in LocalContext (it reads `request.request`). The workflow runtime and some | |
| Server-mode paths inject a raw starlette Request, and queue-created gradio Requests carry | |
| no live one; both are wrapped so ZeroGPU can read the visitor's x-ip-token.""" | |
| if request is None: | |
| return None | |
| if isinstance(request, gr.Request): | |
| if request.request is not None: | |
| return request | |
| return gr.Request(request=_fake_starlette_request(dict(getattr(request, "headers", {}) or {}))) | |
| if isinstance(request, StarletteRequest): | |
| return gr.Request(request=request) | |
| return gr.Request(request=_fake_starlette_request(str(request))) | |
| def _zerogpu_request(request): | |
| """The gradio Request to bind to LocalContext for the GPU call, or None to run anonymously. | |
| The studio's handshaken token (stored per IP) wins over the injected request's own header: | |
| that one may be an anonymous edge-minted token, which bills the Space's anonymous allowance.""" | |
| direct = request.headers.get("x-ip-token") if request is not None else None | |
| ip = _client_ip(request) if request is not None else "" | |
| with _tokens_lock: | |
| hit = _tokens.get(ip) | |
| stored = hit[0] if hit and time.time() - hit[1] <= _TOKEN_TTL else None | |
| if stored and _is_user_token(stored) and not _is_fresh_user_token(stored): | |
| stored = None # expired: the scheduler would reject it anyway | |
| if stored and (_is_user_token(stored) or not direct): | |
| return _as_gradio_request(stored) | |
| if direct: | |
| return _as_gradio_request(request) | |
| return None | |
| def _on_visitor_quota(request, fn, *args): | |
| """Run one GPU call on the visitor's quota when their token is known, else anonymously.""" | |
| zerogpu_request = _zerogpu_request(request) | |
| if zerogpu_request is None: | |
| return _run(fn, *args) | |
| reset = LocalContext.request.set(zerogpu_request) | |
| try: | |
| return _run(fn, *args) | |
| finally: | |
| LocalContext.request.reset(reset) | |
| # ------------------------------------------------------------------ workflow fns | |
| def jeveration_generate(prompt, seed: str = "42", request: gr.Request = None) -> dict: | |
| """Generate one 512 x 512 image from text. | |
| `request` is injected by the workflow runtime and never appears as a canvas port. ZeroGPU | |
| bills whoever owns the X-IP-Token header of the request in LocalContext; pointing the | |
| contextvar at the visitor's request keeps the @spaces.GPU call on their quota instead of | |
| the Space's anonymous allowance. | |
| """ | |
| seed_value = min(max(int(float(seed)), 0), MAX_SEED) | |
| image, _ = _on_visitor_quota(request, _generate, prompt, seed_value) | |
| return _as_media(_publish(image)) | |
| def jeveration_edit(image, task: str = "anime", caption: str = "", seed: str = "42", | |
| request: gr.Request = None) -> dict: | |
| """Apply structure-to-image, colorization or style transfer to an image.""" | |
| _check_choice(task, I2I_TASKS, "Task") | |
| source = _open_rgb(image) | |
| seed_value = min(max(int(float(seed)), 0), MAX_SEED) | |
| _, result, _ = _on_visitor_quota(request, _edit, source, task, caption, False, seed_value) | |
| return _as_media(_publish(result)) | |
| def jeveration_dense(image, request: gr.Request = None) -> tuple[dict, dict, dict]: | |
| """Return segmentation, depth and surface normals for an image.""" | |
| seg, depth, normal, _ = _on_visitor_quota(request, _dense, _open_rgb(image)) | |
| return tuple(_as_media(_publish(result)) for result in (seg, depth, normal)) | |
| # ------------------------------------------------------------------ studio server | |
| server = gr.Server(title="Jeveration Studio") | |
| def _studio_page(): | |
| with open(os.path.join(APP_DIR, "studio.html"), encoding="utf-8") as handle: | |
| return handle.read() | |
| def _example_file(name: str): | |
| """The example pictures, fetched by the studio page and uploaded by the visitor like any file.""" | |
| if name not in KNOWN_EXAMPLE_FILES or os.path.sep in name: | |
| raise gr.Error("Unknown example.") | |
| return FileResponse(os.path.join(EXAMPLES_DIR, name)) | |
| def api_generate(prompt: str, seed: float = 0, randomize: bool = True, | |
| request: gr.Request = None) -> dict: | |
| """Text-to-image with Jeveration (one 512 x 512 forward pass).""" | |
| _remember_token(request) | |
| seed_value = _resolve_seed(seed, randomize) | |
| image, note = _run(_generate, prompt, seed_value) | |
| return {"image_data": _to_png_uri(image), "seed": seed_value, "info": note} | |
| def api_edit(source: str, task: str = "hed", caption: str = "", from_photo: bool = False, | |
| seed: float = 0, randomize: bool = True, request: gr.Request = None) -> dict: | |
| """Structure-to-image, colorization or style transfer with Jeveration.""" | |
| _remember_token(request) | |
| _check_choice(task, I2I_TASKS, "Task") | |
| seed_value = _resolve_seed(seed, randomize) | |
| image = _open_rgb(source) | |
| prepared, result, note = _run(_edit, image, task, caption, bool(from_photo), seed_value) | |
| return {"source_data": _to_png_uri(prepared), "image_data": _to_png_uri(result), "seed": seed_value, | |
| "info": note} | |
| def api_dense(image: str, request: gr.Request = None) -> dict: | |
| """Segmentation (13 classes), depth and surface normals of a picture.""" | |
| _remember_token(request) | |
| seg, depth, normal, note = _run(_dense, _open_rgb(image)) | |
| return {"seg_data": _to_png_uri(seg), "depth_data": _to_png_uri(depth), "normal_data": _to_png_uri(normal), | |
| "info": note} | |
| def api_handshake(request: gr.Request = None) -> dict: | |
| """No-op the studio page calls on load and every minute; @gradio/client only attaches | |
| the visitor's ZeroGPU user token to queued calls, which _remember_token then stashes | |
| for the workflow canvas's runs (whose iframe never completes the handshake).""" | |
| _remember_token(request) | |
| return {"ok": True} | |
| # ------------------------------------------------------------------ realtime edits | |
| # The pattern from akhaliq/p-h3-image-2step (linoyts/qwen-image-2-1-realtime): a held-GPU | |
| # @spaces.GPU generator polls a per-session JSON channel and renders a fresh 512 x 512 frame | |
| # whenever the prompt, task, caption, source or seed changes, so live updates skip the | |
| # per-call reservation. @spaces.GPU runs in a forked subprocess, so requests reach the | |
| # running generator through the file, not a shared variable. | |
| LIVE_DIR = os.path.join(tempfile.gettempdir(), "jeveration_live") | |
| os.makedirs(LIVE_DIR, exist_ok=True) | |
| RT_WINDOW = 85 # seconds of held GPU per realtime window (under the @spaces.GPU duration) | |
| _gpu_live = spaces.GPU(duration=95) if spaces else (lambda fn: fn) | |
| def _live_path(sid): | |
| return os.path.join(LIVE_DIR, f"{sid}.json") | |
| def push_live(prompt, task, caption, from_photo, seed, source, sid): | |
| """Write the latest live request to the session's channel (no GPU). Bumps a version counter.""" | |
| if not sid: | |
| return | |
| path = _live_path(sid) | |
| prev = 0 | |
| if os.path.exists(path): | |
| try: | |
| prev = int(json.load(open(path)).get("ver", 0)) | |
| except Exception: # noqa: BLE001 | |
| prev = 0 | |
| tmp = path + ".tmp" | |
| with open(tmp, "w") as handle: | |
| json.dump({"prompt": prompt or "", "task": task or "hed", "caption": caption or "", | |
| "from_photo": bool(from_photo), "seed": int(seed), "source": source or None, | |
| "ver": prev + 1}, handle) | |
| os.replace(tmp, path) | |
| def _render_live_frame(req): | |
| """One live frame: an edit when a source is set, text-to-image otherwise. The model itself | |
| is the fast tier — one 512 x 512 forward pass per frame.""" | |
| seed = int(req.get("seed", 0)) | |
| if req.get("source"): | |
| image = _open_rgb(req["source"]) | |
| prepared, result, note = _edit_run(image, req.get("task", "hed"), req.get("caption", ""), | |
| bool(req.get("from_photo")), seed) | |
| return {"image_data": _to_png_uri(result), "source_data": _to_png_uri(prepared), | |
| "seed": seed, "info": note} | |
| result, note = _generate_run(req.get("prompt", ""), seed) | |
| return {"image_data": _to_png_uri(result), "seed": seed, "info": note} | |
| def _realtime_session(sid, realtime_on): | |
| """Hold the GPU and yield a fresh frame whenever the session's request changes.""" | |
| if not realtime_on or not sid: | |
| return | |
| path = _live_path(sid) | |
| deadline = time.time() + RT_WINDOW | |
| last_ver = -1 | |
| while time.time() < deadline: | |
| req = None | |
| if os.path.exists(path): | |
| try: | |
| with open(path) as handle: | |
| req = json.load(handle) | |
| except Exception: # noqa: BLE001 | |
| req = None | |
| if req and int(req.get("ver", -1)) != last_ver: | |
| last_ver = int(req["ver"]) | |
| try: | |
| yield _render_live_frame(req) | |
| except Exception as error: # noqa: BLE001 - one bad frame should not end the session | |
| print(f"[realtime] frame skipped: {error!r}", flush=True) | |
| else: | |
| time.sleep(0.05) | |
| def api_live_push(prompt: str = "", task: str = "hed", caption: str = "", from_photo: bool = False, | |
| seed: float = 0, source: str = "", sid: str = "") -> dict: | |
| """Queue the newest live request for the held-GPU realtime session (no GPU call).""" | |
| push_live(prompt, task, caption, bool(from_photo), int(seed), source or None, sid) | |
| return {"ok": True} | |
| def api_live_session(sid: str, realtime_on: bool = True, request: gr.Request = None) -> dict: | |
| """Hold the GPU and stream a fresh 512 x 512 frame whenever the session's request changes. | |
| The -> dict annotation is load-bearing: gr.api derives the endpoint's outputs from the | |
| return annotation, and a generator without one registers ZERO outputs — the queue then | |
| drops every streamed frame with a 'returned too many output values' warning. | |
| """ | |
| _remember_token(request) | |
| if not sid: | |
| raise gr.Error("No realtime session id.") | |
| zerogpu_request = _zerogpu_request(request) | |
| if zerogpu_request is None: | |
| yield from _realtime_session(sid, realtime_on) | |
| return | |
| reset = LocalContext.request.set(zerogpu_request) | |
| try: | |
| yield from _realtime_session(sid, realtime_on) | |
| finally: | |
| LocalContext.request.reset(reset) | |
| if spaces is None: # compile the kernels before the first visitor's request | |
| try: | |
| for _ in range(2): | |
| _generate_run(T2I_EXAMPLES[0], 0) | |
| except Exception as error: # noqa: BLE001 - the demo still works, the first request just pays the warmup | |
| print(f"warmup failed: {error!r}", flush=True) | |
| # The @server.api endpoints are deferred until Server.launch(), which also fires | |
| # the ZeroGPU registration hook (pack weights + startup report) through the | |
| # patched Blocks.launch path. Launch on a loopback port for registration, then | |
| # serve the same app via uvicorn. | |
| _port_env = os.environ.get("GRADIO_SERVER_PORT") | |
| os.environ["GRADIO_SERVER_PORT"] = "7861" | |
| try: | |
| server.launch( | |
| prevent_thread_lock=True, | |
| server_name="127.0.0.1", | |
| server_port=7861, | |
| quiet=True, | |
| show_error=False, | |
| ssr_mode=False, | |
| ) | |
| finally: | |
| if _port_env is None: | |
| del os.environ["GRADIO_SERVER_PORT"] | |
| else: | |
| os.environ["GRADIO_SERVER_PORT"] = _port_env | |
| try: | |
| server.close() | |
| except Exception: | |
| pass | |
| # Mount only after the registration launch above, so the workflow queue stays on | |
| # the public server's event loop. The starter graph chains Generate -> Edit -> Dense. | |
| workflow_demo = gr.Workflow( | |
| graph="workflow.json", | |
| bind={ | |
| "jeveration_generate": jeveration_generate, | |
| "jeveration_edit": jeveration_edit, | |
| "jeveration_dense": jeveration_dense, | |
| }, | |
| ) | |
| workflow_demo.title = "Jeveration Workflow" | |
| server = gr.mount_gradio_app(server, workflow_demo, path="/workflow", ssr_mode=False) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(server, host="0.0.0.0", port=int(os.environ.get("GRADIO_SERVER_PORT", "7860"))) | |