avatar-studio / app.py
smithel's picture
Upload app.py with huggingface_hub
ab17667 verified
Raw History Blame Contribute Delete
6.11 kB
"""Avatar Studio - photo -> illustrated character (stage 1); animate in LTX."""
import spaces # must precede torch on ZeroGPU
import gc
import os
import random
import torch
import gradio as gr
from PIL import Image
MODEL_ID = "unsloth/FLUX.1-Kontext-dev"
LTX_SPACE = "https://huggingface.co/spaces/smithel/ltx-video-13b-fp8"
SKIP_LOAD = os.environ.get("AVATAR_SKIP_LOAD") == "1"
STYLES = {
"3D animated film": "a 3D animated film character, Pixar-style rendering, soft studio lighting, subsurface skin shading",
"Anime": "an anime character, cel-shaded, clean line art, expressive eyes",
"Claymation": "a stop-motion clay figurine with visible fingerprints and soft studio light",
"Comic ink": "a comic-book character, bold ink outlines, halftone shading, limited palette",
"Low-poly game": "a low-poly 3D game character with flat-shaded facets",
"Watercolor": "a watercolor illustration, loose washes, visible paper grain",
"Painted portrait": "an oil-painted fantasy portrait, visible brush strokes, dramatic chiaroscuro",
}
pipe = None
_on_gpu = False
def load_pipeline():
from diffusers import FluxKontextPipeline
p = FluxKontextPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
p.set_progress_bar_config(disable=True)
return p
def to_gpu():
global _on_gpu
if _on_gpu:
return
pipe.to("cuda")
torch.cuda.empty_cache()
_on_gpu = True
if not SKIP_LOAD:
pipe = load_pipeline()
def build_prompt(style, extra):
prompt = (
"Reimagine the person in this photo as "
+ STYLES.get(style, STYLES["3D animated film"])
+ ". Keep their facial identity recognisable: the same face shape, eye "
"spacing, nose, mouth shape, eyebrows and hair colour. They stay the "
"clear subject: centred, facing the camera, waist-up, against a simple "
"neutral background."
)
extra = (extra or "").strip()
if extra:
prompt += " Additional detail: " + extra
return prompt
def prep_image(image, longest=1024):
if image is None:
return None
if image.mode != "RGB":
image = image.convert("RGB")
w, h = image.size
scale = longest / max(w, h)
nw = max(32, int(round(w * scale)) // 32 * 32)
nh = max(32, int(round(h * scale)) // 32 * 32)
return image.resize((nw, nh), Image.LANCZOS)
def estimate_duration(photo, style, extra, steps, guidance, seed, randomize, consent):
return int(min(120, max(20, 15 + float(steps or 28) * 3.8)))
@spaces.GPU(duration=estimate_duration, size="large")
def stylize(photo, style, extra, steps, guidance, seed, randomize, consent):
if not consent:
raise gr.Error("Please confirm this is you, or someone who has agreed to it.")
if photo is None:
raise gr.Error("Upload a photo first.")
if SKIP_LOAD:
return Image.new("RGB", (768, 768), (32, 32, 44)), "Placeholder (AVATAR_SKIP_LOAD=1)."
global pipe
if pipe is None:
pipe = load_pipeline()
to_gpu()
image = prep_image(photo)
steps = int(max(8, min(int(steps or 28), 40)))
guidance = float(max(1.0, min(float(guidance or 2.5), 5.0)))
if randomize or seed is None:
seed = random.randint(0, 2**31 - 1)
seed = int(seed)
result = pipe(
image=image,
prompt=build_prompt(style, extra),
guidance_scale=guidance,
num_inference_steps=steps,
generator=torch.Generator(device="cpu").manual_seed(seed),
).images[0]
gc.collect()
torch.cuda.empty_cache()
caption = ("**%s** - %d steps - seed `%d`\n\nNext: take this image to "
"[LTX-Video](%s), upload it as the *start frame*, and describe the motion."
% (style, steps, seed, LTX_SPACE))
return result, caption
with gr.Blocks(title="Avatar Studio") as demo:
gr.Markdown(
"# Avatar Studio\n"
"Turn a photo into an illustrated or 3D **character** that carries your "
"likeness - then animate it.\n\n"
"*Two stages: generate the character here, then drop the result into the "
"[LTX-Video Space](" + LTX_SPACE + ") as a start frame to make it move.*"
)
with gr.Row():
with gr.Column(scale=5):
photo = gr.Image(label="Your photo - a clear, front-facing shot works best",
type="pil", height=300)
style = gr.Dropdown(choices=list(STYLES), value="3D animated film",
label="Character style")
extra = gr.Textbox(label="Extra detail (optional)",
placeholder="wearing a red hoodie, holding a coffee cup")
with gr.Accordion("Settings", open=False):
steps = gr.Slider(12, 40, value=28, step=1, label="Steps")
guidance = gr.Slider(1.5, 4.0, value=2.5, step=0.1, label="Guidance")
with gr.Row():
seed = gr.Number(value=0, precision=0, label="Seed")
randomize = gr.Checkbox(value=True, label="Randomize")
consent = gr.Checkbox(value=False,
label="This is me, or a person who has agreed to be depicted")
run = gr.Button("Generate character", variant="primary", size="lg")
with gr.Column(scale=6):
out = gr.Image(label="Character", height=440)
info = gr.Markdown("_Nothing generated yet._")
gr.Markdown(
"---\n**What this does and doesn't do.** It reimagines *you* as a drawn "
"or rendered character. It does not map a face onto footage of a real "
"person, and it isn't built for depicting anyone who hasn't agreed to it.\n\n"
"Model: [`unsloth/FLUX.1-Kontext-dev`]"
"(https://huggingface.co/unsloth/FLUX.1-Kontext-dev) - "
"non-commercial licence; check the terms before publishing."
)
run.click(stylize,
inputs=[photo, style, extra, steps, guidance, seed, randomize, consent],
outputs=[out, info])
demo.queue(max_size=8)
demo.launch(mcp_server=True)