Spaces:
Running on Zero

HobbyLM-Image-2 / app.py
rootxhacker's picture
Add watermark verifier tab
06c72db verified
Raw History Blame Contribute Delete
16.1 kB
"""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(
"""
<div id="hero">
<h1>HobbyLM <span class="grad">Image&nbsp;2</span></h1>
<p>A 333M-parameter image model.
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])
with gr.Tab("🔍 Verify"):
gr.Markdown("Check whether an image was made by this model: every output carries an invisible "
"TrustMark watermark with a `HLMI` payload. Runs on CPU — no GPU quota used.")
with gr.Row():
with gr.Column(scale=5):
v_img = gr.Image(label="Image to check", type="pil", height=320)
v_deep = gr.Checkbox(value=False,
label="Deep search (recovers many crops; much slower, up to ~1 min)")
v_btn = gr.Button("Verify", variant="primary", size="lg")
with gr.Column(scale=6):
v_verdict = gr.Markdown()
v_json = gr.JSON(label="Decoder details")
v_btn.click(verify, [v_img, v_deep], [v_verdict, v_json])
gr.HTML(
"""
<div id="footer">
Weights &amp; 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 — check any image in the 🔍 Verify tab.
Small model, honest limits: tiny faces, hands, and long words are hard.
</div>
"""
)
demo.queue(max_size=24).launch(show_error=True)