File size: 22,282 Bytes
5a02309
 
 
 
c49edd3
9c0aaad
 
5a02309
 
5cc4340
55b69b4
5a02309
 
4359a16
5a02309
 
 
 
 
 
 
689120b
 
9c0aaad
5a02309
 
c60ea5a
 
 
f8e8ea2
c60ea5a
55b69b4
c60ea5a
5a02309
55b69b4
5a02309
c60ea5a
 
4359a16
c60ea5a
689120b
c60ea5a
 
 
4359a16
c60ea5a
689120b
5a02309
2d696d8
4359a16
2d696d8
689120b
c400abe
d7ff2fc
4359a16
d7ff2fc
689120b
5a02309
d7ff2fc
4359a16
d7ff2fc
689120b
5a02309
2d696d8
4359a16
2d696d8
689120b
2cc7bf8
2d696d8
f8e8ea2
2d696d8
 
4359a16
2d696d8
f8e8ea2
2d696d8
55b69b4
c49edd3
2d696d8
c49edd3
689120b
2d696d8
9c0aaad
55b69b4
c4d1a9d
9c0aaad
55b69b4
c60ea5a
689120b
c49edd3
2cc7bf8
55b69b4
2cc7bf8
d7ff2fc
c60ea5a
d7ff2fc
 
 
 
 
4359a16
5cc4340
0286d00
f8e8ea2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7ff2fc
 
 
 
f8e8ea2
 
d7ff2fc
5cc4340
689120b
5cc4340
f8e8ea2
 
 
55b69b4
 
 
f8e8ea2
d7ff2fc
0286d00
5cc4340
0286d00
 
2d696d8
 
 
c400abe
df1365d
c400abe
 
 
df1365d
 
c400abe
df1365d
689120b
5cc4340
689120b
 
 
 
 
 
 
 
 
 
 
9c0aaad
689120b
 
9c0aaad
 
 
55b69b4
2d696d8
689120b
 
f8e8ea2
9c0aaad
 
 
 
 
 
689120b
9c0aaad
 
 
689120b
9c0aaad
55b69b4
689120b
0286d00
689120b
5cc4340
2d696d8
 
5a02309
c400abe
55b69b4
2d696d8
5a02309
9c0aaad
5a02309
 
d7ff2fc
5a02309
2d696d8
93c734f
d7ff2fc
689120b
2d696d8
5a02309
 
5cc4340
df1365d
c400abe
 
 
2d696d8
c400abe
 
 
2d696d8
c400abe
df1365d
5cc4340
d7ff2fc
5cc4340
 
5a02309
93c734f
5a02309
 
689120b
5a02309
 
5cc4340
d7ff2fc
5cc4340
5a02309
 
f8e8ea2
 
5a02309
 
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
import gradio as gr
import requests
import time
import base64
import urllib.parse
import random
import os
from io import BytesIO
from PIL import Image
from gradio_client import Client
import concurrent.futures

# ==========================================
# 1. API Keys (টোকেন সিক্রেট ভল্ট থেকে আসবে)
# ==========================================
KEYS = {
    "segmind": "SG_8d03bc9ab924555c",
    "getimg": "sk_6bdYCHa5p3E3dFJKIFuQI_8788b3203803717ab8980138a9a13625f1b4bc2419322bf1ad5e593a6734add2",
    "google": "AIzaSyBdEqDB6SFI2uQ-5FBr-cCeRj-dkiv8pFY",
    "stablehorde": "56kkbwcSPfHIr2YsDkpNDQ",
    "modelslab": "42zL3I6pH7Mv94jhNf4RGyuKGGT3GoEhfXZv47WwmQsfyhgC8XNttfOpvMKL",
    
    # ⚠️ তোমার Secret এর নাম অবশ্যই HF_TOKEN হতে হবে
    "huggingface": os.environ.get("HF_TOKEN") 
}

HEADERS_DEFAULT = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}

def get_image_from_url(url):
    res = requests.get(url, headers=HEADERS_DEFAULT, timeout=15)
    if res.status_code == 200: return Image.open(BytesIO(res.content))
    raise Exception(f"URL Error {res.status_code}")

# ==========================================
# 2. Core API Functions
# ==========================================
def generate_hercai(p, w, h, ar):
    url = f"https://hercai.onrender.com/v3/text2image?prompt={urllib.parse.quote(p)}"
    res = requests.get(url, headers=HEADERS_DEFAULT, timeout=15)
    if res.status_code == 200: return get_image_from_url(res.json().get("url"))
    raise Exception("Hercai Error")

def generate_pollinations(p, w, h, ar):
    url = f"https://image.pollinations.ai/prompt/{urllib.parse.quote(p)}?width={w}&height={h}&nologo=true"
    res = requests.get(url, headers=HEADERS_DEFAULT, timeout=15)
    if res.status_code == 200: return Image.open(BytesIO(res.content))
    raise Exception("Pollinations Error")

def generate_google_imagen(p, w, h, ar):
    res = requests.post(f"https://generativelanguage.googleapis.com/v1beta/models/imagen-3.0-generate-001:predict?key={KEYS['google']}", json={"instances": [{"prompt": p}]}, timeout=15)
    if res.status_code == 200: return Image.open(BytesIO(base64.b64decode(res.json()['predictions'][0]['bytesBase64Encoded'])))
    raise Exception("Google Error")

def generate_segmind(p, w, h, ar):
    res = requests.post("https://api.segmind.com/v1/sdxl1.0-txt2img", headers={"x-api-key": KEYS['segmind']}, json={"prompt": p, "samples": 1, "width": w, "height": h}, timeout=15)
    if res.status_code == 200: return Image.open(BytesIO(res.content))
    raise Exception("Segmind Error")

def generate_getimg(p, w, h, ar):
    res = requests.post("https://api.getimg.ai/v1/essential/text-to-image", headers={"Authorization": f"Bearer {KEYS['getimg']}"}, json={"prompt": p, "width": w, "height": h}, timeout=15)
    if res.status_code == 200: return Image.open(BytesIO(base64.b64decode(res.json()["image"])))
    raise Exception("GetImg Error")

def generate_modelslab(p, w, h, ar):
    res = requests.post("https://modelslab.com/api/v6/images/text2img", json={"key": KEYS['modelslab'], "prompt": p, "width": str(w), "height": str(h)}, timeout=15)
    if res.status_code == 200 and "output" in res.json(): return get_image_from_url(res.json()["output"][0])
    raise Exception("ModelsLab Error")

def generate_stable_horde(p, w, h, ar):
    res = requests.post("https://stablehorde.net/api/v2/generate/async", headers={"apikey": KEYS['stablehorde']}, json={"prompt": p, "params": {"n": 1, "width": 512, "height": 512}}, timeout=10)
    if res.status_code == 202:
        job_id = res.json()['id']
        for _ in range(8): 
            time.sleep(2)
            check = requests.get(f"https://stablehorde.net/api/v2/generate/status/{job_id}", timeout=10)
            if check.status_code == 200 and check.json().get("done", False): return get_image_from_url(check.json()['generations'][0]['img'])
    raise Exception("Horde Timeout")

def generate_hf_api(prompt, model_id, w, h):
    url = f"https://api-inference.huggingface.co/models/{model_id}"
    headers = {"Authorization": f"Bearer {KEYS['huggingface']}"} if KEYS.get('huggingface') else {}
    payload = {"inputs": prompt, "parameters": {"width": w, "height": h}}
    res = requests.post(url, headers=headers, json=payload, timeout=20)
    
    if res.status_code != 200:
        res = requests.post(url, headers=headers, json={"inputs": prompt}, timeout=20)
        
    if res.status_code == 200: return Image.open(BytesIO(res.content))
    raise Exception(f"HF Rate Limit")

# ==========================================
# 3. MEGA API DICTIONARY (200 Servers)
# ==========================================
ALL_APIS = {
    "Pollinations AI (Unlimited)": generate_pollinations,
    "Hercai AI (Unlimited)": generate_hercai,
    "Google Imagen (Daily)": generate_google_imagen,
    "Segmind (Daily)": generate_segmind,
    "GetImg AI (Monthly)": generate_getimg,
    "ModelsLab (Daily)": generate_modelslab,
    "Stable Horde (Unlimited)": generate_stable_horde
}

hf_models_list = [
    ("DreamShaper XL", "Lykon/dreamshaper-xl-1.0"), ("RealVisXL V4.0", "SG161222/RealVisXL_V4.0"), ("OpenJourney", "prompthero/openjourney"),
    ("Midjourney V4", "prompthero/midjourney-v4-diffusion"), ("Animagine XL 3.1", "cagliostrolab/animagine-xl-3.1"), ("Playground v2.5", "playgroundai/playground-v2.5-1024px-aesthetic"),
    ("Realistic Vision V5", "SG161222/Realistic_Vision_V5.1_noVAE"), ("Anything V5", "stablediffusionapi/anything-v5"), ("Anything V4", "andite/anything-v4.0"),
    ("Anything V3", "Linaqruf/anything-v3.0"), ("Waifu Diffusion", "hakurei/waifu-diffusion"), ("Disney Pixar", "stablediffusionapi/disney-pixar-cartoon"),
    ("CyberRealistic", "stablediffusionapi/cyberrealistic"), ("Absolute Reality", "stablediffusionapi/absolute-reality-v181"), ("Juggernaut XL", "stablediffusionapi/juggernaut-xl-v5"),
    ("SDXL Base 1.0", "stabilityai/stable-diffusion-xl-base-1.0"), ("Stable Diffusion 1.5", "runwayml/stable-diffusion-v1-5"), ("Stable Diffusion 1.4", "CompVis/stable-diffusion-v1-4"),
    ("Stable Diffusion 2.1", "stabilityai/stable-diffusion-2-1"), ("EpicRealism", "emilianJR/epiCRealism"), ("Deliberate", "XpucT/Deliberate"),
    ("MeinaMix V11", "Meina/MeinaMix_V11"), ("DreamShaper 8", "Lykon/dreamshaper-8"), ("GhostMix", "GhostMix/GhostMix-V2.0"),
    ("Pastel-Mix", "andite/pastel-mix"), ("Protogen x3.4", "darkstorm2150/Protogen_x3.4_Official_Release"), ("RevAnimated", "stablediffusionapi/rev-animated"),
    ("Comic Babes", "stablediffusionapi/comic-babes"), ("3D Animation Style", "stablediffusionapi/3d-animation-style"), ("NeverEnding Dream", "stablediffusionapi/neverending-dream"),
    ("Reliberate", "stablediffusionapi/reliberate"), ("Edge of Realism", "stablediffusionapi/edge-of-realism"), ("AOM3", "stablediffusionapi/abyssorangemix3"),
    ("AnyLoRA", "stablediffusionapi/anylora"), ("Counterfeit V3", "stablediffusionapi/counterfeit-v30"), ("Dark Sushi Mix", "stablediffusionapi/dark-sushi-mix"),
    ("Photoreal 2.0", "dreamlike-art/dreamlike-photoreal-2.0"), ("Dreamlike Anime", "dreamlike-art/dreamlike-anime-1.0"), ("Dreamlike Diffusion", "dreamlike-art/dreamlike-diffusion-1.0"),
    ("OpenDalle V1.1", "dataautogpt3/OpenDalleV1.1"), ("Nitro Diffusion", "nitrosocke/Nitro-Diffusion"), ("Arcane Diffusion", "nitrosocke/Arcane-Diffusion"),
    ("Mo-Di Diffusion", "nitrosocke/mo-di-diffusion"), ("Elden Ring", "nitrosocke/elden-ring-diffusion"), ("Spider-Verse", "nitrosocke/spider-verse-diffusion"),
    ("Analog Diffusion", "wavymulder/Analog-Diffusion"), ("PaperCut Style", "Fictiverse/Stable_Diffusion_PaperCut_Model"), ("Studio Ghibli", "nitrosocke/Ghibli-Diffusion"),
    ("Classic Animation", "nitrosocke/classic-anim-diffusion"), ("Redshift 3D", "nitrosocke/redshift-diffusion"), ("Van Gogh Style", "dallinmackay/Van-Gogh-diffusion"),
    ("Tron Legacy", "dallinmackay/Tron-Legacy-diffusion"), ("Trinart V2", "naclbit/trinart_stable_diffusion_v2"), ("Epic Diffusion", "johnslegers/epic-diffusion"),
    ("Photorealistic Fuen", "claudfuen/photorealistic-fuen-v1"), ("RPG Artist", "XpucT/RPG"), ("All 526 Animated", "stablediffusionapi/all-526-animated"),
    ("Am I Real", "stablediffusionapi/am-i-real"), ("Analog Diffusion API", "stablediffusionapi/analog-diffusion"), ("AnyGen", "stablediffusionapi/anygen"),
    ("BG Dream", "stablediffusionapi/bg-dream-dir"), ("CetusMix", "stablediffusionapi/cetusmix"), ("Chilled Re-Generic", "stablediffusionapi/chilled-re-generic"),
    ("Children's 3D", "stablediffusionapi/childrens-stories-3d"), ("Complex Lineart", "stablediffusionapi/complex-lineart"), ("Dark Victorian", "stablediffusionapi/dark-victorian-style"),
    ("Dreamshaper V6", "stablediffusionapi/dreamshaper-v6"), ("DucHaiten AI Art", "stablediffusionapi/duchaiten-aiart"), ("DVArch", "stablediffusionapi/dvarch"),
    ("Fantasy World", "stablediffusionapi/fantasy-world"), ("Grapefruit Anime", "stablediffusionapi/grapefruit"), ("Guweiz Style", "stablediffusionapi/guweiz-style"),
    ("Hassaku Anime", "stablediffusionapi/hassaku-hentai-model"), ("MajicMix Realistic", "stablediffusionapi/majicmix-realistic"), ("MeinaMix V9", "stablediffusionapi/meinamix-v9"),
    ("Meina Unreal", "stablediffusionapi/meina-unreal"), ("Meina Pastel", "stablediffusionapi/meina-pastel"), ("MoXin Chinese Art", "stablediffusionapi/moxin"),
    ("Pastel Mix Stylized", "stablediffusionapi/pastel-mix-stylized-anime"), ("Perfect World", "stablediffusionapi/perfect-world"), ("Portrait Plus", "stablediffusionapi/portrait-plus"),
    ("Realistic Vision V2", "stablediffusionapi/realistic-vision-v20"), ("Realistic Vision V4", "stablediffusionapi/realistic-vision-v40"), ("Beautiful People", "stablediffusionapi/shonin-beautiful-people"),
    ("Synthwave Punk", "stablediffusionapi/synthwave-punk-v2"), ("The Ally's Mix III", "stablediffusionapi/the-allys-mix-iii"), ("ToonYou", "stablediffusionapi/toonyou"),
    ("Vintedois", "stablediffusionapi/vintedois-diffusion"), ("Waifu Diffusion V1.4", "stablediffusionapi/waifu-diffusion-v14"), ("Small SD", "OFA-Sys/small-stable-diffusion-v0"),
    ("Realistic Vision V3", "stablediffusionapi/realistic-vision-v30"), ("Realistic Vision V5.0", "stablediffusionapi/realistic-vision-v50"), ("Dreamshaper V7", "stablediffusionapi/dreamshaper-v7"),
    ("MeinaMix V10", "stablediffusionapi/meinamix-v10"), ("Blood Orange Mix", "stablediffusionapi/blood-orange-mix"), ("Abyss Orange Mix 2", "stablediffusionapi/abyssorangemix2"),
    ("Anything V4.5", "stablediffusionapi/anything-v45"), ("Anything V5 Ink", "stablediffusionapi/anything-v5-ink"), ("AZ Ovya CG Art", "stablediffusionapi/a-z-ovya-cg-art"),
    ("Art Diffusion", "stablediffusionapi/art-diffusion"), ("Asian Model", "stablediffusionapi/asian-model"), ("Beautiful Realistic Asian", "stablediffusionapi/beautiful-realistic-asian"),
    ("Chillout App", "stablediffusionapi/chillout-app-factory"), ("ChilloutMix", "stablediffusionapi/chilloutmix"), ("ChilloutMix Ni", "stablediffusionapi/chilloutmix-ni"),
    ("Cosplay Mix", "stablediffusionapi/cosplay-mix"), ("Cyberpunk Anime 2", "stablediffusionapi/cyberpunk-anime"), ("Dark Sushi 2.5D", "stablediffusionapi/dark-sushi-25d"),
    ("Deliberate V2", "stablediffusionapi/deliberate-v2"), ("Deliberate V3", "stablediffusionapi/deliberate-v3"), ("Disney Pixar B", "stablediffusionapi/disney-pixar-cartoon-b"),
    ("EpicRealism Natural", "stablediffusionapi/epicrealism-natural"), ("Fantasy Mix", "stablediffusionapi/fantasy-mix"), ("Flat 2D Animerge", "stablediffusionapi/flat-2d-animerge"),
    ("Galaxy Time Machine", "stablediffusionapi/galaxy-time-machine"), ("GhostMix V1.2", "stablediffusionapi/ghostmix-v12"), ("Hesemix", "stablediffusionapi/hesemix"),
    ("ICBINP", "stablediffusionapi/icbinp"), ("ICBINP Relapse", "stablediffusionapi/icbinp-relapse"), ("Illuminati", "stablediffusionapi/illuminati-diffusion"),
    ("Korean 2.5D", "stablediffusionapi/korean-25d"), ("Liberty", "stablediffusionapi/liberty"), ("Lyriel", "stablediffusionapi/lyriel"),
    ("MajicMix Fantasy", "stablediffusionapi/majicmix-fantasy"), ("MajicMix Sombre", "stablediffusionapi/majicmix-sombre"), ("Meina Alter", "stablediffusionapi/meina-alter"),
    ("Meina Unreal V4", "stablediffusionapi/meina-unreal-v4"), ("Mix Pro V4", "stablediffusionapi/mix-pro-v4"), ("NeverEnding Dream NED", "stablediffusionapi/neverending-dream-ned"),
    ("OpenJourney V4", "stablediffusionapi/openjourney-v4"), ("Perfect World V4", "stablediffusionapi/perfect-world-v4"), ("ReV Animated V1.2", "stablediffusionapi/rev-animated-v12"),
    ("RPG V4", "stablediffusionapi/rpg-v4"), ("Samdoesarts", "stablediffusionapi/samdoesarts"), ("Shonin Beautiful 2", "stablediffusionapi/shonin-beautiful-people"),
    ("Something V2", "stablediffusionapi/something-v2"), ("TMND Mix", "stablediffusionapi/tmnd-mix"), ("ToonYou Beta", "stablediffusionapi/toonyou-beta"),
    ("Yohan Diffusion", "stablediffusionapi/yohan-diffusion"), ("YungZ Anime", "stablediffusionapi/yungz-anime"), ("Anime Pastel Dream", "Lykon/anime-pastel-dream"),
    ("Anyhentai", "stablediffusionapi/anyhentai"), ("AOM3A3", "stablediffusionapi/abyssorangemix3a3"), ("CamelliaMix", "stablediffusionapi/camelliamix"),
    ("Cardos Anime", "stablediffusionapi/cardos-anime"), ("CetusMix Whimsical", "stablediffusionapi/cetusmix-whimsical"), ("ColorBox", "stablediffusionapi/colorbox"),
    ("Counterfeit V2", "stablediffusionapi/counterfeit-v20"), ("CuteYukiMix", "stablediffusionapi/cuteyukimix"), ("Darkest Anime", "stablediffusionapi/darkest-anime"),
    ("Dreamlike Photoreal", "dreamlike-art/dreamlike-photoreal-1.0"), ("Eimis Anime Models", "stablediffusionapi/eimis-anime-models"), ("Elegance", "stablediffusionapi/elegance"),
    ("EpiCRealism Pure", "stablediffusionapi/epicrealism-pure"), ("Ether Real Mix", "stablediffusionapi/ether-real-mix"), ("FaceBomb", "stablediffusionapi/facebomb"),
    ("Galena", "stablediffusionapi/galena"), ("Ghibli Background", "stablediffusionapi/ghibli-background"), ("HassanBlend", "stablediffusionapi/hassanblend"),
    ("Hentai Diffusion", "stablediffusionapi/hentai-diffusion"), ("KawaMix", "stablediffusionapi/kawamix"), ("Ligne Claire", "stablediffusionapi/ligne-claire"),
    ("Lumina", "stablediffusionapi/lumina"), ("Magical Mix", "stablediffusionapi/magical-mix"), ("MechaMix", "stablediffusionapi/mechamix"),
    ("Midnight Mixer", "stablediffusionapi/midnight-mixer"), ("Mix Pro V3", "stablediffusionapi/mix-pro-v3"), ("Niji Journey", "stablediffusionapi/niji-journey"),
    ("OnlyAnime", "stablediffusionapi/onlyanime"), ("Pastel Boys", "stablediffusionapi/pastel-boys"), ("Pixar Style", "stablediffusionapi/pixar-style"),
    ("Realism Engine", "stablediffusionapi/realism-engine"), ("Retro Anime", "stablediffusionapi/retro-anime"), ("SakuraMix", "stablediffusionapi/sakuramix"),
    ("Sci-Fi Anime", "stablediffusionapi/sci-fi-anime"), ("Smooth Anime", "stablediffusionapi/smooth-anime"), ("Steampunk Anime", "stablediffusionapi/steampunk-anime"),
    ("Vaporwave", "stablediffusionapi/vaporwave"), ("Vintage Anime", "stablediffusionapi/vintage-anime"), ("Watercolor Anime", "stablediffusionapi/watercolor-anime")
]

def make_hf_func(model_id):
    return lambda p, w, h, ar: generate_hf_api(p, model_id, w, h)

for name, model_id in hf_models_list:
    ALL_APIS[f"HF: {name}"] = make_hf_func(model_id)

# ==========================================
# 4. GUARANTEED Routing Logic (100% Works)
# ==========================================
def fetch_api_task(api_name, api_func, prompt, w, h, ar):
    try:
        img = api_func(prompt, w, h, ar)
        return img, api_name, None
    except Exception as e:
        return None, api_name, str(e)

def generate_image_logic(prompt, style, size, selected_api):
    if not prompt.strip():
        yield None, "⚠️ **দয়া করে একটি প্রম্পট লিখুন!**"
        return

    if size == "ল্যান্ডস্কেপ (16:9) - YouTube": w, h, ar = 1024, 576, "16:9"
    elif size == "পোর্ট্রেট (9:16) - TikTok": w, h, ar = 576, 1024, "9:16"
    else: w, h, ar = 1024, 1024, "1:1"

    style_modifiers = {
        "ফটোরিয়ালিস্টিক (Photorealistic)": ", ultra realistic, highly detailed, photorealistic, 8k resolution, raw photo, masterpiece, soft cinematic lighting",
        "এনিমে (Anime)": ", high quality anime style, studio ghibli, masterpiece, vibrant colors, detailed shading",
        "থ্রিডি আর্ট (3D)": ", 3d render, unreal engine 5, octane render, beautiful 3d masterpiece",
        "ডিফল্ট (Default)": ""
    }
    enhanced_prompt = f"{prompt.strip()}{style_modifiers.get(style, '')}, aspect ratio {ar}"

    # গ্যারান্টিড অটোমেটিক মোড
    if selected_api == "অটোমেটিক (Auto Fallback)":
        yield None, "⏳ গ্যারান্টিড আনলিমিটেড সার্ভারের সাথে কানেক্ট করা হচ্ছে..."
        
        # ম্যাজিক ট্রিক: সব সময় আনলিমিটেড ফ্রি সার্ভারগুলো লিস্টে থাকবেই
        guaranteed_batch = [
            ("Pollinations AI (Unlimited)", ALL_APIS["Pollinations AI (Unlimited)"]),
            ("Hercai AI (Unlimited)", ALL_APIS["Hercai AI (Unlimited)"])
        ]
        
        # আর সাথে ২০০টার মধ্যে থেকে যেকোনো ২টা HF সার্ভার লটারি করে নেবে
        hf_only_items = [item for item in ALL_APIS.items() if "HF:" in item[0]]
        random_hf_batch = random.sample(hf_only_items, 2)
        
        # মোট ৪টা সার্ভারে একসাথে রিকোয়েস্ট যাবে (এর মধ্যে ২টা ১০০% ফ্রি, তাই ছবি আসবেই)
        final_test_batch = guaranteed_batch + random_hf_batch
        
        successful_images = []
        successful_names = []
        error_logs = []
        
        with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
            futures = {executor.submit(fetch_api_task, name, func, enhanced_prompt, w, h, ar): name for name, func in final_test_batch}
            
            for future in concurrent.futures.as_completed(futures):
                img, name, err = future.result()
                if img:
                    successful_images.append(img)
                    successful_names.append(name)
                else:
                    error_logs.append(f"{name[:10]}")
        
        if successful_images:
            source_text = ", ".join(successful_names)
            yield successful_images, f"✅ **সফল!** ছবি তৈরি হয়েছে।\n(উৎস: {source_text})"
            return 
            
        yield None, f"🚫 **নেটওয়ার্ক সমস্যা!** দয়া করে আবার চেষ্টা করুন। লগ: {error_logs}"

    # ম্যানুয়াল মোড
    else:
        yield None, f"⏳ শুধুমাত্র **{selected_api}**-এ কল করা হচ্ছে..."
        api_func = ALL_APIS[selected_api]
        try:
            image = api_func(enhanced_prompt, w, h, ar)
            if image: yield [image], f"✅ **সফল!** আপনি ম্যানুয়ালি {selected_api} ব্যবহার করেছেন।"
            else: yield None, f"❌ **দুঃখিত!** {selected_api} বর্তমানে ডাউন।"
        except Exception as e:
            yield None, f"❌ **ব্যর্থ!** কোটা শেষ বা সার্ভার ডাউন। অন্য একটি ট্রাই করুন।"

# ==========================================
# 5. Clean Gradio Web UI
# ==========================================
api_choices = ["অটোমেটিক (Auto Fallback)"] + list(ALL_APIS.keys())

with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("<h1 style='text-align: center;'>🎨 Mega AI Image Generator (Guaranteed Routing)</h1>")
    
    with gr.Row():
        with gr.Column(scale=1):
            prompt_input = gr.Textbox(label="ইমেজের বর্ণনা লিখুন (Prompt)", placeholder="A highly detailed futuristic city...", lines=3)
            
            with gr.Row():
                style_input = gr.Dropdown(
                    choices=["ফটোরিয়ালিস্টিক (Photorealistic)", "এনিমে (Anime)", "থ্রিডি আর্ট (3D)", "ডিফল্ট (Default)"],
                    label="ছবির স্টাইল (Style)", value="ফটোরিয়ালিস্টিক (Photorealistic)"
                )
                size_input = gr.Dropdown(
                    choices=["স্কয়ার (1:1) - Instagram", "ল্যান্ডস্কেপ (16:9) - YouTube", "পোর্ট্রেট (9:16) - TikTok"],
                    label="ছবির সাইজ (Size)", value="স্কয়ার (1:1) - Instagram"
                )
            
            api_selector = gr.Dropdown(
                choices=api_choices, label="সার্ভার সিলেক্ট করুন (ডিফল্ট: অটোমেটিক)", value="অটোমেটিক (Auto Fallback)", interactive=True
            )
            
            generate_btn = gr.Button("Generate Image", variant="primary")
            log_box = gr.Markdown("স্ট্যাটাস: অপেক্ষমান...")
        
        with gr.Column(scale=1):
            image_output = gr.Gallery(label="জেনারেট হওয়া ছবি (একাধিক হতে পারে)", columns=2, object_fit="contain", height="auto")

    generate_btn.click(
        fn=generate_image_logic,
        inputs=[prompt_input, style_input, size_input, api_selector],
        outputs=[image_output, log_box]
    )

demo.queue(max_size=50)

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)