Qwen-Image / app.py
multimodalart's picture
Create app.py
b22b80e verified
raw
history blame
6.58 kB
import gradio as gr
import numpy as np
import random
import spaces
import torch
from diffusers import QwenImagePipeline
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"
pipe = QwenImagePipeline.from_pretrained("Qwen/Qwen-Image", torch_dtype=dtype).to(device)
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1536
@spaces.GPU()
def infer(prompt, negative_prompt, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, true_cfg_scale=4.0, distilled_cfg_scale=1.0, progress=gr.Progress(track_tqdm=True)):
"""
Generates an image based on a user's prompt using the Qwen-Image pipeline.
This function takes textual prompts and various generation parameters,
handles seed randomization, and runs the diffusion model to produce an image.
Args:
prompt (str): The positive text prompt to guide image generation.
negative_prompt (str): The negative text prompt to guide the model
on what to avoid in the generated image.
seed (int, optional): The seed for the random number generator to ensure
reproducible results. Defaults to 42.
randomize_seed (bool, optional): If True, a random seed is generated,
overriding the `seed` parameter. Defaults to False.
width (int, optional): The width of the generated image in pixels.
Defaults to 1024.
height (int, optional): The height of the generated image in pixels.
Defaults to 1024.
num_inference_steps (int, optional): The number of denoising steps.
More steps can lead to higher quality but take longer. Defaults to 4.
true_cfg_scale (float, optional): The Classifier-Free Guidance scale.
Controls how strictly the model follows the prompt. Defaults to 4.0.
progress (gr.Progress, optional): A Gradio Progress object to track
the inference progress in the UI.
Returns:
tuple: A tuple containing:
- PIL.Image.Image: The generated image.
- int: The seed used for the generation, which is useful for
reproducibility, especially when `randomize_seed` is True.
"""
if randomize_seed:
seed = random.randint(0, MAX_SEED)
generator = torch.Generator().manual_seed(seed)
image = pipe(
prompt=prompt,
negative_prompt=negative_prompt,
width=width,
height=height,
num_inference_steps=num_inference_steps,
generator=generator,
true_cfg_scale=true_cfg_scale,
guidance_scale=distilled_cfg_scale
).images[0]
return image, seed
examples = [
"a tiny dragon hatching from a crystal egg on Mars",
"a red panda holding a sign that says 'I love bamboo'",
"a photo of a capybara riding a tricycle in Paris. It is wearing a beret and a striped shirt.",
"an anime illustration of a delicious ramen bowl",
"A logo for a bookstore called 'The Whispering Page'. The logo should feature an open book with a tree growing out of it.",
]
css="""
#col-container {
margin: 0 auto;
max-width: 580px;
}
"""
# Build the Gradio UI.
with gr.Blocks(css=css) as demo:
with gr.Column(elem_id="col-container"):
# Title and description for the demo.
gr.Markdown(f"""# Qwen-Image Text-to-Image
Gradio demo for [Qwen-Image](https://huggingface.co/Qwen/Qwen-Image), a powerful text-to-image model from the Qwen (通义千问) team at Alibaba.
""")
with gr.Row():
# Main prompt input.
prompt = gr.Text(
label="Prompt",
show_label=False,
max_lines=1,
placeholder="Enter your prompt",
container=False,
)
# The "Run" button.
run_button = gr.Button("Run", scale=0)
# Negative prompt input.
negative_prompt = gr.Text(
label="Negative Prompt",
max_lines=1,
placeholder="Enter a negative prompt",
value="text, watermark, copyright, blurry, low resolution",
)
# Display area for the generated image.
result = gr.Image(label="Result", show_label=False)
# Accordion for advanced settings.
with gr.Accordion("Advanced Settings", open=False):
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=42,
)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
with gr.Row():
width = gr.Slider(
label="Width",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=1024,
)
height = gr.Slider(
label="Height",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=1024,
)
with gr.Row():
num_inference_steps = gr.Slider(
label="Inference Steps",
minimum=1,
maximum=50,
step=1,
value=4,
)
true_cfg_scale = gr.Slider(
label="CFG Scale",
info="Controls how much the model follows the prompt. Higher values mean stricter adherence.",
minimum=1.0,
maximum=10.0,
step=0.1,
value=4.0
)
distilled_cfg_scale = gr.Slider(
label="Distilled Guidance",
minimum=0.0,
maximum=20.0,
step=0.1,
value=1.0
)
gr.Examples(
examples=examples,
fn=infer,
inputs=[prompt, negative_prompt],
outputs=[result, seed],
cache_examples="lazy"
)
gr.on(
triggers=[run_button.click, prompt.submit, negative_prompt.submit],
fn=infer,
inputs=[prompt, negative_prompt, seed, randomize_seed, width, height, num_inference_steps, true_cfg_scale, distilled_cfg_scale],
outputs=[result, seed]
)
demo.launch(mcp_server=True)