mohammed-aljafry commited on
Commit
b598ef9
·
verified ·
1 Parent(s): 4647da4

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +46 -5
app.py CHANGED
@@ -38,14 +38,21 @@ def find_available_models():
38
  # 2. الدوال الأساسية (load_model, run_single_frame)
39
  # ==============================================================================
40
  def load_model(model_name: str):
 
 
 
 
41
  if not model_name or "لم يتم" in model_name:
42
  return None, "الرجاء اختيار نموذج صالح."
 
43
  weights_path = os.path.join(WEIGHTS_DIR, f"{model_name}.pth")
44
  print(f"Building model: '{model_name}'")
 
45
  model_config = MODELS_SPECIFIC_CONFIGS.get(model_name, {})
46
  model = build_interfuser_model(model_config)
 
47
  if not os.path.exists(weights_path):
48
- gr.Warning(f"ملف الأوزان '{weights_path}' غير موجود.")
49
  else:
50
  try:
51
  state_dic = torch.load(weights_path, map_location=device, weights_only=True)
@@ -53,17 +60,47 @@ def load_model(model_name: str):
53
  print(f"تم تحميل أوزان النموذج '{model_name}' بنجاح.")
54
  except Exception as e:
55
  gr.Warning(f"فشل تحميل الأوزان للنموذج '{model_name}': {e}.")
 
56
  model.to(device)
57
  model.eval()
 
58
  return model, f"تم تحميل نموذج: {model_name}"
59
 
 
60
  def run_single_frame(
61
- model_from_state, rgb_image_path, rgb_left_image_path, rgb_right_image_path,
62
- rgb_center_image_path, lidar_image_path, measurements_path, target_point_list
 
 
 
 
 
 
63
  ):
 
 
 
 
 
 
64
  if model_from_state is None:
65
- raise gr.Error("الرجاء اختيار وتحميل نموذج صالح أولاً من القائمة.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  try:
 
67
  if not (rgb_image_path and measurements_path):
68
  raise gr.Error("الرجاء توفير الصورة الأمامية وملف القياسات على الأقل.")
69
 
@@ -101,10 +138,12 @@ def run_single_frame(
101
  'measurements': measurements_tensor, 'target_point': target_point_tensor
102
  }
103
 
 
104
  with torch.no_grad():
105
- outputs = model_from_state(inputs)
106
  traffic, waypoints, is_junction, traffic_light, stop_sign, _ = outputs
107
 
 
108
  speed, pos, theta = m_dict.get('speed',5.0), [m_dict.get('x',0.0), m_dict.get('y',0.0)], m_dict.get('theta',0.0)
109
  traffic_np, waypoints_np = traffic[0].detach().cpu().numpy().reshape(20,20,-1), waypoints[0].detach().cpu().numpy() * WAYPOINT_SCALE_FACTOR
110
  tracker, controller = Tracker(), InterfuserController(ControllerConfig())
@@ -127,6 +166,7 @@ def run_single_frame(
127
  'object_counts': {'t0': counts_t0,'t1': counts_t1,'t2': counts_t2}}
128
  dashboard_image = display.run_interface(interface_data)
129
 
 
130
  result_dict = {"predicted_waypoints": waypoints_np.tolist(), "control_commands": {"steer": steer,"throttle": throttle,"brake": bool(brake)},
131
  "perception": {"traffic_light_status": light_state,"stop_sign_detected": (stop_sign_state == "Yes"),"is_at_junction_prob": round(is_junction.sigmoid()[0,1].item(), 3)},
132
  "metadata": {"speed_info": metadata[0],"perception_info": metadata[1],"stop_info": metadata[2],"safe_distance": metadata[3]}}
@@ -136,6 +176,7 @@ def run_single_frame(
136
  print(traceback.format_exc())
137
  raise gr.Error(f"حدث خطأ أثناء معالجة الإطار: {e}")
138
 
 
139
  # ==============================================================================
140
  # 4. تعريف واجهة Gradio المحسّنة (مع الإصلاح)
141
  # ==============================================================================
 
38
  # 2. الدوال الأساسية (load_model, run_single_frame)
39
  # ==============================================================================
40
  def load_model(model_name: str):
41
+ """
42
+ (لا تغيير في هذه الدالة)
43
+ تبني وتحمل النموذج المختار وتُرجعه ككائن.
44
+ """
45
  if not model_name or "لم يتم" in model_name:
46
  return None, "الرجاء اختيار نموذج صالح."
47
+
48
  weights_path = os.path.join(WEIGHTS_DIR, f"{model_name}.pth")
49
  print(f"Building model: '{model_name}'")
50
+
51
  model_config = MODELS_SPECIFIC_CONFIGS.get(model_name, {})
52
  model = build_interfuser_model(model_config)
53
+
54
  if not os.path.exists(weights_path):
55
+ gr.Warning(f"ملف الأوزان '{weights_path}' غير موجود. النموذج سيعمل بأوزان عشوائية.")
56
  else:
57
  try:
58
  state_dic = torch.load(weights_path, map_location=device, weights_only=True)
 
60
  print(f"تم تحميل أوزان النموذج '{model_name}' بنجاح.")
61
  except Exception as e:
62
  gr.Warning(f"فشل تحميل الأوزان للنموذج '{model_name}': {e}.")
63
+
64
  model.to(device)
65
  model.eval()
66
+
67
  return model, f"تم تحميل نموذج: {model_name}"
68
 
69
+
70
  def run_single_frame(
71
+ model_from_state, # المدخل من gr.State
72
+ rgb_image_path,
73
+ rgb_left_image_path,
74
+ rgb_right_image_path,
75
+ rgb_center_image_path,
76
+ lidar_image_path,
77
+ measurements_path,
78
+ target_point_list
79
  ):
80
+ """
81
+ (تم تعديل هذه الدالة)
82
+ تعالج إطارًا واحدًا، وتقوم بتحميل النموذج الافتراضي إذا لزم الأمر لجلسات الـ API.
83
+ """
84
+ # --- تعديل للتعامل مع جلسات الـ API ---
85
+ # إذا كانت هذه جلسة API جديدة (model_state فارغ)، قم بتحميل النموذج الافتراضي
86
  if model_from_state is None:
87
+ print("API session detected or model not loaded. Loading default model...")
88
+ available_models = find_available_models()
89
+ if not available_models:
90
+ raise gr.Error("لا توجد نماذج متاحة للتحميل في مجلد 'model/weights'.")
91
+
92
+ default_model_name = available_models[0]
93
+ model_to_use, _ = load_model(default_model_name)
94
+ else:
95
+ # إذا كان النموذج محملًا بالفعل (من جلسة متصفح)، استخدمه مباشرة
96
+ model_to_use = model_from_state
97
+
98
+ if model_to_use is None:
99
+ raise gr.Error("فشل تحميل النموذج. تحقق من السجلات (Logs) في Hugging Face Space.")
100
+ # --- نهاية التعديل ---
101
+
102
  try:
103
+ # --- 1. قراءة ومعالجة المدخلات ---
104
  if not (rgb_image_path and measurements_path):
105
  raise gr.Error("الرجاء توفير الصورة الأمامية وملف القياسات على الأقل.")
106
 
 
138
  'measurements': measurements_tensor, 'target_point': target_point_tensor
139
  }
140
 
141
+ # --- 2. تشغيل النموذج ---
142
  with torch.no_grad():
143
+ outputs = model_to_use(inputs) # <-- استخدام model_to_use
144
  traffic, waypoints, is_junction, traffic_light, stop_sign, _ = outputs
145
 
146
+ # --- 3. المعالجة اللاحقة والتصوّر ---
147
  speed, pos, theta = m_dict.get('speed',5.0), [m_dict.get('x',0.0), m_dict.get('y',0.0)], m_dict.get('theta',0.0)
148
  traffic_np, waypoints_np = traffic[0].detach().cpu().numpy().reshape(20,20,-1), waypoints[0].detach().cpu().numpy() * WAYPOINT_SCALE_FACTOR
149
  tracker, controller = Tracker(), InterfuserController(ControllerConfig())
 
166
  'object_counts': {'t0': counts_t0,'t1': counts_t1,'t2': counts_t2}}
167
  dashboard_image = display.run_interface(interface_data)
168
 
169
+ # --- 4. تجهيز المخرجات ---
170
  result_dict = {"predicted_waypoints": waypoints_np.tolist(), "control_commands": {"steer": steer,"throttle": throttle,"brake": bool(brake)},
171
  "perception": {"traffic_light_status": light_state,"stop_sign_detected": (stop_sign_state == "Yes"),"is_at_junction_prob": round(is_junction.sigmoid()[0,1].item(), 3)},
172
  "metadata": {"speed_info": metadata[0],"perception_info": metadata[1],"stop_info": metadata[2],"safe_distance": metadata[3]}}
 
176
  print(traceback.format_exc())
177
  raise gr.Error(f"حدث خطأ أثناء معالجة الإطار: {e}")
178
 
179
+
180
  # ==============================================================================
181
  # 4. تعريف واجهة Gradio المحسّنة (مع الإصلاح)
182
  # ==============================================================================