tmblack's picture
Update app.py
3ac30f8 verified
raw
history blame
8.24 kB
import gradio as gr
import re
import os
import requests
import uuid
import base64
import traceback
from share_btn import community_icon_html, loading_icon_html, share_js
# সুরক্ষা ফিল্টারের জন্য ওয়ার্ড লিস্ট লোড করুন
try:
word_list_url = "https://huggingface.co/spaces/stabilityai/stable-diffusion/raw/main/list.txt"
response = requests.get(word_list_url, timeout=10)
response.raise_for_status()
word_list = response.text.splitlines()
print(f"সফলভাবে {len(word_list)} টি ফিল্টার শব্দ লোড হয়েছে")
except Exception as e:
print(f"ওয়ার্ড লিস্ট লোড করতে ব্যর্থ: {str(e)}")
word_list = [] # ফিল্টার শব্দ লোড না হলে খালি লিস্ট ব্যবহার করুন
def infer(prompt, negative, scale):
# সুরক্ষা ফিল্টার চেক
for filter_word in word_list:
if re.search(rf"\b{filter_word}\b", prompt, re.IGNORECASE):
print(f"অনুপযুক্ত শব্দ সনাক্ত হয়েছে: {filter_word}")
print(f"প্রম্পট: {prompt}")
raise gr.Error("অনিরাপদ কন্টেন্ট পাওয়া গেছে! অন্য প্রম্পট ব্যবহার করুন।")
# ব্যাকএন্ড URL চেক
url = os.getenv('JAX_BACKEND_URL')
if not url:
print("ব্যাকএন্ড URL সেট করা নেই!")
raise gr.Error("ব্যাকএন্ড সার্ভার কনফিগার করা নেই।")
print(f"ব্যাকএন্ড URL: {url}")
print(f"প্রম্পট: {prompt}")
print(f"নেগেটিভ: {negative}")
print(f"স্কেল: {scale}")
# ব্যাকএন্ডে রিকোয়েস্ট পাঠান
try:
payload = {'prompt': prompt, 'negative_prompt': negative, 'guidance_scale': scale}
response = requests.post(url, json=payload, timeout=120)
response.raise_for_status()
response_data = response.json()
# ইমেজ প্রসেসিং
images = []
for img_data in response_data["images"]:
file_path = f"{uuid.uuid4()}.jpg"
with open(file_path, "wb") as f:
f.write(base64.b64decode(img_data))
images.append(file_path)
print(f"{len(images)} টি ইমেজ জেনারেট হয়েছে")
return images
except requests.exceptions.RequestException as e:
error_msg = f"ব্যাকএন্ডে সংযোগ ব্যর্থ: {str(e)}"
print(error_msg)
raise gr.Error(error_msg)
except (KeyError, ValueError) as e:
error_msg = f"ব্যাকএন্ড থেকে ভুল রেসপন্স: {str(e)}"
print(error_msg)
print(f"রেসপন্স: {response.text[:500]}...")
raise gr.Error("ইমেজ জেনারেট করতে ব্যর্থ। আবার চেষ্টা করুন।")
except Exception as e:
error_msg = f"অপ্রত্যাশিত ত্রুটি: {str(e)}"
traceback.print_exc()
raise gr.Error(error_msg)
# UI স্টাইলিং
css = """
.gradio-container {
max-width: 768px !important;
font-family: 'IBM Plex Sans', sans-serif;
}
.gr-button {
color: white !important;
background: black !important;
}
input[type='range'] {
accent-color: black;
}
#gallery {
min-height: 22rem;
margin-bottom: 15px;
border-radius: .5rem !important;
}
#share-btn-container {
display: flex;
background-color: #000000;
justify-content: center;
align-items: center;
border-radius: 9999px !important;
width: 13rem;
margin-top: 10px;
margin-left: auto;
}
.footer {
margin: 35px 0;
text-align: center;
border-top: 1px solid #e5e5e5;
}
.animate-spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
"""
# উদাহরণ প্রম্পট
examples = [
['একটি সুউচ্চ তুষারাবৃত পর্বতের চূড়ায় ছোট কাঠের কুটির', 'নিম্ন গুণগতমান, অস্পষ্ট', 9],
['ভবিষ্যতের নগরীতে উড়ন্ত গাড়ি', 'মানুষ, বিকৃত', 9],
['সমুদ্রের নীচে সূর্যাস্ত দৃশ্য', 'টেক্সট, লোগো', 9],
['ফুলের বাগানে বসে থাকা একটি সিংহ', 'রিয়েলিস্টিক, ফটো', 9],
['কাচের গম্বুজের ভিতর মহাকাশ স্টেশন', 'অন্ধকার, ভয়ঙ্কর', 9]
]
# Gradio ব্লক তৈরি
with gr.Blocks(css=css) as block:
# হেডার
gr.HTML("""
<div style="text-align: center;">
<h1 style="font-weight: 900; margin: 10px 0;">
Stable Diffusion 2.1 - বাংলা
</h1>
<p>
টেক্সট থেকে ইমেজ জেনারেটর। আপনার মনের ছবি লিখুন, AI এটা বানিয়ে দেবে!
</p>
</div>
""")
# ইনপুট সেকশন
with gr.Row():
with gr.Column(scale=3):
prompt_input = gr.Textbox(
label="প্রম্পট লিখুন",
placeholder="আপনার ইচ্ছামত ছবির বর্ণনা লিখুন...",
lines=2
)
negative_input = gr.Textbox(
label="এড়াতে চান এমন বিষয়",
placeholder="যেসব বিষয় ছবিতে দেখতে চান না...",
lines=1
)
with gr.Column(scale=1, min_width=150):
generate_btn = gr.Button("ইমেজ তৈরি করুন", variant="primary")
# আউটপুট গ্যালারী
gallery = gr.Gallery(
label="জেনারেটেড ইমেজসমূহ",
columns=[2],
height="auto",
preview=True
)
# এডভান্সড সেটিংস
with gr.Accordion("উন্নত সেটিংস", open=False):
scale_slider = gr.Slider(
label="গাইডেন্স স্কেল",
minimum=0, maximum=20, value=9, step=0.1
)
# শেয়ার বাটন
with gr.Group():
gr.HTML(community_icon_html)
gr.HTML(loading_icon_html)
share_btn = gr.Button("কমিউনিটিতে শেয়ার করুন")
# উদাহরণ
gr.Examples(
examples=examples,
inputs=[prompt_input, negative_input, scale_slider],
outputs=gallery,
fn=infer,
cache_examples=False
)
# ইভেন্ট হ্যান্ডলার
prompt_input.submit(
fn=infer,
inputs=[prompt_input, negative_input, scale_slider],
outputs=gallery
)
generate_btn.click(
fn=infer,
inputs=[prompt_input, negative_input, scale_slider],
outputs=gallery,
concurrency_limit=3
)
share_btn.click(None, [], [], js=share_js)
# ফুটার
gr.HTML("""
<div class="footer">
<p>
Powered by <a href="https://huggingface.co/stabilityai">StabilityAI</a>
and <a href="https://huggingface.co/spaces">Hugging Face Spaces</a>
</p>
</div>
""")
# অ্যাপ্লিকেশন চালু করুন
block.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True,
debug=True
)