launch-calcium's picture
Duplicate from that-username-is-not-available/Krea-Char-Design-Data
d809f63
Raw
History Blame Contribute Delete
10.8 kB
"""
Krea 2 Character Design — ZeroGPU Space
=======================================
Runs the CivitAI "[KREA 2] Character Design" LoRA on top of Krea 2 Turbo
(krea/Krea-2-Turbo) via diffusers `Krea2Pipeline`.
- LoRA is pulled from the companion HF dataset into ./models/lora/ at startup.
- Every generation (image + prompt + settings) is saved back to the dataset.
- ZeroGPU-ready: inference runs inside a @spaces.GPU allocation.
"""
import io
import json
import os
import random
import traceback
import uuid
from datetime import datetime, timezone
from pathlib import Path
import gradio as gr
import spaces
import torch
from diffusers import Krea2Pipeline
from huggingface_hub import HfApi, hf_hub_download
# --------------------------------------------------------------------------- #
# Config (all overridable via Space env vars / secrets)
# --------------------------------------------------------------------------- #
HF_TOKEN = os.environ.get("HF_TOKEN")
BASE_MODEL = os.environ.get("BASE_MODEL", "krea/Krea-2-Turbo")
DATASET_REPO = os.environ.get("DATASET_REPO", "that-username-is-not-available/Krea-Char-Design-Data")
LORA_REPO_PATH = os.environ.get("LORA_REPO_PATH", "models/lora/krea2-character-design.safetensors")
SAVE_GENERATIONS = os.environ.get("SAVE_GENERATIONS", "1") == "1"
TRIGGER_WORD = "Character design"
ADAPTER_NAME = "char_design"
MAX_SEED = 2**31 - 1
LORA_LOCAL_DIR = Path("models/lora")
LORA_LOCAL_PATH = LORA_LOCAL_DIR / "krea2-character-design.safetensors"
# --------------------------------------------------------------------------- #
# Fetch the LoRA from the dataset into ./models/lora/ (once, at startup)
# --------------------------------------------------------------------------- #
def ensure_lora() -> bool:
LORA_LOCAL_DIR.mkdir(parents=True, exist_ok=True)
if LORA_LOCAL_PATH.exists():
return True
try:
hf_hub_download(
repo_id=DATASET_REPO,
repo_type="dataset",
filename=LORA_REPO_PATH,
local_dir=".",
token=HF_TOKEN,
)
print(f"[startup] LoRA downloaded -> {LORA_LOCAL_PATH}")
return LORA_LOCAL_PATH.exists()
except Exception as e: # noqa: BLE001
print(f"[startup] Could not download LoRA: {e}")
return False
LORA_READY = ensure_lora()
# --------------------------------------------------------------------------- #
# Lazy pipeline loader (cached). Kept out of module scope so the CPU box
# doesn't OOM at boot — the 12B model is only touched on first generation.
# --------------------------------------------------------------------------- #
_PIPE = None
def get_pipeline():
global _PIPE
if _PIPE is None:
print(f"[load] loading {BASE_MODEL} ...")
pipe = Krea2Pipeline.from_pretrained(
BASE_MODEL, torch_dtype=torch.bfloat16, token=HF_TOKEN
)
if LORA_LOCAL_PATH.exists():
pipe.load_lora_weights(str(LORA_LOCAL_PATH), adapter_name=ADAPTER_NAME)
print("[load] LoRA weights loaded")
else:
print("[load] WARNING: LoRA file missing, running base model only")
_PIPE = pipe
return _PIPE
# --------------------------------------------------------------------------- #
# Persist generations back to the HF dataset (best-effort, non-blocking)
# --------------------------------------------------------------------------- #
def save_to_dataset(images, meta: dict):
if not (SAVE_GENERATIONS and HF_TOKEN and DATASET_REPO):
return
try:
api = HfApi(token=HF_TOKEN)
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
for idx, img in enumerate(images):
uid = uuid.uuid4().hex[:8]
stem = f"generations/{ts}_{uid}_{idx}"
buf = io.BytesIO()
img.save(buf, format="PNG")
buf.seek(0)
api.upload_file(
path_or_fileobj=buf,
path_in_repo=f"{stem}.png",
repo_id=DATASET_REPO,
repo_type="dataset",
)
record = {**meta, "index": idx, "timestamp": ts, "image_file": f"{stem}.png"}
api.upload_file(
path_or_fileobj=io.BytesIO(json.dumps(record, indent=2).encode()),
path_in_repo=f"{stem}.json",
repo_id=DATASET_REPO,
repo_type="dataset",
)
print(f"[save] {len(images)} generation(s) pushed to {DATASET_REPO}")
except Exception as e: # noqa: BLE001
print(f"[save] dataset save failed: {e}")
# --------------------------------------------------------------------------- #
# Inference (ZeroGPU)
# --------------------------------------------------------------------------- #
@spaces.GPU(duration=120)
def generate(
prompt,
negative_prompt,
use_trigger,
steps,
guidance,
width,
height,
lora_scale,
num_images,
seed,
randomize_seed,
progress=gr.Progress(track_tqdm=True),
):
if not prompt or not prompt.strip():
raise gr.Error("Please enter a prompt describing your character.")
if not LORA_LOCAL_PATH.exists():
raise gr.Error(
"LoRA file is not available. Check the dataset repo / HF_TOKEN secret."
)
try:
pipe = get_pipeline()
pipe.to("cuda")
pipe.set_adapters(ADAPTER_NAME, adapter_weights=[float(lora_scale)])
except Exception as e: # noqa: BLE001
traceback.print_exc()
raise gr.Error(
"Could not load the model. This Space needs ZeroGPU hardware and "
"access to the gated Krea 2 model (accept the license + set HF_TOKEN). "
f"Details: {e}"
)
if randomize_seed:
seed = random.randint(0, MAX_SEED)
seed = int(seed)
generator = torch.Generator(device="cuda").manual_seed(seed)
full_prompt = f"{TRIGGER_WORD}, {prompt.strip()}" if use_trigger else prompt.strip()
images = pipe(
prompt=full_prompt,
negative_prompt=(negative_prompt or None),
num_inference_steps=int(steps),
guidance_scale=float(guidance),
width=int(width),
height=int(height),
num_images_per_prompt=int(num_images),
generator=generator,
).images
save_to_dataset(
images,
{
"prompt": full_prompt,
"user_prompt": prompt.strip(),
"negative_prompt": negative_prompt or "",
"trigger_word_applied": bool(use_trigger),
"base_model": BASE_MODEL,
"lora": "krea2-character-design",
"lora_scale": float(lora_scale),
"steps": int(steps),
"guidance_scale": float(guidance),
"width": int(width),
"height": int(height),
"seed": seed,
},
)
return images, seed
# --------------------------------------------------------------------------- #
# UI
# --------------------------------------------------------------------------- #
EXAMPLES = [
["a cyberpunk street samurai with a neon katana, cracked visor helmet"],
["a whimsical forest fox spirit, glowing runes, oversized scarf"],
["a chunky retro sci-fi maintenance robot with a single big eye"],
["a fantasy desert nomad warrior, layered cloth armor, sand goggles"],
]
CSS = """
#title-block h1 { font-size: 2.1rem; margin-bottom: 0.2rem; }
.gradio-container { max-width: 1200px !important; }
footer { visibility: hidden; }
"""
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), css=CSS, title="Krea 2 Character Design") as demo:
with gr.Column(elem_id="title-block"):
gr.Markdown(
"# 🎨 Krea 2 · Character Design\n"
"Generate full character design sheets — front / side / back views, expression "
"studies, palettes & accessories — with the **[KREA 2] Character Design** LoRA "
"running on **Krea 2 Turbo**."
)
if not LORA_READY:
gr.Markdown(
"> ⚠️ **LoRA not loaded yet.** Ensure the dataset repo exists and the "
"`HF_TOKEN` secret is set with access to it."
)
with gr.Row():
with gr.Column(scale=5):
prompt = gr.Textbox(
label="Prompt",
placeholder="a cyberpunk street samurai with a neon katana...",
lines=3,
elem_id="prompt-input",
)
with gr.Row():
run_btn = gr.Button("Generate ✨", variant="primary", scale=3, elem_id="generate-btn")
use_trigger = gr.Checkbox(
value=True, label='Auto-add trigger "Character design"', scale=2
)
negative_prompt = gr.Textbox(
label="Negative prompt (used only when guidance > 0)",
placeholder="blurry, low quality, watermark",
lines=1,
)
with gr.Accordion("Advanced settings", open=False):
with gr.Row():
steps = gr.Slider(1, 52, value=8, step=1, label="Steps (Turbo ≈ 8)")
guidance = gr.Slider(0.0, 8.0, value=0.0, step=0.1, label="Guidance (Turbo ≈ 0)")
with gr.Row():
width = gr.Slider(512, 1536, value=1024, step=64, label="Width")
height = gr.Slider(512, 1536, value=1024, step=64, label="Height")
with gr.Row():
lora_scale = gr.Slider(0.0, 1.5, value=1.0, step=0.05, label="LoRA strength")
num_images = gr.Slider(1, 2, value=1, step=1, label="Images")
with gr.Row():
seed = gr.Slider(0, MAX_SEED, value=0, step=1, label="Seed")
randomize_seed = gr.Checkbox(value=True, label="Randomize seed")
gr.Examples(examples=EXAMPLES, inputs=[prompt], label="Prompt ideas")
with gr.Column(scale=6):
gallery = gr.Gallery(
label="Results",
columns=2,
height=560,
object_fit="contain",
elem_id="output-gallery",
)
used_seed = gr.Number(label="Seed used", interactive=False)
gr.Markdown(
"Base: [`krea/Krea-2-Turbo`](https://huggingface.co/krea/Krea-2-Turbo) · "
"LoRA: [CivitAI 2815175](https://civitai.com/models/2815175) · "
"Generations are archived to the companion HF dataset."
)
inputs = [
prompt, negative_prompt, use_trigger, steps, guidance,
width, height, lora_scale, num_images, seed, randomize_seed,
]
run_btn.click(generate, inputs=inputs, outputs=[gallery, used_seed])
prompt.submit(generate, inputs=inputs, outputs=[gallery, used_seed])
if __name__ == "__main__":
demo.queue().launch()