Spaces:
Running on Zero
Running on Zero
Fail-safe prefetched watermark, cuda staging at startup, faster defaults
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""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 textrendering. 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 workersinherit it) and moved to CUDA inside the @spaces.GPU calls."""import osimport randomimport threadingimport gradio as grimport torchfrom 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_typedef _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_typedef _safe_jstpt(schema, defs=None):if isinstance(schema, bool):return "Any"return _orig_jstpt(schema, defs)_gcu._json_schema_to_python_type = _safe_jstpt# --- ZeroGPU decorator, with a no-op fallback for local runs ---try:import spacesexcept Exception:class _Spaces:@staticmethoddef GPU(*a, **k):if a and callable(a[0]):return a[0]def deco(f):return freturn decospaces = _Spaces()REPO = "rootxhacker/HobbyLM-image-2"CKPT = "model_v2_768u.pt"_m = None_err = []_ready = threading.Event()def _build():"""Download the checkpoint and build the pipeline on CPU in the main process at startup."""global _mtry:path = hf_hub_download(REPO, CKPT, token=os.environ.get("HF_TOKEN"))from hobby_image.inference import HobbyImage_m = HobbyImage(path, device="cpu")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 _mdef _seed(seed):seed = int(seed)return random.randint(0, 2**31 - 1) if seed < 0 else seed@spaces.GPU(duration=120)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)[0]return img, s@spaces.GPU(duration=120)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)[0]return img, s@spaces.GPU(duration=120)def spell(prompt, steps, cfg_t, cfg_i, seed):from hobby_image.glyph import quotedif 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)[0]return 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("""<div id="hero"><h1>HobbyLM <span class="grad">Image 2</span></h1><p>A 333M-parameter image model trained on a hobby budget.One checkpoint, three tricks — generate pictures, edit them with plain instructions,and spell words into the scene.</p><div class="chips"><span class="chip">333M flow-matching DiT</span><span class="chip">768px generation</span><span class="chip">instruction editing</span><span class="chip">text rendering</span></div></div>""")with gr.Tab("✨ Generate"):with gr.Row():with gr.Column(scale=5):g_prompt = gr.Textbox(label="Prompt", lines=3, autofocus=True,placeholder="a red fox sitting in a snowy forest, golden hour light, photo")g_res = gr.Radio([768, 512], value=768, label="Resolution")g_btn = gr.Button("Generate", variant="primary", size="lg")with gr.Accordion("Advanced", open=False):g_steps = gr.Slider(20, 60, value=50, step=1, label="Steps")g_cfg = gr.Slider(1.0, 9.0, value=4.5, step=0.5, label="Guidance (CFG)")g_seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")with gr.Column(scale=6):g_out = gr.Image(label="Result", elem_classes="out-image", format="jpeg")g_used = gr.Number(label="Seed used", precision=0, interactive=False)gr.Examples(GEN_EXAMPLES, inputs=[g_prompt], label="Try one")g_btn.click(generate, [g_prompt, g_res, g_steps, g_cfg, g_seed], [g_out, g_used])g_prompt.submit(generate, [g_prompt, g_res, g_steps, g_cfg, g_seed], [g_out, g_used])with gr.Tab("🪄 Edit"):gr.Markdown("Upload a picture (or generate one first), then say what to change. Any aspect ratio works; edits run at 512px.")with gr.Row():with gr.Column(scale=5):e_img = gr.Image(label="Image to edit", type="pil", height=320)e_prompt = gr.Textbox(label="Instruction", lines=2, placeholder="make it autumn")e_btn = gr.Button("Apply edit", variant="primary", size="lg")with gr.Accordion("Advanced", open=False):e_steps = gr.Slider(20, 60, value=50, step=1, label="Steps")e_cfg_t = gr.Slider(1.0, 12.0, value=7.5, step=0.5, label="Text guidance (how strongly to follow the instruction)")e_cfg_i = gr.Slider(1.0, 3.0, value=1.2, step=0.1, label="Image guidance (how much of the source to keep)")e_seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")with gr.Column(scale=6):e_out = gr.Image(label="Edited image", elem_classes="out-image", format="jpeg")e_used = gr.Number(label="Seed used", precision=0, interactive=False)gr.Examples(EDIT_EXAMPLES, inputs=[e_img, e_prompt], label="Try one")e_btn.click(edit, [e_img, e_prompt, e_steps, e_cfg_t, e_cfg_i, e_seed], [e_out, e_used])e_prompt.submit(edit, [e_img, e_prompt, e_steps, e_cfg_t, e_cfg_i, e_seed], [e_out, e_used])with gr.Tab("🔤 Spell"):gr.Markdown('Put the words to draw in **"double quotes"**. One to three short words in bold print ''(signs, shirts, mugs, posters) work best; handwriting and long words often misspell.')with gr.Row():with gr.Column(scale=5):s_prompt = gr.Textbox(label="Prompt", lines=3,placeholder='a wooden sign that says "OPEN" hanging on a cafe door')s_btn = gr.Button("Generate", variant="primary", size="lg")with gr.Accordion("Advanced", open=False):s_steps = gr.Slider(20, 60, value=50, step=1, label="Steps")s_cfg_t = gr.Slider(1.0, 9.0, value=5.0, step=0.5, label="Text guidance")s_cfg_i = gr.Slider(1.0, 3.0, value=1.5, step=0.1, label="Glyph guidance")s_seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")with gr.Column(scale=6):s_out = gr.Image(label="Result", elem_classes="out-image", format="jpeg")s_used = gr.Number(label="Seed used", precision=0, interactive=False)gr.Examples(SPELL_EXAMPLES, inputs=[s_prompt], label="Try one")s_btn.click(spell, [s_prompt, s_steps, s_cfg_t, s_cfg_i, s_seed], [s_out, s_used])s_prompt.submit(spell, [s_prompt, s_steps, s_cfg_t, s_cfg_i, s_seed], [s_out, s_used])gr.HTML("""<div id="footer">Weights & samples: <a href="https://huggingface.co/rootxhacker/HobbyLM-image-2">rootxhacker/HobbyLM-image-2</a>· ComfyUI nodes included in the repo · First request after a cold start downloads the model (~1 min).<br>Every output carries an invisible TrustMark watermark and is labelled AI-generated.Small model, honest limits: tiny faces, hands, and long words are hard.</div>""")demo.queue(max_size=24).launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290"""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 textrendering. 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 workersinherit it) and moved to CUDA inside the @spaces.GPU calls."""import osimport randomimport threadingimport time# ZeroGPU: `spaces` must be imported before torch so its CUDA interception is active.try:import spaces_ZERO = Trueexcept Exception:_ZERO = Falseclass _Spaces:@staticmethoddef GPU(*a, **k):if a and callable(a[0]):return a[0]def deco(f):return freturn decospaces = _Spaces()import gradio as grimport torchfrom 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_typedef _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_typedef _safe_jstpt(schema, defs=None):if isinstance(schema, bool):return "Any"return _orig_jstpt(schema, defs)_gcu._json_schema_to_python_type = _safe_jstptREPO = "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' soZeroGPU attaches them fast instead of paying a CPU->GPU copy on every call."""global _m, _wm_oktry:path = hf_hub_download(REPO, CKPT, token=os.environ.get("HF_TOKEN"))from hobby_image.inference import HobbyImagem = HobbyImage(path, device="cpu")for _ in range(3): # trustmark downloads its decoder on first init; retry transient failurestry:from hobby_image import watermark as WMWM._trustmark()_wm_ok = Truebreakexcept Exception: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 = mexcept 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 _mdef _seed(seed):seed = int(seed)return random.randint(0, 2**31 - 1) if seed < 0 else seeddef _wm(img):"""Watermark as a best effort: a TrustMark hiccup must never fail the generation."""if not _wm_ok:return imgtry:from hobby_image import watermark as WMreturn WM.embed(img, _m.wm_tag)except Exception:return img@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 quotedif 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("""<div id="hero"><h1>HobbyLM <span class="grad">Image 2</span></h1><p>A 333M-parameter image model trained on a hobby budget.One checkpoint, three tricks — generate pictures, edit them with plain instructions,and spell words into the scene.</p><div class="chips"><span class="chip">333M flow-matching DiT</span><span class="chip">768px generation</span><span class="chip">instruction editing</span><span class="chip">text rendering</span></div></div>""")with gr.Tab("✨ Generate"):with gr.Row():with gr.Column(scale=5):g_prompt = gr.Textbox(label="Prompt", lines=3, autofocus=True,placeholder="a red fox sitting in a snowy forest, golden hour light, photo")g_res = gr.Radio([768, 512], value=768, label="Resolution")g_btn = gr.Button("Generate", variant="primary", size="lg")with gr.Accordion("Advanced", open=False):g_steps = gr.Slider(10, 60, value=30, step=1, label="Steps")g_cfg = gr.Slider(1.0, 9.0, value=4.5, step=0.5, label="Guidance (CFG)")g_seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")with gr.Column(scale=6):g_out = gr.Image(label="Result", elem_classes="out-image", format="jpeg")g_used = gr.Number(label="Seed used", precision=0, interactive=False)gr.Examples(GEN_EXAMPLES, inputs=[g_prompt], label="Try one")g_btn.click(generate, [g_prompt, g_res, g_steps, g_cfg, g_seed], [g_out, g_used])g_prompt.submit(generate, [g_prompt, g_res, g_steps, g_cfg, g_seed], [g_out, g_used])with gr.Tab("🪄 Edit"):gr.Markdown("Upload a picture (or generate one first), then say what to change. Any aspect ratio works; edits run at 512px.")with gr.Row():with gr.Column(scale=5):e_img = gr.Image(label="Image to edit", type="pil", height=320)e_prompt = gr.Textbox(label="Instruction", lines=2, placeholder="make it autumn")e_btn = gr.Button("Apply edit", variant="primary", size="lg")with gr.Accordion("Advanced", open=False):e_steps = gr.Slider(10, 60, value=40, step=1, label="Steps")e_cfg_t = gr.Slider(1.0, 12.0, value=7.5, step=0.5, label="Text guidance (how strongly to follow the instruction)")e_cfg_i = gr.Slider(1.0, 3.0, value=1.2, step=0.1, label="Image guidance (how much of the source to keep)")e_seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")with gr.Column(scale=6):e_out = gr.Image(label="Edited image", elem_classes="out-image", format="jpeg")e_used = gr.Number(label="Seed used", precision=0, interactive=False)gr.Examples(EDIT_EXAMPLES, inputs=[e_img, e_prompt], label="Try one")e_btn.click(edit, [e_img, e_prompt, e_steps, e_cfg_t, e_cfg_i, e_seed], [e_out, e_used])e_prompt.submit(edit, [e_img, e_prompt, e_steps, e_cfg_t, e_cfg_i, e_seed], [e_out, e_used])with gr.Tab("🔤 Spell"):gr.Markdown('Put the words to draw in **"double quotes"**. One to three short words in bold print ''(signs, shirts, mugs, posters) work best; handwriting and long words often misspell.')with gr.Row():with gr.Column(scale=5):s_prompt = gr.Textbox(label="Prompt", lines=3,placeholder='a wooden sign that says "OPEN" hanging on a cafe door')s_btn = gr.Button("Generate", variant="primary", size="lg")with gr.Accordion("Advanced", open=False):s_steps = gr.Slider(10, 60, value=40, step=1, label="Steps")s_cfg_t = gr.Slider(1.0, 9.0, value=5.0, step=0.5, label="Text guidance")s_cfg_i = gr.Slider(1.0, 3.0, value=1.5, step=0.1, label="Glyph guidance")s_seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")with gr.Column(scale=6):s_out = gr.Image(label="Result", elem_classes="out-image", format="jpeg")s_used = gr.Number(label="Seed used", precision=0, interactive=False)gr.Examples(SPELL_EXAMPLES, inputs=[s_prompt], label="Try one")s_btn.click(spell, [s_prompt, s_steps, s_cfg_t, s_cfg_i, s_seed], [s_out, s_used])s_prompt.submit(spell, [s_prompt, s_steps, s_cfg_t, s_cfg_i, s_seed], [s_out, s_used])gr.HTML("""<div id="footer">Weights & samples: <a href="https://huggingface.co/rootxhacker/HobbyLM-image-2">rootxhacker/HobbyLM-image-2</a>· ComfyUI nodes included in the repo · First request after a cold start downloads the model (~1 min).<br>Every output carries an invisible TrustMark watermark and is labelled AI-generated.Small model, honest limits: tiny faces, hands, and long words are hard.</div>""")demo.queue(max_size=24).launch()
app.py+290-254