alomari7 commited on
Commit
f0fb06d
·
verified ·
1 Parent(s): e3de1b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -32
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py (النسخة النهائية والمصححة)
2
 
3
  import gradio as gr
4
  import numpy as np
@@ -7,11 +7,11 @@ import torch
7
  from diffusers import DiffusionPipeline
8
  import time
9
 
10
- # --- 1. الإعدادات والثوابت ---
11
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
12
  DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
13
 
14
- MODEL_ID = "YourUsername/Takween-v1" # هام: استبدل هذا باسم نموذجك على Hugging Face
15
  BASE_MODEL_ID = "runwayml/stable-diffusion-v1-5"
16
  MAX_SEED = np.iinfo(np.int32).max
17
 
@@ -23,19 +23,17 @@ LOGO_SVG = """
23
  </svg>
24
  """
25
 
26
- # --- 2. تحميل النموذج ---
27
- # تم التحقق من صحة هذا الجزء لتجنب أي أخطاء نحوية
28
  try:
29
  pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=DTYPE, safety_checker=None)
30
  print(f"✅ Trained model '{MODEL_ID}' loaded successfully.")
31
  except Exception:
32
  print(f"❌ Could not load trained model '{MODEL_ID}'. Loading base model.")
33
- # هذا هو السطر الذي تم التحقق من صحته
34
  pipe = DiffusionPipeline.from_pretrained(BASE_MODEL_ID, torch_dtype=DTYPE, safety_checker=None)
35
 
36
  pipe = pipe.to(DEVICE)
37
 
38
- # --- 3. تصميم الثيم الاحترافي ---
39
  theme = gr.themes.Base(
40
  primary_hue=gr.themes.colors.purple,
41
  secondary_hue=gr.themes.colors.neutral,
@@ -49,7 +47,7 @@ theme = gr.themes.Base(
49
  button_primary_background_fill_hover="*primary_600",
50
  )
51
 
52
- # --- 4. دالة التوليد مع تحديثات الواجهة ---
53
  def infer(prompt, negative_prompt, guidance_scale, num_inference_steps, seed, randomize_seed):
54
  if randomize_seed:
55
  seed = random.randint(0, MAX_SEED)
@@ -58,7 +56,7 @@ def infer(prompt, negative_prompt, guidance_scale, num_inference_steps, seed, ra
58
 
59
  yield {
60
  output_image: gr.update(value=None, interactive=False, visible=True),
61
- run_button: gr.update(interactive=False, value="...جاري التكوين"),
62
  }
63
 
64
  image = pipe(
@@ -72,47 +70,76 @@ def infer(prompt, negative_prompt, guidance_scale, num_inference_steps, seed, ra
72
  yield {
73
  output_image: gr.update(value=image, interactive=True),
74
  output_seed: gr.update(value=seed),
75
- run_button: gr.update(interactive=True, value="كوّن مرة أخرى"),
76
  }
77
 
78
- # --- 5. بناء الواجهة الاحترافية ---
79
  with gr.Blocks(theme=theme, css="#footer {text-align: center;}") as demo:
 
80
  with gr.Row():
81
- gr.HTML(f"<div style='display: flex; align-items: center; gap: 12px;'>{LOGO_SVG}<h1>مشروع تكوين</h1></div>")
82
- gr.Markdown("#### نموذج متخصص في تحويل الأوصاف النصية إلى صور هندسية دقيقة.")
 
83
  gr.HTML("<hr>")
 
 
84
  with gr.Row():
 
85
  with gr.Column(scale=1):
86
- prompt = gr.Textbox(label="الوصف (Prompt)", placeholder=" دائرة حمراء بحدود سوداء سميكة...", lines=3)
87
- negative_prompt = gr.Textbox(label="الوصف السلبي (Negative Prompt)", placeholder=" جودة منخفضة، ضبابية، تشوه...")
88
- with gr.Accordion("الإعدادات المتقدمة", open=False):
89
- guidance_scale = gr.Slider(label="مقياس التوجيه", minimum=1.0, maximum=20.0, value=7.5, step=0.1)
90
- num_inference_steps = gr.Slider(label="عدد الخطوات", minimum=10, maximum=100, value=30, step=1)
 
91
  with gr.Row():
92
- seed = gr.Number(label="البذرة (Seed)", value=0, precision=0)
93
- randomize_seed = gr.Checkbox(label="عشوائي", value=True)
94
- run_button = gr.Button("كوّن الصورة", variant="primary")
95
- gr.Examples(examples=["A filled red circle with a thick black border", "An outline blue triangle positioned to the left of a yellow square", "A green star overlapping a purple rectangle"], inputs=[prompt])
 
 
 
 
 
 
 
 
 
 
 
96
  with gr.Column(scale=2):
97
- output_image = gr.Image(label="الصورة المولّدة", interactive=False, height=512)
98
- output_seed = gr.Textbox(label="البذرة المستخدمة (Seed)", interactive=False)
 
 
99
  gr.HTML("<hr>")
100
- with gr.Accordion("فريق العمل والشكر والتقدير", open=False):
101
  gr.Markdown("""
102
- <div style='text-align: right; direction: rtl;'>
103
- <h4><b>فريق العمل:</b> أسامة سعيد و طارق العمري</h4>
104
- <h4><b>شكر وتقدير خاص:</b></h4>
105
- <p>نتقدم بجزيل الشكر للدكتور القدير/ <b>أكرم الصباري</b> (أستاذ الذكاء الاصطناعي وتعلم الآلة) والمهندسة/ <b>فاتن الحيافي</b> (أستاذة الجانب العملي) على إرشادهما ودعمهما المستمر.</p>
 
 
 
 
 
 
 
 
 
106
  </div>
107
  """)
108
- gr.Markdown("<p id='footer'>© 2025 مشروع تكوين. جميع الحقوق محفوظة.</p>")
109
-
 
110
  run_button.click(
111
  fn=infer,
112
  inputs=[prompt, negative_prompt, guidance_scale, num_inference_steps, seed, randomize_seed],
113
  outputs=[output_image, output_seed, run_button],
114
  )
115
 
116
- # --- 6. تشغيل التطبيق ---
117
  if __name__ == "__main__":
118
  demo.launch()
 
1
+ # app.py (English LTR Version)
2
 
3
  import gradio as gr
4
  import numpy as np
 
7
  from diffusers import DiffusionPipeline
8
  import time
9
 
10
+ # --- 1. Settings and Constants ---
11
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
12
  DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
13
 
14
+ MODEL_ID = "YourUsername/Takween-v1" # IMPORTANT: Replace with your model's name on Hugging Face
15
  BASE_MODEL_ID = "runwayml/stable-diffusion-v1-5"
16
  MAX_SEED = np.iinfo(np.int32).max
17
 
 
23
  </svg>
24
  """
25
 
26
+ # --- 2. Model Loading ---
 
27
  try:
28
  pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=DTYPE, safety_checker=None)
29
  print(f"✅ Trained model '{MODEL_ID}' loaded successfully.")
30
  except Exception:
31
  print(f"❌ Could not load trained model '{MODEL_ID}'. Loading base model.")
 
32
  pipe = DiffusionPipeline.from_pretrained(BASE_MODEL_ID, torch_dtype=DTYPE, safety_checker=None)
33
 
34
  pipe = pipe.to(DEVICE)
35
 
36
+ # --- 3. Professional Theme ---
37
  theme = gr.themes.Base(
38
  primary_hue=gr.themes.colors.purple,
39
  secondary_hue=gr.themes.colors.neutral,
 
47
  button_primary_background_fill_hover="*primary_600",
48
  )
49
 
50
+ # --- 4. Inference Function with UI Updates ---
51
  def infer(prompt, negative_prompt, guidance_scale, num_inference_steps, seed, randomize_seed):
52
  if randomize_seed:
53
  seed = random.randint(0, MAX_SEED)
 
56
 
57
  yield {
58
  output_image: gr.update(value=None, interactive=False, visible=True),
59
+ run_button: gr.update(interactive=False, value="Generating..."),
60
  }
61
 
62
  image = pipe(
 
70
  yield {
71
  output_image: gr.update(value=image, interactive=True),
72
  output_seed: gr.update(value=seed),
73
+ run_button: gr.update(interactive=True, value="Generate Again"),
74
  }
75
 
76
+ # --- 5. Professional UI Layout ---
77
  with gr.Blocks(theme=theme, css="#footer {text-align: center;}") as demo:
78
+ # Header
79
  with gr.Row():
80
+ gr.HTML(f"<div style='display: flex; align-items: center; gap: 12px;'>{LOGO_SVG}<h1>Takween Project</h1></div>")
81
+
82
+ gr.Markdown("#### A specialized model for generating precise geometric images from text descriptions.")
83
  gr.HTML("<hr>")
84
+
85
+ # Main Layout (2 columns)
86
  with gr.Row():
87
+ # Left Column: Controls
88
  with gr.Column(scale=1):
89
+ prompt = gr.Textbox(label="Prompt", placeholder="A red circle with thick black borders...", lines=3)
90
+ negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="Low quality, blurry, distorted...")
91
+
92
+ with gr.Accordion("Advanced Settings", open=False):
93
+ guidance_scale = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=20.0, value=7.5, step=0.1)
94
+ num_inference_steps = gr.Slider(label="Number of Steps", minimum=10, maximum=100, value=30, step=1)
95
  with gr.Row():
96
+ seed = gr.Number(label="Seed", value=0, precision=0)
97
+ randomize_seed = gr.Checkbox(label="Randomize", value=True)
98
+
99
+ run_button = gr.Button("Generate Image", variant="primary")
100
+
101
+ gr.Examples(
102
+ examples=[
103
+ "A filled red circle with a thick black border",
104
+ "An outline blue triangle positioned to the left of a yellow square",
105
+ "A green star overlapping a purple rectangle",
106
+ ],
107
+ inputs=[prompt]
108
+ )
109
+
110
+ # Right Column: Results
111
  with gr.Column(scale=2):
112
+ output_image = gr.Image(label="Generated Image", interactive=False, height=512)
113
+ output_seed = gr.Textbox(label="Seed Used", interactive=False)
114
+
115
+ # Footer
116
  gr.HTML("<hr>")
117
+ with gr.Accordion("Team and Acknowledgments", open=False):
118
  gr.Markdown("""
119
+ <div style='text-align: left;'>
120
+ <h4><b>Development Team:</b></h4>
121
+ <ul>
122
+ <li>Osama Saeed</li>
123
+ <li>Tariq Al-Amri</li>
124
+ </ul>
125
+ <hr>
126
+ <h4><b>Special Thanks:</b></h4>
127
+ <p>We extend our sincere gratitude for the guidance and support of:</p>
128
+ <ul>
129
+ <li><b>Dr. Akram Al-Sabari</b> (Professor of AI and Machine Learning)</li>
130
+ <li><b>Eng. Faten Al-Hayafi</b> (Practical Side Instructor)</li>
131
+ </ul>
132
  </div>
133
  """)
134
+ gr.Markdown("<p id='footer'>© 2025 Takween Project. Developed by Osama Saeed & Tariq Al-Amri. All rights reserved.</p>")
135
+
136
+ # Event Listeners
137
  run_button.click(
138
  fn=infer,
139
  inputs=[prompt, negative_prompt, guidance_scale, num_inference_steps, seed, randomize_seed],
140
  outputs=[output_image, output_seed, run_button],
141
  )
142
 
143
+ # --- 6. Launch the App ---
144
  if __name__ == "__main__":
145
  demo.launch()