Update app.py
Browse files
app.py
CHANGED
|
@@ -11,7 +11,7 @@ from gradio_client import Client
|
|
| 11 |
import concurrent.futures
|
| 12 |
|
| 13 |
# ==========================================
|
| 14 |
-
# 1. API Keys (টোকেন
|
| 15 |
# ==========================================
|
| 16 |
KEYS = {
|
| 17 |
"segmind": "SG_8d03bc9ab924555c",
|
|
@@ -19,8 +19,6 @@ KEYS = {
|
|
| 19 |
"google": "AIzaSyBdEqDB6SFI2uQ-5FBr-cCeRj-dkiv8pFY",
|
| 20 |
"stablehorde": "56kkbwcSPfHIr2YsDkpNDQ",
|
| 21 |
"modelslab": "42zL3I6pH7Mv94jhNf4RGyuKGGT3GoEhfXZv47WwmQsfyhgC8XNttfOpvMKL",
|
| 22 |
-
|
| 23 |
-
# 🔒 টোকেন এখন সরাসরি কোডে নেই, সিক্রেট সেটিংস থেকে আসবে
|
| 24 |
"huggingface": os.environ.get("HF_TOKEN")
|
| 25 |
}
|
| 26 |
|
|
@@ -36,33 +34,33 @@ def get_image_from_url(url):
|
|
| 36 |
# ==========================================
|
| 37 |
def generate_hercai(p, w, h, ar):
|
| 38 |
url = f"https://hercai.onrender.com/v3/text2image?prompt={urllib.parse.quote(p)}"
|
| 39 |
-
res = requests.get(url, headers=HEADERS_DEFAULT, timeout=
|
| 40 |
if res.status_code == 200: return get_image_from_url(res.json().get("url"))
|
| 41 |
raise Exception(f"Hercai Error {res.status_code}")
|
| 42 |
|
| 43 |
def generate_pollinations(p, w, h, ar):
|
| 44 |
url = f"https://image.pollinations.ai/prompt/{urllib.parse.quote(p)}?width={w}&height={h}&nologo=true"
|
| 45 |
-
res = requests.get(url, headers=HEADERS_DEFAULT, timeout=
|
| 46 |
if res.status_code == 200: return Image.open(BytesIO(res.content))
|
| 47 |
raise Exception(f"Pollinations Error {res.status_code}")
|
| 48 |
|
| 49 |
def generate_google_imagen(p, w, h, ar):
|
| 50 |
-
res = requests.post(f"https://generativelanguage.googleapis.com/v1beta/models/imagen-3.0-generate-001:predict?key={KEYS['google']}", json={"instances": [{"prompt": p}]}, timeout=
|
| 51 |
if res.status_code == 200: return Image.open(BytesIO(base64.b64decode(res.json()['predictions'][0]['bytesBase64Encoded'])))
|
| 52 |
raise Exception(f"Google Error {res.status_code}")
|
| 53 |
|
| 54 |
def generate_segmind(p, w, h, ar):
|
| 55 |
-
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=
|
| 56 |
if res.status_code == 200: return Image.open(BytesIO(res.content))
|
| 57 |
raise Exception(f"Segmind Error {res.status_code}")
|
| 58 |
|
| 59 |
def generate_getimg(p, w, h, ar):
|
| 60 |
-
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=
|
| 61 |
if res.status_code == 200: return Image.open(BytesIO(base64.b64decode(res.json()["image"])))
|
| 62 |
raise Exception(f"GetImg Error {res.status_code}")
|
| 63 |
|
| 64 |
def generate_modelslab(p, w, h, ar):
|
| 65 |
-
res = requests.post("https://modelslab.com/api/v6/images/text2img", json={"key": KEYS['modelslab'], "prompt": p, "width": str(w), "height": str(h)}, timeout=
|
| 66 |
if res.status_code == 200 and "output" in res.json(): return get_image_from_url(res.json()["output"][0])
|
| 67 |
raise Exception(f"ModelsLab Error {res.status_code}")
|
| 68 |
|
|
@@ -70,30 +68,19 @@ def generate_stable_horde(p, w, h, ar):
|
|
| 70 |
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)
|
| 71 |
if res.status_code == 202:
|
| 72 |
job_id = res.json()['id']
|
| 73 |
-
for _ in range(
|
| 74 |
time.sleep(2)
|
| 75 |
check = requests.get(f"https://stablehorde.net/api/v2/generate/status/{job_id}", timeout=10)
|
| 76 |
if check.status_code == 200 and check.json().get("done", False): return get_image_from_url(check.json()['generations'][0]['img'])
|
| 77 |
raise Exception("Horde Timeout")
|
| 78 |
|
| 79 |
-
def generate_hf_flux(p, w, h, ar):
|
| 80 |
-
client = Client("black-forest-labs/FLUX.1-schnell")
|
| 81 |
-
res = client.predict(prompt=p, seed=0, randomize_seed=True, width=w, height=h, num_inference_steps=4, api_name="/infer")
|
| 82 |
-
return Image.open(res[0])
|
| 83 |
-
|
| 84 |
-
def generate_hf_sdxl_lightning(p, w, h, ar):
|
| 85 |
-
client = Client("ByteDance/SDXL-Lightning")
|
| 86 |
-
res = client.predict(p, "4-Step", api_name="/generate_image")
|
| 87 |
-
return Image.open(res)
|
| 88 |
-
|
| 89 |
-
def generate_hf_sd3(p, w, h, ar):
|
| 90 |
-
client = Client("stabilityai/stable-diffusion-3.5-large")
|
| 91 |
-
res = client.predict(prompt=p, negative_prompt="", seed=0, randomize_seed=True, width=w, height=h, guidance_scale=4.5, num_inference_steps=40, api_name="/infer")
|
| 92 |
-
return Image.open(res[0])
|
| 93 |
-
|
| 94 |
def generate_hf_api(prompt, model_id, w, h):
|
| 95 |
url = f"https://api-inference.huggingface.co/models/{model_id}"
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
payload = {"inputs": prompt, "parameters": {"width": w, "height": h}}
|
| 98 |
res = requests.post(url, headers=headers, json=payload, timeout=20)
|
| 99 |
|
|
@@ -113,10 +100,7 @@ ALL_APIS = {
|
|
| 113 |
"Segmind (Daily)": generate_segmind,
|
| 114 |
"GetImg AI (Monthly)": generate_getimg,
|
| 115 |
"ModelsLab (Daily)": generate_modelslab,
|
| 116 |
-
"Stable Horde (Unlimited)": generate_stable_horde
|
| 117 |
-
"HF Space: FLUX.1": generate_hf_flux,
|
| 118 |
-
"HF Space: SDXL Light": generate_hf_sdxl_lightning,
|
| 119 |
-
"HF Space: SD3.5": generate_hf_sd3,
|
| 120 |
}
|
| 121 |
|
| 122 |
hf_models_list = [
|
|
@@ -189,7 +173,7 @@ for name, model_id in hf_models_list:
|
|
| 189 |
ALL_APIS[f"HF: {name}"] = make_hf_func(model_id)
|
| 190 |
|
| 191 |
# ==========================================
|
| 192 |
-
# 4. Smart
|
| 193 |
# ==========================================
|
| 194 |
def fetch_api_task(api_name, api_func, prompt, w, h, ar):
|
| 195 |
try:
|
|
@@ -199,6 +183,11 @@ def fetch_api_task(api_name, api_func, prompt, w, h, ar):
|
|
| 199 |
return None, api_name, str(e)
|
| 200 |
|
| 201 |
def generate_image_logic(prompt, style, size, selected_api):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
if not prompt.strip():
|
| 203 |
yield None, "⚠️ **দয়া করে একটি প্রম্পট লিখুন!**"
|
| 204 |
return
|
|
@@ -216,16 +205,17 @@ def generate_image_logic(prompt, style, size, selected_api):
|
|
| 216 |
enhanced_prompt = f"{prompt.strip()}{style_modifiers.get(style, '')}, aspect ratio {ar}"
|
| 217 |
|
| 218 |
if selected_api == "অটোমেটিক (Auto Fallback)":
|
| 219 |
-
yield None, "⏳
|
| 220 |
|
|
|
|
| 221 |
all_api_items = list(ALL_APIS.items())
|
| 222 |
-
selected_batch = random.sample(all_api_items,
|
| 223 |
|
| 224 |
successful_images = []
|
| 225 |
successful_names = []
|
| 226 |
error_logs = []
|
| 227 |
|
| 228 |
-
with concurrent.futures.ThreadPoolExecutor(max_workers=
|
| 229 |
futures = {executor.submit(fetch_api_task, name, func, enhanced_prompt, w, h, ar): name for name, func in selected_batch}
|
| 230 |
|
| 231 |
for future in concurrent.futures.as_completed(futures):
|
|
@@ -241,7 +231,7 @@ def generate_image_logic(prompt, style, size, selected_api):
|
|
| 241 |
yield successful_images, f"✅ **সফল!** {len(successful_images)} টি সার্ভার ছবি বানাতে পেরেছে।\n(উৎস: {source_text})"
|
| 242 |
return
|
| 243 |
|
| 244 |
-
yield None, f"🚫 **দুঃখিত!**
|
| 245 |
|
| 246 |
else:
|
| 247 |
yield None, f"⏳ শুধুমাত্র **{selected_api}**-এ কল করা হচ্ছে..."
|
|
@@ -259,7 +249,7 @@ def generate_image_logic(prompt, style, size, selected_api):
|
|
| 259 |
api_choices = ["অটোমেটিক (Auto Fallback)"] + list(ALL_APIS.keys())
|
| 260 |
|
| 261 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 262 |
-
gr.Markdown("<h1 style='text-align: center;'>🎨 Mega AI Image Generator (
|
| 263 |
|
| 264 |
with gr.Row():
|
| 265 |
with gr.Column(scale=1):
|
|
@@ -283,7 +273,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 283 |
log_box = gr.Markdown("স্ট্যাটাস: অপেক্ষমান...")
|
| 284 |
|
| 285 |
with gr.Column(scale=1):
|
| 286 |
-
image_output = gr.Gallery(label="জেনারেট হওয়া ছবি
|
| 287 |
|
| 288 |
generate_btn.click(
|
| 289 |
fn=generate_image_logic,
|
|
|
|
| 11 |
import concurrent.futures
|
| 12 |
|
| 13 |
# ==========================================
|
| 14 |
+
# 1. API Keys (টোকেন সিক্রেট ভল্ট থেকে আসবে)
|
| 15 |
# ==========================================
|
| 16 |
KEYS = {
|
| 17 |
"segmind": "SG_8d03bc9ab924555c",
|
|
|
|
| 19 |
"google": "AIzaSyBdEqDB6SFI2uQ-5FBr-cCeRj-dkiv8pFY",
|
| 20 |
"stablehorde": "56kkbwcSPfHIr2YsDkpNDQ",
|
| 21 |
"modelslab": "42zL3I6pH7Mv94jhNf4RGyuKGGT3GoEhfXZv47WwmQsfyhgC8XNttfOpvMKL",
|
|
|
|
|
|
|
| 22 |
"huggingface": os.environ.get("HF_TOKEN")
|
| 23 |
}
|
| 24 |
|
|
|
|
| 34 |
# ==========================================
|
| 35 |
def generate_hercai(p, w, h, ar):
|
| 36 |
url = f"https://hercai.onrender.com/v3/text2image?prompt={urllib.parse.quote(p)}"
|
| 37 |
+
res = requests.get(url, headers=HEADERS_DEFAULT, timeout=15)
|
| 38 |
if res.status_code == 200: return get_image_from_url(res.json().get("url"))
|
| 39 |
raise Exception(f"Hercai Error {res.status_code}")
|
| 40 |
|
| 41 |
def generate_pollinations(p, w, h, ar):
|
| 42 |
url = f"https://image.pollinations.ai/prompt/{urllib.parse.quote(p)}?width={w}&height={h}&nologo=true"
|
| 43 |
+
res = requests.get(url, headers=HEADERS_DEFAULT, timeout=15)
|
| 44 |
if res.status_code == 200: return Image.open(BytesIO(res.content))
|
| 45 |
raise Exception(f"Pollinations Error {res.status_code}")
|
| 46 |
|
| 47 |
def generate_google_imagen(p, w, h, ar):
|
| 48 |
+
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)
|
| 49 |
if res.status_code == 200: return Image.open(BytesIO(base64.b64decode(res.json()['predictions'][0]['bytesBase64Encoded'])))
|
| 50 |
raise Exception(f"Google Error {res.status_code}")
|
| 51 |
|
| 52 |
def generate_segmind(p, w, h, ar):
|
| 53 |
+
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)
|
| 54 |
if res.status_code == 200: return Image.open(BytesIO(res.content))
|
| 55 |
raise Exception(f"Segmind Error {res.status_code}")
|
| 56 |
|
| 57 |
def generate_getimg(p, w, h, ar):
|
| 58 |
+
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)
|
| 59 |
if res.status_code == 200: return Image.open(BytesIO(base64.b64decode(res.json()["image"])))
|
| 60 |
raise Exception(f"GetImg Error {res.status_code}")
|
| 61 |
|
| 62 |
def generate_modelslab(p, w, h, ar):
|
| 63 |
+
res = requests.post("https://modelslab.com/api/v6/images/text2img", json={"key": KEYS['modelslab'], "prompt": p, "width": str(w), "height": str(h)}, timeout=15)
|
| 64 |
if res.status_code == 200 and "output" in res.json(): return get_image_from_url(res.json()["output"][0])
|
| 65 |
raise Exception(f"ModelsLab Error {res.status_code}")
|
| 66 |
|
|
|
|
| 68 |
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)
|
| 69 |
if res.status_code == 202:
|
| 70 |
job_id = res.json()['id']
|
| 71 |
+
for _ in range(8):
|
| 72 |
time.sleep(2)
|
| 73 |
check = requests.get(f"https://stablehorde.net/api/v2/generate/status/{job_id}", timeout=10)
|
| 74 |
if check.status_code == 200 and check.json().get("done", False): return get_image_from_url(check.json()['generations'][0]['img'])
|
| 75 |
raise Exception("Horde Timeout")
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
def generate_hf_api(prompt, model_id, w, h):
|
| 78 |
url = f"https://api-inference.huggingface.co/models/{model_id}"
|
| 79 |
+
# টোকেন চেক
|
| 80 |
+
if not KEYS.get('huggingface'):
|
| 81 |
+
raise Exception("Token Missing")
|
| 82 |
+
|
| 83 |
+
headers = {"Authorization": f"Bearer {KEYS['huggingface']}"}
|
| 84 |
payload = {"inputs": prompt, "parameters": {"width": w, "height": h}}
|
| 85 |
res = requests.post(url, headers=headers, json=payload, timeout=20)
|
| 86 |
|
|
|
|
| 100 |
"Segmind (Daily)": generate_segmind,
|
| 101 |
"GetImg AI (Monthly)": generate_getimg,
|
| 102 |
"ModelsLab (Daily)": generate_modelslab,
|
| 103 |
+
"Stable Horde (Unlimited)": generate_stable_horde
|
|
|
|
|
|
|
|
|
|
| 104 |
}
|
| 105 |
|
| 106 |
hf_models_list = [
|
|
|
|
| 173 |
ALL_APIS[f"HF: {name}"] = make_hf_func(model_id)
|
| 174 |
|
| 175 |
# ==========================================
|
| 176 |
+
# 4. Safe Smart Routing Logic (Batch = 3)
|
| 177 |
# ==========================================
|
| 178 |
def fetch_api_task(api_name, api_func, prompt, w, h, ar):
|
| 179 |
try:
|
|
|
|
| 183 |
return None, api_name, str(e)
|
| 184 |
|
| 185 |
def generate_image_logic(prompt, style, size, selected_api):
|
| 186 |
+
# টোকেন চেক: যদি টোকেন না থাকে, তবে ইউজারকে ওয়ার্নিং দেবে
|
| 187 |
+
if not KEYS.get("huggingface"):
|
| 188 |
+
yield None, "⚠️ **Secret Token পাওয়া যায়নি!** দয়া করে Settings > Factory Rebuild এ ক্লিক করুন।"
|
| 189 |
+
return
|
| 190 |
+
|
| 191 |
if not prompt.strip():
|
| 192 |
yield None, "⚠️ **দয়া করে একটি প্রম্পট লিখুন!**"
|
| 193 |
return
|
|
|
|
| 205 |
enhanced_prompt = f"{prompt.strip()}{style_modifiers.get(style, '')}, aspect ratio {ar}"
|
| 206 |
|
| 207 |
if selected_api == "অটোমেটিক (Auto Fallback)":
|
| 208 |
+
yield None, "⏳ নিরাপদভাবে ৩টি র্যান্ডম সার্ভার বেছে নেওয়া হচ্ছে..."
|
| 209 |
|
| 210 |
+
# আইপি ব্লক এড়াতে একসাথে ১০টার বদলে ৩টা সার্ভার বেছে নেবে
|
| 211 |
all_api_items = list(ALL_APIS.items())
|
| 212 |
+
selected_batch = random.sample(all_api_items, 3)
|
| 213 |
|
| 214 |
successful_images = []
|
| 215 |
successful_names = []
|
| 216 |
error_logs = []
|
| 217 |
|
| 218 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
| 219 |
futures = {executor.submit(fetch_api_task, name, func, enhanced_prompt, w, h, ar): name for name, func in selected_batch}
|
| 220 |
|
| 221 |
for future in concurrent.futures.as_completed(futures):
|
|
|
|
| 231 |
yield successful_images, f"✅ **সফল!** {len(successful_images)} টি সার্ভার ছবি বানাতে পেরেছে।\n(উৎস: {source_text})"
|
| 232 |
return
|
| 233 |
|
| 234 |
+
yield None, f"🚫 **দুঃখিত!** সার্ভারগুলো এখন ব্যস্ত। দয়া করে আবার 'Generate Image' এ ক্লিক করুন।"
|
| 235 |
|
| 236 |
else:
|
| 237 |
yield None, f"⏳ শুধুমাত্র **{selected_api}**-এ কল করা হচ্ছে..."
|
|
|
|
| 249 |
api_choices = ["অটোমেটিক (Auto Fallback)"] + list(ALL_APIS.keys())
|
| 250 |
|
| 251 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 252 |
+
gr.Markdown("<h1 style='text-align: center;'>🎨 Mega AI Image Generator (Safe Routing)</h1>")
|
| 253 |
|
| 254 |
with gr.Row():
|
| 255 |
with gr.Column(scale=1):
|
|
|
|
| 273 |
log_box = gr.Markdown("স্ট্যাটাস: অপেক্ষমান...")
|
| 274 |
|
| 275 |
with gr.Column(scale=1):
|
| 276 |
+
image_output = gr.Gallery(label="জেনারেট হওয়া ছবি", columns=2, object_fit="contain", height="auto")
|
| 277 |
|
| 278 |
generate_btn.click(
|
| 279 |
fn=generate_image_logic,
|