you0you22's picture
Update app.py
7431d72 verified
import gradio as gr
import numpy as np
import random
import torch
from diffusers import DiffusionPipeline
from transformers import pipeline as hf_pipeline
# Device setup
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
# Load smaller, faster model for CPU
print("🚀 Loading Stable Diffusion 2-1 (optimized for CPU)")
model_repo_id = "stabilityai/sdxl-turbo"
pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
pipe = pipe.to(device)
# Load Arabic → English translator
print("🌍 Loading Arabic to English Translator")
translator = hf_pipeline("translation", model="Helsinki-NLP/opus-mt-ar-en")
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
# Translation helper
def translate_ar_to_en(text):
if not text.strip():
return text
try:
translated = translator(text)[0]['translation_text']
return translated
except Exception as e:
print("Translation error:", e)
return text
# Inference
def infer(
prompt,
negative_prompt,
seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
progress=gr.Progress(track_tqdm=True),
):
# Simulate daily limit check
if prompt.strip() == "limit_test":
return None, seed, "❌ لقد إنتهى الإستخدام المجاني اليومي\n📆 يمكنك إستكمال إنشاء الصور غدا\n💬 ادعمني، أريد إنشاء مولد صور عربي غير محدود للجمهور العربي"
if randomize_seed:
seed = random.randint(0, MAX_SEED)
# Translate prompt to English
translated_prompt = translate_ar_to_en(prompt)
translated_negative = translate_ar_to_en(negative_prompt)
# Generate image
image = pipe(
prompt=translated_prompt,
negative_prompt=translated_negative,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
width=width,
height=height,
generator=torch.Generator().manual_seed(seed),
).images[0]
return image, seed, ""
# Example prompts
examples = [
"قطة تركب دراجة نارية في الصحراء",
"رائد فضاء يركب حصانًا أخضر",
"كوكب الأرض من الفضاء",
]
# CSS
css = """
#col-container {margin: 0 auto; max-width: 640px; direction: rtl;}
.support-button {margin: 5px; padding: 10px 20px; border: none; border-radius: 5px; width: 100%; font-size: 16px;}
.paypal {background-color: #0070ba; color: white;}
.kofi {background-color: #29abe0; color: white;}
.bank {background-color: #4caf50; color: white;}
#loading-box {text-align: center; font-size: 18px; color: #ff9800; margin-top: 10px;}
"""
with gr.Blocks(css=css) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown("""
## 🧠 🢃مولد الصور العربي بالذكاء الاصطناعي في الأسفل
اكتب وصفًا وسيقوم الذكاء الاصطناعي بإنشاء صورة فريدة بناءً عليه.
---
💖 **أنا أطمح لبناء أول برنامج منشئ الصور عربي بالكامل وغير محدود:**
💖 **كن من أول الداعمين لتصبح عضوا مؤسسا ويكون لك حق استعمال البرنامج لمدة غير محدودة:**
💖 **هل تريد دعمي؟ إليك الطرق المتاحة:**
""")
# Support buttons
with gr.Column():
gr.HTML('<a href="https://www.paypal.com/" target="_blank"><button class="support-button paypal">💸 PayPal - استخدم البريد: touati0youcef@gmail.com</button></a>')
gr.HTML('<a href="https://ko-fi.com/hiho938663" target="_blank"><button class="support-button kofi">☕ Ko-fi - Ko-fi.com/hiho938663 للتبرع</button></a>')
gr.HTML('<a href="https://youcef847.github.io/support-me/" target="_blank"><button class="support-button bank">🏦 حسابي https://youcef847.github.io/support-me/ تفاصيل هنا</button></a>')
with gr.Row():
prompt = gr.Text(
label="الوصف",
show_label=False,
max_lines=1,
placeholder="✏️ اكتب وصف الصورة هنا",
container=False,
)
run_button = gr.Button("🚀 إنشاء", scale=0, variant="primary")
# Loading animation
loading_box = gr.HTML("", elem_id="loading-box")
result = gr.Image(label="النتيجة", show_label=False)
limit_message = gr.Textbox(label="📢 الرسائل", interactive=False)
with gr.Accordion("⚙️ إعدادات متقدمة", open=False):
negative_prompt = gr.Text(
label="الوصف السلبي",
max_lines=1,
placeholder="أدخل وصفًا سلبيًا",
visible=False,
)
seed = gr.Slider(label="البذرة", minimum=0, maximum=MAX_SEED, step=1, value=0)
randomize_seed = gr.Checkbox(label="بذرة عشوائية", value=True)
with gr.Row():
width = gr.Slider(
label="العرض",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32, # multiples of 32 are safest for Stable Diffusion
value=384 # default close to your 250 target, but fully compatible
)
height = gr.Slider(
label="الارتفاع",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=384
)
with gr.Row():
guidance_scale = gr.Slider(
label="مقياس التوجيه",
minimum=0.0,
maximum=10.0,
step=0.1,
value=0.0 # SDXL Turbo works well at 0 for speed
)
num_inference_steps = gr.Slider(
label="عدد خطوات الاستدلال",
minimum=1,
maximum=10, # turbo doesn't need high steps
step=1,
value=2 # fast default
)
gr.Examples(examples=examples, inputs=[prompt])
def show_loading(*args):
return "<div>⏳ جاري إنشاء الصورة، يرجى الانتظار...</div>",
def clear_loading(*args):
return "",
run_button.click(fn=show_loading, inputs=[], outputs=[loading_box]).then(
fn=infer,
inputs=[prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
outputs=[result, seed, limit_message]
).then(fn=clear_loading, inputs=[], outputs=[loading_box])
if __name__ == "__main__":
demo.launch()