Mahendra0160's picture
Update app.py
6f92187 verified
Raw
History Blame Contribute Delete
16.1 kB
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)