File size: 8,503 Bytes
99582fb
de41cc1
 
 
 
 
 
 
 
85df522
 
 
de41cc1
85df522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de41cc1
6e4901a
de41cc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e4901a
de41cc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e4901a
d6c9b79
6e4901a
de41cc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e4901a
 
 
 
85df522
6e4901a
 
 
 
 
de41cc1
 
 
 
 
 
5320fe2
de41cc1
 
 
 
 
 
 
 
 
6e4901a
d6c9b79
de41cc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85df522
de41cc1
 
 
 
 
 
d6c9b79
de41cc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import spaces
import gradio as gr
import torch
from PIL import Image
from transformers import AutoProcessor
from longcat_image.models import LongCatImageTransformer2DModel
from longcat_image.pipelines import LongCatImageEditPipeline
import numpy as np

# Load model directly at startup
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model_id = 'meituan-longcat/LongCat-Image-Edit'

print(f"πŸ”„ Loading model from {model_id}...")

# Load text processor
text_processor = AutoProcessor.from_pretrained(
    model_id, 
    subfolder='tokenizer'
)

# Load transformer
transformer = LongCatImageTransformer2DModel.from_pretrained(
    model_id, 
    subfolder='transformer',
    torch_dtype=torch.bfloat16, 
    use_safetensors=True
).to(device)

# Load pipeline
pipe = LongCatImageEditPipeline.from_pretrained(
    model_id,
    transformer=transformer,
    text_processor=text_processor,
)
pipe.to(device, torch.bfloat16)

print(f"βœ… Model loaded successfully on {device}")

@spaces.GPU(duration=120)
def edit_image(
    input_image: Image.Image,
    prompt: str,
    negative_prompt: str,
    guidance_scale: float,
    num_inference_steps: int,
    seed: int,
    progress=gr.Progress()
):
    """Edit image based on text prompt"""
    
    if input_image is None:
        raise gr.Error("Please upload an image first")
    
    if not prompt or prompt.strip() == "":
        raise gr.Error("Please enter an edit instruction")
    
    try:
        progress(0.1, desc="Preparing image...")
        
        # Convert to RGB if needed
        if input_image.mode != 'RGB':
            input_image = input_image.convert('RGB')
        
        progress(0.2, desc="Generating edited image...")
        
        # Set random seed for reproducibility
        generator = torch.Generator("cuda" if torch.cuda.is_available() else "cpu").manual_seed(seed)
        
        # Run the pipeline
        with torch.inference_mode():
            output = pipe(
                input_image,
                prompt,
                negative_prompt=negative_prompt,
                guidance_scale=guidance_scale,
                num_inference_steps=num_inference_steps,
                num_images_per_prompt=1,
                generator=generator
            )
        
        progress(1.0, desc="Done!")
        
        edited_image = output.images[0]
        
        return edited_image
        
    except Exception as e:
        raise gr.Error(f"Error during image editing: {str(e)}")

# Example prompts
example_prompts = [
    ["ε°†ηŒ«ε˜ζˆη‹—", "", 4.5, 50, 42],
    ["Change the cat to a dog", "", 4.5, 50, 42],
    ["ε°†θƒŒζ™―ε˜ζˆζ΅·ζ»©", "", 4.5, 50, 43],
    ["Make it nighttime", "", 4.5, 50, 44],
    ["ε°†ε›Ύη‰‡θ½¬ζ’δΈΊζ²Ήη”»ι£Žζ Ό", "", 4.5, 50, 45],
]

# Build Gradio interface
with gr.Blocks(fill_height=True) as demo:
    gr.HTML("""
        <div style="text-align: center; margin-bottom: 20px;">
            <h1>🎨 LongCat Image Edit</h1>
            <p style="font-size: 16px; color: #666;">
                Transform your images with AI-powered editing using natural language instructions
            </p>
            <p style="font-size: 14px; margin-top: 10px;">
                Built with <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #4A90E2; text-decoration: none;">anycoder</a>
            </p>
            <p style="font-size: 12px; color: #888; margin-top: 5px;">
                ⚑ Powered by Zero-GPU | πŸ€— Model: <a href="https://huggingface.co/meituan-longcat/LongCat-Image-Edit" target="_blank" style="color: #4A90E2;">meituan-longcat/LongCat-Image-Edit</a>
            </p>
        </div>
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### πŸ“€ Input")
            input_image = gr.Image(
                label="Upload Image",
                type="pil",
                sources=["upload", "clipboard"],
                height=400
            )
            
            prompt = gr.Textbox(
                label="Edit Instruction",
                placeholder="Describe how you want to edit the image (e.g., 'ε°†ηŒ«ε˜ζˆη‹—' or 'Change the cat to a dog')",
                lines=3
            )
            
            with gr.Accordion("βš™οΈ Advanced Settings", open=False):
                negative_prompt = gr.Textbox(
                    label="Negative Prompt (Optional)",
                    placeholder="What you don't want in the image",
                    lines=2
                )
                
                guidance_scale = gr.Slider(
                    minimum=1.0,
                    maximum=10.0,
                    value=4.5,
                    step=0.5,
                    label="Guidance Scale",
                    info="Higher values = stronger adherence to prompt"
                )
                
                num_inference_steps = gr.Slider(
                    minimum=20,
                    maximum=100,
                    value=50,
                    step=5,
                    label="Inference Steps",
                    info="More steps = higher quality but slower"
                )
                
                seed = gr.Slider(
                    minimum=0,
                    maximum=999999,
                    value=42,
                    step=1,
                    label="Random Seed",
                    info="Use same seed for reproducible results"
                )
            
            edit_btn = gr.Button("✨ Edit Image", variant="primary", size="lg")
            
            gr.Markdown("""
            <div style="padding: 10px; background-color: #f0f7ff; border-radius: 8px; margin-top: 10px;">
                <p style="margin: 0; font-size: 12px; color: #555;">
                    ⏱️ <strong>Note:</strong> Zero-GPU provides 120 seconds of GPU time per request. 
                    Model is loaded at startup from Hugging Face Hub.
                    Processing typically takes 30-60 seconds depending on settings.
                </p>
            </div>
            """)
            
        with gr.Column(scale=1):
            gr.Markdown("### 🎯 Output")
            output_image = gr.Image(
                label="Edited Image",
                type="pil",
                height=400,
                buttons=["download"]
            )
            
            gr.Markdown("### πŸ’‘ Tips")
            gr.Markdown("""
            - Upload a clear, well-lit image for best results
            - Be specific in your edit instructions
            - Supports both English and Chinese prompts
            - Try different guidance scales for varied results
            - Higher inference steps = better quality (but slower)
            - GPU time is limited - optimize your settings for speed
            - Model loads automatically from Hugging Face Hub
            """)
    
    # Examples section
    gr.Markdown("### πŸ“ Example Prompts")
    gr.Examples(
        examples=example_prompts,
        inputs=[prompt, negative_prompt, guidance_scale, num_inference_steps, seed],
        label="Click to try these examples"
    )
    
    # Event handlers
    edit_btn.click(
        fn=edit_image,
        inputs=[
            input_image,
            prompt,
            negative_prompt,
            guidance_scale,
            num_inference_steps,
            seed
        ],
        outputs=output_image,
        api_visibility="public"
    )
    
    # Footer
    gr.HTML("""
        <div style="text-align: center; margin-top: 40px; padding: 20px; border-top: 1px solid #eee;">
            <p style="color: #666; font-size: 14px;">
                Powered by <a href="https://huggingface.co/meituan-longcat/LongCat-Image-Edit" target="_blank" style="color: #4A90E2;">LongCat Image Edit</a> with Zero-GPU | 
                <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #4A90E2;">Built with anycoder</a>
            </p>
        </div>
    """)

# Launch the app
if __name__ == "__main__":
    demo.launch(
        theme=gr.themes.Soft(
            primary_hue="blue",
            secondary_hue="indigo",
            neutral_hue="slate",
            font=gr.themes.GoogleFont("Inter"),
            text_size="lg",
            spacing_size="lg",
            radius_size="md"
        ),
        footer_links=[
            {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
        ]
    )