Spaces:
Running on Zero

MOSS-Image / app.py
dfasdfasdfadfasdf's picture
Upload app.py with huggingface_hub
9e87072 verified
Raw History Blame Contribute Delete
5.49 kB
import spaces # must come before torch / diffusers
import random
import time
import gradio as gr
import torch
from diffusers import DiffusionPipeline
MODEL_ID = "OpenMOSS-Team/MOSS-Image-SFT" # diffusers-format source of Comfy-Org/MOSS-Image SFT weights
MAX_SEED = 2**32 - 1
pipe = DiffusionPipeline.from_pretrained(
MODEL_ID,
custom_pipeline="pipeline_moss_image",
trust_remote_code=True,
torch_dtype={"default": torch.bfloat16, "vae": torch.float32},
)
pipe.to("cuda")
SCHEDULER_CLS = type(pipe.scheduler)
SCHEDULER_CONFIG = pipe.scheduler.config
def _duration(prompt, negative_prompt="", width=1024, height=1024, steps=50, *args, **kwargs):
# measured ~1.1 s/step at 1024x1024 on ZeroGPU; attention grows faster than pixel count
megapixels = (width * height) / (1024 * 1024)
return min(240, int(20 + steps * 1.2 * megapixels**1.3))
@spaces.GPU(duration=_duration)
def generate(
prompt: str,
negative_prompt: str = "",
width: int = 1024,
height: int = 1024,
steps: int = 50,
guidance_scale: float = 3.0,
shift: float = 5.0,
seed: int = 42,
randomize_seed: bool = False,
progress=gr.Progress(track_tqdm=True),
):
"""Generate an image with MOSS-Image (SFT).
Args:
prompt: Natural-language description, tag sequence, or JSON layout of the image.
negative_prompt: What to avoid (empty by default).
width: Image width in pixels, multiple of 16.
height: Image height in pixels, multiple of 16.
steps: Number of flow-matching Euler steps.
guidance_scale: Classifier-free guidance scale.
shift: Scheduler timestep shift.
seed: Random seed.
randomize_seed: Pick a random seed instead of `seed`.
Returns:
The generated image, the seed used and a status line.
"""
if not prompt or not prompt.strip():
raise gr.Error("Enter a prompt.")
width, height = int(width) // 16 * 16, int(height) // 16 * 16
if randomize_seed:
seed = random.randint(0, MAX_SEED)
seed = int(seed)
pipe.scheduler = SCHEDULER_CLS.from_config(SCHEDULER_CONFIG, shift=float(shift))
start = time.perf_counter()
image = pipe(
prompt,
negative_prompt=negative_prompt or "",
height=height,
width=width,
num_inference_steps=int(steps),
guidance_scale=float(guidance_scale),
uncond_skip_layers=[22],
generator=torch.Generator("cpu").manual_seed(seed),
).images[0]
elapsed = time.perf_counter() - start
return image, seed, f"{width}×{height} · {int(steps)} steps · CFG {guidance_scale:g} · seed {seed} · {elapsed:.1f}s"
EXAMPLES = [
[
'A wide view of a refrigerator beside a kitchen counter with a fruit bowl. A small sticky note on the '
'refrigerator door is handwritten in Chinese:\n"记得买牛奶和鸡蛋!\n牛奶两盒,鸡蛋一打。\n顺便带一袋面包。"'
],
["A cozy bookstore café at dusk, warm lamps, rain on the window, a chalkboard sign reading \"OPEN LATE — FRESH COFFEE\""],
["Studio photo of a ceramic fox figurine on a linen cloth, soft window light, shallow depth of field"],
["A vintage travel poster for Kraków with the Wawel castle, bold flat colors, title text \"KRAKÓW\" at the top"],
]
CSS = "#col { max-width: 1100px; margin: 0 auto; }"
with gr.Blocks(title="MOSS-Image") as demo:
with gr.Column(elem_id="col"):
gr.Markdown(
"# 🖼️ MOSS-Image\n"
"Text-to-image with [MOSS-Image](https://huggingface.co/Comfy-Org/MOSS-Image) "
"(SFT, via [OpenMOSS-Team/MOSS-Image-SFT](https://huggingface.co/OpenMOSS-Team/MOSS-Image-SFT)). "
"Good at rendering Chinese and English text; also accepts JSON layout prompts."
)
with gr.Row():
with gr.Column(scale=1):
prompt = gr.Textbox(label="Prompt", lines=5, placeholder="Describe the image…")
run = gr.Button("Generate", variant="primary")
with gr.Accordion("Advanced settings", open=False):
negative_prompt = gr.Textbox(label="Negative prompt", lines=2)
with gr.Row():
width = gr.Slider(512, 1536, value=1024, step=16, label="Width")
height = gr.Slider(512, 1536, value=1024, step=16, label="Height")
steps = gr.Slider(10, 60, value=50, step=1, label="Steps")
guidance_scale = gr.Slider(1.0, 8.0, value=3.0, step=0.1, label="CFG")
shift = gr.Slider(1.0, 10.0, value=5.0, step=0.1, label="Shift")
with gr.Row():
seed = gr.Number(value=42, precision=0, label="Seed", minimum=0, maximum=MAX_SEED)
randomize_seed = gr.Checkbox(value=True, label="Random seed")
with gr.Column(scale=1):
result = gr.Image(label="Result", format="png")
status = gr.Markdown()
gr.Examples(
examples=EXAMPLES,
inputs=[prompt],
outputs=[result, seed, status],
fn=generate,
cache_examples=True,
cache_mode="lazy",
)
inputs = [prompt, negative_prompt, width, height, steps, guidance_scale, shift, seed, randomize_seed]
gr.on([run.click, prompt.submit], fn=generate, inputs=inputs, outputs=[result, seed, status])
demo.launch(mcp_server=True, css=CSS)