Spaces:
Running on Zero
Running on Zero
File size: 5,492 Bytes
1b331a0 9e87072 1b331a0 9e87072 1b331a0 9e87072 1b331a0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 | 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)
|