Upgrade image model to FLUX.2-klein-4B + align training pipeline
Browse filesimage_generator.py:
- Replace FLUX.1-schnell with FLUX.2-klein-4B (Apache 2.0, better quality)
- Use Flux2KleinPipeline, guidance_scale=1.0, float16 on MPS
- Share NUMZOO_STYLE constant so live prompts match training captions exactly
- Log generation time (β
Generated in Xs)
scripts/generate_dataset.py:
- Switch to FLUX.1-dev via HF Inference API (fal-ai provider, HF Pro token)
- Import NUMZOO_STYLE from image_generator β single source of truth
- Add --count N flag to generate a subset (e.g. --count 5 for a test run)
- Load GEMINI_API_KEY / HF_TOKEN from .env via python-dotenv
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- image_generator.py +30 -39
- scripts/generate_dataset.py +68 -49
image_generator.py
CHANGED
|
@@ -15,24 +15,24 @@ if not hasattr(torch, "xpu"):
|
|
| 15 |
torch.xpu = _MockXPU()
|
| 16 |
|
| 17 |
# ---------------------------------------------------------------------------
|
| 18 |
-
# Detect HuggingFace Spaces
|
| 19 |
# ---------------------------------------------------------------------------
|
| 20 |
|
| 21 |
IS_HF_SPACE = os.environ.get("SPACE_ID") is not None
|
| 22 |
-
if IS_HF_SPACE:
|
| 23 |
-
import spaces
|
| 24 |
-
import sys
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
# ---------------------------------------------------------------------------
|
| 38 |
# Emoji β descriptive text maps (fed into FLUX prompt)
|
|
@@ -107,31 +107,26 @@ def get_pipeline():
|
|
| 107 |
if _pipe is not None:
|
| 108 |
return _pipe
|
| 109 |
|
| 110 |
-
from diffusers import
|
| 111 |
|
| 112 |
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
print(f"Loading FLUX.1-schnell pipeline⦠(token={'set' if hf_token else 'NOT SET'}, dtype={dtype})")
|
| 119 |
-
_pipe = FluxPipeline.from_pretrained(
|
| 120 |
-
"black-forest-labs/FLUX.1-schnell",
|
| 121 |
torch_dtype=dtype,
|
| 122 |
token=hf_token,
|
| 123 |
)
|
| 124 |
|
| 125 |
if IS_HF_SPACE:
|
| 126 |
-
# ZeroGPU always has CUDA β don't rely on torch.cuda.is_available()
|
| 127 |
-
# which can return False outside the @spaces.GPU context
|
| 128 |
_pipe = _pipe.to("cuda")
|
| 129 |
elif torch.cuda.is_available():
|
| 130 |
_pipe = _pipe.to("cuda")
|
| 131 |
elif use_mps:
|
| 132 |
-
|
| 133 |
-
# to MPS one at a time, then immediately returned to CPU.
|
| 134 |
-
_pipe.enable_sequential_cpu_offload()
|
| 135 |
else:
|
| 136 |
_pipe = _pipe.to("cpu")
|
| 137 |
|
|
@@ -144,17 +139,21 @@ def get_pipeline():
|
|
| 144 |
|
| 145 |
def _generate(animals: list[str], places: list[str]):
|
| 146 |
try:
|
|
|
|
| 147 |
pipe = get_pipeline()
|
| 148 |
prompt = build_prompt(animals, places)
|
| 149 |
print(f"Generating | prompt: {prompt}")
|
| 150 |
|
|
|
|
|
|
|
| 151 |
result = pipe(
|
| 152 |
prompt=prompt,
|
| 153 |
num_inference_steps=4,
|
| 154 |
-
guidance_scale=
|
| 155 |
height=512,
|
| 156 |
width=512,
|
| 157 |
)
|
|
|
|
| 158 |
return result.images[0], prompt
|
| 159 |
|
| 160 |
except Exception as e:
|
|
@@ -168,14 +167,6 @@ def _generate(animals: list[str], places: list[str]):
|
|
| 168 |
# Public API β two versions depending on environment
|
| 169 |
# ---------------------------------------------------------------------------
|
| 170 |
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
@spaces.GPU(duration=120)
|
| 175 |
-
def generate_reward_image(animals: list[str], places: list[str]):
|
| 176 |
-
"""Generate reward image on HF Spaces ZeroGPU."""
|
| 177 |
-
return _generate(animals, places)
|
| 178 |
-
else:
|
| 179 |
-
def generate_reward_image(animals: list[str], places: list[str]):
|
| 180 |
-
"""Generate reward image locally."""
|
| 181 |
-
return _generate(animals, places)
|
|
|
|
| 15 |
torch.xpu = _MockXPU()
|
| 16 |
|
| 17 |
# ---------------------------------------------------------------------------
|
| 18 |
+
# Detect HuggingFace Spaces
|
| 19 |
# ---------------------------------------------------------------------------
|
| 20 |
|
| 21 |
IS_HF_SPACE = os.environ.get("SPACE_ID") is not None
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
# ---------------------------------------------------------------------------
|
| 24 |
+
# Persistent storage cache β survives sleep/restart on HF Spaces
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
# Enable in Space Settings β Storage (mount at /data).
|
| 27 |
+
# HF_HOME env var can also be set manually in Space Settings β Variables,
|
| 28 |
+
# but this block handles it automatically when /data is present.
|
| 29 |
+
if IS_HF_SPACE and os.path.isdir("/data"):
|
| 30 |
+
_cache_dir = "/data/hf_cache"
|
| 31 |
+
os.makedirs(_cache_dir, exist_ok=True)
|
| 32 |
+
os.environ.setdefault("HF_HOME", _cache_dir)
|
| 33 |
+
print(f"Persistent cache active β {_cache_dir}")
|
| 34 |
+
else:
|
| 35 |
+
print("HF Space detected β model will load on first call and stay cached in memory." if IS_HF_SPACE else "Local mode.")
|
| 36 |
|
| 37 |
# ---------------------------------------------------------------------------
|
| 38 |
# Emoji β descriptive text maps (fed into FLUX prompt)
|
|
|
|
| 107 |
if _pipe is not None:
|
| 108 |
return _pipe
|
| 109 |
|
| 110 |
+
from diffusers import Flux2KleinPipeline
|
| 111 |
|
| 112 |
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
| 113 |
+
# float16 on MPS (bfloat16 not fully supported), bfloat16 everywhere else
|
| 114 |
+
use_mps = (not IS_HF_SPACE) and (not torch.cuda.is_available()) and torch.backends.mps.is_available()
|
| 115 |
+
dtype = torch.float16 if use_mps else torch.bfloat16
|
| 116 |
|
| 117 |
+
print(f"Loading FLUX.2-klein-4B pipeline⦠(token={'set' if hf_token else 'NOT SET'}, dtype={dtype})")
|
| 118 |
+
_pipe = Flux2KleinPipeline.from_pretrained(
|
| 119 |
+
"black-forest-labs/FLUX.2-klein-4B",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
torch_dtype=dtype,
|
| 121 |
token=hf_token,
|
| 122 |
)
|
| 123 |
|
| 124 |
if IS_HF_SPACE:
|
|
|
|
|
|
|
| 125 |
_pipe = _pipe.to("cuda")
|
| 126 |
elif torch.cuda.is_available():
|
| 127 |
_pipe = _pipe.to("cuda")
|
| 128 |
elif use_mps:
|
| 129 |
+
_pipe = _pipe.to("mps")
|
|
|
|
|
|
|
| 130 |
else:
|
| 131 |
_pipe = _pipe.to("cpu")
|
| 132 |
|
|
|
|
| 139 |
|
| 140 |
def _generate(animals: list[str], places: list[str]):
|
| 141 |
try:
|
| 142 |
+
import time
|
| 143 |
pipe = get_pipeline()
|
| 144 |
prompt = build_prompt(animals, places)
|
| 145 |
print(f"Generating | prompt: {prompt}")
|
| 146 |
|
| 147 |
+
guidance = 1.0 if IS_HF_SPACE else 0.0 # klein=1.0, schnell=0.0
|
| 148 |
+
t0 = time.time()
|
| 149 |
result = pipe(
|
| 150 |
prompt=prompt,
|
| 151 |
num_inference_steps=4,
|
| 152 |
+
guidance_scale=guidance,
|
| 153 |
height=512,
|
| 154 |
width=512,
|
| 155 |
)
|
| 156 |
+
print(f"β
Generated in {time.time() - t0:.1f}s")
|
| 157 |
return result.images[0], prompt
|
| 158 |
|
| 159 |
except Exception as e:
|
|
|
|
| 167 |
# Public API β two versions depending on environment
|
| 168 |
# ---------------------------------------------------------------------------
|
| 169 |
|
| 170 |
+
def generate_reward_image(animals: list[str], places: list[str]):
|
| 171 |
+
"""Generate reward image β works locally (MPS/CPU) and on HF Spaces (persistent GPU)."""
|
| 172 |
+
return _generate(animals, places)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scripts/generate_dataset.py
CHANGED
|
@@ -1,21 +1,33 @@
|
|
| 1 |
"""
|
| 2 |
NumZoo training dataset generator.
|
| 3 |
|
| 4 |
-
Generates 80 images matching the NumZoo aesthetic using
|
|
|
|
|
|
|
| 5 |
- Kawaii chibi animals with big sparkling eyes
|
| 6 |
- Rich scene backgrounds (no white background)
|
| 7 |
- Warm pastel palette, fairy lights, cozy props
|
| 8 |
-
-
|
| 9 |
|
| 10 |
Output: training/image_001.jpg + training/image_001.txt (caption)
|
| 11 |
|
| 12 |
Requirements:
|
| 13 |
-
pip install
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
Usage:
|
| 16 |
-
|
| 17 |
-
python scripts/generate_dataset.py
|
| 18 |
python scripts/generate_dataset.py --start 41 # resume from image 41
|
|
|
|
| 19 |
"""
|
| 20 |
|
| 21 |
import os
|
|
@@ -31,18 +43,16 @@ try:
|
|
| 31 |
except ImportError:
|
| 32 |
pass # dotenv optional β can also export GEMINI_API_KEY manually
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
# ---------------------------------------------------------------------------
|
| 35 |
# 80 prompts β 8 scene categories Γ 10 animals
|
| 36 |
-
#
|
| 37 |
# ---------------------------------------------------------------------------
|
| 38 |
|
| 39 |
-
STYLE = (
|
| 40 |
-
"kawaii children's book illustration, pastel anime art style, "
|
| 41 |
-
"soft painterly lighting, detailed rich background with warm fairy lights, "
|
| 42 |
-
"cozy magical atmosphere, cute chibi character with big sparkling eyes, "
|
| 43 |
-
"soft pastel color palette, highly detailed scene, no text"
|
| 44 |
-
)
|
| 45 |
-
|
| 46 |
PROMPTS: list[tuple[str, str]] = [
|
| 47 |
# ββ 1. Cozy cabin interior ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
("cozy_cabin_01", f"a fluffy bunny curled on an armchair by a stone fireplace inside a wooden cabin, "
|
|
@@ -225,59 +235,67 @@ PROMPTS: list[tuple[str, str]] = [
|
|
| 225 |
assert len(PROMPTS) == 80, f"Expected 80 prompts, got {len(PROMPTS)}"
|
| 226 |
|
| 227 |
# ---------------------------------------------------------------------------
|
| 228 |
-
# Generator using
|
| 229 |
# ---------------------------------------------------------------------------
|
| 230 |
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
)
|
| 249 |
-
|
| 250 |
-
for part in response.parts:
|
| 251 |
-
if part.inline_data is not None:
|
| 252 |
-
return part.as_image()
|
| 253 |
-
|
| 254 |
-
raise RuntimeError("No image in response")
|
| 255 |
|
| 256 |
|
| 257 |
def main():
|
| 258 |
parser = argparse.ArgumentParser()
|
| 259 |
-
parser.add_argument("--start",
|
| 260 |
-
parser.add_argument("--
|
|
|
|
|
|
|
| 261 |
args = parser.parse_args()
|
| 262 |
|
| 263 |
-
if not
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
|
|
|
| 267 |
|
| 268 |
out_dir = Path(__file__).parent.parent / "training"
|
| 269 |
out_dir.mkdir(exist_ok=True)
|
| 270 |
|
| 271 |
-
total
|
|
|
|
| 272 |
|
| 273 |
-
|
| 274 |
-
print(f"
|
|
|
|
| 275 |
print()
|
| 276 |
|
|
|
|
|
|
|
| 277 |
for i, (name, prompt) in enumerate(PROMPTS):
|
| 278 |
n = i + 1
|
| 279 |
if n < args.start:
|
| 280 |
continue
|
|
|
|
|
|
|
| 281 |
|
| 282 |
img_path = out_dir / f"image_{n:03d}.jpg"
|
| 283 |
txt_path = out_dir / f"image_{n:03d}.txt"
|
|
@@ -293,16 +311,17 @@ def main():
|
|
| 293 |
continue
|
| 294 |
|
| 295 |
try:
|
| 296 |
-
image = generate_image(prompt)
|
| 297 |
image.save(img_path, "JPEG", quality=95)
|
| 298 |
txt_path.write_text(prompt)
|
|
|
|
| 299 |
print(f" β
saved {img_path.name}")
|
| 300 |
except Exception as e:
|
| 301 |
print(f" β failed: {e}")
|
| 302 |
time.sleep(5) # brief pause on error before continuing
|
| 303 |
|
| 304 |
-
|
| 305 |
-
print(f"\nDone. {generated}/{total}
|
| 306 |
|
| 307 |
|
| 308 |
if __name__ == "__main__":
|
|
|
|
| 1 |
"""
|
| 2 |
NumZoo training dataset generator.
|
| 3 |
|
| 4 |
+
Generates 80 images matching the NumZoo aesthetic using FLUX.1-dev via the
|
| 5 |
+
HuggingFace Inference API (fal-ai provider β best quality, free credits on signup).
|
| 6 |
+
|
| 7 |
- Kawaii chibi animals with big sparkling eyes
|
| 8 |
- Rich scene backgrounds (no white background)
|
| 9 |
- Warm pastel palette, fairy lights, cozy props
|
| 10 |
+
- Square 1024Γ1024 output to match the app layout
|
| 11 |
|
| 12 |
Output: training/image_001.jpg + training/image_001.txt (caption)
|
| 13 |
|
| 14 |
Requirements:
|
| 15 |
+
pip install huggingface_hub pillow python-dotenv
|
| 16 |
+
|
| 17 |
+
Setup (HF Pro β just your existing token):
|
| 18 |
+
1. Get your HF token at https://huggingface.co/settings/tokens
|
| 19 |
+
(fine-grained, with "Make calls to Inference Providers" permission)
|
| 20 |
+
2. Add to .env:
|
| 21 |
+
HF_TOKEN=hf_...
|
| 22 |
+
|
| 23 |
+
With HF Pro your token already has credits on fal-ai, replicate, together etc.
|
| 24 |
+
No separate provider account needed.
|
| 25 |
|
| 26 |
Usage:
|
| 27 |
+
python scripts/generate_dataset.py # all 80 via fal-ai (FLUX.1-dev)
|
| 28 |
+
python scripts/generate_dataset.py --count 5 # first 5 only (test run)
|
| 29 |
python scripts/generate_dataset.py --start 41 # resume from image 41
|
| 30 |
+
python scripts/generate_dataset.py --provider hf-inference # HF native (schnell)
|
| 31 |
"""
|
| 32 |
|
| 33 |
import os
|
|
|
|
| 43 |
except ImportError:
|
| 44 |
pass # dotenv optional β can also export GEMINI_API_KEY manually
|
| 45 |
|
| 46 |
+
# Import the canonical style string from image_generator so training captions
|
| 47 |
+
# and live prompts are always identical.
|
| 48 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 49 |
+
from image_generator import NUMZOO_STYLE as STYLE # noqa: E402
|
| 50 |
+
|
| 51 |
# ---------------------------------------------------------------------------
|
| 52 |
# 80 prompts β 8 scene categories Γ 10 animals
|
| 53 |
+
# STYLE is appended to every prompt so the LoRA learns it as a trigger
|
| 54 |
# ---------------------------------------------------------------------------
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
PROMPTS: list[tuple[str, str]] = [
|
| 57 |
# ββ 1. Cozy cabin interior ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 58 |
("cozy_cabin_01", f"a fluffy bunny curled on an armchair by a stone fireplace inside a wooden cabin, "
|
|
|
|
| 235 |
assert len(PROMPTS) == 80, f"Expected 80 prompts, got {len(PROMPTS)}"
|
| 236 |
|
| 237 |
# ---------------------------------------------------------------------------
|
| 238 |
+
# Generator using FLUX.1-dev via HuggingFace Inference API
|
| 239 |
# ---------------------------------------------------------------------------
|
| 240 |
|
| 241 |
+
# Provider β model routing:
|
| 242 |
+
# fal-ai β FLUX.1-dev (best quality, free credits at fal.ai)
|
| 243 |
+
# hf-inference β FLUX.1-schnell (HF free tier, lower quality)
|
| 244 |
+
PROVIDERS = {
|
| 245 |
+
"fal-ai": "black-forest-labs/FLUX.1-dev",
|
| 246 |
+
"hf-inference": "black-forest-labs/FLUX.1-schnell",
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
def generate_image(prompt: str, provider: str = "fal-ai") -> "PIL.Image.Image":
|
| 250 |
+
from huggingface_hub import InferenceClient
|
| 251 |
+
|
| 252 |
+
# HF Pro token covers all providers β no separate provider key needed
|
| 253 |
+
hf_token = os.environ.get("HF_TOKEN")
|
| 254 |
+
model = PROVIDERS.get(provider, PROVIDERS["fal-ai"])
|
| 255 |
+
client = InferenceClient(provider=provider, api_key=hf_token)
|
| 256 |
+
|
| 257 |
+
image = client.text_to_image(
|
| 258 |
+
prompt,
|
| 259 |
+
model=model,
|
| 260 |
+
width=1024,
|
| 261 |
+
height=1024,
|
| 262 |
)
|
| 263 |
+
return image # InferenceClient already returns a PIL Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
|
| 266 |
def main():
|
| 267 |
parser = argparse.ArgumentParser()
|
| 268 |
+
parser.add_argument("--start", type=int, default=1, help="Resume from image N (1-based)")
|
| 269 |
+
parser.add_argument("--count", type=int, default=None, help="Generate at most N images then stop")
|
| 270 |
+
parser.add_argument("--provider", type=str, default="fal-ai", help="Inference provider: fal-ai | hf-inference")
|
| 271 |
+
parser.add_argument("--dry-run", action="store_true", help="Print prompts without generating")
|
| 272 |
args = parser.parse_args()
|
| 273 |
|
| 274 |
+
if not args.dry_run:
|
| 275 |
+
if not os.environ.get("HF_TOKEN"):
|
| 276 |
+
print("β HF_TOKEN not found. Add it to .env")
|
| 277 |
+
print(" Get yours at https://huggingface.co/settings/tokens")
|
| 278 |
+
sys.exit(1)
|
| 279 |
|
| 280 |
out_dir = Path(__file__).parent.parent / "training"
|
| 281 |
out_dir.mkdir(exist_ok=True)
|
| 282 |
|
| 283 |
+
total = len(PROMPTS)
|
| 284 |
+
end_at = (args.start - 1 + args.count) if args.count else total # inclusive upper bound (index)
|
| 285 |
|
| 286 |
+
count_label = f"{args.count} images" if args.count else f"all {total} images"
|
| 287 |
+
print(f"NumZoo dataset generator β {count_label} β {out_dir}")
|
| 288 |
+
print(f"Range: {args.start}β{min(end_at, total)} of {total}")
|
| 289 |
print()
|
| 290 |
|
| 291 |
+
generated_this_run = 0
|
| 292 |
+
|
| 293 |
for i, (name, prompt) in enumerate(PROMPTS):
|
| 294 |
n = i + 1
|
| 295 |
if n < args.start:
|
| 296 |
continue
|
| 297 |
+
if n > end_at:
|
| 298 |
+
break
|
| 299 |
|
| 300 |
img_path = out_dir / f"image_{n:03d}.jpg"
|
| 301 |
txt_path = out_dir / f"image_{n:03d}.txt"
|
|
|
|
| 311 |
continue
|
| 312 |
|
| 313 |
try:
|
| 314 |
+
image = generate_image(prompt, provider=args.provider)
|
| 315 |
image.save(img_path, "JPEG", quality=95)
|
| 316 |
txt_path.write_text(prompt)
|
| 317 |
+
generated_this_run += 1
|
| 318 |
print(f" β
saved {img_path.name}")
|
| 319 |
except Exception as e:
|
| 320 |
print(f" β failed: {e}")
|
| 321 |
time.sleep(5) # brief pause on error before continuing
|
| 322 |
|
| 323 |
+
total_on_disk = len(list(out_dir.glob("*.jpg")))
|
| 324 |
+
print(f"\nDone. {generated_this_run} generated this run Β· {total_on_disk}/{total} total in {out_dir}")
|
| 325 |
|
| 326 |
|
| 327 |
if __name__ == "__main__":
|