Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -9,54 +9,68 @@ import numpy as np
|
|
| 9 |
from PIL import Image
|
| 10 |
import cv2
|
| 11 |
import math
|
| 12 |
-
|
| 13 |
-
# --- استيراد من الملفات المنظمة في مشروعك ---
|
| 14 |
-
from model import build_interfuser_model
|
| 15 |
-
from logic import (
|
| 16 |
-
transform, lidar_transform, InterfuserController, ControllerConfig,
|
| 17 |
-
Tracker, DisplayInterface, render, render_waypoints, render_self_car,
|
| 18 |
-
ensure_rgb, WAYPOINT_SCALE_FACTOR, T1_FUTURE_TIME, T2_FUTURE_TIME
|
| 19 |
-
)
|
| 20 |
|
| 21 |
# ==============================================================================
|
| 22 |
-
# 1. إعدادات و
|
| 23 |
# ==============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
WEIGHTS_DIR = "model"
|
| 25 |
-
EXAMPLES_DIR = "examples"
|
| 26 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 27 |
|
| 28 |
-
MODELS_SPECIFIC_CONFIGS = {
|
| 29 |
-
"interfuser_baseline": { "rgb_backbone_name": "r50", "embed_dim": 256, "direct_concat": True },
|
| 30 |
-
"interfuser_lightweight": { "rgb_backbone_name": "r26", "embed_dim": 128, "enc_depth": 4, "dec_depth": 4, "direct_concat": True }
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
def find_available_models():
|
| 34 |
if not os.path.isdir(WEIGHTS_DIR): return []
|
| 35 |
return [f.replace(".pth", "") for f in os.listdir(WEIGHTS_DIR) if f.endswith(".pth")]
|
| 36 |
|
| 37 |
# ==============================================================================
|
| 38 |
-
# 2. الدوال الأساسية
|
| 39 |
# ==============================================================================
|
| 40 |
|
| 41 |
def load_model(model_name: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
if not model_name or "لم يتم" in model_name:
|
| 43 |
return None, "الرجاء اختيار نموذج صالح."
|
|
|
|
| 44 |
weights_path = os.path.join(WEIGHTS_DIR, f"{model_name}.pth")
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
return model,
|
| 60 |
|
| 61 |
|
| 62 |
def run_single_frame(
|
|
@@ -64,7 +78,7 @@ def run_single_frame(
|
|
| 64 |
rgb_center_image_path, lidar_image_path, measurements_path, target_point_list
|
| 65 |
):
|
| 66 |
"""
|
| 67 |
-
|
| 68 |
"""
|
| 69 |
if model_from_state is None:
|
| 70 |
print("API session detected or model not loaded. Loading default model...")
|
|
@@ -78,50 +92,30 @@ def run_single_frame(
|
|
| 78 |
raise gr.Error("فشل تحميل النموذج. تحقق من السجلات (Logs).")
|
| 79 |
|
| 80 |
try:
|
| 81 |
-
# --- 1. التحقق من المدخلات المطلوبة ---
|
| 82 |
if not (rgb_image_path and measurements_path):
|
| 83 |
raise gr.Error("الرجاء توفير الصورة الأمامية وملف القياسات على الأقل.")
|
| 84 |
-
|
| 85 |
-
# --- 2. قراءة ومعالجة المدخلات مع معالجة أخطاء مفصلة ---
|
| 86 |
-
try:
|
| 87 |
-
rgb_image_pil = Image.open(rgb_image_path).convert("RGB")
|
| 88 |
-
except Exception as e:
|
| 89 |
-
raise gr.Error(f"فشل تحميل صورة الكاميرا الأمامية. تأكد من أن الملف صحيح. الخطأ: {e}")
|
| 90 |
-
|
| 91 |
-
def load_optional_image(path, default_image):
|
| 92 |
-
if path:
|
| 93 |
-
try:
|
| 94 |
-
return Image.open(path).convert("RGB")
|
| 95 |
-
except Exception as e:
|
| 96 |
-
raise gr.Error(f"فشل تحميل الصورة الاختيارية '{os.path.basename(path)}'. الخطأ: {e}")
|
| 97 |
-
return default_image
|
| 98 |
-
|
| 99 |
-
rgb_left_pil = load_optional_image(rgb_left_image_path, rgb_image_pil)
|
| 100 |
-
rgb_right_pil = load_optional_image(rgb_right_image_path, rgb_image_pil)
|
| 101 |
-
rgb_center_pil = load_optional_image(rgb_center_image_path, rgb_image_pil)
|
| 102 |
-
|
| 103 |
-
if lidar_image_path:
|
| 104 |
-
try:
|
| 105 |
-
lidar_array = np.load(lidar_image_path)
|
| 106 |
-
if lidar_array.max() > 0: lidar_array = (lidar_array / lidar_array.max()) * 255.0
|
| 107 |
-
lidar_pil = Image.fromarray(lidar_array.astype(np.uint8)).convert('RGB')
|
| 108 |
-
except Exception as e:
|
| 109 |
-
raise gr.Error(f"فشل تحميل ملف الليدار (.npy). تأكد من أن الملف صحيح. الخطأ: {e}")
|
| 110 |
-
else:
|
| 111 |
-
lidar_pil = Image.fromarray(np.zeros((112, 112, 3), dtype=np.uint8))
|
| 112 |
-
|
| 113 |
-
try:
|
| 114 |
-
with open(measurements_path, 'r') as f: m_dict = json.load(f)
|
| 115 |
-
except Exception as e:
|
| 116 |
-
raise gr.Error(f"فشل تحميل أو قراءة ملف القياسات (.json). تأكد من أنه بصيغة صحيحة. الخطأ: {e}")
|
| 117 |
|
| 118 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
front_tensor = transform(rgb_image_pil).unsqueeze(0).to(device)
|
| 120 |
left_tensor = transform(rgb_left_pil).unsqueeze(0).to(device)
|
| 121 |
right_tensor = transform(rgb_right_pil).unsqueeze(0).to(device)
|
| 122 |
center_tensor = transform(rgb_center_pil).unsqueeze(0).to(device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
lidar_tensor = lidar_transform(lidar_pil).unsqueeze(0).to(device)
|
| 124 |
|
|
|
|
|
|
|
| 125 |
measurements_tensor = torch.tensor([[
|
| 126 |
m_dict.get('x',0.0), m_dict.get('y',0.0), m_dict.get('theta',0.0), m_dict.get('speed',5.0),
|
| 127 |
m_dict.get('steer',0.0), m_dict.get('throttle',0.0), float(m_dict.get('brake',0.0)),
|
|
@@ -132,112 +126,86 @@ def run_single_frame(
|
|
| 132 |
|
| 133 |
inputs = {'rgb': front_tensor, 'rgb_left': left_tensor, 'rgb_right': right_tensor, 'rgb_center': center_tensor, 'lidar': lidar_tensor, 'measurements': measurements_tensor, 'target_point': target_point_tensor}
|
| 134 |
|
| 135 |
-
# ---
|
| 136 |
with torch.no_grad():
|
| 137 |
outputs = model_to_use(inputs)
|
| 138 |
traffic, waypoints, is_junction, traffic_light, stop_sign, _ = outputs
|
| 139 |
|
| 140 |
-
# ---
|
| 141 |
-
speed
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
-
# ... (كود الرسم)
|
| 148 |
-
map_t0, counts_t0 = render(updated_traffic, t=0)
|
| 149 |
-
map_t1, counts_t1 = render(updated_traffic, t=T1_FUTURE_TIME)
|
| 150 |
-
map_t2, counts_t2 = render(updated_traffic, t=T2_FUTURE_TIME)
|
| 151 |
-
wp_map = render_waypoints(waypoints_np)
|
| 152 |
-
self_car_map = render_self_car(np.array([0,0]), [math.cos(0), math.sin(0)], [4.0, 2.0])
|
| 153 |
-
map_t0 = cv2.add(cv2.add(map_t0, wp_map), self_car_map)
|
| 154 |
-
map_t0 = cv2.resize(map_t0, (400, 400))
|
| 155 |
-
map_t1 = cv2.add(ensure_rgb(map_t1), ensure_rgb(self_car_map)); map_t1 = cv2.resize(map_t1, (200, 200))
|
| 156 |
-
map_t2 = cv2.add(ensure_rgb(map_t2), ensure_rgb(self_car_map)); map_t2 = cv2.resize(map_t2, (200, 200))
|
| 157 |
display = DisplayInterface()
|
| 158 |
-
light_state, stop_sign_state = "Red" if traffic_light.sigmoid()[0,0].item() > 0.5 else "Green", "Yes" if stop_sign.sigmoid()[0,1].item() > 0.5 else "No"
|
| 159 |
interface_data = {'camera_view': np.array(rgb_image_pil),'map_t0': map_t0,'map_t1': map_t1,'map_t2': map_t2,
|
| 160 |
-
'text_info': {'Control': f"S:{steer:.2f} T:{throttle:.2f} B:{int(brake)}",
|
| 161 |
-
'object_counts': {'t0': counts_t0,'t1': counts_t1,'t2': counts_t2}}
|
| 162 |
dashboard_image = display.run_interface(interface_data)
|
| 163 |
|
| 164 |
-
# ---
|
| 165 |
control_commands_dict = {"steer": steer, "throttle": throttle, "brake": bool(brake)}
|
| 166 |
return Image.fromarray(dashboard_image), control_commands_dict
|
| 167 |
|
| 168 |
-
except gr.Error as e:
|
| 169 |
-
raise e # أعد إظهار أخطاء Gradio كما هي
|
| 170 |
except Exception as e:
|
| 171 |
-
|
| 172 |
-
raise gr.Error(f"حدث خطأ
|
| 173 |
-
|
| 174 |
|
| 175 |
# ==============================================================================
|
| 176 |
-
#
|
| 177 |
# ==============================================================================
|
| 178 |
-
# ... (كود الواجهة بالكامل يبقى كما هو من النسخة السابقة) ...
|
| 179 |
available_models = find_available_models()
|
| 180 |
|
| 181 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), css=".gradio-container {max-width: 95% !important;}") as demo:
|
| 182 |
model_state = gr.State(value=None)
|
| 183 |
|
| 184 |
gr.Markdown("# 🚗 محاكاة القيادة الذاتية باستخدام Interfuser")
|
| 185 |
-
gr.Markdown("مرحباً بك في واجهة اختبار نموذج Interfuser.
|
| 186 |
|
| 187 |
with gr.Row():
|
| 188 |
-
# -- العمود الأيسر: الإعدادات والمدخلات --
|
| 189 |
with gr.Column(scale=1):
|
| 190 |
with gr.Group():
|
| 191 |
gr.Markdown("## ⚙️ الخطوة 1: اختر النموذج")
|
| 192 |
with gr.Row():
|
| 193 |
-
model_selector = gr.Dropdown(
|
| 194 |
-
label="النماذج المتاحة",
|
| 195 |
-
choices=available_models,
|
| 196 |
-
value=available_models[0] if available_models else "لم يتم العثور على نماذج"
|
| 197 |
-
)
|
| 198 |
status_textbox = gr.Textbox(label="حالة النموذج", interactive=False)
|
| 199 |
|
| 200 |
with gr.Group():
|
| 201 |
gr.Markdown("## 🗂️ الخطوة 2: ارفع ملفات السيناريو")
|
| 202 |
-
|
| 203 |
with gr.Group():
|
| 204 |
gr.Markdown("**(مطلوب)**")
|
| 205 |
api_rgb_image_path = gr.File(label="صورة الكاميرا الأمامية (RGB)", type="filepath")
|
| 206 |
api_measurements_path = gr.File(label="ملف القياسات (JSON)", type="filepath")
|
| 207 |
-
|
| 208 |
-
with gr.Accordion("📷 مدخلات اختيارية (كاميرات ومستشعرات إضافية)", open=False):
|
| 209 |
api_rgb_left_image_path = gr.File(label="كاميرا اليسار (RGB)", type="filepath")
|
| 210 |
api_rgb_right_image_path = gr.File(label="كاميرا اليمين (RGB)", type="filepath")
|
| 211 |
api_rgb_center_image_path = gr.File(label="كاميرا الوسط (RGB)", type="filepath")
|
| 212 |
api_lidar_image_path = gr.File(label="بيانات الليدار (NPY)", type="filepath")
|
| 213 |
-
|
| 214 |
api_target_point_list = gr.JSON(label="📍 النقطة المستهدفة (x, y)", value=[0.0, 100.0])
|
| 215 |
-
|
| 216 |
api_run_button = gr.Button("🚀 شغل المحاكاة", variant="primary", scale=2)
|
| 217 |
|
| 218 |
with gr.Group():
|
| 219 |
gr.Markdown("### ✨ أمثلة جاهزة")
|
| 220 |
-
gr.Markdown("انقر على مثال لتعبئة الحقول تلقائياً (يتطلب وجود مجلد `examples`).")
|
| 221 |
gr.Examples(
|
| 222 |
-
|
| 223 |
[os.path.join(EXAMPLES_DIR, "sample1", "rgb.jpg"), os.path.join(EXAMPLES_DIR, "sample1", "measurements.json")],
|
| 224 |
-
[os.path.join(EXAMPLES_DIR, "sample2", "rgb.jpg"), os.path.join(EXAMPLES_DIR, "
|
| 225 |
],
|
| 226 |
-
inputs=[api_rgb_image_path, api_measurements_path],
|
| 227 |
-
label="اختر سيناريو اختبار"
|
| 228 |
-
)
|
| 229 |
|
| 230 |
-
# -- العمود الأيمن: المخرجات --
|
| 231 |
with gr.Column(scale=2):
|
| 232 |
with gr.Group():
|
| 233 |
gr.Markdown("## 📊 الخطوة 3: شاهد النتائج")
|
| 234 |
api_output_image = gr.Image(label="لوحة التحكم المرئية (Dashboard)", type="pil", interactive=False)
|
| 235 |
api_control_json = gr.JSON(label="أوامر التحكم (JSON)")
|
| 236 |
|
| 237 |
-
# --- ربط منطق الواجهة ---
|
| 238 |
if available_models:
|
| 239 |
demo.load(fn=load_model, inputs=model_selector, outputs=[model_state, status_textbox])
|
| 240 |
-
|
| 241 |
model_selector.change(fn=load_model, inputs=model_selector, outputs=[model_state, status_textbox])
|
| 242 |
|
| 243 |
api_run_button.click(
|
|
@@ -249,9 +217,9 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), cs
|
|
| 249 |
)
|
| 250 |
|
| 251 |
# ==============================================================================
|
| 252 |
-
#
|
| 253 |
# ==============================================================================
|
| 254 |
if __name__ == "__main__":
|
| 255 |
if not available_models:
|
| 256 |
-
|
| 257 |
demo.queue().launch(debug=True, share=True)
|
|
|
|
| 9 |
from PIL import Image
|
| 10 |
import cv2
|
| 11 |
import math
|
| 12 |
+
import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# ==============================================================================
|
| 15 |
+
# 1. إعداد الاستيرادات والإعدادات الأساسية
|
| 16 |
# ==============================================================================
|
| 17 |
+
|
| 18 |
+
# إعداد بسيط لعرض الرسائل الإعلامية والأخطاء
|
| 19 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 20 |
+
|
| 21 |
+
# --- استيراد من وحدات المشروع المنظمة ---
|
| 22 |
+
try:
|
| 23 |
+
from model_definition import create_model_config, load_and_prepare_model
|
| 24 |
+
except ImportError:
|
| 25 |
+
raise ImportError("فشل استيراد من 'model.architecture'. تأكد من وجود الملف وأن مسار بايثون صحيح.")
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
from simulation_modules import (
|
| 29 |
+
InterfuserController, ControllerConfig, DisplayInterface,
|
| 30 |
+
render, render_waypoints, render_self_car, ensure_rgb,
|
| 31 |
+
WAYPOINT_SCALE_FACTOR, T1_FUTURE_TIME, T2_FUTURE_TIME,
|
| 32 |
+
transform, lidar_transform, Tracker # تأكد من وجود transform هنا
|
| 33 |
+
)
|
| 34 |
+
except ImportError:
|
| 35 |
+
raise ImportError("فشل استيراد من 'simulation_modules'. تأكد من وجود الملف وأن مسار بايثون صحيح.")
|
| 36 |
+
|
| 37 |
+
# --- إعدادات ومسارات النماذج ---
|
| 38 |
WEIGHTS_DIR = "model"
|
| 39 |
+
EXAMPLES_DIR = "examples"
|
| 40 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def find_available_models():
|
| 43 |
if not os.path.isdir(WEIGHTS_DIR): return []
|
| 44 |
return [f.replace(".pth", "") for f in os.listdir(WEIGHTS_DIR) if f.endswith(".pth")]
|
| 45 |
|
| 46 |
# ==============================================================================
|
| 47 |
+
# 2. الدوال الأساسية (load_model, run_single_frame)
|
| 48 |
# ==============================================================================
|
| 49 |
|
| 50 |
def load_model(model_name: str):
|
| 51 |
+
"""
|
| 52 |
+
(نسخة مبسطة)
|
| 53 |
+
تستخدم الآن الدوال المساعدة الجديدة لإنشاء وتحميل النموذج.
|
| 54 |
+
"""
|
| 55 |
if not model_name or "لم يتم" in model_name:
|
| 56 |
return None, "الرجاء اختيار نموذج صالح."
|
| 57 |
+
|
| 58 |
weights_path = os.path.join(WEIGHTS_DIR, f"{model_name}.pth")
|
| 59 |
+
|
| 60 |
+
# 1. إنشاء إعدادات النموذج المتوافقة مع الأوزان
|
| 61 |
+
config = create_model_config(model_path=weights_path)
|
| 62 |
+
|
| 63 |
+
# 2. إنشاء وتحميل النموذج بخطوة واحدة
|
| 64 |
+
try:
|
| 65 |
+
model = load_and_prepare_model(config, device)
|
| 66 |
+
status_message = f"تم تحميل نموذج: {model_name}"
|
| 67 |
+
if model is None: raise RuntimeError("فشلت دالة load_and_prepare_model")
|
| 68 |
+
except Exception as e:
|
| 69 |
+
model = None
|
| 70 |
+
status_message = f"فشل تحميل النموذج: {e}"
|
| 71 |
+
logging.error(traceback.format_exc())
|
| 72 |
+
|
| 73 |
+
return model, status_message
|
| 74 |
|
| 75 |
|
| 76 |
def run_single_frame(
|
|
|
|
| 78 |
rgb_center_image_path, lidar_image_path, measurements_path, target_point_list
|
| 79 |
):
|
| 80 |
"""
|
| 81 |
+
تعتمد الآن على الوحدات المستوردة بشكل كامل.
|
| 82 |
"""
|
| 83 |
if model_from_state is None:
|
| 84 |
print("API session detected or model not loaded. Loading default model...")
|
|
|
|
| 92 |
raise gr.Error("فشل تحميل النموذج. تحقق من السجلات (Logs).")
|
| 93 |
|
| 94 |
try:
|
|
|
|
| 95 |
if not (rgb_image_path and measurements_path):
|
| 96 |
raise gr.Error("الرجاء توفير الصورة الأمامية وملف القياسات على الأقل.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
# --- 1. قراءة ومعالجة المدخلات ---
|
| 99 |
+
rgb_image_pil = Image.open(rgb_image_path).convert("RGB")
|
| 100 |
+
rgb_left_pil = Image.open(rgb_left_image_path).convert("RGB") if rgb_left_image_path else rgb_image_pil
|
| 101 |
+
rgb_right_pil = Image.open(rgb_right_image_path).convert("RGB") if rgb_right_image_path else rgb_image_pil
|
| 102 |
+
rgb_center_pil = Image.open(rgb_center_image_path).convert("RGB") if rgb_center_image_path else rgb_image_pil
|
| 103 |
+
|
| 104 |
front_tensor = transform(rgb_image_pil).unsqueeze(0).to(device)
|
| 105 |
left_tensor = transform(rgb_left_pil).unsqueeze(0).to(device)
|
| 106 |
right_tensor = transform(rgb_right_pil).unsqueeze(0).to(device)
|
| 107 |
center_tensor = transform(rgb_center_pil).unsqueeze(0).to(device)
|
| 108 |
+
|
| 109 |
+
if lidar_image_path:
|
| 110 |
+
lidar_array = np.load(lidar_image_path)
|
| 111 |
+
if lidar_array.max() > 0: lidar_array = (lidar_array / lidar_array.max()) * 255.0
|
| 112 |
+
lidar_pil = Image.fromarray(lidar_array.astype(np.uint8)).convert('RGB')
|
| 113 |
+
else:
|
| 114 |
+
lidar_pil = Image.fromarray(np.zeros((112, 112, 3), dtype=np.uint8))
|
| 115 |
lidar_tensor = lidar_transform(lidar_pil).unsqueeze(0).to(device)
|
| 116 |
|
| 117 |
+
with open(measurements_path, 'r') as f: m_dict = json.load(f)
|
| 118 |
+
|
| 119 |
measurements_tensor = torch.tensor([[
|
| 120 |
m_dict.get('x',0.0), m_dict.get('y',0.0), m_dict.get('theta',0.0), m_dict.get('speed',5.0),
|
| 121 |
m_dict.get('steer',0.0), m_dict.get('throttle',0.0), float(m_dict.get('brake',0.0)),
|
|
|
|
| 126 |
|
| 127 |
inputs = {'rgb': front_tensor, 'rgb_left': left_tensor, 'rgb_right': right_tensor, 'rgb_center': center_tensor, 'lidar': lidar_tensor, 'measurements': measurements_tensor, 'target_point': target_point_tensor}
|
| 128 |
|
| 129 |
+
# --- 2. تشغيل النموذج ---
|
| 130 |
with torch.no_grad():
|
| 131 |
outputs = model_to_use(inputs)
|
| 132 |
traffic, waypoints, is_junction, traffic_light, stop_sign, _ = outputs
|
| 133 |
|
| 134 |
+
# --- 3. المعالجة اللاحقة والتصوّر ---
|
| 135 |
+
speed = m_dict.get('speed', 5.0)
|
| 136 |
+
controller = InterfuserController(ControllerConfig())
|
| 137 |
+
steer, throttle, brake, metadata_str = controller.run_step(speed, waypoints, is_junction.sigmoid()[0,1].item(), traffic_light.sigmoid()[0,0].item(), stop_sign.sigmoid()[0,1].item(), {})
|
| 138 |
+
|
| 139 |
+
map_t0, _ = render(traffic[0])
|
| 140 |
+
map_t1, _ = render(traffic[0], t=T1_FUTURE_TIME)
|
| 141 |
+
map_t2, _ = render(traffic[0], t=T2_FUTURE_TIME)
|
| 142 |
+
wp_map = render_waypoints(waypoints[0])
|
| 143 |
+
map_t0 = cv2.add(map_t0, wp_map)
|
| 144 |
+
map_t0 = render_self_car(map_t0)
|
| 145 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
display = DisplayInterface()
|
|
|
|
| 147 |
interface_data = {'camera_view': np.array(rgb_image_pil),'map_t0': map_t0,'map_t1': map_t1,'map_t2': map_t2,
|
| 148 |
+
'text_info': {'Control': f"S:{steer:.2f} T:{throttle:.2f} B:{int(brake)}", 'Metadata': metadata_str}}
|
|
|
|
| 149 |
dashboard_image = display.run_interface(interface_data)
|
| 150 |
|
| 151 |
+
# --- 4. تجهيز المخرجات ---
|
| 152 |
control_commands_dict = {"steer": steer, "throttle": throttle, "brake": bool(brake)}
|
| 153 |
return Image.fromarray(dashboard_image), control_commands_dict
|
| 154 |
|
|
|
|
|
|
|
| 155 |
except Exception as e:
|
| 156 |
+
logging.error(traceback.format_exc())
|
| 157 |
+
raise gr.Error(f"حدث خطأ أثناء معالجة الإطار: {e}")
|
|
|
|
| 158 |
|
| 159 |
# ==============================================================================
|
| 160 |
+
# 3. تعريف واجهة Gradio (لا تغيير هنا)
|
| 161 |
# ==============================================================================
|
|
|
|
| 162 |
available_models = find_available_models()
|
| 163 |
|
| 164 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), css=".gradio-container {max-width: 95% !important;}") as demo:
|
| 165 |
model_state = gr.State(value=None)
|
| 166 |
|
| 167 |
gr.Markdown("# 🚗 محاكاة القيادة الذاتية باستخدام Interfuser")
|
| 168 |
+
gr.Markdown("مرحباً بك في واجهة اختبار نموذج Interfuser.")
|
| 169 |
|
| 170 |
with gr.Row():
|
|
|
|
| 171 |
with gr.Column(scale=1):
|
| 172 |
with gr.Group():
|
| 173 |
gr.Markdown("## ⚙️ الخطوة 1: اختر النموذج")
|
| 174 |
with gr.Row():
|
| 175 |
+
model_selector = gr.Dropdown(label="النماذج المتاحة", choices=available_models, value=available_models[0] if available_models else "لم يتم العثور على نماذج")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
status_textbox = gr.Textbox(label="حالة النموذج", interactive=False)
|
| 177 |
|
| 178 |
with gr.Group():
|
| 179 |
gr.Markdown("## 🗂️ الخطوة 2: ارفع ملفات السيناريو")
|
|
|
|
| 180 |
with gr.Group():
|
| 181 |
gr.Markdown("**(مطلوب)**")
|
| 182 |
api_rgb_image_path = gr.File(label="صورة الكاميرا الأمامية (RGB)", type="filepath")
|
| 183 |
api_measurements_path = gr.File(label="ملف القياسات (JSON)", type="filepath")
|
| 184 |
+
with gr.Accordion("📷 مدخلات اختيارية", open=False):
|
|
|
|
| 185 |
api_rgb_left_image_path = gr.File(label="كاميرا اليسار (RGB)", type="filepath")
|
| 186 |
api_rgb_right_image_path = gr.File(label="كاميرا اليمين (RGB)", type="filepath")
|
| 187 |
api_rgb_center_image_path = gr.File(label="كاميرا الوسط (RGB)", type="filepath")
|
| 188 |
api_lidar_image_path = gr.File(label="بيانات الليدار (NPY)", type="filepath")
|
|
|
|
| 189 |
api_target_point_list = gr.JSON(label="📍 النقطة المستهدفة (x, y)", value=[0.0, 100.0])
|
|
|
|
| 190 |
api_run_button = gr.Button("🚀 شغل المحاكاة", variant="primary", scale=2)
|
| 191 |
|
| 192 |
with gr.Group():
|
| 193 |
gr.Markdown("### ✨ أمثلة جاهزة")
|
|
|
|
| 194 |
gr.Examples(
|
| 195 |
+
examples=[
|
| 196 |
[os.path.join(EXAMPLES_DIR, "sample1", "rgb.jpg"), os.path.join(EXAMPLES_DIR, "sample1", "measurements.json")],
|
| 197 |
+
[os.path.join(EXAMPLES_DIR, "sample2", "rgb.jpg"), os.path.join(EXAMPLES_DIR, "sample1", "measurements.json")]
|
| 198 |
],
|
| 199 |
+
inputs=[api_rgb_image_path, api_measurements_path], label="اختر سيناريو اختبار")
|
|
|
|
|
|
|
| 200 |
|
|
|
|
| 201 |
with gr.Column(scale=2):
|
| 202 |
with gr.Group():
|
| 203 |
gr.Markdown("## 📊 الخطوة 3: شاهد النتائج")
|
| 204 |
api_output_image = gr.Image(label="لوحة التحكم المرئية (Dashboard)", type="pil", interactive=False)
|
| 205 |
api_control_json = gr.JSON(label="أوامر التحكم (JSON)")
|
| 206 |
|
|
|
|
| 207 |
if available_models:
|
| 208 |
demo.load(fn=load_model, inputs=model_selector, outputs=[model_state, status_textbox])
|
|
|
|
| 209 |
model_selector.change(fn=load_model, inputs=model_selector, outputs=[model_state, status_textbox])
|
| 210 |
|
| 211 |
api_run_button.click(
|
|
|
|
| 217 |
)
|
| 218 |
|
| 219 |
# ==============================================================================
|
| 220 |
+
# 4. تشغيل التطبيق
|
| 221 |
# ==============================================================================
|
| 222 |
if __name__ == "__main__":
|
| 223 |
if not available_models:
|
| 224 |
+
logging.warning("لم يتم العثور على أي ملفات نماذج (.pth) في مجلد 'model/weights'.")
|
| 225 |
demo.queue().launch(debug=True, share=True)
|