File size: 14,010 Bytes
ff3266f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf4c13a
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import os
import subprocess
subprocess.run('pip install flash-attn==2.6.3 --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
import random
import spaces
import numpy as np
import torch
from PIL import Image
import gradio as gr
from transformers import AutoModelForCausalLM
from test_img_edit import pipe_img_edit
from test_img_to_txt import pipe_txt_gen
from test_txt_to_img import pipe_t2i


# Constants
MAX_SEED = 10000

hf_token = os.getenv("HF_TOKEN")

HUB_MODEL_ID = "AIDC-AI/Ovis-U1-3B"
model, loading_info = AutoModelForCausalLM.from_pretrained(
    HUB_MODEL_ID, 
    torch_dtype=torch.bfloat16,
    output_loading_info=True,
    token=hf_token,
    trust_remote_code=True
    )
print(f'Loading info of Ovis-U1:\n{loading_info}')

model = model.eval().to("cuda")
model = model.to(torch.bfloat16)

def set_global_seed(seed: int = 42):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)

def randomize_seed_fn(seed: int, randomize: bool) -> int:
    return random.randint(0, MAX_SEED) if randomize else seed

@spaces.GPU
def process_txt_to_img(prompt: str, height: int, width: int, steps: int, final_seed: int, guidance_scale: float, progress: gr.Progress = gr.Progress(track_tqdm=True)) -> list[Image.Image]:
    set_global_seed(final_seed)
    images = pipe_t2i(model, prompt, height, width, steps, cfg=guidance_scale, seed=final_seed)
    return images

@spaces.GPU
def process_img_to_txt(prompt: str, img: Image.Image, progress: gr.Progress = gr.Progress(track_tqdm=True)) -> str:
    output_text = pipe_txt_gen(model, img, prompt)
    return output_text

@spaces.GPU
def process_img_txt_to_img(prompt: str, img: Image.Image, steps: int, final_seed: int, txt_cfg: float, img_cfg: float, progress: gr.Progress = gr.Progress(track_tqdm=True)) -> list[Image.Image]:
    set_global_seed(final_seed)
    images = pipe_img_edit(model, img, prompt, steps, txt_cfg, img_cfg, seed=final_seed)
    return images

# Gradio UI
with gr.Blocks(title="Ovis-U1-3B") as demo:
    gr.Markdown('''# Ovis-U1-3B
    ''')

    with gr.Row():
        with gr.Column():
            with gr.Tabs():
                with gr.TabItem("Image + Text → Image"):
                    edit_image_input = gr.Image(label="Input Image", type="pil")
                    with gr.Row():
                        edit_prompt_input = gr.Textbox(
                            label="Prompt",
                            show_label=False,
                            placeholder="Describe the editing instruction...",
                            container=False,
                            lines=1
                        )
                        run_edit_image_btn = gr.Button("Run", scale=0)

                    with gr.Accordion("Advanced Settings", open=False):

                        with gr.Row():

                            edit_img_guidance_slider = gr.Slider(
                                label="Image Guidance Scale",
                                minimum=1.0, maximum=10.0,
                                step=0.1, value=1.5
                            )

                            edit_txt_guidance_slider = gr.Slider(
                                label="Text Guidance Scale",
                                minimum=1.0, maximum=30.0,
                                step=0.5, value=6.0
                            )

                        edit_num_steps_slider = gr.Slider(
                            label='Steps',
                            minimum=40, maximum=100, 
                            value=50, step=1
                        )
                        edit_seed_slider = gr.Slider(
                            label="Seed",
                            minimum=0, maximum=int(MAX_SEED),
                            step=1, value=42
                        )
                        edit_randomize_checkbox = gr.Checkbox(
                            label="Randomize seed", value=False
                        )

                    img_edit_examples_data = [
                        ["imgs/train.png", "Modify this image in a Ghibli style. "],
                        ["imgs/chair.png", "Transfer the image into a faceted low-poly 3-D render style."],
                        ["imgs/car.png", "Replace the tiny house on wheels in the image with a vintage car."],
                    ]
                    gr.Examples(
                        examples=img_edit_examples_data,
                        inputs=[edit_image_input, edit_prompt_input],
                        cache_examples=False, 
                        label="Image Editing Examples"
                    )

                with gr.TabItem("Text → Image"):
                    with gr.Row():
                        prompt_gen_input = gr.Textbox(
                            label="Prompt",
                            show_label=False,
                            placeholder="Describe the image you want...",
                            container=False,
                            lines=1
                        )
                        run_image_gen_btn = gr.Button("Run", scale=0)

                    with gr.Accordion("Advanced Settings", open=False):
                        with gr.Row():
                            height_slider = gr.Slider(
                                label='height', 
                                minimum=256, maximum=1536, 
                                value=1024, step=32
                            )
                            width_slider = gr.Slider(
                                label='width', 
                                minimum=256, maximum=1536, 
                                value=1024, step=32
                            )

                        guidance_slider = gr.Slider(
                            label="Guidance Scale",
                            minimum=1.0, maximum=30.0,
                            step=0.5, value=5.0
                        )
                        
                        num_steps_slider = gr.Slider(
                            label='Steps',
                            minimum=40, maximum=100, 
                            value=50, step=1
                        )
                        seed_slider = gr.Slider(
                            label="Seed",
                            minimum=0, maximum=int(MAX_SEED),
                            step=1, value=42
                        )
                        randomize_checkbox = gr.Checkbox(
                            label="Randomize seed", value=False
                        )

                    text_gen_examples_data = [
                        ["A breathtaking fairy with teal wings sits gracefully on a lotus flower in a serene pond, exuding elegance."],
                        ["A winter mountain landscape at deep night with snowy terrain and colorful flowers, under beautiful clouds and no people, portrayed as an anime background illustration with intricate detail and sharp focus."],
                        ["A photo of a pug wearing a cowboy hat and bandana, sitting on a hay bale."]
                    ]
                    gr.Examples(
                        examples=text_gen_examples_data,
                        inputs=[prompt_gen_input],
                        cache_examples=False, 
                        label="Image Generation Examples"
                    )

                with gr.TabItem("Image → Text"):
                    image_understand_input = gr.Image(label="Input Image", type="pil")
                    with gr.Row():
                        prompt_understand_input = gr.Textbox(
                            label="Prompt",
                            show_label=False,
                            placeholder="Describe the question about image...",
                            container=False,
                            lines=1
                        )
                        run_image_understand_btn = gr.Button("Run", scale=0)

                    image_understanding_examples_data = [
                        ["imgs/table.webp", "In what scenario does this picture take place?"],
                        ["imgs/count.png", "How many broccoli are there in the picture?"],
                        ["imgs/foot.webp", "Where is this picture located?"],
                    ]
                    gr.Examples(
                        examples=image_understanding_examples_data,
                        inputs=[image_understand_input, prompt_understand_input],
                        cache_examples=False, 
                        label="Image Understanding Examples"
                    )
            
            clean_btn  = gr.Button("Clear All Inputs/Outputs")

        with gr.Column():
            output_gallery = gr.Gallery(label="Generated Images", columns=2, visible=True) # Default to visible, content will control
            output_text    = gr.Textbox(label="Generated Text", visible=False, lines=5, interactive=False)

    @spaces.GPU
    def run_img_txt_to_img_tab(prompt, img, steps, seed, txt_cfg, img_cfg, progress=gr.Progress(track_tqdm=True)):
        if img is None:
            return (
                gr.update(value=[], visible=False),
                gr.update(value="Please upload an image for editing.", visible=True)
            )
        # Seed is already finalized by the randomize_seed_fn in the click chain
        imgs = process_img_txt_to_img(prompt, img, steps, seed, txt_cfg, img_cfg, progress=progress)
        return (
            gr.update(value=imgs, visible=True),
            gr.update(value="", visible=False)
        )

    @spaces.GPU
    def run_txt_to_img_tab(prompt, height, width, steps, seed, guidance, progress=gr.Progress(track_tqdm=True)):
        # Seed is already finalized by the randomize_seed_fn in the click chain
        imgs = process_txt_to_img(prompt, height, width, steps, seed, guidance, progress=progress)
        return (
            gr.update(value=imgs, visible=True),
            gr.update(value="", visible=False)
        )

    @spaces.GPU
    def run_img_to_txt_tab(img, prompt, progress=gr.Progress(track_tqdm=True)):
        if img is None:
            return (
                gr.update(value=[], visible=False),
                gr.update(value="Please upload an image for understanding.", visible=True)
            )
        txt = process_img_to_txt(prompt, img, progress=progress)
        return (
            gr.update(value=[], visible=False),
            gr.update(value=txt, visible=True)
        )

    def clean_all_fn():
        return (
            # Tab 1 inputs
            gr.update(value=None),
            gr.update(value=""),
            gr.update(value=1.5),
            gr.update(value=6.0),
            gr.update(value=50),
            gr.update(value=42),
            gr.update(value=False),
            # Tab 2 inputs
            gr.update(value=""),  # prompt_gen_input
            gr.update(value=1024),
            gr.update(value=1024),
            gr.update(value=5.0),
            gr.update(value=50),
            gr.update(value=42),  # seed_slider
            gr.update(value=False), # randomize_checkbox
            # Tab 3 inputs
            gr.update(value=None), # image_understand_input
            gr.update(value=""),  # prompt_understand_input
            # Outputs
            gr.update(value=[], visible=True), # output_gallery (reset and keep visible for next gen)
            gr.update(value="", visible=False) # output_text (reset and hide)
        )

    # Event listeners for Image + Text -> Image
    edit_inputs = [edit_prompt_input, edit_image_input, edit_num_steps_slider, edit_seed_slider, edit_txt_guidance_slider, edit_img_guidance_slider]
    
    run_edit_image_btn.click(
        fn=randomize_seed_fn,
        inputs=[edit_seed_slider, edit_randomize_checkbox],
        outputs=[edit_seed_slider]
    ).then(
        fn=run_img_txt_to_img_tab,
        inputs=edit_inputs, 
        outputs=[output_gallery, output_text]
    )

    edit_prompt_input.submit(
        fn=randomize_seed_fn,
        inputs=[edit_seed_slider, edit_randomize_checkbox],
        outputs=[edit_seed_slider]
    ).then(
        fn=run_img_txt_to_img_tab,
        inputs=edit_inputs,
        outputs=[output_gallery, output_text]
    )

    # Event listeners for Text -> Image
    gen_inputs = [prompt_gen_input, height_slider, width_slider, num_steps_slider, seed_slider, guidance_slider]
    
    run_image_gen_btn.click(
        fn=randomize_seed_fn,
        inputs=[seed_slider, randomize_checkbox],
        outputs=[seed_slider]
    ).then(
        fn=run_txt_to_img_tab,
        inputs=gen_inputs, 
        outputs=[output_gallery, output_text]
    )

    prompt_gen_input.submit(
        fn=randomize_seed_fn,
        inputs=[seed_slider, randomize_checkbox],
        outputs=[seed_slider]
    ).then(
        fn=run_txt_to_img_tab,
        inputs=gen_inputs,
        outputs=[output_gallery, output_text]
    )

    # Event listeners for Image -> Text
    understand_inputs = [image_understand_input, prompt_understand_input]

    run_image_understand_btn.click(
        fn=run_img_to_txt_tab,
        inputs=understand_inputs,
        outputs=[output_gallery, output_text]
    )

    prompt_understand_input.submit(
        fn=run_img_to_txt_tab,
        inputs=understand_inputs,
        outputs=[output_gallery, output_text]
    )

    clean_btn.click(
        fn=clean_all_fn,
        inputs=[],
        outputs=[
            edit_image_input, edit_prompt_input, edit_img_guidance_slider, edit_txt_guidance_slider,
            edit_num_steps_slider, edit_seed_slider, edit_randomize_checkbox,
            prompt_gen_input, height_slider, width_slider, guidance_slider, num_steps_slider, seed_slider, randomize_checkbox, 
            image_understand_input, prompt_understand_input,
            output_gallery, output_text
        ]
    )

if __name__ == "__main__":
    demo.launch(share=True, ssr_mode=False)