Restore FLUX.2 Klein 9B (Fibo evaluation complete)
Browse files- README.md +1 -1
- app.py +201 -202
- requirements.txt +1 -0
README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
---
|
| 2 |
title: klein
|
| 3 |
-
emoji: "
|
| 4 |
colorFrom: gray
|
| 5 |
colorTo: gray
|
| 6 |
sdk: gradio
|
|
|
|
| 1 |
---
|
| 2 |
title: klein
|
| 3 |
+
emoji: "🎨"
|
| 4 |
colorFrom: gray
|
| 5 |
colorTo: gray
|
| 6 |
sdk: gradio
|
app.py
CHANGED
|
@@ -1,202 +1,201 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
-
#
|
| 4 |
-
#
|
| 5 |
-
#
|
| 6 |
-
#
|
| 7 |
-
#
|
| 8 |
-
#
|
| 9 |
-
#
|
| 10 |
-
#
|
| 11 |
-
#
|
| 12 |
-
#
|
| 13 |
-
#
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
import
|
| 19 |
-
|
| 20 |
-
import
|
| 21 |
-
|
| 22 |
-
import
|
| 23 |
-
import
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
#
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
#
|
| 48 |
-
#
|
| 49 |
-
#
|
| 50 |
-
#
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
""
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
out
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
demo.launch()
|
|
|
|
| 1 |
+
# FLUX.2 Klein 9B — reference-image editing with runtime LoRA.
|
| 2 |
+
#
|
| 3 |
+
# This is the model that answers both open requests at once. Qwen-Image-Edit
|
| 4 |
+
# holds identity but renders glossy; Z-Image looks photographic but its editing
|
| 5 |
+
# pipeline needs siglip weights Tongyi has not released; neither supports LoRA
|
| 6 |
+
# on our stack. Klein is tagged image-to-image, takes one or more reference
|
| 7 |
+
# images, and Flux2KleinPipeline carries load_lora_weights — so one checkpoint
|
| 8 |
+
# covers generation, editing and per-character LoRA.
|
| 9 |
+
#
|
| 10 |
+
# Started on the 4B because it is Apache-2.0 and ungated. Its output was not
|
| 11 |
+
# convincing enough, so this runs the 9B — see the note at MODEL below.
|
| 12 |
+
#
|
| 13 |
+
# `import spaces` first and stays first — it patches torch.cuda.*, and once CUDA
|
| 14 |
+
# is initialised in the main process it is too late to intercept.
|
| 15 |
+
import spaces
|
| 16 |
+
|
| 17 |
+
import base64
|
| 18 |
+
import random
|
| 19 |
+
import traceback
|
| 20 |
+
from io import BytesIO
|
| 21 |
+
|
| 22 |
+
import gradio as gr
|
| 23 |
+
import numpy as np
|
| 24 |
+
import torch
|
| 25 |
+
from diffusers import Flux2KleinPipeline
|
| 26 |
+
|
| 27 |
+
# 9B, not the 4B this started on — the 4B's output was not convincing enough.
|
| 28 |
+
# It is gated behind Black Forest Labs' flux-non-commercial-license, so the
|
| 29 |
+
# account running this Space must accept the terms on the model page first, and
|
| 30 |
+
# the Space needs an HF_TOKEN secret to authenticate the download. Without both,
|
| 31 |
+
# the build dies on a 403 fetching model_index.json.
|
| 32 |
+
MODEL = "black-forest-labs/FLUX.2-klein-9B"
|
| 33 |
+
|
| 34 |
+
dtype = torch.bfloat16
|
| 35 |
+
pipe = Flux2KleinPipeline.from_pretrained(MODEL, torch_dtype=dtype)
|
| 36 |
+
|
| 37 |
+
# Eagerly at module scope: ZeroGPU intercepts this, packs the weights to disk
|
| 38 |
+
# and streams them into VRAM on the first decorated call. Loading lazily inside
|
| 39 |
+
# the decorator makes every caller pay the cost instead of nobody.
|
| 40 |
+
pipe = pipe.to("cuda")
|
| 41 |
+
|
| 42 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 43 |
+
STEPS = 4 # Klein is distilled; the reference Space defaults to 4
|
| 44 |
+
GUIDANCE = 2.5
|
| 45 |
+
|
| 46 |
+
# Adapters are cached by name and never re-downloaded. Loading a LoRA per
|
| 47 |
+
# request would re-fetch tens of megabytes every call, and the Space process
|
| 48 |
+
# survives between calls, so the cache is free. Adapters also STACK if you do
|
| 49 |
+
# not manage them — set_adapters replaces the active set, and disable_lora
|
| 50 |
+
# turns them all off, which is what an unadorned request needs.
|
| 51 |
+
LOADED = set()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _apply_loras(specs):
|
| 55 |
+
"""specs is a list of {repo, weight_name, scale}. Empty disables all."""
|
| 56 |
+
if not specs:
|
| 57 |
+
pipe.disable_lora()
|
| 58 |
+
return []
|
| 59 |
+
names, scales = [], []
|
| 60 |
+
for i, spec in enumerate(specs):
|
| 61 |
+
repo = spec.get("repo")
|
| 62 |
+
if not repo:
|
| 63 |
+
continue
|
| 64 |
+
weight_name = spec.get("weight_name") or None
|
| 65 |
+
name = spec.get("adapter_name") or f"a{abs(hash((repo, weight_name))) % 10**8}"
|
| 66 |
+
if name not in LOADED:
|
| 67 |
+
pipe.load_lora_weights(repo, weight_name=weight_name, adapter_name=name)
|
| 68 |
+
LOADED.add(name)
|
| 69 |
+
names.append(name)
|
| 70 |
+
scales.append(float(spec.get("scale", 1.0)))
|
| 71 |
+
if not names:
|
| 72 |
+
pipe.disable_lora()
|
| 73 |
+
return []
|
| 74 |
+
pipe.set_adapters(names, adapter_weights=scales)
|
| 75 |
+
return names
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _duration(*a, **k):
|
| 79 |
+
# ZeroGPU bills the duration REQUESTED but ABORTS anything that overruns,
|
| 80 |
+
# so one flat number either wastes quota on small images or kills big ones.
|
| 81 |
+
w = int(k.get("width") or 1024)
|
| 82 |
+
h = int(k.get("height") or 1024)
|
| 83 |
+
return min(120, max(30, round((w * h) / 40000)))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@spaces.GPU(duration=_duration)
|
| 87 |
+
def infer(image_1, image_2, prompt, seed=0, randomize_seed=True,
|
| 88 |
+
guidance_scale=GUIDANCE, num_inference_steps=STEPS,
|
| 89 |
+
width=1024, height=1024, loras=None,
|
| 90 |
+
progress=gr.Progress(track_tqdm=True)):
|
| 91 |
+
"""Edit one or two reference images according to a prompt."""
|
| 92 |
+
if randomize_seed:
|
| 93 |
+
seed = random.randint(0, MAX_SEED)
|
| 94 |
+
|
| 95 |
+
_apply_loras(loras or [])
|
| 96 |
+
|
| 97 |
+
images = [im for im in (image_1, image_2) if im is not None]
|
| 98 |
+
if not images:
|
| 99 |
+
raise gr.Error("At least one reference image is required.")
|
| 100 |
+
|
| 101 |
+
out = pipe(
|
| 102 |
+
image=images if len(images) > 1 else images[0],
|
| 103 |
+
prompt=prompt,
|
| 104 |
+
width=int(width),
|
| 105 |
+
height=int(height),
|
| 106 |
+
num_inference_steps=int(num_inference_steps),
|
| 107 |
+
guidance_scale=float(guidance_scale),
|
| 108 |
+
generator=torch.Generator("cuda").manual_seed(int(seed)),
|
| 109 |
+
).images[0]
|
| 110 |
+
|
| 111 |
+
return out, seed
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
with gr.Blocks(delete_cache=(3600, 86400)) as demo:
|
| 115 |
+
with gr.Column():
|
| 116 |
+
# No public interface. This is a backend for one application, and a
|
| 117 |
+
# landing page only attracts traffic that spends the ZeroGPU quota. The
|
| 118 |
+
# controls below still exist, hidden, because hiding them removes the
|
| 119 |
+
# interface without removing the event registration that publishes the
|
| 120 |
+
# API — delete the components and the endpoint goes with them.
|
| 121 |
+
gr.HTML(
|
| 122 |
+
"""
|
| 123 |
+
<div style="text-align:center;padding:4rem 1rem;
|
| 124 |
+
font-family:system-ui,sans-serif;color:#999;font-size:.9rem">
|
| 125 |
+
This Space has no public interface.
|
| 126 |
+
</div>
|
| 127 |
+
"""
|
| 128 |
+
)
|
| 129 |
+
with gr.Row(visible=False):
|
| 130 |
+
image_1 = gr.Image(label="Image 1", type="pil")
|
| 131 |
+
image_2 = gr.Image(label="Image 2", type="pil")
|
| 132 |
+
prompt = gr.Text(label="Prompt")
|
| 133 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
|
| 134 |
+
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 135 |
+
guidance = gr.Slider(label="Guidance", minimum=0.0, maximum=10.0, step=0.1, value=GUIDANCE)
|
| 136 |
+
steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=STEPS)
|
| 137 |
+
run = gr.Button("Edit")
|
| 138 |
+
result = gr.Image(label="Result")
|
| 139 |
+
out_seed = gr.Number(label="Seed used")
|
| 140 |
+
|
| 141 |
+
gr.on(
|
| 142 |
+
triggers=[run.click, prompt.submit],
|
| 143 |
+
fn=infer,
|
| 144 |
+
inputs=[image_1, image_2, prompt, seed, randomize_seed, guidance, steps],
|
| 145 |
+
outputs=[result, out_seed],
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ============================================================
|
| 150 |
+
# API
|
| 151 |
+
# ============================================================
|
| 152 |
+
def _load(src):
|
| 153 |
+
"""Fetch an https URL or decode a data URL into a PIL image."""
|
| 154 |
+
import base64 as _b64
|
| 155 |
+
import urllib.request as _url
|
| 156 |
+
from PIL import Image as _Image
|
| 157 |
+
if src.startswith("http://") or src.startswith("https://"):
|
| 158 |
+
req = _url.Request(src, headers={"User-Agent": "tecwyze/1.0"})
|
| 159 |
+
with _url.urlopen(req, timeout=30) as resp:
|
| 160 |
+
raw = resp.read(25 * 1024 * 1024)
|
| 161 |
+
else:
|
| 162 |
+
if src.startswith("data:"):
|
| 163 |
+
src = src.split(",", 1)[1]
|
| 164 |
+
raw = _b64.b64decode(src)
|
| 165 |
+
return _Image.open(BytesIO(raw)).convert("RGB")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# Named dressfit_tryon because the existing client already calls that with this
|
| 169 |
+
# positional order. A tidier name would break every caller for no gain.
|
| 170 |
+
def dressfit_tryon(person: str, garment: str = "", prompt: str = "",
|
| 171 |
+
steps: float = STEPS, guidance: float = GUIDANCE,
|
| 172 |
+
seed: float = 0, randomize: bool = True,
|
| 173 |
+
loras: list | None = None) -> dict:
|
| 174 |
+
"""Edit an image. person is the image to edit, garment is an optional second
|
| 175 |
+
image, prompt says what to change, loras is an optional list of
|
| 176 |
+
{repo, weight_name, scale}. Images are https or data URLs."""
|
| 177 |
+
try:
|
| 178 |
+
first = _load(person)
|
| 179 |
+
second = _load(garment) if garment else None
|
| 180 |
+
# Match the reference's own aspect. The pipeline draws a fresh canvas at
|
| 181 |
+
# whatever size it is given, so forcing a square distorts a portrait.
|
| 182 |
+
w, h = first.size
|
| 183 |
+
w = max(256, min(2048, round(w / 32) * 32))
|
| 184 |
+
h = max(256, min(2048, round(h / 32) * 32))
|
| 185 |
+
out, used = infer(first, second, prompt, int(seed), bool(randomize),
|
| 186 |
+
float(guidance), int(steps), w, h, loras or [])
|
| 187 |
+
buf = BytesIO()
|
| 188 |
+
out.save(buf, format="PNG")
|
| 189 |
+
return {"status": "success", "seed": int(used),
|
| 190 |
+
"image": "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()}
|
| 191 |
+
except Exception as exc:
|
| 192 |
+
# Return the traceback to the caller, not only the logs — the client is
|
| 193 |
+
# the only thing watching and each log round trip costs an attempt.
|
| 194 |
+
return {"status": "error", "message": "".join(traceback.format_exception(exc))[-2500:]}
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
with demo:
|
| 198 |
+
gr.api(dressfit_tryon, api_name="dressfit_tryon")
|
| 199 |
+
|
| 200 |
+
if __name__ == "__main__":
|
| 201 |
+
demo.launch()
|
|
|
requirements.txt
CHANGED
|
@@ -3,3 +3,4 @@ transformers
|
|
| 3 |
accelerate
|
| 4 |
safetensors
|
| 5 |
sentencepiece
|
|
|
|
|
|
| 3 |
accelerate
|
| 4 |
safetensors
|
| 5 |
sentencepiece
|
| 6 |
+
peft
|