File size: 16,313 Bytes
53a42bb
 
1182d82
53a42bb
 
6a1c863
53a42bb
 
 
 
 
 
 
7492786
8e10f35
2ec806f
53a42bb
4a39f23
1182d82
 
8e10f35
ba100e2
1182d82
 
 
 
8e10f35
 
ba100e2
8e10f35
 
 
 
 
 
1182d82
ba100e2
53a42bb
 
1182d82
53a42bb
1182d82
53a42bb
 
1182d82
 
 
 
 
 
 
 
 
 
 
 
fe208e4
1182d82
fe208e4
1182d82
 
fe208e4
 
1182d82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc55ad2
1182d82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7492786
1182d82
8c764ec
 
 
1182d82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c764ec
 
1182d82
 
 
 
 
 
8c764ec
 
1182d82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe208e4
1182d82
 
 
 
53a42bb
1182d82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53a42bb
1182d82
 
53a42bb
1182d82
 
 
 
 
53a42bb
1182d82
 
 
53a42bb
 
 
1182d82
 
daee001
1182d82
 
 
 
 
 
 
 
 
 
 
 
daee001
1182d82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53a42bb
 
1182d82
 
 
ad8d7d1
53a42bb
1182d82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import numpy as np
import os, random, json, spaces, torch, time

import torch
from transformers import AutoProcessor, AutoTokenizer
from longcat_image.models import LongCatImageTransformer2DModel
from longcat_image.pipelines import LongCatImagePipeline

from utils.image_utils import rescale_image
from utils.prompt_utils import polish_prompt


# Force rebuild v20
MODEL_REPO = "meituan-longcat/LongCat-Image"
MAX_SEED = np.iinfo(np.int32).max

print("Loading LongCat-Image model... v12")
text_processor = AutoTokenizer.from_pretrained(
    MODEL_REPO,
    subfolder = 'tokenizer'
)
transformer = LongCatImageTransformer2DModel.from_pretrained(
    MODEL_REPO ,
    subfolder = 'transformer',
    torch_dtype=torch.bfloat16,
    use_safetensors=True
).to("cuda")

pipe = LongCatImagePipeline.from_pretrained(
    MODEL_REPO,
    transformer=transformer,
    text_processor=text_processor
)
pipe.to("cuda", torch.bfloat16)
print("Model loaded successfully!")


@spaces.GPU
def generate_image(
    prompt,
    aspect_ratio,
    progress=gr.Progress(track_tqdm=True),
):
    """Generate an image using LongCat-Image model."""
    if not prompt.strip():
        raise gr.Error("Please enter a prompt to generate an image.")

    # Parse aspect ratio to get dimensions
    aspect_ratio_map = {
        "1:1 (1024x1024)": (1024, 1024),
        "4:3 (1024x768)": (1024, 768),
        "3:4 (768x1024)": (768, 1024),
        "16:9 (1024x576)": (1024, 576),
        "9:16 (576x1024)": (576, 1024),
    }

    width, height = aspect_ratio_map.get(aspect_ratio, (1024, 1024))

    # Generate random seed
    seed = random.randint(0, MAX_SEED)
    generator = torch.Generator().manual_seed(seed)

    progress(0.1, desc="Generating image...")

    try:
        image = pipe(
            prompt=prompt,
            negative_prompt="blurry ugly bad",
            width=width,
            height=height,
            generator=generator,
            guidance_scale=1.5,
            num_inference_steps=20,
            enable_prompt_rewrite=False
        ).images[0]

        progress(1.0, desc="Complete!")
        return image

    except Exception as e:
        raise gr.Error(f"Generation failed: {str(e)}")


# Apple-style CSS for dark theme
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: #f5f5f7 !important;
    margin: 0 0 16px 0 !important;
}

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

/* Textbox */
textarea {
    font-size: 17px !important;
    line-height: 1.47 !important;
    border-radius: 12px !important;
    border: 1px solid #424245 !important;
    padding: 12px 16px !important;
    background: #1d1d1f !important;
    color: #f5f5f7 !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 !important;
    border-radius: 18px;
    padding: 32px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    border: none !important;
    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;
}

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

/* Labels */
label {
    color: #f5f5f7 !important;
}

/* Dropdown */
.gr-dropdown {
    background: #1d1d1f !important;
    border: 1px solid #424245 !important;
    border-radius: 12px !important;
    color: #f5f5f7 !important;
}

select, .wrap-inner {
    background: #1d1d1f !important;
    color: #f5f5f7 !important;
    border-color: #424245 !important;
}

/* Fix column width to prevent shrinking */
.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 */
.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;
}

/* Hide progress indicator in input section */
.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 responsive behavior */
@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: 28px !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;
    }
}

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

.footer {
    display: 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'] });
}
"""

# Create the interface
with gr.Blocks(
    title="LongCat-Image",
    fill_height=False,
) as demo:

    # Two-column layout
    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">LongCat-Image</h1>
            </div>
            """)

            prompt = gr.Textbox(
                placeholder="Describe the image you want to create...",
                value="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.",
                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,
            )

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

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

    # Event handlers
    generate_btn.click(
        fn=generate_image,
        inputs=[prompt, aspect_ratio],
        outputs=output_image,
        show_progress="full"
    )

    prompt.submit(
        fn=generate_image,
        inputs=[prompt, aspect_ratio],
        outputs=output_image,
        show_progress="full"
    )

    # Load event to force width with JavaScript
    demo.load(None, None, None, js=js_code)


if __name__ == "__main__":
    demo.launch(
        mcp_server=True,
        share=False,
        show_error=True,
        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='#000000',
            body_background_fill_dark='#000000',
            button_primary_background_fill='#0071e3',
            button_primary_background_fill_hover='#0077ed',
            button_primary_text_color='#ffffff',
            block_background_fill='#1d1d1f',
            block_background_fill_dark='#1d1d1f',
            block_border_width='0px',
            block_shadow='0 2px 12px rgba(0, 0, 0, 0.4)',
            block_shadow_dark='0 2px 12px rgba(0, 0, 0, 0.4)',
            input_background_fill='#1d1d1f',
            input_background_fill_dark='#1d1d1f',
            input_border_width='1px',
            input_border_color='#424245',
            input_border_color_dark='#424245',
            input_shadow='none',
            input_shadow_focus='0 0 0 4px rgba(0, 113, 227, 0.15)',
        ),
        css=apple_css,
    )