alomari7 commited on
Commit
120deb9
·
verified ·
1 Parent(s): 0cdd2b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -134
app.py CHANGED
@@ -5,50 +5,69 @@ import numpy as np
5
  import random
6
  import torch
7
  from diffusers import DiffusionPipeline
 
8
 
9
- # --- 1. إعداد النموذج والجهاز ---
10
 
11
- # التحقق من وجود GPU وتحديد نوع البيانات
12
- device = "cuda" if torch.cuda.is_available() else "cpu"
13
- torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
14
 
 
15
  # هام: استبدل "YourUsername/Takween-v1" بالمعرف الخاص بنموذجك الذي رفعته على Hugging Face
16
- MODEL_ID = "YourUsername/Takween-v1"
17
  BASE_MODEL_ID = "runwayml/stable-diffusion-v1-5"
18
 
19
- # تحميل النموذج مع خطة بديلة
20
- try:
21
- pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch_dtype)
22
- print(f"✅ Trained model '{MODEL_ID}' loaded successfully from the Hub.")
23
- except Exception as e:
24
- print(f"❌ Could not load trained model '{MODEL_ID}'. Loading base model. Error: {e}")
25
- pipe = DiffusionPipeline.
26
- from_pretrained(BASE_MODEL_ID, torch_dtype=torch_dtype)
27
-
28
- pipe = pipe.to(device)
29
-
30
- # تحديد أقصى قيمة للبذرة العشوائية
31
  MAX_SEED = np.iinfo(np.int32).max
32
 
33
- # --- 2. دالة توليد الصور ---
34
-
35
- def infer(
36
- prompt,
37
- negative_prompt,
38
- seed,
39
- randomize_seed,
40
- guidance_scale,
41
- num_inference_steps,
42
- progress=gr.Progress(track_tqdm=True),
43
- ):
44
- """
45
- تستقبل هذه الدالة المدخلات من الواجهة وتقوم بتوليد الصورة.
46
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  if randomize_seed:
48
  seed = random.randint(0, MAX_SEED)
49
-
50
- generator = torch.Generator(device=device).manual_seed(seed)
51
-
 
 
 
 
 
 
 
52
  image = pipe(
53
  prompt=prompt,
54
  negative_prompt=negative_prompt,
@@ -56,110 +75,73 @@ def infer(
56
  num_inference_steps=int(num_inference_steps),
57
  generator=generator,
58
  ).images[0]
59
-
60
- # إرجاع الصورة والبذرة المستخدمة لعرضها في الواجهة
61
- return image, seed
62
-
63
-
64
- # --- 3. تصميم واجهة Gradio ---
65
-
66
- # أمثلة خاصة بمشروع تكوين
67
- examples = [
68
- "A filled red circle with a black border",
69
- "An outline blue triangle positioned to the left of a yellow square",
70
- "A green star overlapping a purple rectangle",
71
- ]
72
-
73
- # تنسيق CSS بسيط لتوسيط الواجهة
74
- css = """
75
- #col-container {
76
- margin: 0 auto;
77
- max-width: 700px;
78
- }
79
- """
80
-
81
- # بناء الواجهة باستخدام gr.Blocks
82
- with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
83
- with gr.Column(elem_id="col-container"):
84
- # العنوان الرئيسي
85
- gr.Markdown("# مشروع تكوين (Takween Project)")
86
- gr.Markdown("#### نموذج متخصص في تحويل الأوصاف النصية إلى صور هندسية دقيقة.")
87
-
88
- # صف الإدخال الرئيسي وزر التش��يل
89
- with gr.Row():
90
- prompt = gr.Text(
91
- label="أدخل الوصف النصي هنا (Prompt)",
92
- show_label=False,
93
- max_lines=1,
94
- placeholder="دائرة حمراء ممتلئة على خلفية زرقاء...",
95
- container=False,
 
 
 
 
96
  )
97
- run_button = gr.Button("تكوين", scale=0, variant="primary")
98
-
99
- # عرض الصورة الناتجة
100
- result_image = gr.Image(label="الصورة المولدة", show_label=False)
101
 
102
- # قسم الإعدادات المتقدمة
103
- with gr.Accordion("الإعدادات المتقدمة (Advanced Settings)", open=False):
104
- negative_prompt = gr.Text(
105
- label="الوصف السلبي (Negative Prompt)",
106
- max_lines=1,
107
- placeholder="أدخل ما لا ترغب في رؤيته في الصورة",
108
- )
109
-
110
- with gr.Row():
111
- seed = gr.Slider(
112
- label="البذرة (Seed)",
113
- minimum=0,
114
- maximum=MAX_SEED,
115
- step=1,
116
- value=0,
117
- )
118
- randomize_seed = gr.Checkbox(label="بذرة عشوائية", value=True)
119
-
120
- with gr.Row():
121
- guidance_scale = gr.Slider(
122
- label="مقياس التوجيه (Guidance Scale)",
123
- minimum=0.0,
124
- maximum=20.0,
125
- step=0.1,
126
- value=7.5, # قيمة مثالية لنموذج SD v1.5
127
- )
128
- num_inference_steps = gr.Slider(
129
- label="عدد خطوات التوليد",
130
- minimum=1,
131
- maximum=100,
132
- step=1,
133
- value=30, # قيمة جيدة ومتوازنة
134
- )
135
-
136
- # عرض أمثلة جاهزة
137
- gr.Examples(examples=examples, inputs=[prompt])
138
-
139
- # قسم حقوق الملكية
140
- gr.Markdown(
141
- """
142
- <div style='text-align: center; font-size: 12px; color: grey;'>
143
- <p>© 2025 مشروع تكوين | تطوير: أسامة سعيد وطارق العمري. جميع الحقوق محفوظة.</p>
144
- </div>
145
- """
146
- )
147
-
148
- # ربط المدخلات والمخرجات بالدالة
149
- gr.on(
150
- triggers=[run_button.click, prompt.submit],
151
  fn=infer,
152
- inputs=[
153
- prompt,
154
- negative_prompt,
155
- seed,
156
- randomize_seed,
157
- guidance_scale,
158
- num_inference_steps,
159
- ],
160
- outputs=[result_image, seed],
161
  )
162
 
163
- # لتشغيل الواجهة محلياً
164
  if __name__ == "__main__":
165
  demo.launch()
 
5
  import random
6
  import torch
7
  from diffusers import DiffusionPipeline
8
+ import time
9
 
10
+ # --- 1. الإعدادات والثوابت ---
11
 
12
+ # تحديد الجهاز ونوع البيانات
13
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
14
+ DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
15
 
16
+ # معرفات النماذج
17
  # هام: استبدل "YourUsername/Takween-v1" بالمعرف الخاص بنموذجك الذي رفعته على Hugging Face
18
+ MODEL_ID = "YourUsername/Takween-v1"
19
  BASE_MODEL_ID = "runwayml/stable-diffusion-v1-5"
20
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  MAX_SEED = np.iinfo(np.int32).max
22
 
23
+ # شعار المشروع (SVG مدمج)
24
+ LOGO_SVG = """
25
+ <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
26
+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z"></path>
27
+ <path d="M7 7h10v2H7z"></path>
28
+ <path d="M12 7v10"></path>
29
+ </svg>
30
+ """
31
+
32
+ # --- 2. تحميل النموذج ---
33
+ try:
34
+ pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=DTYPE, safety_checker=None)
35
+ print(f"✅ Trained model '{MODEL_ID}' loaded successfully.")
36
+ except Exception:
37
+ print(f"❌ Could not load trained model '{MODEL_ID}'. Loading base model.")
38
+ pipe = DiffusionPipeline.from_pretrained(BASE_MODEL_ID, torch_dtype=DTYPE, safety_checker=None)
39
+
40
+ pipe = pipe.to(DEVICE)
41
+
42
+ # --- 3. تصميم الثيم الاحترافي ---
43
+ theme = gr.themes.Base(
44
+ primary_hue=gr.themes.colors.purple,
45
+ secondary_hue=gr.themes.colors.neutral,
46
+ font=[gr.themes.GoogleFont("IBM Plex Sans"), "system-ui", "sans-serif"],
47
+ ).set(
48
+ body_background_fill="*neutral_50",
49
+ block_background_fill="white",
50
+ block_border_width="1px",
51
+ block_shadow="*shadow_drop_lg",
52
+ button_shadow="*shadow_push",
53
+ button_primary_background_fill="*primary_500",
54
+ button_primary_background_fill_hover="*primary_600",
55
+ )
56
+
57
+ # --- 4. دالة التوليد مع تحديثات الواجهة ---
58
+ def infer(prompt, negative_prompt, guidance_scale, num_inference_steps, seed, randomize_seed):
59
  if randomize_seed:
60
  seed = random.randint(0, MAX_SEED)
61
+
62
+ generator = torch.Generator(device=DEVICE).manual_seed(seed)
63
+
64
+ # تحديث الواجهة لإظهار حالة التحميل
65
+ yield {
66
+ output_image: gr.update(value=None, interactive=False, visible=True),
67
+ run_button: gr.update(interactive=False, value="...جاري التكوين"),
68
+ }
69
+
70
+ # توليد الصورة
71
  image = pipe(
72
  prompt=prompt,
73
  negative_prompt=negative_prompt,
 
75
  num_inference_steps=int(num_inference_steps),
76
  generator=generator,
77
  ).images[0]
78
+
79
+ # تحديث الواجهة بالنتائج النهائية
80
+ yield {
81
+ output_image: gr.update(value=image, interactive=True),
82
+ output_seed: gr.update(value=seed),
83
+ run_button: gr.update(interactive=True, value="كوّن مرة أخرى"),
84
+ }
85
+
86
+
87
+ # --- 5. بناء الواجهة الاحترافية ---
88
+ with gr.Blocks(theme=theme, css="#footer {text-align: center;}") as demo:
89
+ # رأس الصفحة (Header)
90
+ with gr.Row():
91
+ gr.HTML(f"<div style='display: flex; align-items: center; gap: 12px;'>{LOGO_SVG}<h1>مشروع تكوين</h1></div>")
92
+
93
+ gr.Markdown("#### نموذج متخصص في تحويل الأوصاف النصية إلى صور هندسية دقيقة.")
94
+ gr.HTML("<hr>")
95
+
96
+ # الهيكل الرئيسي (عمودين)
97
+ with gr.Row():
98
+ # العمود الأيسر: الإعدادات
99
+ with gr.Column(scale=1):
100
+ prompt = gr.Textbox(label="الوصف (Prompt)", placeholder=" دائرة حمراء بحدود سوداء سميكة...", lines=3)
101
+ negative_prompt = gr.Textbox(label="الوصف السلبي (Negative Prompt)", placeholder=" جودة منخفضة، ضبابية، تشوه...")
102
+
103
+ with gr.Accordion("الإعدادات المتقدمة", open=False):
104
+ guidance_scale = gr.Slider(label=قياس التوجيه", minimum=1.0, maximum=20.0, value=7.5, step=0.1)
105
+ num_inference_steps = gr.Slider(label="عدد الخطوات", minimum=10, maximum=100, value=30, step=1)
106
+ with gr.Row():
107
+ seed = gr.Number(label="البذرة (Seed)", value=0, precision=0)
108
+ randomize_seed = gr.Checkbox(label="عشوائي", value=True)
109
+
110
+ run_button = gr.Button("كوّن الصورة", variant="primary")
111
+
112
+ gr.Examples(
113
+ examples=[
114
+ "A filled red circle with a thick black border",
115
+ "An outline blue triangle positioned to the left of a yellow square",
116
+ "A green star overlapping a purple rectangle",
117
+ ],
118
+ inputs=[prompt]
119
  )
 
 
 
 
120
 
121
+ # العمود الأيمن: النتائج
122
+ with gr.Column(scale=2):
123
+ output_image = gr.Image(label="الصورة المولّدة", interactive=False, height=512)
124
+ output_seed = gr.Textbox(label="البذرة المستخدمة (Seed)", interactive=False)
125
+
126
+ # تذييل الصفح�� (Footer)
127
+ gr.HTML("<hr>")
128
+ with gr.Accordion("فريق العمل والشكر والتقدير", open=False):
129
+ gr.Markdown("""
130
+ <div style='text-align: right; direction: rtl;'>
131
+ <h4><b>فريق العمل:</b> أسامة سعيد و طارق العمري</h4>
132
+ <h4><b>شكر وتقدير خاص:</b></h4>
133
+ <p>نتقدم بجزيل الشكر للدكتور القدير/ <b>أكرم الصباري</b> (أستاذ الذكاء الاصطناعي وتعلم الآلة) والمهندسة/ <b>فاتن الحيافي</b> (أستاذة الجانب العملي) على إرشادهما ودعمهما المستمر.</p>
134
+ </div>
135
+ """)
136
+ gr.Markdown("<p id='footer'>© 2025 مشروع تكوين. جميع الحقوق محفوظة.</p>")
137
+
138
+ # ربط الأحداث بالدوال
139
+ run_button.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  fn=infer,
141
+ inputs=[prompt, negative_prompt, guidance_scale, num_inference_steps, seed, randomize_seed],
142
+ outputs=[output_image, output_seed, run_button],
 
 
 
 
 
 
 
143
  )
144
 
145
+ # --- 6. تشغيل التطبيق ---
146
  if __name__ == "__main__":
147
  demo.launch()