"""HobbyLM Image 2 — Gradio Space for the 333M three-task image model. One checkpoint (model_v2_768u) does text-to-image, instruction editing and in-image text rendering. The model code is vendored in `hobby_image/` (custom architecture, no AutoModel). Written for ZeroGPU: the model is built once in the main process on CPU (forked GPU workers inherit it) and moved to CUDA inside the @spaces.GPU calls. """ import os import random import threading import time # ZeroGPU: `spaces` must be imported before torch so its CUDA interception is active. try: import spaces _ZERO = True except Exception: _ZERO = False class _Spaces: @staticmethod def GPU(*a, **k): if a and callable(a[0]): return a[0] def deco(f): return f return deco spaces = _Spaces() import gradio as gr import torch from huggingface_hub import hf_hub_download # --- gradio_client bug workaround (boolean schemas crash /info and the UI shows "No API found") --- import gradio_client.utils as _gcu # noqa: E402 _orig_get_type = _gcu.get_type def _safe_get_type(schema): if not isinstance(schema, dict): return "Any" return _orig_get_type(schema) _gcu.get_type = _safe_get_type _orig_jstpt = _gcu._json_schema_to_python_type def _safe_jstpt(schema, defs=None): if isinstance(schema, bool): return "Any" return _orig_jstpt(schema, defs) _gcu._json_schema_to_python_type = _safe_jstpt REPO = "rootxhacker/HobbyLM-image-2" CKPT = "model_v2_768u.pt" _m = None _err = [] _wm_ok = False _ready = threading.Event() def _build(): """Startup (main process, so forked GPU workers inherit everything): download the checkpoint, build the pipeline, prefetch the TrustMark watermark model, and stage weights on 'cuda' so ZeroGPU attaches them fast instead of paying a CPU->GPU copy on every call.""" global _m, _wm_ok try: path = hf_hub_download(REPO, CKPT, token=os.environ.get("HF_TOKEN")) from hobby_image.inference import HobbyImage m = HobbyImage(path, device="cpu") try: # pre-place the bundled TrustMark weights so no download is attempted import shutil import trustmark as _tmpkg tdir = os.path.join(os.path.dirname(_tmpkg.__file__), "models") here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "trustmark_models") for f in os.listdir(here): shutil.copy(os.path.join(here, f), os.path.join(tdir, f)) except Exception: pass # fall through; the retry loop below may still download them from PIL import Image from hobby_image import watermark as WM for _ in range(3): # trustmark fetches any missing/invalid file on first init try: # device='cpu' is load-bearing on ZeroGPU: TrustMark's auto-select sees the faked # cuda in the main process and would initialise CUDA outside a GPU context, # which breaks every later @spaces.GPU call. from trustmark import TrustMark WM._tm = TrustMark(verbose=False, model_type="Q", encoding_type=1, loadRemover=False, device="cpu") WM.embed(Image.new("RGB", (256, 256), "gray")) # proves encoder weights really loaded _wm_ok = True break except Exception: WM._tm = None # a half-initialised TrustMark would otherwise be cached time.sleep(3) if _ZERO: try: for mod in (m.model, m.fusion, m.ae, m.clip, m.t5): mod.to("cuda") m.dev = "cuda" except Exception: pass # stay on CPU; _model() moves per call instead _m = m except Exception as e: # surfaced to the user on the first click _err.append(f"{type(e).__name__}: {e}") finally: _ready.set() threading.Thread(target=_build, daemon=True).start() def _model(): _ready.wait() if _m is None: raise gr.Error("The model failed to load — " + (_err[0] if _err else "unknown error")) if _m.dev != "cuda" and torch.cuda.is_available(): for mod in (_m.model, _m.fusion, _m.ae, _m.clip, _m.t5): mod.to("cuda") _m.dev = "cuda" return _m def _seed(seed): seed = int(seed) return random.randint(0, 2**31 - 1) if seed < 0 else seed def _wm(img): """Watermark as a best effort: a TrustMark hiccup must never fail the generation.""" if not _wm_ok: return img try: from hobby_image import watermark as WM return WM.embed(img, _m.wm_tag) except Exception: return img def verify(image, deep): """CPU-only: decode the TrustMark watermark and say whether this is HobbyLM-Image output.""" if image is None: raise gr.Error("Upload an image to check.") _ready.wait() if not _wm_ok: raise gr.Error("The watermark decoder is unavailable on this Space right now.") from hobby_image import watermark as WM r = WM.detect(image, deep=bool(deep)) if r.get("hobbylm"): rot = f", rotated {r['rotation']}°" if r.get("rotation") else "" verdict = (f"✅ **HobbyLM-Image output** — payload `{r.get('payload')}`, " f"checkpoint tag `{r.get('tag')}`{rot}.") elif r.get("present"): verdict = "⚠️ A TrustMark watermark is present, but it is **not** a HobbyLM-Image payload." else: verdict = ("❌ **No HobbyLM-Image watermark found.** Heavy crops, strong re-encoding or " "screenshots can destroy the mark, so this is not proof the image isn't model output.") return verdict, r @spaces.GPU(duration=75) def generate(prompt, res, steps, cfg, seed): if not (prompt or "").strip(): raise gr.Error("Describe the image first.") m, s = _model(), _seed(seed) img = m.generate([prompt.strip()], res=int(res), steps=int(steps), cfg=float(cfg), seed=s, watermark=False)[0] return _wm(img), s @spaces.GPU(duration=75) def edit(image, instruction, steps, cfg_t, cfg_i, seed): if image is None: raise gr.Error("Upload or pick an image to edit.") if not (instruction or "").strip(): raise gr.Error("Say what to change, e.g. “make it autumn”.") m, s = _model(), _seed(seed) img = m.edit([image], [instruction.strip()], steps=int(steps), cfg_t=float(cfg_t), cfg_i=float(cfg_i), seed=s, watermark=False)[0] return _wm(img), s @spaces.GPU(duration=75) def spell(prompt, steps, cfg_t, cfg_i, seed): from hobby_image.glyph import quoted if not (prompt or "").strip(): raise gr.Error("Describe the scene first.") if not quoted(prompt): raise gr.Error('Put the words to draw in "double quotes" — e.g. a cafe sign that says "OPEN".') m, s = _model(), _seed(seed) img = m.text([prompt.strip()], steps=int(steps), cfg_t=float(cfg_t), cfg_i=float(cfg_i), seed=s, watermark=False)[0] return _wm(img), s # ---------------------------------------------------------------- UI ---------------------------------------------------------------- CSS = """ .gradio-container {max-width: 1080px !important; margin: 0 auto !important;} #hero {text-align: center; padding: 26px 0 6px;} #hero h1 {font-size: 2.4rem; font-weight: 800; letter-spacing: -0.02em; margin: 0;} #hero h1 .grad {background: linear-gradient(90deg, #6366f1, #ec4899); -webkit-background-clip: text; background-clip: text; color: transparent;} #hero p {color: var(--body-text-color-subdued); margin: 8px auto 0; max-width: 640px; font-size: 1.02rem;} #hero .chips {margin-top: 14px; display: flex; gap: 8px; justify-content: center; flex-wrap: wrap;} #hero .chip {font-size: 0.8rem; padding: 4px 12px; border-radius: 999px; border: 1px solid var(--border-color-primary); color: var(--body-text-color-subdued);} #footer {text-align: center; color: var(--body-text-color-subdued); font-size: 0.82rem; padding: 18px 0 8px; line-height: 1.7;} #footer a {color: inherit; text-decoration: underline;} .out-image img {border-radius: 12px;} button.primary {font-weight: 600;} .tab-nav button {font-size: 1rem;} """ THEME = gr.themes.Soft( primary_hue=gr.themes.colors.indigo, neutral_hue=gr.themes.colors.slate, font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"], ).set(button_large_radius="12px", block_radius="14px") GEN_EXAMPLES = [ ["a red fox sitting in a snowy forest, golden hour light, photo"], ["a yellow vintage car parked in front of a pastel blue house"], ["a lighthouse on a cliff at sunset, dramatic clouds"], ["a cozy reading nook by a window with plants and warm lamp light"], ["an astronaut riding a horse on the moon, digital art"], ["three red apples in a row on a wooden table"], ] EDIT_EXAMPLES = [ ["examples/dog.jpg", "make it autumn"], ["examples/dog.jpg", "turn it into a watercolor painting"], ["examples/dog.jpg", "make it night time"], ] SPELL_EXAMPLES = [ ['a wooden sign that says "OPEN" hanging on a cafe door'], ['a road sign in the desert that says "NEXT EXIT" under a blue sky'], ['a person wearing a t-shirt that says "HELLO"'], ['a storefront banner that says "SUMMER SALE"'], ] with gr.Blocks(theme=THEME, css=CSS, title="HobbyLM Image 2") as demo: gr.HTML( """
A 333M-parameter image model. One checkpoint, three tricks — generate pictures, edit them with plain instructions, and spell words into the scene.