File size: 7,056 Bytes
a11ae15
 
 
 
cb4c95e
 
a11ae15
cb4c95e
a11ae15
 
cb4c95e
 
 
33d5616
a11ae15
 
 
cb4c95e
 
 
862fb75
a11ae15
 
 
cb4c95e
862fb75
cb4c95e
 
862fb75
cb4c95e
 
862fb75
cb4c95e
 
862fb75
cb4c95e
a11ae15
 
 
 
 
 
 
 
 
 
 
cb4c95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
862fb75
 
 
cb4c95e
862fb75
 
cb4c95e
862fb75
cb4c95e
 
 
 
 
 
862fb75
a11ae15
cb4c95e
a11ae15
 
7431d72
cb4c95e
 
 
 
 
 
 
 
 
 
1483983
 
cb4c95e
a11ae15
862fb75
 
 
 
cb4c95e
862fb75
 
cb4c95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a11ae15
33d5616
 
709a519
33d5616
 
709a519
33d5616
 
 
709a519
33d5616
 
709a519
33d5616
cb4c95e
a11ae15
33d5616
 
 
 
 
 
 
 
 
 
 
 
 
 
a11ae15
 
 
cb4c95e
 
 
 
 
 
 
a11ae15
cb4c95e
 
 
a11ae15
 
 
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
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()