TaiYouWeb's picture
Update app.py
d32a354 verified
try:
import spaces
USING_SPACES = True
except ImportError:
USING_SPACES = False
import gradio as gr
from PIL import Image
import os
import torch
import random
import time
import numpy as np
from OmniGen import OmniGenPipeline
random.seed(time.time())
MAX_SEED = np.iinfo(np.int32).max
SPACES_GPU_DURATION = 180
def gpu_decorator(duration=60):
def actual_decorator(func):
if USING_SPACES:
return spaces.GPU(duration=duration)(func)
return func
return actual_decorator
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
if randomize_seed:
seed = random.randint(0, MAX_SEED)
return seed
def updata_input_images(images):
if not images:
return gr.Gallery(label="Input Images", value=[], show_label=False, show_share_button=False, container=False)
images_with_names = [(image, f"image_{i + 1}") for i, image in enumerate(images)]
return gr.Gallery(label="Input Images", value=images_with_names, show_label=False, show_share_button=False, container=False)
def add_more_images(input_images, more_images):
input_images = input_images if input_images is not None else []
image_list = input_images + more_images
return gr.File(value=image_list, file_count="multiple",label="Input Images (Multi-select)"), gr.File(value=[], file_count="multiple",label="Add Image (More)")
pipe = OmniGenPipeline.from_pretrained("Shitao/OmniGen-v1")
@gpu_decorator(duration=SPACES_GPU_DURATION)
def generate(prompt, input_images, width, height, inference_steps, guidance_scale, randomize_seed, separate_cfg_infer, use_kv_cache, img_guidance_scale, offload_kv_cache, offload_model, use_input_image_size_as_output, max_input_image_size, progress=gr.Progress(track_tqdm=True)):
print({"prompt": prompt, "input_images": input_images, "width": width, "height": height, "inference_steps": inference_steps, "guidance_scale": guidance_scale, "randomize_seed": randomize_seed, "separate_cfg_infer": separate_cfg_infer, "use_kv_cache": use_kv_cache, "img_guidance_scale": img_guidance_scale, "offload_model": offload_model, "use_input_image_size_as_output": use_input_image_size_as_output, "max_input_image_size": max_input_image_size})
try:
seed = randomize_seed_fn(0, randomize_seed)
img = pipe(
prompt=prompt,
input_images=input_images,
width=width,
height=height,
num_inference_steps=inference_steps,
guidance_scale=guidance_scale,
seed=seed,
separate_cfg_infer=separate_cfg_infer,
use_kv_cache=use_kv_cache,
img_guidance_scale=img_guidance_scale,
offload_kv_cache=offload_kv_cache,
offload_model=offload_model,
use_input_image_size_as_output=use_input_image_size_as_output,
max_input_image_size=max_input_image_size,
)
return img[0], seed
except Exception as e:
error_message = str(e)
raise gr.Error(error_message)
description = """
### Description
OmniGen is a unified image generation model that you can use to perform various tasks, including but not limited to text-to-image generation, subject-driven generation, Identity-Preserving Generation, and image-conditioned generation.
For multi-modal to image generation, you should pass a string as `prompt`, and a list of image paths as `input_images`. The placeholder in the prompt should be in the format of `<img><|image_*|></img>` (for the first image, the placeholder is <img><|image_1|></img>. for the second image, the the placeholder is <img><|image_2|></img>).
For example, use an image of a woman to generate a new image:
prompt = "A woman holds a bouquet of flowers and faces the camera. Thw woman is \<img\>\<|image_1|\>\</img\>."
---
### Tips
For out of memory or time cost, you can refer to [./docs/inference.md#requiremented-resources](https://github.com/VectorSpaceLab/OmniGen/blob/main/docs/inference.md#requiremented-resources) to select a appropriate setting.
```
- If time cost is too long, please try to reduce the `max_input_image_size`.
- Oversaturated: If the image appears oversaturated, please reduce the `guidance_scale`.
- Not match the prompt: If the image does not match the prompt, please try to increase the `guidance_scale`.
- Low-quality: More detailed prompt will lead to better results.
- Animate Style: If the genereate images is in animate style, you can try to add `photo` to the prompt`.
- Edit generated image. If you generate a image by omnigen and then want to edit it, you cannot use the same seed to edit this image. For example, use seed=0 to generate image, and should use seed=1 to edit this image.
- For image editing tasks, we recommend placing the image before the editing instruction. For example, use `<img><|image_1|></img> remove suit`, rather than `remove suit <img><|image_1|></img>`.
- For image editing task and controlnet task, we recommend to set the height and width of output image as the same as input image. For example, if you want to edit a 512x512 image, you should set the height and width of output image as 512x512. You also can set the `use_input_image_size_as_output` to automatically set the height and width of output image as the same as input image.
```
"""
article = """
---
**Citation**
<br>
If you find this repository useful, please consider giving a star ⭐ and citation
```
@article{xiao2024omnigen,
title={Omnigen: Unified image generation},
author={Xiao, Shitao and Wang, Yueze and Zhou, Junjie and Yuan, Huaying and Xing, Xingrun and Yan, Ruiran and Wang, Shuting and Huang, Tiejun and Liu, Zheng},
journal={arXiv preprint arXiv:2409.11340},
year={2024}
}
```
**Contact**
<br>
If you have any questions, please feel free to open an issue or directly reach us out via [email(Shitao Xiao)](mailto:[email protected]).
"""
with gr.Blocks() as demo:
gr.Markdown("### Description\nThis is a duplicate from [Shitao/OmniGen](https://huggingface.co./spaces/Shitao/OmniGen). For more detailed information, please refer to the original source.\n")
with gr.Row(equal_height=True):
with gr.Column():
input_images_gallery = gr.Gallery(label="Input Images", show_label=False, show_share_button=False, object_fit="contain")
with gr.Row():
input_images = gr.File(file_count="multiple",label="Input Images (Multi-select)")
add_more_input_image = gr.File(file_count="multiple",label="Add Image (More, additional)")
with gr.Accordion("Advanced Settings", open=True):
with gr.Row():
offload_kv_cache = gr.Checkbox(label="offload_kv_cache", value=True)
offload_model = gr.Checkbox(label="offload_model", info="Offload model to CPU, which will significantly reduce the memory cost but slow down the generation speed. You can cancle separate_cfg_infer and set offload_model=True. If both separate_cfg_infer and offload_model be True, further reduce the memory, but slowest generation", value=False)
with gr.Row():
separate_cfg_infer = gr.Checkbox(label="Separate cfg infer", info="Whether to use separate inference process for different guidance. This will reduce the memory cost.", value=True)
use_kv_cache = gr.Checkbox(label="Use kv cache", value=True)
img_guidance_scale = gr.Slider(label="Image guidance scale", minimum=1.0, maximum=2.0, value=1.6, step=0.1)
with gr.Row():
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
seed = gr.Slider(0, MAX_SEED, value=0, step=1, label="Seed")
with gr.Column():
result = gr.Image(label="Generated Image", show_label=False, show_download_button=True, format="png")
gr.Markdown(value=f"### Notice\nPlease note that the ZeroGPU duration limit is **{SPACES_GPU_DURATION}** seconds.\nConfigure parameters wisely to ensure task completion within this time.", container=True, line_breaks=True)
prompt = gr.TextArea(label="Prompt", placeholder="Enter your prompt", value="The woman in <img><|image_1|></img> waves her hand happily in the crowd.", show_copy_button=True)
with gr.Row():
use_input_image_size_as_output = gr.Checkbox(label="use_input_image_size_as_output", info="Automatically adjust the output image size to be same as input image size. For editing and controlnet task, it can make sure the output image has the same size with input image leading to better performance", value=False)
max_input_image_size = gr.Slider(label="max_input_image_size", minimum=128, maximum=1920, value=1024, step=16)
with gr.Row():
width = gr.Slider(128, 1920, value=1024, step=16, label="Width")
height = gr.Slider(128, 1920, value=1024, step=16, label="Height")
with gr.Row():
inference_steps = gr.Slider(10, 100, value=50, step=1, label="Inference Steps")
guidance_scale = gr.Slider(1.0, 20.0, value=2.5, step=0.1, label="Guidance Scale")
run_button = gr.Button("Generate")
gr.Markdown(description)
gr.Markdown("### Example prompts\n```\n1.A woman holds a bouquet of flowers and faces the camera. The woman is <img><|image_1|></img>.\n2.<img><|image_1|></img> What item can be used to see the current time? Please remove it.\n3.Two men are celebrating with raised glasses in a restaurant. One man is <img><|image_1|></img>. The other man is <img><|image_2|></img>.\n4.The flower <img><|image_1|></img> is placed in the vase which is in the middle of <img><|image_2|></img> on a wooden table of a living room.\n```")
gr.Markdown(article)
input_images.change(
updata_input_images,
inputs=input_images,
outputs=input_images_gallery
)
add_more_input_image.change(
add_more_images,
inputs=[input_images, add_more_input_image],
outputs=[input_images, add_more_input_image]
)
run_button.click(
generate,
inputs=[prompt, input_images, width, height, inference_steps, guidance_scale, randomize_seed, separate_cfg_infer, use_kv_cache, img_guidance_scale, offload_kv_cache, offload_model, use_input_image_size_as_output, max_input_image_size],
outputs=[result, seed]
)
if __name__ == "__main__":
demo.queue(max_size=10).launch(ssr_mode=False)