File size: 16,080 Bytes
f71e03f
 
829e0f1
 
f71e03f
 
7e7ff89
f71e03f
 
7b49c49
f71e03f
7b49c49
f71e03f
829e0f1
f71e03f
829e0f1
f71e03f
829e0f1
f71e03f
 
7b49c49
 
 
 
 
 
 
829e0f1
f71e03f
829e0f1
f71e03f
7e7ff89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f92187
7e7ff89
 
 
 
f71e03f
7b49c49
f71e03f
 
7e7ff89
 
 
 
 
 
 
7b49c49
7e7ff89
7b49c49
829e0f1
f71e03f
7e7ff89
 
 
 
 
 
 
 
 
 
 
 
6f92187
 
 
 
 
7e7ff89
 
6f92187
7e7ff89
 
 
 
7b49c49
7e7ff89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f92187
7e7ff89
6f92187
7b49c49
829e0f1
6f92187
7b49c49
7e7ff89
829e0f1
7e7ff89
 
 
f71e03f
7b49c49
7e7ff89
 
7b49c49
 
 
7e7ff89
 
7b49c49
7e7ff89
 
829e0f1
7b49c49
 
 
7e7ff89
 
 
 
 
 
 
 
 
 
 
 
 
 
7b49c49
 
6f92187
7b49c49
7e7ff89
f71e03f
 
829e0f1
f71e03f
 
7e7ff89
 
 
 
f71e03f
 
7e7ff89
7b49c49
7e7ff89
f71e03f
 
 
7e7ff89
 
7b49c49
7e7ff89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b49c49
7e7ff89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b49c49
7e7ff89
 
 
 
7b49c49
 
7e7ff89
 
 
 
 
7b49c49
7e7ff89
 
 
 
 
 
 
 
7b49c49
7e7ff89
 
7b49c49
 
7e7ff89
 
 
 
 
 
 
 
 
 
6f92187
7e7ff89
 
 
 
6f92187
7e7ff89
 
 
 
6f92187
7e7ff89
 
 
 
 
6f92187
f71e03f
7e7ff89
 
 
6f92187
7e7ff89
 
 
 
f71e03f
7e7ff89
 
 
 
 
 
 
 
f71e03f
 
7e7ff89
 
 
f71e03f
 
7e7ff89
 
 
 
f71e03f
7e7ff89
 
f71e03f
 
 
7e7ff89
 
 
 
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
import gradio as gr
import torch
from diffusers import StableDiffusionPipeline, LCMScheduler
import time

# ============================================
# LCM मॉडल लोडिंग
# ============================================

model_id = "SimianLuo/LCM_Dreamshaper_v7"

print("🔄 LCM मॉडल लोड हो रहा है...")

pipe = StableDiffusionPipeline.from_pretrained(
    model_id,
    torch_dtype=torch.float32,
    safety_checker=None,
    requires_safety_checker=False
)

pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)

try:
    pipe.enable_attention_slicing()
    pipe.enable_vae_slicing()
    print("✅ मेमोरी ऑप्टिमाइज़ेशन सक्रिय")
except Exception as e:
    print(f"नोट: {e}")

print("✅ मॉडल तैयार है!")

# ============================================
# प्लेटफॉर्म प्रीसेट्स
# ============================================

PLATFORM_PRESETS = {
    "📱 Instagram Post (Square)": {"width": 1080, "height": 1080},
    "📱 Instagram Story": {"width": 1080, "height": 1920},
    "📱 Instagram Portrait": {"width": 1080, "height": 1350},
    "📱 Instagram Landscape": {"width": 1080, "height": 566},
    "📘 Facebook Post": {"width": 1200, "height": 630},
    "📘 Facebook Cover": {"width": 851, "height": 315},
    "🐦 Twitter/X Post": {"width": 1600, "height": 900},
    "🐦 Twitter/X Header": {"width": 1500, "height": 500},
    "📺 YouTube Thumbnail": {"width": 1280, "height": 720},
    "📺 YouTube Channel Banner": {"width": 2560, "height": 1440},
    "💼 LinkedIn Post": {"width": 1200, "height": 627},
    "💼 LinkedIn Banner": {"width": 1584, "height": 396},
    "📌 Pinterest Pin": {"width": 1000, "height": 1500},
    "🎵 TikTok Video": {"width": 1080, "height": 1920},
    "💬 WhatsApp Status": {"width": 1080, "height": 1920},
    "🖥️ Desktop Wallpaper (HD)": {"width": 1920, "height": 1080},
    "🖥️ Desktop Wallpaper (4K)": {"width": 3840, "height": 2160},
    "📱 Mobile Wallpaper": {"width": 1080, "height": 1920},
    "🎨 Square (1:1)": {"width": 1024, "height": 1024},
    "🎨 Portrait (2:3)": {"width": 1024, "height": 1536},
    "🎨 Landscape (3:2)": {"width": 1536, "height": 1024},
    "🎨 Wide (16:9)": {"width": 1280, "height": 720},
    "✏️ Custom Size": {"width": 512, "height": 512},
}

QUALITY_PRESETS = {
    "⚡ Ultra Fast (Draft)": {"steps": 2, "guidance": 0.8},
    "🚀 Fast (Good)": {"steps": 4, "guidance": 1.0},
    "🎯 Balanced (Better)": {"steps": 6, "guidance": 1.2},
    "💎 High Quality (Best)": {"steps": 8, "guidance": 1.5},
    "🔬 Custom": {"steps": 4, "guidance": 1.0},
}

# ============================================
# प्लेटफॉर्म बदलने पर ऑटो-अपडेट फंक्शन
# ============================================

def update_size_from_preset(platform_choice):
    """प्लेटफॉर्म चुनने पर width और height अपडेट करें"""
    if platform_choice in PLATFORM_PRESETS:
        preset = PLATFORM_PRESETS[platform_choice]
        return preset["width"], preset["height"]
    return 512, 512

def update_quality_from_preset(quality_choice):
    """क्वालिटी प्रीसेट चुनने पर steps और guidance अपडेट करें"""
    if quality_choice in QUALITY_PRESETS:
        preset = QUALITY_PRESETS[quality_choice]
        return preset["steps"], preset["guidance"]
    return 4, 1.0

# ============================================
# इमेज जनरेशन फंक्शन
# ============================================

def generate_image(
    prompt, negative_prompt, 
    platform_choice, quality_choice,
    custom_width, custom_height, 
    custom_steps, custom_guidance,
    seed, enhance_prompt
):
    """
    एडवांस्ड इमेज जनरेशन फंक्शन
    """
    # खाली प्रॉम्प्ट चेक करें
    if not prompt or prompt.strip() == "":
        return None, "❌ कृपया प्रॉम्पट डालें"
    
    # साइज़ सेट करें
    if platform_choice == "✏️ Custom Size":
        width = int(custom_width)
        height = int(custom_height)
    else:
        preset = PLATFORM_PRESETS.get(platform_choice, {"width": 512, "height": 512})
        width = preset["width"]
        height = preset["height"]
    
    # साइज़ लिमिट चेक (CPU मेमोरी के लिए)
    max_pixels = 1024 * 1024  # 1MP
    if width * height > max_pixels:
        scale = (max_pixels / (width * height)) ** 0.5
        width = int(width * scale)
        height = int(height * scale)
        width = (width // 64) * 64
        height = (height // 64) * 64
        size_warning = f"⚠️ बड़ी इमेज को {width}x{height} पर रिसाइज़ किया गया"
    else:
        width = (width // 64) * 64
        height = (height // 64) * 64
        size_warning = ""
    
    # क्वालिटी सेट करें
    if quality_choice == "🔬 Custom":
        steps = int(custom_steps)
        guidance_scale = float(custom_guidance)
    else:
        preset = QUALITY_PRESETS.get(quality_choice, {"steps": 4, "guidance": 1.0})
        steps = preset["steps"]
        guidance_scale = preset["guidance"]
    
    # प्रॉम्प्ट एन्हांसमेंट
    if enhance_prompt:
        if not prompt.lower().startswith("raw photo"):
            prompt = "RAW photo, hyperrealistic, " + prompt
        if "8k" not in prompt.lower():
            prompt = prompt + ", 8k, highly detailed, cinematic lighting"
    
    # नेगेटिव प्रॉम्प्ट
    if not negative_prompt:
        negative_prompt = "cartoon, anime, illustration, painting, drawing, 3d render, blurry, low quality, distorted, ugly, bad anatomy"
    
    # सीड
    if seed is None or seed < 0:
        actual_seed = int(time.time()) % 9999999
        generator = torch.Generator().manual_seed(actual_seed)
    else:
        actual_seed = int(seed)
        generator = torch.Generator().manual_seed(actual_seed)
    
    print(f"\n{'='*50}")
    print(f"🎨 जनरेट हो रहा है...")
    print(f"   साइज़: {width}x{height}")
    print(f"   स्टेप्स: {steps}, गाइडेंस: {guidance_scale}")
    print(f"   सीड: {actual_seed}")
    
    try:
        start_time = time.time()
        
        result = pipe(
            prompt=prompt,
            negative_prompt=negative_prompt,
            num_inference_steps=steps,
            guidance_scale=guidance_scale,
            generator=generator,
            width=width,
            height=height,
            output_type="pil",
            num_images_per_prompt=1
        )
        
        end_time = time.time()
        gen_time = round(end_time - start_time, 1)
        
        success_msg = f"""
        ✅ **इमेज जनरेट हो गई!**
        - समय: {gen_time} सेकंड
        - साइज़: {width} x {height}
        - सीड: {actual_seed}
        {size_warning}
        """
        
        print(f"✅ इमेज {gen_time} सेकंड में जनरेट हुई!")
        
        return result.images[0], success_msg
        
    except Exception as e:
        error_msg = f"❌ एरर: {str(e)[:200]}"
        print(f"❌ एरर: {e}")
        return None, error_msg

# ============================================
# Gradio UI
# ============================================

with gr.Blocks(
    title="AI Image Generator - Custom Sizes & Quality",
    theme=gr.themes.Soft()
) as demo:
    
    gr.Markdown("""
    # 🎨 AI इमेज जनरेटर - कस्टम साइज़ और क्वालिटी
    
    **किसी भी सोशल मीडिया प्लेटफॉर्म के लिए परफेक्ट साइज़ की इमेज बनाएं!**
    """)
    
    with gr.Row():
        # ===== बायां कॉलम - इनपुट =====
        with gr.Column(scale=2):
            
            # प्रॉम्प्ट सेक्शन
            with gr.Group():
                gr.Markdown("### 📝 प्रॉम्प्ट")
                prompt = gr.Textbox(
                    label="आप क्या बनाना चाहते हैं?",
                    placeholder="जैसे: beautiful sunset over mountains, golden hour...",
                    value="beautiful sunset over mountains, golden hour, ocean view",
                    lines=3,
                    show_label=False
                )
                
                enhance_prompt = gr.Checkbox(
                    label="✨ प्रॉम्प्ट ऑटो-एन्हांस करें (RAW photo, 8k, cinematic जोड़ें)",
                    value=True
                )
                
                negative_prompt = gr.Textbox(
                    label="🚫 नेगेटिव प्रॉम्प्ट (क्या नहीं चाहिए)",
                    value="cartoon, anime, illustration, painting, drawing, blurry, low quality, ugly, bad anatomy",
                    lines=2
                )
            
            # प्लेटफॉर्म और साइज़ सेक्शन
            with gr.Group():
                gr.Markdown("### 📐 प्लेटफॉर्म और साइज़")
                
                platform_choice = gr.Dropdown(
                    choices=list(PLATFORM_PRESETS.keys()),
                    value="🎨 Square (1:1)",
                    label="📱 प्लेटफॉर्म चुनें",
                    info="सोशल मीडिया प्लेटफॉर्म के हिसाब से ऑटो-साइज़"
                )
                
                with gr.Row():
                    custom_width = gr.Number(
                        label="चौड़ाई (px)",
                        value=512,
                        minimum=256,
                        maximum=2048,
                        step=64,
                    )
                    custom_height = gr.Number(
                        label="ऊंचाई (px)",
                        value=512,
                        minimum=256,
                        maximum=2048,
                        step=64,
                    )
            
            # क्वालिटी सेक्शन
            with gr.Group():
                gr.Markdown("### ⚙️ क्वालिटी सेटिंग्स")
                
                quality_choice = gr.Dropdown(
                    choices=list(QUALITY_PRESETS.keys()),
                    value="🚀 Fast (Good)",
                    label="🎯 क्वालिटी प्रीसेट",
                    info="तेज़ = कम समय, बेहतर = ज़्यादा डिटेल"
                )
                
                with gr.Row():
                    custom_steps = gr.Slider(
                        label="🔢 स्टेप्स",
                        minimum=1,
                        maximum=12,
                        value=4,
                        step=1,
                    )
                    custom_guidance = gr.Slider(
                        label="🎯 गाइडेंस स्केल",
                        minimum=0.5,
                        maximum=2.0,
                        value=1.0,
                        step=0.1,
                    )
            
            # सीड और जनरेट बटन
            with gr.Row():
                seed = gr.Number(
                    label="🎲 सीड (-1 = रैंडम)",
                    value=-1,
                    precision=0
                )
                
                generate_btn = gr.Button(
                    "✨ इमेज जनरेट करें",
                    variant="primary",
                    size="lg",
                    scale=2
                )
        
        # ===== दायां कॉलम - आउटपुट =====
        with gr.Column(scale=1):
            output_image = gr.Image(
                label="जनरेटेड इमेज",
                height=400,
                show_label=True
            )
            
            status_text = gr.Markdown(
                "👆 ऊपर सेटिंग्स चुनें और जनरेट करें"
            )
            
            with gr.Accordion("📊 परफॉरमेंस गाइड", open=False):
                gr.Markdown("""
                | क्वालिटी | स्टेप्स | CPU समय | कब इस्तेमाल करें |
                |:---|:---:|:---:|:---|
                | Ultra Fast | 2 | 5-8s | आइडिया टेस्टिंग |
                | Fast | 4 | 10-15s | सोशल मीडिया पोस्ट |
                | Balanced | 6 | 15-25s | ब्लॉग/वेबसाइट |
                | High Quality | 8 | 25-40s | प्रिंट/पोस्टर |
                """)
    
    # ===== इवेंट हैंडलर्स (फिक्स किए हुए) =====
    
    def on_platform_change(choice):
        """प्लेटफॉर्म बदलने पर साइज़ अपडेट करें"""
        w, h = update_size_from_preset(choice)
        return w, h
    
    platform_choice.change(
        fn=on_platform_change,
        inputs=[platform_choice],
        outputs=[custom_width, custom_height]
    )
    
    def on_quality_change(choice):
        """क्वालिटी बदलने पर steps और guidance अपडेट करें"""
        s, g = update_quality_from_preset(choice)
        return s, g
    
    quality_choice.change(
        fn=on_quality_change,
        inputs=[quality_choice],
        outputs=[custom_steps, custom_guidance]
    )
    
    # जनरेट बटन
    generate_btn.click(
        fn=generate_image,
        inputs=[
            prompt, negative_prompt,
            platform_choice, quality_choice,
            custom_width, custom_height,
            custom_steps, custom_guidance,
            seed, enhance_prompt
        ],
        outputs=[output_image, status_text]
    )
    
    # ===== उदाहरण =====
    gr.Markdown("### 📋 तुरंत ट्राई करें")
    
    gr.Examples(
        examples=[
            ["RAW photo, red Ferrari on coastal highway, sunset", "cartoon, anime, blurry", "📱 Instagram Post (Square)", "🚀 Fast (Good)", 1080, 1080, 4, 1.0, 42, True],
            ["cute golden retriever puppy in flower garden", "cartoon, drawing, ugly", "📌 Pinterest Pin", "🎯 Balanced (Better)", 1000, 1500, 6, 1.2, 123, True],
            ["astronaut floating in space, earth background", "cartoon, 3d render", "📺 YouTube Thumbnail", "🚀 Fast (Good)", 1280, 720, 4, 1.0, 456, True],
            ["Indian bride in red lehenga, golden jewelry", "cartoon, illustration, deformed", "📱 Instagram Story", "💎 High Quality (Best)", 1080, 1920, 8, 1.5, 789, True],
        ],
        inputs=[prompt, negative_prompt, platform_choice, quality_choice, custom_width, custom_height, custom_steps, custom_guidance, seed, enhance_prompt],
        label=""
    )

if __name__ == "__main__":
    print("=" * 50)
    print("🚀 AI इमेज जनरेटर - कस्टम साइज़ और क्वालिटी")
    print("=" * 50)
    demo.queue(max_size=5).launch(show_error=True)