mohammed-aljafry commited on
Commit
47d05b3
·
verified ·
1 Parent(s): 9a056ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -52
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py - النسخة النهائية والصحيحة
2
 
3
  import os
4
  import json
@@ -23,18 +23,15 @@ EXAMPLES_DIR = "examples"
23
  # ==============================================================================
24
 
25
  def image_to_base64(pil_image):
26
- """يحول صورة PIL إلى سلسلة نصية Base64."""
27
  buffered = io.BytesIO()
28
  pil_image.save(buffered, format="JPEG")
29
  return base64.b64encode(buffered.getvalue()).decode('utf-8')
30
 
31
  def base64_to_image(b64_string):
32
- """يحول سلسلة نصية Base64 إلى صورة PIL."""
33
  img_data = base64.b64decode(b64_string)
34
  return Image.open(io.BytesIO(img_data))
35
 
36
  def start_new_session():
37
- """يبدأ جلسة جديدة على الخادم."""
38
  print("Requesting to start a new session...")
39
  try:
40
  response = requests.post(API_START_SESSION_URL, timeout=30)
@@ -52,7 +49,6 @@ def start_new_session():
52
  raise gr.Error(error_message)
53
 
54
  def handle_end_session(session_id):
55
- """ينهي الجلسة الحالية على الخادم."""
56
  if not session_id:
57
  return "لا توجد جلسة نشطة لإنهائها.", None, gr.update(visible=False)
58
  print(f"Requesting to end session: {session_id}")
@@ -68,13 +64,15 @@ def handle_end_session(session_id):
68
  raise gr.Error(error_message)
69
 
70
  def run_single_frame_via_api(session_id, rgb_image_path, measurements_path):
71
- """يرسل إطارًا واحدًا للمعالجة عبر الـ API."""
72
  if not session_id:
73
  raise gr.Error("لا توجد جلسة نشطة. يرجى بدء جلسة جديدة أولاً.")
74
  if not (rgb_image_path and measurements_path):
75
  raise gr.Error("الرجاء توفير الصورة الأمامية وملف القياسات على الأقل.")
76
  try:
77
  rgb_image_pil = Image.open(rgb_image_path).convert("RGB")
 
 
 
78
  with open(measurements_path, 'r') as f:
79
  measurements_dict = json.load(f)
80
  image_b64 = image_to_base64(rgb_image_pil)
@@ -97,36 +95,56 @@ def run_single_frame_via_api(session_id, rgb_image_path, measurements_path):
97
  raise gr.Error("لم يتم إرجاع صورة لوحة التحكم من الـ API.")
98
  output_image = base64_to_image(dashboard_b64)
99
  return output_image, control_commands
 
 
100
  except requests.exceptions.RequestException as e:
101
  raise gr.Error(f"حدث خطأ أثناء الاتصال بالـ API: {e}")
102
  except Exception as e:
103
  raise gr.Error(f"حدث خطأ غير متوقع: {e}")
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  # ==============================================================================
106
  # 4. تعريف واجهة Gradio
107
  # ==============================================================================
108
 
109
- CUSTOM_CSS = """
110
- .gradio-container {max-width: 100% !important;}
111
- #examples-container .gradio-table {
112
- table-layout: fixed !important;
113
- width: 100% !important;
114
- }
115
-
116
- /* إخفاء العمود الثالث (عمود ملف JSON) */
117
- #examples-container .gradio-table th:nth-child(3),
118
- #examples-container .gradio-table td:nth-child(3) {
119
- display: none !important;
120
- }
121
-
122
- /* تنسيق الأعمدة الرقمية (تبدأ من الرابع) */
123
- #examples-container .gradio-table th:nth-child(n+4),
124
- #examples-container .gradio-table td:nth-child(n+4) {
125
- width: 110px !important;
126
- text-align: center !important;
127
- vertical-align: middle !important;
128
- }
129
- """
130
 
131
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), css=CUSTOM_CSS) as demo:
132
  session_id_state = gr.State(value=None)
@@ -153,33 +171,35 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), cs
153
  api_measurements_path = gr.File(label="(JSON)", type="filepath")
154
  api_run_button = gr.Button("🚀 أرسل البيانات للمعالجة", variant="primary")
155
 
156
- with gr.Group(elem_id="examples-container"):
157
  gr.Markdown("### ✨ أمثلة جاهزة")
158
- if os.path.isdir(EXAMPLES_DIR):
159
- try:
160
- data1 = json.load(open(os.path.join(EXAMPLES_DIR, "sample1", "measurements.json")))
161
- data2 = json.load(open(os.path.join(EXAMPLES_DIR, "sample2", "measurements.json")))
162
- data3 = json.load(open(os.path.join(EXAMPLES_DIR, "sample3", "measurements.json")))
163
-
164
- with gr.Column(visible=False):
165
- example_speed = gr.Textbox()
166
- example_theta = gr.Textbox()
167
- example_pos = gr.Textbox()
168
- example_target = gr.Textbox()
169
-
170
- gr.Examples(
171
- examples=[
172
- [os.path.join(EXAMPLES_DIR, "sample1", "rgb.jpg"), os.path.join(EXAMPLES_DIR, "sample1", "measurements.json"), f"{data1.get('speed', 0.0):.2f}", f"{data1.get('theta', 0.0):.2f}", str(data1.get('pos_global', 'N/A')), str(data1.get('target_point', 'N/A'))],
173
- [os.path.join(EXAMPLES_DIR, "sample2", "rgb.jpg"), os.path.join(EXAMPLES_DIR, "sample2", "measurements.json"), f"{data2.get('speed', 0.0):.2f}", f"{data2.get('theta', 0.0):.2f}", str(data2.get('pos_global', 'N/A')), str(data2.get('target_point', 'N/A'))],
174
- [os.path.join(EXAMPLES_DIR, "sample3", "rgb.jpg"), os.path.join(EXAMPLES_DIR, "sample3", "measurements.json"), f"{data3.get('speed', 0.0):.2f}", f"{data3.get('theta', 0.0):.2f}", str(data3.get('pos_global', 'N/A')), str(data3.get('target_point', 'N/A'))]
175
- ],
176
- inputs=[api_rgb_image_path, api_measurements_path, example_speed, example_theta, example_pos, example_target],
177
- label="اختر سيناريو اختبار"
178
- )
179
- except FileNotFoundError:
180
- gr.Markdown("لم يتم العثور على ملفات الأمثلة داخل مجلد `examples`.")
 
 
181
  else:
182
- gr.Markdown("لم يتم العثور على مجلد الأمثلة (`examples`).")
183
 
184
  with gr.Column(scale=3):
185
  with gr.Group():
@@ -192,4 +212,5 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), cs
192
  api_run_button.click(fn=run_single_frame_via_api, inputs=[session_id_state, api_rgb_image_path, api_measurements_path], outputs=[api_output_image, api_control_json])
193
 
194
  if __name__ == "__main__":
 
195
  demo.queue().launch(debug=True)
 
1
+ # app.py - النسخة النهائية باستخدام gr.Dataset
2
 
3
  import os
4
  import json
 
23
  # ==============================================================================
24
 
25
  def image_to_base64(pil_image):
 
26
  buffered = io.BytesIO()
27
  pil_image.save(buffered, format="JPEG")
28
  return base64.b64encode(buffered.getvalue()).decode('utf-8')
29
 
30
  def base64_to_image(b64_string):
 
31
  img_data = base64.b64decode(b64_string)
32
  return Image.open(io.BytesIO(img_data))
33
 
34
  def start_new_session():
 
35
  print("Requesting to start a new session...")
36
  try:
37
  response = requests.post(API_START_SESSION_URL, timeout=30)
 
49
  raise gr.Error(error_message)
50
 
51
  def handle_end_session(session_id):
 
52
  if not session_id:
53
  return "لا توجد جلسة نشطة لإنهائها.", None, gr.update(visible=False)
54
  print(f"Requesting to end session: {session_id}")
 
64
  raise gr.Error(error_message)
65
 
66
  def run_single_frame_via_api(session_id, rgb_image_path, measurements_path):
 
67
  if not session_id:
68
  raise gr.Error("لا توجد جلسة نشطة. يرجى بدء جلسة جديدة أولاً.")
69
  if not (rgb_image_path and measurements_path):
70
  raise gr.Error("الرجاء توفير الصورة الأمامية وملف القياسات على الأقل.")
71
  try:
72
  rgb_image_pil = Image.open(rgb_image_path).convert("RGB")
73
+ # التأكد من أن المسار هو ملف صالح قبل فتحه
74
+ if not isinstance(measurements_path, str) or not os.path.exists(measurements_path):
75
+ raise gr.Error(f"مسار ملف القياسات غير صالح أو مفقود: {measurements_path}")
76
  with open(measurements_path, 'r') as f:
77
  measurements_dict = json.load(f)
78
  image_b64 = image_to_base64(rgb_image_pil)
 
95
  raise gr.Error("لم يتم إرجاع صورة لوحة التحكم من الـ API.")
96
  output_image = base64_to_image(dashboard_b64)
97
  return output_image, control_commands
98
+ except FileNotFoundError:
99
+ raise gr.Error(f"لم يتم العثور على الملف: {measurements_path}")
100
  except requests.exceptions.RequestException as e:
101
  raise gr.Error(f"حدث خطأ أثناء الاتصال بالـ API: {e}")
102
  except Exception as e:
103
  raise gr.Error(f"حدث خطأ غير متوقع: {e}")
104
 
105
+ # ==============================================================================
106
+ # 3. إعداد بيانات الأمثلة
107
+ # ==============================================================================
108
+ # قائمة تحتوي على البيانات الكاملة لكل مثال
109
+ FULL_EXAMPLES_DATA = []
110
+ # قائمة تحتوي فقط على البيانات التي سيتم عرضها في الجدول
111
+ SAMPLES_FOR_DISPLAY = []
112
+
113
+ if os.path.isdir(EXAMPLES_DIR):
114
+ try:
115
+ for i in range(1, 4):
116
+ sample_name = f"sample{i}"
117
+ img_path = os.path.join(EXAMPLES_DIR, sample_name, "rgb.jpg")
118
+ json_path = os.path.join(EXAMPLES_DIR, sample_name, "measurements.json")
119
+
120
+ with open(json_path, 'r') as f:
121
+ data = json.load(f)
122
+
123
+ # إضافة البيانات الكاملة
124
+ FULL_EXAMPLES_DATA.append({
125
+ "img_path": img_path,
126
+ "json_path": json_path
127
+ })
128
+
129
+ # إضافة بيانات العرض فقط
130
+ SAMPLES_FOR_DISPLAY.append([
131
+ img_path,
132
+ f"{data.get('speed', 0.0):.2f}",
133
+ f"{data.get('theta', 0.0):.2f}",
134
+ str(data.get('pos_global', 'N/A')),
135
+ str(data.get('target_point', 'N/A'))
136
+ ])
137
+ except FileNotFoundError:
138
+ print(f"تحذير: لم يتم العثور على بعض ملفات الأمثلة في مجلد '{EXAMPLES_DIR}'.")
139
+ FULL_EXAMPLES_DATA = []
140
+ SAMPLES_FOR_DISPLAY = []
141
+
142
  # ==============================================================================
143
  # 4. تعريف واجهة Gradio
144
  # ==============================================================================
145
 
146
+ # لم نعد بحاجة إلى CSS معقد
147
+ CUSTOM_CSS = ".gradio-container {max-width: 100% !important;}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), css=CUSTOM_CSS) as demo:
150
  session_id_state = gr.State(value=None)
 
171
  api_measurements_path = gr.File(label="(JSON)", type="filepath")
172
  api_run_button = gr.Button("🚀 أرسل البيانات للمعالجة", variant="primary")
173
 
174
+ with gr.Group():
175
  gr.Markdown("### ✨ أمثلة جاهزة")
176
+ if SAMPLES_FOR_DISPLAY:
177
+ # --- دالة التحديد ---
178
+ def on_example_select(evt: gr.SelectData):
179
+ # evt.index هو رقم الصف الذي تم الضغط عليه
180
+ selected_example = FULL_EXAMPLES_DATA[evt.index]
181
+ return gr.update(value=selected_example["img_path"]), gr.update(value=selected_example["json_path"])
182
+
183
+ # --- استخدام gr.Dataset ---
184
+ example_dataset = gr.Dataset(
185
+ components=[
186
+ gr.Image(label="الصورة", type="filepath"),
187
+ gr.Textbox(label="السرعة"),
188
+ gr.Textbox(label="الاتجاه"),
189
+ gr.Textbox(label="الموقع"),
190
+ gr.Textbox(label="الهدف")
191
+ ],
192
+ samples=SAMPLES_FOR_DISPLAY,
193
+ label="اختر سيناريو اختبار"
194
+ )
195
+ # --- ربط حدث التحديد بالدالة ---
196
+ example_dataset.select(
197
+ fn=on_example_select,
198
+ inputs=None,
199
+ outputs=[api_rgb_image_path, api_measurements_path]
200
+ )
201
  else:
202
+ gr.Markdown("لم يتم العثور على أمثلة صالحة.")
203
 
204
  with gr.Column(scale=3):
205
  with gr.Group():
 
212
  api_run_button.click(fn=run_single_frame_via_api, inputs=[session_id_state, api_rgb_image_path, api_measurements_path], outputs=[api_output_image, api_control_json])
213
 
214
  if __name__ == "__main__":
215
+ # قم بإعادة تشغيل الـ Space بعد لصق هذا الكود
216
  demo.queue().launch(debug=True)