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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106328a
ea70609
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d41a998
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f09725d
ea70609
 
 
 
 
 
 
 
 
 
 
 
 
 
f09725d
ea70609
 
 
 
 
f09725d
ea70609
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f09725d
 
ea70609
 
 
 
 
 
 
 
106328a
 
 
 
 
ea70609
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d41a998
ea70609
106328a
 
ea70609
f09725d
 
ea70609
 
 
 
 
 
 
 
 
 
f09725d
 
d41a998
 
 
106328a
d41a998
 
 
 
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
import os
import torch
import gradio as gr
import spaces
import random
import numpy as np

from diffusers.utils import logging
from PIL import Image

from diffusers import OvisImagePipeline


logging.set_verbosity_error()

MAX_SEED = np.iinfo(np.int32).max

device = "cuda"
_dtype = torch.bfloat16
hf_token = os.getenv("HF_TOKEN")

pipe = OvisImagePipeline.from_pretrained(
    "AIDC-AI/Ovis-Image-7B",
    token=hf_token,
    torch_dtype=torch.bfloat16
)
pipe.to("cuda")

examples = [
    "Five shimmering goldfish weave through crevices between stones; four are red-and-white, while one is silver-white. By the pond's edge, a golden shaded British Shorthair cat watches them intently, counting on blind luck. Watercolor style.",
    "Solar punk vehicle in a bustling city",
    "An anthropomorphic cat riding a Harley Davidson in Arizona with sunglasses and a leather jacket",
    "An elderly woman poses for a high fashion photoshoot in colorful, patterned clothes with a cyberpunk 2077 vibe",
]

def get_image_size(aspect_ratio):
    """Converts aspect ratio string to width, height tuple."""
    if "(" in aspect_ratio and "x" in aspect_ratio:
        try:
            res_part = aspect_ratio.split("(")[1].split(")")[0]
            width, height = res_part.split("x")
            return int(width), int(height)
        except:
            pass
    return 1024, 1024

apple_css = """
/* Global Styles */
.gradio-container {
    max-width: 85vw !important;
    margin: 0 auto !important;
    padding: 48px 20px !important;
    font-family: -apple-system, BlinkMacSystemFont, 'Inter', 'Segoe UI', 'Roboto', sans-serif !important;
}

/* Disable all transitions globally to prevent layout shifts */
* {
    transition: none !important;
    animation: none !important;
}

/* Header */
.header-container {
    text-align: left;
    margin-bottom: 24px;
}

.main-title {
    font-size: 32px !important;
    font-weight: 600 !important;
    letter-spacing: -0.02em !important;
    line-height: 1.07 !important;
    color: #1d1d1f !important;
    margin: 0 0 16px 0 !important;
}

.subtitle {
    font-size: 21px !important;
    font-weight: 400 !important;
    line-height: 1.38 !important;
    color: #6e6e73 !important;
    margin: 0 0 24px 0 !important;
}

.attribution-link {
    display: inline-block;
    font-size: 14px !important;
    color: #0071e3 !important;
    text-decoration: none !important;
    font-weight: 400 !important;
    transition: color 0.2s ease !important;
}

.attribution-link:hover {
    color: #0077ed !important;
    text-decoration: underline !important;
}

/* Input Section */
.input-section {
    background: #ffffff;
    border-radius: 18px;
    padding: 32px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* Textbox */
textarea {
    font-size: 17px !important;
    line-height: 1.47 !important;
    border-radius: 12px !important;
    border: 1px solid #d2d2d7 !important;
    padding: 12px 16px !important;
    background: #ffffff !important;
    font-family: -apple-system, BlinkMacSystemFont, 'Inter', sans-serif !important;
    min-height: 200px !important;
    max-height: 400px !important;
    height: 200px !important;
    resize: vertical !important;
    overflow-y: auto !important;
    margin-bottom: 16px !important;
}

textarea:focus {
    border-color: #0071e3 !important;
    box-shadow: 0 0 0 4px rgba(0, 113, 227, 0.15) !important;
    outline: none !important;
}

textarea::placeholder {
    color: #86868b !important;
}

/* Button */
button.primary {
    font-size: 17px !important;
    font-weight: 400 !important;
    padding: 12px 32px !important;
    border-radius: 980px !important;
    background: #0071e3 !important;
    border: none !important;
    color: #ffffff !important;
    min-height: 44px !important;
    letter-spacing: -0.01em !important;
    cursor: pointer !important;
}

button.primary:hover {
    background: #0077ed !important;
}

button.primary:active {
    opacity: 0.9 !important;
}

/* Output Section */
div.output-section {
    background: #ffffff;
    border-radius: 18px;
    padding: 32px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 80vh;
    max-height: 90vh;
    will-change: auto;
    position: relative;
}

.output-section * {
    transform: none !important;
    transition: none !important;
    animation: none !important;
}

.output-section img {
    border-radius: 12px !important;
    max-width: 100% !important;
    max-height: 85vh !important;
    width: auto !important;
    height: auto !important;
    object-fit: contain !important;
    transform: none !important;
    transition: none !important;
    animation: none !important;
    backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
}

/* Make progress/generation area fill more space */
.output-section > div {
    width: 100% !important;
    min-height: 75vh !important;
    max-height: 85vh !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
}

.output-section > div > div {
    min-height: 75vh !important;
    max-height: 85vh !important;
    width: 100% !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
}

.output-section * {
    max-width: 100% !important;
}

/* Footer */
.footer-text {
    text-align: center;
    margin-top: 48px;
    font-size: 14px !important;
    color: #86868b !important;
    line-height: 1.43 !important;
}

/* Progress */
.progress-bar {
    background: #0071e3 !important;
    border-radius: 4px !important;
}

/* Dark Mode */
.dark .main-title {
    color: #ffffff !important;
}

.dark .subtitle {
    color: #a1a1a6 !important;
}

.input-section .main-title {
    color: #ffffff !important;
}

.dark .input-section .main-title {
    color: #f5f5f7 !important;
}

.dark .input-section,
.dark .output-section {
    background: #1d1d1f;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.4);
}

.dark textarea {
    background: #1d1d1f !important;
    border-color: #424245 !important;
    color: #f5f5f7 !important;
}

.dark textarea::placeholder {
    color: #86868b !important;
}

/* Inline labels */
label.inline-label {
    display: flex !important;
    align-items: center !important;
    min-width: 120px !important;
    margin: 0 !important;
    padding: 0 12px 0 0 !important;
    font-weight: 400 !important;
    font-size: 14px !important;
    color: #1d1d1f !important;
}

/* Fix column width to prevent shrinking - target Gradio's generated structure */
.input-section {
    min-width: 550px !important;
    max-width: 550px !important;
    width: 550px !important;
    flex-shrink: 0 !important;
    flex-grow: 0 !important;
}

/* Lock the output section to fill remaining space */
.output-section {
    flex-grow: 1 !important;
    flex-shrink: 0 !important;
    flex-basis: auto !important;
}

/* Prevent Gradio columns from flexing */
.gradio-column {
    flex-shrink: 0 !important;
}

/* Stabilize row layout - force horizontal layout with maximum specificity */
.gradio-row,
div.gradio-row,
.gradio-container .gradio-row,
.gradio-container > .gradio-row,
.gradio-container div.gradio-row {
    align-items: flex-start !important;
    flex-direction: row !important;
    display: flex !important;
    flex-wrap: nowrap !important;
    width: 100% !important;
}

/* Force columns to stay inline */
.gradio-row > .gradio-column,
.gradio-row > div {
    display: inline-flex !important;
    vertical-align: top !important;
}

/* First column - input section */
.gradio-row > .gradio-column:first-child,
.gradio-row > div:first-child {
    width: 550px !important;
    min-width: 550px !important;
    max-width: 550px !important;
    flex: 0 0 550px !important;
}

/* Second column - output section */
.gradio-row > .gradio-column:last-child,
.gradio-row > div:last-child {
    flex: 1 1 auto !important;
    min-width: 0 !important;
}

/* Lock textbox container size */
.input-section .gr-textbox,
.input-section label[for] {
    width: 100% !important;
}

/* Prevent form from expanding */
.input-section form {
    width: 100% !important;
    max-width: 100% !important;
}

/* Ensure seed input always visible */
.input-section input[type="number"] {
    display: block !important;
    visibility: visible !important;
}

/* Hide progress indicator in input section - target specific progress elements */
.input-section .progress-container,
.input-section [class*="progress-bar"],
.input-section [class*="progress-text"],
.input-section [class*="progress-level"],
.input-section .progress,
.input-section .eta-bar {
    display: none !important;
    visibility: hidden !important;
    height: 0 !important;
    overflow: hidden !important;
}

/* Override ALL responsive behavior - force horizontal layout at ALL viewport sizes */
@media (max-width: 2000px) {
    .gradio-row,
    div.gradio-row,
    .gradio-container .gradio-row,
    .gradio-container > .gradio-row {
        flex-direction: row !important;
        flex-wrap: nowrap !important;
        display: flex !important;
    }

    .gradio-row > .gradio-column,
    .gradio-row > div {
        display: inline-flex !important;
    }

    .gradio-row > .gradio-column:first-child,
    .gradio-row > div:first-child {
        width: 550px !important;
        min-width: 550px !important;
        max-width: 550px !important;
        flex: 0 0 550px !important;
    }

    .gradio-row > .gradio-column:last-child,
    .gradio-row > div:last-child {
        flex: 1 1 auto !important;
        min-width: 0 !important;
    }
}

/* Responsive text sizing only */
@media (max-width: 734px) {
    .main-title {
        font-size: 40px !important;
    }

    .subtitle {
        font-size: 19px !important;
    }

    .gradio-container {
        padding: 32px 16px !important;
    }

    .input-section,
    .output-section {
        padding: 24px !important;
    }

    /* FORCE horizontal layout even on mobile */
    .gradio-row,
    div.gradio-row {
        flex-direction: row !important;
        flex-wrap: nowrap !important;
    }
}

/* Remove default Gradio styling */
.contain {
    padding: 0 !important;
}

/* Hide Gradio footer */
footer {
    display: none !important;
}

.footer {
    display: none !important;
}

/* Target main app container */
#root, #app {
    width: 100% !important;
    max-width: none !important;
}
"""

# JavaScript to force horizontal layout
js_code = """
function() {
    function forceHorizontalLayout() {
        // Set container width
        const container = document.querySelector('.gradio-container');
        if (container) {
            container.style.maxWidth = '85vw';
            container.style.width = '85vw';
        }

        // Target the main row specifically
        const mainRow = document.getElementById('main-row');
        if (mainRow) {
            mainRow.style.flexDirection = 'row';
            mainRow.style.flexWrap = 'nowrap';
            mainRow.style.display = 'flex';
            mainRow.style.width = '100%';
        }

        // Force ALL rows to stay horizontal
        const rows = document.querySelectorAll('.gradio-row');
        rows.forEach(row => {
            row.style.flexDirection = 'row';
            row.style.flexWrap = 'nowrap';
            row.style.display = 'flex';
        });

        // Target specific columns
        const inputCol = document.getElementById('input-column');
        if (inputCol) {
            inputCol.style.width = '550px';
            inputCol.style.minWidth = '550px';
            inputCol.style.maxWidth = '550px';
            inputCol.style.flex = '0 0 550px';
            inputCol.style.display = 'inline-flex';
            inputCol.style.flexDirection = 'column';
        }

        const outputCol = document.getElementById('output-column');
        if (outputCol) {
            outputCol.style.flex = '1 1 auto';
            outputCol.style.minWidth = '0';
            outputCol.style.display = 'inline-flex';
            outputCol.style.flexDirection = 'column';
        }

        // Fallback: force all column children of rows
        const columns = document.querySelectorAll('.gradio-row > .gradio-column, .gradio-row > div');
        columns.forEach((col, index) => {
            if (index === 0) {
                col.style.width = '550px';
                col.style.minWidth = '550px';
                col.style.maxWidth = '550px';
                col.style.flex = '0 0 550px';
            } else if (index === 1) {
                col.style.flex = '1 1 auto';
                col.style.minWidth = '0';
            }
            col.style.display = 'inline-flex';
        });
    }

    // Run immediately
    forceHorizontalLayout();

    // Run again after delays to override Gradio's dynamic changes
    setTimeout(forceHorizontalLayout, 100);
    setTimeout(forceHorizontalLayout, 500);
    setTimeout(forceHorizontalLayout, 1000);
    setTimeout(forceHorizontalLayout, 2000);

    // Set up mutation observer to reapply on DOM changes
    const observer = new MutationObserver(forceHorizontalLayout);
    observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
}
"""

@spaces.GPU(duration=75)
def infer(
    prompt,
    seed=42,
    randomize_seed=False,
    aspect_ratio="1:1 (1024x1024)",
    guidance_scale=5.0,
    num_inference_steps=50,
    progress=gr.Progress(track_tqdm=True),
):
    """Generates an image using the Ovis-Image pipeline."""
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)

    width, height = get_image_size(aspect_ratio)

    print(f'inference with prompt: {prompt}, size: {height}x{width}, seed: {seed}, steps: {num_inference_steps}, cfg: {guidance_scale}')

    generator = torch.Generator().manual_seed(seed)
    image = pipe(
        prompt,
        negative_prompt="",
        height=height,
        width=width,
        num_inference_steps=num_inference_steps,
        true_cfg_scale=guidance_scale,
        generator=generator,
    ).images[0]

    return image, seed

custom_theme = gr.themes.Soft(
    primary_hue=gr.themes.colors.blue,
    secondary_hue=gr.themes.colors.slate,
    neutral_hue=gr.themes.colors.gray,
    spacing_size=gr.themes.sizes.spacing_lg,
    radius_size=gr.themes.sizes.radius_lg,
    text_size=gr.themes.sizes.text_md,
    font=[gr.themes.GoogleFont("Inter"), "SF Pro Display", "-apple-system", "BlinkMacSystemFont", "system-ui", "sans-serif"],
    font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "SF Mono", "ui-monospace", "monospace"],
).set(
    body_background_fill='#f5f5f7',
    body_background_fill_dark='#000000',
    button_primary_background_fill='#0071e3',
    button_primary_background_fill_hover='#0077ed',
    button_primary_text_color='#ffffff',
    block_background_fill='#ffffff',
    block_background_fill_dark='#1d1d1f',
    block_border_width='0px',
    block_shadow='0 2px 12px rgba(0, 0, 0, 0.08)',
    block_shadow_dark='0 2px 12px rgba(0, 0, 0, 0.4)',
    input_background_fill='#ffffff',
    input_background_fill_dark='#1d1d1f',
    input_border_width='1px',
    input_border_color='#d2d2d7',
    input_border_color_dark='#424245',
    input_shadow='none',
    input_shadow_focus='0 0 0 4px rgba(0, 113, 227, 0.15)',
)

with gr.Blocks(
    title="Ovis-Image",
    fill_height=False,
) as demo:
    # Two-column layout - variant='panel' prevents responsive stacking
    with gr.Row(equal_height=False, variant="panel", elem_id="main-row"):
        # Left column - Input controls (fixed width)
        with gr.Column(scale=0, min_width=550, elem_classes="input-section", elem_id="input-column"):
            # Title above prompt box
            gr.HTML("""
                <div class="header-container">
                    <h1 class="main-title">Ovis-Image</h1>
                </div>
            """)

            prompt = gr.Textbox(
                placeholder="Describe the image you want to create...",
                value=examples[0],
                lines=7,
                max_lines=7,
                label="Prompt",
                show_label=True,
                container=True,
                autoscroll=False,
            )

            aspect_ratio = gr.Dropdown(
                choices=[
                    "1:1 (1024x1024)",
                    "4:3 (1024x768)",
                    "3:4 (768x1024)",
                    "16:9 (1024x576)",
                    "9:16 (576x1024)",
                ],
                value="1:1 (1024x1024)",
                label="Aspect Ratio",
                show_label=True,
                container=True,
            )

            run_button = gr.Button(
                "Generate",
                variant="primary",
                size="lg",
                elem_classes="primary"
            )

            # Hidden advanced settings (still functional but not visible)
            seed = gr.Slider(
                label="Seed",
                minimum=0,
                maximum=MAX_SEED,
                step=1,
                value=0,
                visible=False
            )
            randomize_seed = gr.Checkbox(label="Randomize seed", value=True, visible=False)
            guidance_scale = gr.Slider(
                label="Guidance scale",
                minimum=0.0,
                maximum=14.0,
                step=0.1,
                value=5.0,
                visible=False
            )
            num_inference_steps = gr.Slider(
                label="Number of inference steps",
                minimum=1,
                maximum=100,
                step=1,
                value=50,
                visible=False
            )

        # Right column - Image output
        with gr.Column(scale=2, elem_classes="output-section", elem_id="output-column"):
            result = gr.Image(
                label="Result",
                show_label=False,
                type="pil",
                format="png",
            )

    # Event handlers - using gr.on() like original Qwen-Image
    gr.on(
        triggers=[run_button.click, prompt.submit],
        fn=infer,
        inputs=[
            prompt,
            seed,
            randomize_seed,
            aspect_ratio,
            guidance_scale,
            num_inference_steps,
        ],
        outputs=[result, seed],
    )

    # Load JS after DOM is ready (like Qwen-Image)
    demo.load(None, None, None, js=js_code)

if __name__ == '__main__':
    demo.launch(
        theme=custom_theme,
        css=apple_css,
    )