Spaces:
Running on Zero
Running on Zero
HobbyLM Image 2 Space: generate / edit / spell
Browse filesFiles changed (11)
- .gitattributes+1
- README.md+38-6
- app.pyAdded+254
- examples/dog.jpgAdded
- hobby_image/__init__.pyAdded
- hobby_image/dit.pyAdded+191
- hobby_image/glyph.pyAdded+41
- hobby_image/inference.pyAdded+169
- hobby_image/v2.pyAdded+83
- hobby_image/watermark.pyAdded+155
- requirements.txtAdded+11
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexamples/dog.jpg filter=lfs diff=lfs merge=lfs -text
12345678910111213---title: HobbyLM Image 2emoji: 🦀colorFrom: pinkcolorTo: greensdk: gradiosdk_version: 6.32.0python_version: '3.13'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445---title: HobbyLM Image 2emoji: 🎨colorFrom: indigocolorTo: pinksdk: gradiosdk_version: 5.9.1app_file: app.pypinned: falselicense: mitshort_description: Generate, edit & spell text with a 333M hobby-trained modelmodels:- rootxhacker/HobbyLM-image-2tags:- text-to-image- image-editing- text-rendering- flow-matching- dit- dc-ae- tiny-model---# 🎨 HobbyLM Image 2Interactive demo of **HobbyLM-Image v2** — a 333M-parameter flow-matching DiT (DC-AE f32c32latents, CLIP-L + FLAN-T5-Large conditioning) trained end to end on a hobby budget. Onecheckpoint (`model_v2_768u`) does three things:- **✨ Generate** — text-to-image at 512 / 768px.- **🪄 Edit** — instruction editing ("make it autumn") on any image, any aspect ratio.- **🔤 Spell** — render the words you put in "double quotes" into the scene.Weights, benchmark scores (GenEval 2, GEdit-Bench) and ComfyUI nodes:[rootxhacker/HobbyLM-image-2](https://huggingface.co/rootxhacker/HobbyLM-image-2).## HardwareWritten for **ZeroGPU** (`@spaces.GPU` on the three inference functions); it also runs on anyCUDA GPU locally. The Space needs an `HF_TOKEN` secret with read access to the model repo.## ProvenanceEvery output carries an invisible TrustMark watermark (payload `HLMI768u`) so images made herecan be identified as model output. Verify with `python -m hobby_image.detect image.jpg`.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""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 threading
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_jstpt
# --- ZeroGPU decorator, with a no-op fallback for local runs ---try: import spacesexcept Exception: 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()
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 _m try: 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 _m
def _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 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)[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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191"""DreamLite in-context DiT on a DC-AE f32c32 latent — the $300 path.
DC-AE compresses 32x spatially (vs VAE f8's 8x), so a 512px image -> 16x16x32 latent. The two-panelcanvas (target|source, width-concat) is 16x32x32 = ONLY 512 tokens (vs the conv U-Net's 64x128=8,192positions). A DiT on 512 tokens is ~order-of-magnitude cheaper to train than the conv U-Net, which ishow the budget drops from ~$1.66k toward ~$300. Trade-off: f32 reconstruction is slightly weaker thanf8c16 on fine text (acceptable for the V0 "global + simple-local edits" scope).
Standard DiT (AdaLN-Zero on self-attn + MLP) + cross-attention to the frozen-VLM refiner tokens, flow-matching velocity. Two-panel handled by a learned left/right panel embedding; loss uses the left half."""from __future__ import annotations
import mathfrom dataclasses import dataclass
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch import Tensor
@dataclassclass DiTConfig: in_channels: int = 34 # 32 DC-AE latent ch + 2 optional mask ch out_channels: int = 32 latent_h: int = 16 # 512px / 32 = 16 (256px -> 8) panel_w: int = 16 # per-panel width; canvas width = 2*panel_w patch: int = 1 # DC-AE latent is already compressed -> patch 1 d_model: int = 1024 depth: int = 16 heads: int = 16 mlp_ratio: float = 3.0 ctx_dim: int = 1024 n_tasks: int = 3
def sinusoidal(t: Tensor, dim: int) -> Tensor: half = dim // 2 f = torch.exp(-math.log(10000.0) * torch.arange(half, device=t.device) / half) a = t.float()[:, None] * f[None, :] return torch.cat([a.cos(), a.sin()], dim=-1)
def modulate(x: Tensor, shift: Tensor, scale: Tensor) -> Tensor: return x * (1 + scale[:, None]) + shift[:, None]
class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps
def forward(self, x: Tensor) -> Tensor: return F.rms_norm(x, (x.size(-1),), self.weight, self.eps)
class Attention(nn.Module): def __init__(self, dim: int, heads: int, ctx_dim: int | None = None, qk_norm: bool = True): super().__init__() self.heads = heads self.hd = dim // heads self.cross = ctx_dim is not None self.q = nn.Linear(dim, dim, bias=False) self.kv = nn.Linear(ctx_dim or dim, 2 * dim, bias=False) self.o = nn.Linear(dim, dim, bias=False) # QK-norm: RMSNorm on Q,K (over head_dim) BEFORE the dot product — the key training-stability # fix for DiTs (Inf-DiT/Lumina-Next/SD3); bounds the attention logits, prevents divergence. self.qn = RMSNorm(self.hd) if qk_norm else nn.Identity() self.kn = RMSNorm(self.hd) if qk_norm else nn.Identity()
def forward(self, x: Tensor, ctx: Tensor | None = None, mask: Tensor | None = None) -> Tensor: """mask: optional (B, M) bool over the context tokens, True = attend (cross-attn padding mask).""" B, N, _ = x.shape src = ctx if self.cross else x q = self.qn(self.q(x).view(B, N, self.heads, self.hd)).transpose(1, 2) kv = self.kv(src).view(B, src.shape[1], 2, self.heads, self.hd) k = self.kn(kv[:, :, 0]).transpose(1, 2) v = kv[:, :, 1].transpose(1, 2) o = F.scaled_dot_product_attention(q, k, v, attn_mask=None if mask is None else mask[:, None, None, :]) return self.o(o.transpose(1, 2).reshape(B, N, -1))
class DiTBlock(nn.Module): def __init__(self, cfg: DiTConfig): super().__init__() d = cfg.d_model self.ln1 = nn.LayerNorm(d, elementwise_affine=False, eps=1e-6) self.sa = Attention(d, cfg.heads) self.lnc = nn.LayerNorm(d, eps=1e-6) self.ca = Attention(d, cfg.heads, ctx_dim=cfg.ctx_dim) self.ln2 = nn.LayerNorm(d, elementwise_affine=False, eps=1e-6) h = int(d * cfg.mlp_ratio) self.mlp = nn.Sequential(nn.Linear(d, h), nn.GELU(approximate="tanh"), nn.Linear(h, d)) self.adaln = nn.Sequential(nn.SiLU(), nn.Linear(d, 6 * d)) nn.init.zeros_(self.adaln[-1].weight); nn.init.zeros_(self.adaln[-1].bias)
def forward(self, x: Tensor, cond: Tensor, ctx: Tensor, ctx_mask: Tensor | None = None) -> Tensor: sa_s, sa_sc, sa_g, ml_s, ml_sc, ml_g = self.adaln(cond).chunk(6, dim=-1) x = x + sa_g[:, None] * self.sa(modulate(self.ln1(x), sa_s, sa_sc)) x = x + self.ca(self.lnc(x), ctx, ctx_mask) # cross-attn to text tokens x = x + ml_g[:, None] * self.mlp(modulate(self.ln2(x), ml_s, ml_sc)) return x
class HobbyImageDiT(nn.Module): def __init__(self, cfg: DiTConfig): super().__init__() self.cfg = cfg d = cfg.d_model self.canvas_w = 2 * cfg.panel_w self.n_tokens = (cfg.latent_h // cfg.patch) * (self.canvas_w // cfg.patch) self.patch_embed = nn.Conv2d(cfg.in_channels, d, cfg.patch, stride=cfg.patch) self.pos = nn.Parameter(torch.zeros(1, self.n_tokens, d)) self.panel = nn.Parameter(torch.zeros(2, d)) # left/right self.t_mlp = nn.Sequential(nn.Linear(d, d), nn.SiLU(), nn.Linear(d, d)) self.task_emb = nn.Embedding(cfg.n_tasks, d) self.blocks = nn.ModuleList([DiTBlock(cfg) for _ in range(cfg.depth)]) self.ln_f = nn.LayerNorm(d, elementwise_affine=False, eps=1e-6) self.adaln_f = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d)) nn.init.zeros_(self.adaln_f[-1].weight); nn.init.zeros_(self.adaln_f[-1].bias) self.head = nn.Linear(d, cfg.patch * cfg.patch * cfg.out_channels) nn.init.zeros_(self.head.weight); nn.init.zeros_(self.head.bias) nn.init.trunc_normal_(self.pos, std=0.02)
def forward(self, x: Tensor, t: Tensor, ctx: Tensor, task: Tensor | None = None, ctx_mask: Tensor | None = None) -> Tensor: """x: (B, in_ch, H, W) DC-AE latent. W = 2*panel_w -> two-panel canvas [target | source] (the original layout); W = panel_w -> SINGLE panel (text-to-image without the blank source panel: half the tokens). H may differ from cfg.latent_h: the learned pos-embed grid is then resampled, so one set of weights serves several resolutions. t: (B,). ctx: (B, M, ctx_dim). ctx_mask: (B, M) bool. Returns velocity (B, out_ch, H, W).""" cfg = self.cfg B, _, H, W = x.shape h = self.patch_embed(x).flatten(2).transpose(1, 2) # (B, N, d) gh, gw = H // cfg.patch, W // cfg.patch ch, cw = cfg.latent_h // cfg.patch, self.canvas_w // cfg.patch # stored pos grid (canvas) if gh == ch and gw == cw: # native two-panel canvas (original path) h = h + self.pos col = torch.arange(self.n_tokens, device=x.device) % gw left = (col < gw // 2) h = h + torch.where(left[None, :, None], self.panel[0], self.panel[1]) else: fw = gh * cw // ch # canvas width at this resolution assert gw in (fw, fw // 2), f"bad latent shape {H}x{W} for stored grid {ch}x{cw}" pos = self.pos.float().view(1, ch, cw, -1) if gh != ch: pos = F.interpolate(pos.permute(0, 3, 1, 2), size=(gh, fw), mode="bicubic", align_corners=False, antialias=gh < ch).permute(0, 2, 3, 1) if gw == fw: # two-panel at a resampled resolution pan = torch.cat([self.panel[0].expand(gw // 2, -1), self.panel[1].expand(gw // 2, -1)]) pos = pos + pan[None, None] else: # single panel = left (target) half only pos = pos[:, :, :gw] + self.panel[0] h = h + pos.reshape(1, gh * gw, -1).to(h.dtype) cond = self.t_mlp(sinusoidal(t * 1000.0, cfg.d_model)) if task is not None: cond = cond + self.task_emb(task) for blk in self.blocks: h = blk(h, cond, ctx, ctx_mask) s, sc = self.adaln_f(cond).chunk(2, dim=-1) h = modulate(self.ln_f(h), s, sc) h = self.head(h) # (B, N, p*p*out) # unpatchify h = h.view(B, gh, gw, cfg.patch, cfg.patch, cfg.out_channels) h = h.permute(0, 5, 1, 3, 2, 4).reshape(B, cfg.out_channels, H, W) return h
def count_params(m: nn.Module) -> int: return sum(p.numel() for p in m.parameters())
# 512px: DC-AE f32 -> 16x16x32 per panel; two-panel canvas 16x32; 512 tokens.V0_DCAE_512 = DiTConfig(in_channels=34, out_channels=32, latent_h=16, panel_w=16, patch=1, d_model=1024, depth=16, heads=16, mlp_ratio=3.0, ctx_dim=1024)# 256px pilot: 8x8x32 per panel; canvas 8x16; 128 tokens.V0_DCAE_256 = DiTConfig(in_channels=34, out_channels=32, latent_h=8, panel_w=8, patch=1, d_model=1024, depth=16, heads=16, mlp_ratio=3.0, ctx_dim=1024)
if __name__ == "__main__": for name, cfg in [("512", V0_DCAE_512), ("256", V0_DCAE_256)]: m = HobbyImageDiT(cfg) x = torch.randn(2, cfg.in_channels, cfg.latent_h, 2 * cfg.panel_w) t = torch.rand(2); ctx = torch.randn(2, 256, cfg.ctx_dim); task = torch.zeros(2, dtype=torch.long) with torch.no_grad(): y = m(x, t, ctx, task) print(f"DiT {name}: {count_params(m)/1e6:.1f}M params | {m.n_tokens} tokens | " f"in {tuple(x.shape)} -> out {tuple(y.shape)}")1234567891011121314151617181920212223242526272829303132333435363738394041"""Glyph panel for text rendering (task id 2): the words to draw, rendered in a plain font on a white square atthe place they should appear. The DiT sees this panel next to the noisy target, the same two-panel layout asinstruction editing, and learns to copy the spelling into the scene."""import re
def glyph_panel(items, res: int = 512): """items: [(text, (x0, y0, x1, y1)), ...] in pixel coordinates of a res x res image -> PIL image.""" from PIL import Image, ImageDraw, ImageFont im = Image.new("RGB", (res, res), "white") d = ImageDraw.Draw(im) for text, (x0, y0, x1, y1) in items: bw, bh = max(8, x1 - x0), max(8, y1 - y0) s = max(8, int(bh * 0.95)) f = ImageFont.load_default(size=s) l, t, r, b = d.textbbox((0, 0), text, font=f) if r - l > bw: # too wide for the box: shrink to fit s = max(8, int(s * bw / (r - l))) f = ImageFont.load_default(size=s) l, t, r, b = d.textbbox((0, 0), text, font=f) d.text((x0 + (bw - (r - l)) / 2 - l, y0 + (bh - (b - t)) / 2 - t), text, font=f, fill="black") return im
def quoted(prompt: str): """Strings inside double (or curly) quotes in a prompt, in order.""" return [m.strip() for m in re.findall(r'["“]([^"”]{1,40})["”]', prompt) if m.strip()]
def default_layout(texts, res: int = 512): """Boxes for prompts that give no layout: lines stacked around the image centre, each as wide as its letters allow at a height of about 1/6 of the image.""" n = len(texts) h = min(res // 6, int(res * 0.6 / max(1, n))) y = (res - n * h - (n - 1) * h // 4) // 2 out = [] for t in texts: w = min(int(res * 0.84), int(h * 0.62 * max(2, len(t)))) out.append((t, ((res - w) // 2, y, (res + w) // 2, y + h))) y += h + h // 4 return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169"""HobbyLM-Image v2 inference: text-to-image, instruction editing and text rendering from one checkpoint.
from hobby_image.inference import HobbyImage m = HobbyImage("model_v2_768u.pt") m.generate(["a red fox sitting in a snowy forest, golden hour light, photo"])[0].save("fox.jpg") m.edit([Image.open("fox.jpg")], ["make it autumn"])[0].save("fox_autumn.jpg") m.text(['a wooden sign that says "OPEN" hanging on a cafe door'])[0].save("open.jpg")
Command line: python -m hobby_image.inference --ckpt model_v2_768u.pt --prompt "a lighthouse on a cliff at sunset" --out out.jpg python -m hobby_image.inference --ckpt model_v2_768u.pt --image in.jpg --prompt "make the car blue" --out edit.jpg python -m hobby_image.inference --ckpt model_v2_768u.pt --text --prompt 'a road sign that says "NEXT EXIT"' --out sign.jpg
Every output carries an invisible watermark (hobby_image/watermark.py) unless watermark=False is passed, andthe command line also writes an AI-generated label into the file's metadata. Check an image with python -m hobby_image.detect image.jpg
Tasks (the DiT's task id): 0 = text-to-image on one panel; 1 = edit, two panels [noisy target | source image];2 = text rendering, two panels [noisy target | glyph panel with the words in a plain font]."""import numpy as npimport torchfrom PIL import Image
from . import v2 as V2from .dit import HobbyImageDiT, DiTConfigfrom .glyph import glyph_panel, quoted, default_layoutfrom . import watermark as WM
DCAE = "mit-han-lab/dc-ae-f32c32-sana-1.1-diffusers"
class HobbyImage: def __init__(self, ckpt: str, device: str = "cuda"): from diffusers import AutoencoderDC from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, AutoTokenizer self.dev = device import os self.name = os.path.splitext(os.path.basename(ckpt))[0] self.wm_tag = self.name[-4:] if self.name.startswith("model_v2_") else WM.DEFAULT_TAG ck = torch.load(ckpt, map_location=device, weights_only=False) self.lat_std, self.sf, self.meta = float(ck["lat_std"]), float(ck["sf"]), ck["v2"] self.model = HobbyImageDiT(DiTConfig(**ck["cfg_dict"])).to(device).eval() self.model.load_state_dict(ck["sd"]) self.fusion = V2.TextFusion(1024, self.model.cfg.ctx_dim).to(device).eval() self.fusion.load_state_dict(ck["fusion"]) self.ae = AutoencoderDC.from_pretrained(DCAE, torch_dtype=torch.bfloat16).to(device).eval() self.tok = CLIPTokenizer.from_pretrained(V2.CLIP_ID) self.clip = CLIPTextModel.from_pretrained(V2.CLIP_ID, torch_dtype=torch.bfloat16).to(device).eval() self.t5_tok = AutoTokenizer.from_pretrained(ck["v2"]["t5"]) self.t5 = T5EncoderModel.from_pretrained(ck["v2"]["t5"], torch_dtype=torch.bfloat16).to(device).eval()
# ---- latents <-> images ---- def _decode(self, z): out = [] with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): for j in range(0, len(z), 8): out.append(self.ae.decode((z[j:j + 8] * self.lat_std / self.sf).bfloat16()).sample.float().clamp(-1, 1)) arr = ((torch.cat(out).permute(0, 2, 3, 1) + 1) * 127.5).clamp(0, 255).byte().cpu().numpy() return [Image.fromarray(a) for a in arr]
def _encode(self, pil_list): x = torch.from_numpy(np.stack([np.asarray(p.convert("RGB")) for p in pil_list])).to(self.dev) x = x.permute(0, 3, 1, 2).float() / 127.5 - 1 with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): lat = self.ae.encode(x.bfloat16()).latent.float() return lat * self.sf / self.lat_std
def _mark(self, ims, watermark): return [WM.embed(im, self.wm_tag) for im in ims] if watermark else ims
def _text(self, prompts): ctx, mask = V2.encode_text(list(prompts), self.tok, self.clip, self.t5_tok, self.t5, self.fusion, self.dev) return (ctx, mask) + tuple(V2.null_like(ctx, mask))
# ---- task 0: text-to-image ---- @torch.no_grad() def generate(self, prompts, res: int = 768, steps: int = 50, cfg: float = 4.5, seed: int = 0, watermark: bool = True): """Square images at 512 or 768px. 768px uses the timestep shift stored in the checkpoint.""" n, lat = len(prompts), res // 32 ctx, mask, uctx, umask = self._text(prompts) z = torch.randn(n, 32, lat, lat, device=self.dev, generator=torch.Generator(self.dev).manual_seed(seed)) sh = V2.ckpt_shift(self.meta, res) ts = [1 - sh * (1 - k / steps) / (1 + (sh - 1) * (1 - k / steps)) for k in range(steps + 1)] task = torch.zeros(n, dtype=torch.long, device=self.dev) pad = torch.zeros(n, 2, lat, lat, device=self.dev) for i in range(steps): tt = torch.full((n,), ts[i], device=self.dev) inp = torch.cat([z, pad], dim=1) with torch.autocast("cuda", dtype=torch.bfloat16): vc = self.model(inp, tt, ctx, task, mask).float() vu = self.model(inp, tt, uctx, task, umask).float() z = z + (vu + cfg * (vc - vu)) * (ts[i + 1] - ts[i]) return self._mark(self._decode(z), watermark)
# ---- tasks 1 and 2: two-panel sampling with separate text and image guidance ---- @torch.no_grad() def _two_panel(self, src, prompts, task_id, steps, cfg_t, cfg_i, seed): n, h, w = src.shape[0], src.shape[2], src.shape[3] ctx, mask, uctx, umask = self._text(prompts) z = torch.randn(n, 32, h, w, device=self.dev, generator=torch.Generator(self.dev).manual_seed(seed)) task = torch.full((n,), task_id, dtype=torch.long, device=self.dev) pad = torch.zeros(n, 2, h, 2 * w, device=self.dev) for i in range(steps): tt = torch.full((n,), i / steps, device=self.dev) a = torch.cat([torch.cat([z, src], dim=-1), pad], dim=1) b = torch.cat([torch.cat([z, torch.zeros_like(src)], dim=-1), pad], dim=1) with torch.autocast("cuda", dtype=torch.bfloat16): vf = self.model(a, tt, ctx, task, mask).float()[..., :w] # text + panel vi = self.model(a, tt, uctx, task, umask).float()[..., :w] # panel only vu = self.model(b, tt, uctx, task, umask).float()[..., :w] # neither z = z + (vu + cfg_i * (vi - vu) + cfg_t * (vf - vi)) / steps return z
def edit(self, images, instructions, steps: int = 50, cfg_t: float = 7.5, cfg_i: float = 1.2, seed: int = 0, res: int = 512, watermark: bool = True): """Instruction editing at 512px. The editor is square: other shapes are padded by repeating the edge pixels, edited, cropped back and resized to the input size.""" fitted, boxes = [], [] for im in images: im = im.convert("RGB") w, h = im.size s = res / max(w, h) nw, nh = max(32, round(w * s)), max(32, round(h * s)) a = np.asarray(im.resize((nw, nh), Image.LANCZOS)) l, t = (res - nw) // 2, (res - nh) // 2 fitted.append(Image.fromarray(np.pad(a, ((t, res - nh - t), (l, res - nw - l), (0, 0)), mode="edge"))) boxes.append((l, t, l + nw, t + nh)) z = self._two_panel(self._encode(fitted), instructions, 1, steps, cfg_t, cfg_i, seed) out = [o.crop(b).resize(im.size, Image.LANCZOS) for o, b, im in zip(self._decode(z), boxes, images)] return self._mark(out, watermark) # marked after the resize back to the input size
def text(self, prompts, layouts=None, steps: int = 50, cfg_t: float = 5.0, cfg_i: float = 1.5, seed: int = 0, res: int = 512, watermark: bool = True): """Text rendering at 512px. The words inside double quotes in each prompt are drawn into a glyph panel, one word per line around the image centre, unless `layouts` gives [(word, (x0, y0, x1, y1)), ...] per prompt. Short words in bold print on flat surfaces work best.""" panels = [] for k, p in enumerate(prompts): items = layouts[k] if layouts else default_layout([w for t in quoted(p) for w in t.split()], res) panels.append(glyph_panel(items, res)) return self._mark(self._decode(self._two_panel(self._encode(panels), prompts, 2, steps, cfg_t, cfg_i, seed)), watermark)
if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("--ckpt", required=True) ap.add_argument("--prompt", required=True) ap.add_argument("--image", default="", help="source image: run an instruction edit") ap.add_argument("--text", action="store_true", help='render the words in "double quotes" (glyph task)') ap.add_argument("--res", type=int, default=768) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", default="out.jpg") ap.add_argument("--no-watermark", action="store_true", help="skip the invisible watermark and the metadata label") a = ap.parse_args() m = HobbyImage(a.ckpt) wm = not a.no_watermark if a.image: task, im = "edit", m.edit([Image.open(a.image)], [a.prompt], seed=a.seed, watermark=wm)[0] elif a.text: task, im = "text", m.text([a.prompt], seed=a.seed, watermark=wm)[0] else: task, im = "generate", m.generate([a.prompt], res=a.res, seed=a.seed, watermark=wm)[0] if wm: WM.save(im, a.out, model=m.name, task=task, prompt=a.prompt, seed=a.seed) else: im.save(a.out) print("wrote", a.out)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""HobbyLM-Image v2 conditioning + sampling helpers.
v2 keeps the v1 DiT weights but (a) runs text-to-image on a SINGLE panel (no blank source panel ->half the tokens) and (b) conditions on CLIP-L tokens *plus* FLAN-T5 encoder tokens, fused into onecross-attention context. CLIP-L alone caps compositional prompts (counting / position / attributebinding); T5 tokens are projected into the CLIP context width so the pretrained cross-attentionkeeps working from step 0."""from __future__ import annotations
import torchimport torch.nn as nnfrom torch import Tensor
CLIP_ID = "openai/clip-vit-large-patch14"T5_ID = "google/flan-t5-large"CLIP_LEN = 64T5_LEN = 96
class TextFusion(nn.Module): """[CLIP tokens (ctx_dim) | proj(T5 tokens)] -> (ctx, mask). CLIP tokens are all attended (as in v1 training); T5 padding is masked out."""
def __init__(self, t5_dim: int = 1024, ctx_dim: int = 768): super().__init__() self.ln = nn.LayerNorm(t5_dim) self.proj = nn.Linear(t5_dim, ctx_dim) nn.init.normal_(self.proj.weight, std=0.02); nn.init.zeros_(self.proj.bias)
def forward(self, clip_h: Tensor, t5_h: Tensor, t5_mask: Tensor) -> tuple[Tensor, Tensor]: t = self.proj(self.ln(t5_h.float())) * t5_mask[..., None].float() ctx = torch.cat([clip_h.float(), t], dim=1) mask = torch.cat([torch.ones(clip_h.shape[:2], dtype=torch.bool, device=clip_h.device), t5_mask.bool()], dim=1) return ctx, mask
def null_like(ctx: Tensor, mask: Tensor) -> tuple[Tensor, Tensor]: """Unconditional branch used in training (10% drop): all-zero context, nothing masked.""" return torch.zeros_like(ctx), torch.ones_like(mask)
@torch.no_grad()def encode_text(texts, clip_tok, clip, t5_tok, t5, fusion, dev="cuda"): """texts -> fused (ctx, mask) with frozen encoders (bf16 autocast).""" ci = clip_tok(texts, padding="max_length", max_length=CLIP_LEN, truncation=True, return_tensors="pt").input_ids.to(dev) tt = t5_tok(texts, padding="max_length", max_length=T5_LEN, truncation=True, return_tensors="pt") ti, tm = tt.input_ids.to(dev), tt.attention_mask.to(dev) with torch.autocast("cuda", dtype=torch.bfloat16): ch = clip(ci).last_hidden_state th = t5(input_ids=ti, attention_mask=tm).last_hidden_state return fusion(ch, th, tm)
def ckpt_shift(meta: dict, res: int) -> float: """Sampling shift for a checkpoint's meta (ck["v2"]) at `res`: the trained high-res shift at the high-res training resolution, 1.0 everywhere else.""" if str(res) in (meta.get("shifts") or {}): # checkpoints trained at several high resolutions return float(meta["shifts"][str(res)]) return float(meta.get("hi_shift") or 1.0) if meta.get("hi_res") == res else 1.0
@torch.no_grad()def sample(dit, ctx, mask, uctx, umask, z, n_steps: int = 50, cfg: float = 4.0, shift: float = 1.0): """Single-panel Euler flow-matching sampler with classifier-free guidance (t: 0 = noise -> 1 = data). shift > 1 spends more steps at high noise (SD3 resolution shift on the noise level 1 - t); use the value the checkpoint was trained with at that resolution (ck["v2"]["hi_shift"]), 1.0 otherwise.""" n = z.shape[0] task = torch.zeros(n, dtype=torch.long, device=z.device) pad = torch.zeros(n, 2, z.shape[2], z.shape[3], device=z.device) # unused mask channels ts = [i / n_steps for i in range(n_steps + 1)] if shift != 1.0: ts = [1 - shift * (1 - t) / (1 + (shift - 1) * (1 - t)) for t in ts] for i in range(n_steps): tt = torch.full((n,), ts[i], device=z.device) inp = torch.cat([z, pad], dim=1) with torch.autocast("cuda", dtype=torch.bfloat16): vc = dit(inp, tt, ctx, task, mask).float() vu = dit(inp, tt, uctx, task, umask).float() z = z + (vu + cfg * (vc - vu)) * (ts[i + 1] - ts[i]) return z123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Provenance marks for HobbyLM-Image outputs: an invisible watermark in the pixels and a metadata tag in the file.
Invisible watermark: TrustMark (Adobe, MIT licence, arXiv 2311.18297), variant Q, BCH_5 error correction. Thepayload is 8 ASCII characters: the prefix "HLMI" plus a 4-character tag for the checkpoint (default "768u").An image counts as HobbyLM-Image output only if the decoder reports a valid codeword AND the payload startswith "HLMI", so a stray valid codeword in an unrelated image does not count.
Metadata: an IPTC digital-source-type of "trainedAlgorithmicMedia" (the label platforms read for AI-generatedimages) in an XMP packet, plus a JSON record of model, task, prompt and seed. Metadata is lost when a file isre-encoded or screenshotted; the pixel watermark is the part meant to survive that.
Neither mark is tamper-proof. TrustMark ships its own remover, and anyone running the open weights can turn thewatermark off. The marks identify output from people who leave the defaults on.
from hobby_image.watermark import embed, detect, save im = embed(im) # PIL in, PIL out detect(im) # {'hobbylm': True, 'tag': '768u', 'payload': 'HLMI768u', 'present': True, ...} detect(im, deep=True) # also searches for a cropped image; slow (up to ~130 decodes)
Detection tries the image at 0, 90, 180 and 270 degrees. The watermark does not survive a crop that removes morethan about a third of the area on its own; deep=True puts the image back on larger blank canvases (the decoderneeds the mark at roughly its original position and scale) and recovers most crops that keep 40% or more of thearea. Crops keeping a quarter of the area or less, and small-angle rotations, are not recovered. save(im, "out.png", task="generate", prompt="...", seed=0)"""import json
PREFIX = "HLMI"DEFAULT_TAG = "768u"SOURCE_TYPE = "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia"_tm = None
def _trustmark(): global _tm if _tm is None: from trustmark import TrustMark _tm = TrustMark(verbose=False, model_type="Q", encoding_type=1, loadRemover=False) # encoding 1 = BCH_5 return _tm
def embed(im, tag: str = DEFAULT_TAG, strength: float = 1.0): """Returns a copy of the PIL image carrying the invisible watermark PREFIX + tag (tag: up to 4 ASCII characters).""" tag = (tag or DEFAULT_TAG)[:4].ljust(4, "_") return _trustmark().encode(im.convert("RGB"), PREFIX + tag, MODE="text", WM_STRENGTH=strength)
_SCALES = (1.0, 1.15, 1.32, 1.5) # canvas size / crop size, per axis, crop centred_ANCHORS = tuple((a, b) for a in (0.0, 0.5, 1.0) for b in (0.0, 0.5, 1.0) if (a, b) != (0.5, 0.5))_ANCHOR_SCALES = (1.0, 1.2, 1.41)
def _canvas(im, sx, sy, ax=0.5, ay=0.5): """The image on a canvas sx, sy times its size, filled with its mean colour; ax, ay in 0..1 place it.""" from PIL import Image w, h = round(im.width * sx), round(im.height * sy) c = Image.new("RGB", (w, h), tuple(int(v) for v in im.resize((1, 1), Image.BOX).getpixel((0, 0)))) c.paste(im, (round((w - im.width) * ax), round((h - im.height) * ay))) return c
def _candidates(im, deep): from PIL import Image rots = [(0, im)] + [(d, im.transpose(t)) for d, t in ((90, Image.ROTATE_90), (180, Image.ROTATE_180), (270, Image.ROTATE_270))] for d, r in rots: # the image as it is, at the four right angles yield d, False, r if not deep: return for d, r in rots: # a centred crop for sx in _SCALES: for sy in _SCALES: if (sx, sy) != (1.0, 1.0): yield d, True, _canvas(r, sx, sy) for ax, ay in _ANCHORS: # a crop taken from a corner or an edge for sx in _ANCHOR_SCALES: for sy in _ANCHOR_SCALES: if (sx, sy) != (1.0, 1.0): yield 0, True, _canvas(im, sx, sy, ax, ay)
def detect(im, deep: bool = False): """{'hobbylm', 'tag', 'payload', 'present', 'rotation', 'crop_search', 'decodes'}. `present` is TrustMark's own verdict on the image as given (a valid codeword of any origin); `hobbylm` also requires our prefix. `rotation` is the angle at which the mark was read and `crop_search` says whether the crop search found it. deep=True adds the crop search (slow: up to about 130 decodes when nothing is found).""" im = im.convert("RGB") tm, first, n = _trustmark(), None, 0 for rot, searched, cand in _candidates(im, deep): secret, present, _schema = tm.decode(cand, MODE="text") n += 1 present = bool(present) and isinstance(secret, str) if first is None: first = (secret if present else "", present) if present and secret.startswith(PREFIX): return {"hobbylm": True, "tag": secret[len(PREFIX):len(PREFIX) + 4].rstrip("_"), "payload": secret, "present": True, "rotation": rot, "crop_search": searched, "decodes": n} return {"hobbylm": False, "tag": None, "payload": first[0], "present": first[1], "rotation": None, "crop_search": False, "decodes": n}
def _xmp(record: dict) -> bytes: desc = json.dumps(record, ensure_ascii=True).replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """) return ( '<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>' '<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">' '<rdf:Description rdf:about="" xmlns:Iptc4xmpExt="http://iptc.org/std/Iptc4xmpExt/2008-02-29/" ' 'xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" ' f'Iptc4xmpExt:DigitalSourceType="{SOURCE_TYPE}" xmp:CreatorTool="HobbyLM-Image v2">' f'<dc:description><rdf:Alt><rdf:li xml:lang="x-default">{desc}</rdf:li></rdf:Alt></dc:description>' '</rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>' ).encode("utf-8")
def save(im, path: str, model: str = "model_v2_" + DEFAULT_TAG, task: str = "", prompt: str = "", seed=None, watermarked: bool = True, quality: int = 95): """Saves a PNG, JPEG or WebP with the AI-generated label and a JSON record in the file's metadata.""" record = {"generator": "HobbyLM-Image v2", "model": model, "task": task, "prompt": prompt, "seed": seed, "ai_generated": True, "invisible_watermark": "TrustMark-Q " + PREFIX if watermarked else None} xmp = _xmp(record) ext = path.lower().rsplit(".", 1)[-1] if ext == "png": from PIL import PngImagePlugin info = PngImagePlugin.PngInfo() info.add_text("Software", "HobbyLM-Image v2") info.add_text("hobbylm", json.dumps(record)) info.add_itxt("XML:com.adobe.xmp", xmp.decode("utf-8")) im.save(path, pnginfo=info) elif ext in ("jpg", "jpeg"): im.convert("RGB").save(path, quality=quality, xmp=xmp) elif ext == "webp": im.save(path, quality=quality, xmp=xmp) else: im.save(path) return record
def read_metadata(path: str): """The record written by save(), or None. Also reports whether the AI-generated label is present.""" from PIL import Image im = Image.open(path) raw = im.info.get("hobbylm") xmp = im.info.get("XML:com.adobe.xmp") or im.info.get("xmp") or b"" if isinstance(xmp, bytes): xmp = xmp.decode("utf-8", "ignore") rec = None if raw: rec = json.loads(raw) elif "<rdf:li" in xmp: try: body = xmp.split("<rdf:li", 1)[1].split(">", 1)[1].split("</rdf:li>", 1)[0] rec = json.loads(body.replace(""", '"').replace("<", "<").replace(">", ">").replace("&", "&")) except Exception: rec = None return {"record": rec, "ai_generated_label": SOURCE_TYPE in xmp}1234567891011gradio==5.9.1huggingface_hub>=0.28,<1.0transformers==4.49.0diffusers==0.32.2acceleratesafetensorspillownumpysentencepieceprotobuftrustmark.gitattributes+1
README.md+38-6
app.pyAdded+254
examples/dog.jpgAdded

Large File Pointer Details
- SHA256: 0953b9df91d00f95fa07b14b15dd01a8039d93482af9821c64482935a859d505
- Pointer size: 131 Bytes
- Size of remote file: 103 kB
hobby_image/__init__.pyAdded
hobby_image/dit.pyAdded+191
hobby_image/glyph.pyAdded+41
hobby_image/inference.pyAdded+169
hobby_image/v2.pyAdded+83
hobby_image/watermark.pyAdded+155
requirements.txtAdded+11