Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -259,9 +259,319 @@
|
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
-
# الحديد
|
| 263 |
-
# app.py (النسخة المدمجة مع FastAPI)
|
| 264 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
import os
|
| 266 |
import json
|
| 267 |
import traceback
|
|
@@ -271,11 +581,11 @@ import numpy as np
|
|
| 271 |
from PIL import Image
|
| 272 |
import io
|
| 273 |
import base64
|
| 274 |
-
|
| 275 |
import cv2
|
| 276 |
import math
|
| 277 |
-
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
|
| 278 |
-
from
|
|
|
|
| 279 |
|
| 280 |
# --- استيراد من الملفات المنظمة في مشروعك ---
|
| 281 |
from model import build_interfuser_model
|
|
@@ -285,25 +595,45 @@ from logic import (
|
|
| 285 |
ensure_rgb, WAYPOINT_SCALE_FACTOR, T1_FUTURE_TIME, T2_FUTURE_TIME
|
| 286 |
)
|
| 287 |
|
| 288 |
-
#
|
| 289 |
-
|
| 290 |
-
#
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
# ==============================================================================
|
| 296 |
# 1. إعدادات ومسارات النماذج (لا تغيير)
|
| 297 |
# ==============================================================================
|
|
|
|
| 298 |
WEIGHTS_DIR = "model"
|
| 299 |
EXAMPLES_DIR = "examples"
|
| 300 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 301 |
-
|
| 302 |
MODELS_SPECIFIC_CONFIGS = {
|
| 303 |
"interfuser_baseline": { "rgb_backbone_name": "r50", "embed_dim": 256, "direct_concat": True },
|
| 304 |
"interfuser_lightweight": { "rgb_backbone_name": "r26", "embed_dim": 128, "enc_depth": 4, "dec_depth": 4, "direct_concat": True }
|
| 305 |
}
|
| 306 |
-
|
| 307 |
def find_available_models():
|
| 308 |
if not os.path.isdir(WEIGHTS_DIR): return []
|
| 309 |
return [f.replace(".pth", "") for f in os.listdir(WEIGHTS_DIR) if f.endswith(".pth")]
|
|
@@ -311,12 +641,9 @@ def find_available_models():
|
|
| 311 |
# ==============================================================================
|
| 312 |
# 2. الدوال الأساسية (لا تغيير)
|
| 313 |
# ==============================================================================
|
| 314 |
-
|
| 315 |
-
# ... (دالة load_model تبقى كما هي تمامًا) ...
|
| 316 |
def load_model(model_name: str):
|
| 317 |
-
|
| 318 |
-
if not model_name or "لم يتم" in model_name:
|
| 319 |
-
return None, "الرجاء اختيار نموذج صالح."
|
| 320 |
weights_path = os.path.join(WEIGHTS_DIR, f"{model_name}.pth")
|
| 321 |
print(f"Building model: '{model_name}'")
|
| 322 |
model_config = MODELS_SPECIFIC_CONFIGS.get(model_name, {})
|
|
@@ -328,18 +655,12 @@ def load_model(model_name: str):
|
|
| 328 |
state_dic = torch.load(weights_path, map_location=device, weights_only=True)
|
| 329 |
model.load_state_dict(state_dic)
|
| 330 |
print(f"تم تحميل أوزان النموذج '{model_name}' بنجاح.")
|
| 331 |
-
except Exception as e:
|
| 332 |
-
gr.Warning(f"فشل تحميل الأوزان للنموذج '{model_name}': {e}.")
|
| 333 |
model.to(device)
|
| 334 |
model.eval()
|
| 335 |
return model, f"تم تحميل نموذج: {model_name}"
|
| 336 |
|
| 337 |
-
|
| 338 |
-
def run_single_frame(
|
| 339 |
-
model_from_state, rgb_image_path, rgb_left_image_path, rgb_right_image_path,
|
| 340 |
-
rgb_center_image_path, lidar_image_path, measurements_path, target_point_list
|
| 341 |
-
):
|
| 342 |
-
# ... نفس الكود ...
|
| 343 |
if model_from_state is None:
|
| 344 |
print("API session detected or model not loaded. Loading default model...")
|
| 345 |
available_models = find_available_models()
|
|
@@ -347,18 +668,11 @@ def run_single_frame(
|
|
| 347 |
model_to_use, _ = load_model(available_models[0])
|
| 348 |
else:
|
| 349 |
model_to_use = model_from_state
|
| 350 |
-
|
| 351 |
-
if model_to_use is None:
|
| 352 |
-
raise gr.Error("فشل تحميل النموذج. تحقق من السجلات (Logs).")
|
| 353 |
-
|
| 354 |
try:
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
try:
|
| 359 |
-
rgb_image_pil = Image.open(rgb_image_path).convert("RGB")
|
| 360 |
-
except Exception as e:
|
| 361 |
-
raise gr.Error(f"فشل تحميل صورة الكاميرا الأمامية. تأكد من أن الملف صحيح. الخطأ: {e}")
|
| 362 |
def load_optional_image(path, default_image):
|
| 363 |
if path:
|
| 364 |
try: return Image.open(path).convert("RGB")
|
|
@@ -373,8 +687,7 @@ def run_single_frame(
|
|
| 373 |
if lidar_array.max() > 0: lidar_array = (lidar_array / lidar_array.max()) * 255.0
|
| 374 |
lidar_pil = Image.fromarray(lidar_array.astype(np.uint8)).convert('RGB')
|
| 375 |
except Exception as e: raise gr.Error(f"فشل تحميل ملف الليدار (.npy). تأكد من أن الملف صحيح. الخطأ: {e}")
|
| 376 |
-
else:
|
| 377 |
-
lidar_pil = Image.fromarray(np.zeros((112, 112, 3), dtype=np.uint8))
|
| 378 |
try:
|
| 379 |
with open(measurements_path, 'r') as f: m_dict = json.load(f)
|
| 380 |
except Exception as e: raise gr.Error(f"فشل تحميل أو قراءة ملف القياسات (.json). تأكد من أنه بصيغة صحيحة. الخطأ: {e}")
|
|
@@ -413,37 +726,46 @@ def run_single_frame(
|
|
| 413 |
print(traceback.format_exc())
|
| 414 |
raise gr.Error(f"حدث خطأ غير متوقع أثناء معالجة الإطار: {e}")
|
| 415 |
|
| 416 |
-
#
|
| 417 |
-
|
| 418 |
-
#
|
| 419 |
-
@app.post(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 420 |
async def flutter_predict_endpoint(
|
| 421 |
-
rgb_image: UploadFile = File(..., description="صورة الكاميرا الأمامية
|
| 422 |
-
measurements_json: UploadFile = File(..., description="ملف القياسات
|
| 423 |
-
target_point: str = Form(
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
|
|
|
|
|
|
| 429 |
):
|
| 430 |
-
"""
|
| 431 |
-
نقطة نهاية بسيطة ومخصصة لتطبيق فلاتر.
|
| 432 |
-
تستقبل الملفات مباشرة وتستدعي دالة النموذج.
|
| 433 |
-
"""
|
| 434 |
print("✅ Custom API endpoint /api/predict_flutter called!")
|
| 435 |
|
| 436 |
-
# دالة داخلية لحفظ الملفات المرفوعة مؤقتاً
|
| 437 |
async def save_upload_file(upload_file: UploadFile, destination: str):
|
| 438 |
if not upload_file: return None
|
| 439 |
try:
|
| 440 |
-
with open(destination, "wb") as f:
|
| 441 |
-
f.write(await upload_file.read())
|
| 442 |
return destination
|
| 443 |
-
except Exception as e:
|
| 444 |
-
raise HTTPException(status_code=500, detail=f"Could not save file: {e}")
|
| 445 |
|
| 446 |
-
# حفظ الملفات المطلوبة والاختيارية في مسارات مؤقتة
|
| 447 |
temp_rgb_path = await save_upload_file(rgb_image, "temp_rgb.png")
|
| 448 |
temp_measurements_path = await save_upload_file(measurements_json, "temp_measurements.json")
|
| 449 |
temp_left_path = await save_upload_file(rgb_left_image, "temp_left.png")
|
|
@@ -451,66 +773,44 @@ async def flutter_predict_endpoint(
|
|
| 451 |
temp_center_path = await save_upload_file(rgb_center_image, "temp_center.png")
|
| 452 |
temp_lidar_path = await save_upload_file(lidar_data, "temp_lidar.npy")
|
| 453 |
|
| 454 |
-
try:
|
| 455 |
-
|
| 456 |
-
except json.JSONDecodeError:
|
| 457 |
-
raise HTTPException(status_code=400, detail="Invalid JSON format for target_point.")
|
| 458 |
|
| 459 |
try:
|
| 460 |
-
# استدعاء دالة النموذج مباشرة بالمسارات المؤقتة
|
| 461 |
-
# لا نحتاج لـ model_from_state لأننا سنقوم بتحميل النموذج مباشرة
|
| 462 |
dashboard_pil, commands_dict = run_single_frame(
|
| 463 |
-
model_from_state=None,
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
rgb_right_image_path=temp_right_path,
|
| 467 |
-
rgb_center_image_path=temp_center_path,
|
| 468 |
-
lidar_image_path=temp_lidar_path,
|
| 469 |
-
measurements_path=temp_measurements_path,
|
| 470 |
target_point_list=target_point_list
|
| 471 |
)
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
# --- ✅ التعديل هنا ---
|
| 475 |
-
# تحويل صورة PIL إلى بيانات ثنائية في الذاكرة
|
| 476 |
buffered = io.BytesIO()
|
| 477 |
dashboard_pil.save(buffered, format="PNG")
|
| 478 |
-
# تشفير البيانات الثنائية إلى نص Base64
|
| 479 |
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 480 |
|
| 481 |
print("✅ Model execution successful. Returning commands and Base64 image.")
|
| 482 |
|
| 483 |
-
#
|
| 484 |
-
return
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
# # FastAPI لا يمكنه إرجاع كائن PIL مباشرة، يجب تحويله
|
| 490 |
-
# # يمكننا إعادته كـ Base64 أو حفظه وإرجاع مساره
|
| 491 |
-
# # للتبسيط، سنرجع فقط أوامر التحكم
|
| 492 |
-
# print("✅ Model execution successful. Returning control commands.")
|
| 493 |
-
# return commands_dict
|
| 494 |
-
|
| 495 |
except gr.Error as e:
|
| 496 |
-
# تحويل أخطاء Gradio إلى أخطاء HTTP
|
| 497 |
raise HTTPException(status_code=400, detail=str(e))
|
| 498 |
except Exception as e:
|
| 499 |
print(traceback.format_exc())
|
| 500 |
raise HTTPException(status_code=500, detail=f"An internal server error occurred: {e}")
|
| 501 |
finally:
|
| 502 |
-
# ✅ تنظيف الملفات المؤقتة بعد الاستخدام
|
| 503 |
for path in [temp_rgb_path, temp_measurements_path, temp_left_path, temp_right_path, temp_center_path, temp_lidar_path]:
|
| 504 |
if path and os.path.exists(path):
|
| 505 |
os.remove(path)
|
| 506 |
|
| 507 |
-
|
| 508 |
# ==============================================================================
|
| 509 |
-
#
|
| 510 |
# ==============================================================================
|
|
|
|
| 511 |
available_models = find_available_models()
|
| 512 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), css=".gradio-container {max-width: 95% !important;}") as demo:
|
| 513 |
-
# ... (كل كود واجهة Gradio يبقى كما هو تمامًا) ...
|
| 514 |
model_state = gr.State(value=None)
|
| 515 |
gr.Markdown("# 🚗 محاكاة القيادة الذاتية باستخدام Interfuser")
|
| 516 |
gr.Markdown("مرحباً بك في واجهة اختبار نموذج Interfuser. اتبع الخطوات أدناه لتشغيل المحاكاة على إطار واحد.")
|
|
@@ -548,21 +848,14 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), cs
|
|
| 548 |
model_selector.change(fn=load_model, inputs=model_selector, outputs=[model_state, status_textbox])
|
| 549 |
api_run_button.click(fn=run_single_frame, inputs=[model_state, api_rgb_image_path, api_rgb_left_image_path, api_rgb_right_image_path, api_rgb_center_image_path, api_lidar_image_path, api_measurements_path, api_target_point_list], outputs=[api_output_image, api_control_json], api_name="run_single_frame")
|
| 550 |
|
| 551 |
-
#
|
| 552 |
-
#
|
| 553 |
-
#
|
| 554 |
-
# هذه هي الخطوة السحرية التي تدمج العالمين معًا.
|
| 555 |
-
# app = gr.mount_ публіk(app, demo, path="/")
|
| 556 |
app = gr.mount_gradio_app(app, demo, path="/")
|
| 557 |
|
| 558 |
-
#
|
| 559 |
-
#
|
| 560 |
-
#
|
| 561 |
-
|
| 562 |
-
# هذا الجزء يخبر السكربت أنه عند تشغيله مباشرة،
|
| 563 |
-
# يجب أن يقوم بتشغيل تطبيق FastAPI باستخدام خادم uvicorn.
|
| 564 |
if __name__ == "__main__":
|
| 565 |
import uvicorn
|
| 566 |
-
# Hugging Face Spaces يتوقع أن يعمل التطبيق على المنفذ 7860
|
| 567 |
-
# و host="0.0.0.0" يجعله متاحًا للوصول من خارج الحاوية (container)
|
| 568 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
+
# # الحديد
|
| 263 |
+
# # app.py (النسخة المدمجة مع FastAPI)
|
| 264 |
|
| 265 |
+
# import os
|
| 266 |
+
# import json
|
| 267 |
+
# import traceback
|
| 268 |
+
# import torch
|
| 269 |
+
# import gradio as gr
|
| 270 |
+
# import numpy as np
|
| 271 |
+
# from PIL import Image
|
| 272 |
+
# import io
|
| 273 |
+
# import base64
|
| 274 |
+
|
| 275 |
+
# import cv2
|
| 276 |
+
# import math
|
| 277 |
+
# from fastapi import FastAPI, UploadFile, File, Form, HTTPException # ✅ استيراد FastAPI
|
| 278 |
+
# from typing import List # ✅ استيراد للـ Type Hinting
|
| 279 |
+
|
| 280 |
+
# # --- استيراد من الملفات المنظمة في مشروعك ---
|
| 281 |
+
# from model import build_interfuser_model
|
| 282 |
+
# from logic import (
|
| 283 |
+
# transform, lidar_transform, InterfuserController, ControllerConfig,
|
| 284 |
+
# Tracker, DisplayInterface, render, render_waypoints, render_self_car,
|
| 285 |
+
# ensure_rgb, WAYPOINT_SCALE_FACTOR, T1_FUTURE_TIME, T2_FUTURE_TIME
|
| 286 |
+
# )
|
| 287 |
+
|
| 288 |
+
# # ✅ ==============================================================================
|
| 289 |
+
# # ✅ 0. إنشاء تطبيق FastAPI الرئيسي
|
| 290 |
+
# # ✅ ==============================================================================
|
| 291 |
+
# # هذا هو التطبيق الرئيسي الذي سيتم تشغيله.
|
| 292 |
+
# # سيحتوي على كل من واجهة Gradio وواجهة API المخصصة.
|
| 293 |
+
# app = FastAPI()
|
| 294 |
+
|
| 295 |
+
# # ==============================================================================
|
| 296 |
+
# # 1. إعدادات ومسارات النماذج (لا تغيير)
|
| 297 |
+
# # ==============================================================================
|
| 298 |
+
# WEIGHTS_DIR = "model"
|
| 299 |
+
# EXAMPLES_DIR = "examples"
|
| 300 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 301 |
+
|
| 302 |
+
# MODELS_SPECIFIC_CONFIGS = {
|
| 303 |
+
# "interfuser_baseline": { "rgb_backbone_name": "r50", "embed_dim": 256, "direct_concat": True },
|
| 304 |
+
# "interfuser_lightweight": { "rgb_backbone_name": "r26", "embed_dim": 128, "enc_depth": 4, "dec_depth": 4, "direct_concat": True }
|
| 305 |
+
# }
|
| 306 |
+
|
| 307 |
+
# def find_available_models():
|
| 308 |
+
# if not os.path.isdir(WEIGHTS_DIR): return []
|
| 309 |
+
# return [f.replace(".pth", "") for f in os.listdir(WEIGHTS_DIR) if f.endswith(".pth")]
|
| 310 |
+
|
| 311 |
+
# # ==============================================================================
|
| 312 |
+
# # 2. الدوال الأساسية (لا تغيير)
|
| 313 |
+
# # ==============================================================================
|
| 314 |
+
|
| 315 |
+
# # ... (دالة load_model تبقى كما هي تمامًا) ...
|
| 316 |
+
# def load_model(model_name: str):
|
| 317 |
+
# # ... نفس الكود ...
|
| 318 |
+
# if not model_name or "لم يتم" in model_name:
|
| 319 |
+
# return None, "الرجاء اختيار نموذج صالح."
|
| 320 |
+
# weights_path = os.path.join(WEIGHTS_DIR, f"{model_name}.pth")
|
| 321 |
+
# print(f"Building model: '{model_name}'")
|
| 322 |
+
# model_config = MODELS_SPECIFIC_CONFIGS.get(model_name, {})
|
| 323 |
+
# model = build_interfuser_model(model_config)
|
| 324 |
+
# if not os.path.exists(weights_path):
|
| 325 |
+
# gr.Warning(f"ملف الأوزان '{weights_path}' غير موجود.")
|
| 326 |
+
# else:
|
| 327 |
+
# try:
|
| 328 |
+
# state_dic = torch.load(weights_path, map_location=device, weights_only=True)
|
| 329 |
+
# model.load_state_dict(state_dic)
|
| 330 |
+
# print(f"تم تحميل أوزان النموذج '{model_name}' بنجاح.")
|
| 331 |
+
# except Exception as e:
|
| 332 |
+
# gr.Warning(f"فشل تحميل الأوزان للنموذج '{model_name}': {e}.")
|
| 333 |
+
# model.to(device)
|
| 334 |
+
# model.eval()
|
| 335 |
+
# return model, f"تم تحميل نموذج: {model_name}"
|
| 336 |
+
|
| 337 |
+
# # ... (دالة run_single_frame تبقى كما هي تمامًا) ...
|
| 338 |
+
# def run_single_frame(
|
| 339 |
+
# model_from_state, rgb_image_path, rgb_left_image_path, rgb_right_image_path,
|
| 340 |
+
# rgb_center_image_path, lidar_image_path, measurements_path, target_point_list
|
| 341 |
+
# ):
|
| 342 |
+
# # ... نفس الكود ...
|
| 343 |
+
# if model_from_state is None:
|
| 344 |
+
# print("API session detected or model not loaded. Loading default model...")
|
| 345 |
+
# available_models = find_available_models()
|
| 346 |
+
# if not available_models: raise gr.Error("لا توجد نماذج متاحة للتحميل.")
|
| 347 |
+
# model_to_use, _ = load_model(available_models[0])
|
| 348 |
+
# else:
|
| 349 |
+
# model_to_use = model_from_state
|
| 350 |
+
|
| 351 |
+
# if model_to_use is None:
|
| 352 |
+
# raise gr.Error("فشل تحميل النموذج. تحقق من السجلات (Logs).")
|
| 353 |
+
|
| 354 |
+
# try:
|
| 355 |
+
# # ... (بقية الكود داخل الدالة لا يتغير) ...
|
| 356 |
+
# if not (rgb_image_path and measurements_path):
|
| 357 |
+
# raise gr.Error("الرجاء توفير الصورة الأمامية وملف القياسات على الأقل.")
|
| 358 |
+
# try:
|
| 359 |
+
# rgb_image_pil = Image.open(rgb_image_path).convert("RGB")
|
| 360 |
+
# except Exception as e:
|
| 361 |
+
# raise gr.Error(f"فشل تحميل صورة الكاميرا الأمامية. تأكد من أن الملف صحيح. الخطأ: {e}")
|
| 362 |
+
# def load_optional_image(path, default_image):
|
| 363 |
+
# if path:
|
| 364 |
+
# try: return Image.open(path).convert("RGB")
|
| 365 |
+
# except Exception as e: raise gr.Error(f"فشل تحميل الصورة الاختيارية '{os.path.basename(path)}'. الخطأ: {e}")
|
| 366 |
+
# return default_image
|
| 367 |
+
# rgb_left_pil = load_optional_image(rgb_left_image_path, rgb_image_pil)
|
| 368 |
+
# rgb_right_pil = load_optional_image(rgb_right_image_path, rgb_image_pil)
|
| 369 |
+
# rgb_center_pil = load_optional_image(rgb_center_image_path, rgb_image_pil)
|
| 370 |
+
# if lidar_image_path:
|
| 371 |
+
# try:
|
| 372 |
+
# lidar_array = np.load(lidar_image_path)
|
| 373 |
+
# if lidar_array.max() > 0: lidar_array = (lidar_array / lidar_array.max()) * 255.0
|
| 374 |
+
# lidar_pil = Image.fromarray(lidar_array.astype(np.uint8)).convert('RGB')
|
| 375 |
+
# except Exception as e: raise gr.Error(f"فشل تحميل ملف الليدار (.npy). تأكد من أن الملف صحيح. الخطأ: {e}")
|
| 376 |
+
# else:
|
| 377 |
+
# lidar_pil = Image.fromarray(np.zeros((112, 112, 3), dtype=np.uint8))
|
| 378 |
+
# try:
|
| 379 |
+
# with open(measurements_path, 'r') as f: m_dict = json.load(f)
|
| 380 |
+
# except Exception as e: raise gr.Error(f"فشل تحميل أو قراءة ملف القياسات (.json). تأكد من أنه بصيغة صحيحة. الخطأ: {e}")
|
| 381 |
+
# front_tensor = transform(rgb_image_pil).unsqueeze(0).to(device)
|
| 382 |
+
# left_tensor = transform(rgb_left_pil).unsqueeze(0).to(device)
|
| 383 |
+
# right_tensor = transform(rgb_right_pil).unsqueeze(0).to(device)
|
| 384 |
+
# center_tensor = transform(rgb_center_pil).unsqueeze(0).to(device)
|
| 385 |
+
# lidar_tensor = lidar_transform(lidar_pil).unsqueeze(0).to(device)
|
| 386 |
+
# measurements_tensor = torch.tensor([[m_dict.get('x',0.0), m_dict.get('y',0.0), m_dict.get('theta',0.0), m_dict.get('speed',5.0), m_dict.get('steer',0.0), m_dict.get('throttle',0.0), float(m_dict.get('brake',0.0)), m_dict.get('command',2.0), float(m_dict.get('is_junction',0.0)), float(m_dict.get('should_brake',0.0))]], dtype=torch.float32).to(device)
|
| 387 |
+
# target_point_tensor = torch.tensor([target_point_list], dtype=torch.float32).to(device)
|
| 388 |
+
# 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}
|
| 389 |
+
# with torch.no_grad():
|
| 390 |
+
# outputs = model_to_use(inputs)
|
| 391 |
+
# traffic, waypoints, is_junction, traffic_light, stop_sign, _ = outputs
|
| 392 |
+
# 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)
|
| 393 |
+
# traffic_np, waypoints_np = traffic[0].detach().cpu().numpy().reshape(20,20,-1), waypoints[0].detach().cpu().numpy() * WAYPOINT_SCALE_FACTOR
|
| 394 |
+
# tracker, controller = Tracker(), InterfuserController(ControllerConfig())
|
| 395 |
+
# updated_traffic = tracker.update_and_predict(traffic_np.copy(), pos, theta, 0)
|
| 396 |
+
# steer, throttle, brake, metadata = controller.run_step(speed, waypoints_np, is_junction.sigmoid()[0,1].item(), traffic_light.sigmoid()[0,0].item(), stop_sign.sigmoid()[0,1].item(), updated_traffic)
|
| 397 |
+
# map_t0, counts_t0 = render(updated_traffic, t=0)
|
| 398 |
+
# map_t1, counts_t1 = render(updated_traffic, t=T1_FUTURE_TIME)
|
| 399 |
+
# map_t2, counts_t2 = render(updated_traffic, t=T2_FUTURE_TIME)
|
| 400 |
+
# wp_map = render_waypoints(waypoints_np)
|
| 401 |
+
# self_car_map = render_self_car(np.array([0,0]), [math.cos(0), math.sin(0)], [4.0, 2.0])
|
| 402 |
+
# map_t0 = cv2.add(cv2.add(map_t0, wp_map), self_car_map); map_t0 = cv2.resize(map_t0, (400, 400))
|
| 403 |
+
# map_t1 = cv2.add(ensure_rgb(map_t1), ensure_rgb(self_car_map)); map_t1 = cv2.resize(map_t1, (200, 200))
|
| 404 |
+
# map_t2 = cv2.add(ensure_rgb(map_t2), ensure_rgb(self_car_map)); map_t2 = cv2.resize(map_t2, (200, 200))
|
| 405 |
+
# display = DisplayInterface()
|
| 406 |
+
# 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"
|
| 407 |
+
# interface_data = {'camera_view': np.array(rgb_image_pil),'map_t0': map_t0,'map_t1': map_t1,'map_t2': map_t2, 'text_info': {'Control': f"S:{steer:.2f} T:{throttle:.2f} B:{int(brake)}",'Light': f"L: {light_state}",'Stop': f"St: {stop_sign_state}"}, 'object_counts': {'t0': counts_t0,'t1': counts_t1,'t2': counts_t2}}
|
| 408 |
+
# dashboard_image = display.run_interface(interface_data)
|
| 409 |
+
# control_commands_dict = {"steer": steer, "throttle": throttle, "brake": bool(brake)}
|
| 410 |
+
# return Image.fromarray(dashboard_image), control_commands_dict
|
| 411 |
+
# except gr.Error as e: raise e
|
| 412 |
+
# except Exception as e:
|
| 413 |
+
# print(traceback.format_exc())
|
| 414 |
+
# raise gr.Error(f"حدث خطأ غير متوقع أثناء معالجة الإطار: {e}")
|
| 415 |
+
|
| 416 |
+
# # ✅ ==============================================================================
|
| 417 |
+
# # ✅ 3. تعريف نقطة النهاية المخصصة (Custom API) باستخدام FastAPI
|
| 418 |
+
# # ✅ ==============================================================================
|
| 419 |
+
# @app.post("/api/predict_flutter", tags=["Flutter API"])
|
| 420 |
+
# async def flutter_predict_endpoint(
|
| 421 |
+
# rgb_image: UploadFile = File(..., description="صورة الكاميرا الأمامية المطلوبة"),
|
| 422 |
+
# measurements_json: UploadFile = File(..., description="ملف القياسات المطلوب بصيغة JSON"),
|
| 423 |
+
# target_point: str = Form(default='[0.0, 100.0]', description="النقطة المستهدفة كـ JSON string"),
|
| 424 |
+
# # المدخلات الاختيارية
|
| 425 |
+
# rgb_left_image: UploadFile = File(None),
|
| 426 |
+
# rgb_right_image: UploadFile = File(None),
|
| 427 |
+
# rgb_center_image: UploadFile = File(None),
|
| 428 |
+
# lidar_data: UploadFile = File(None),
|
| 429 |
+
# ):
|
| 430 |
+
# """
|
| 431 |
+
# نقطة نهاية بسيطة ومخصصة لتطبيق فلاتر.
|
| 432 |
+
# تستقبل الملفات مباشرة وتستدعي دالة النموذج.
|
| 433 |
+
# """
|
| 434 |
+
# print("✅ Custom API endpoint /api/predict_flutter called!")
|
| 435 |
+
|
| 436 |
+
# # دالة داخلية لحفظ الملفات المرفوعة مؤقتاً
|
| 437 |
+
# async def save_upload_file(upload_file: UploadFile, destination: str):
|
| 438 |
+
# if not upload_file: return None
|
| 439 |
+
# try:
|
| 440 |
+
# with open(destination, "wb") as f:
|
| 441 |
+
# f.write(await upload_file.read())
|
| 442 |
+
# return destination
|
| 443 |
+
# except Exception as e:
|
| 444 |
+
# raise HTTPException(status_code=500, detail=f"Could not save file: {e}")
|
| 445 |
+
|
| 446 |
+
# # حفظ الملفات المطلوبة والاختيارية في مسارات مؤقتة
|
| 447 |
+
# temp_rgb_path = await save_upload_file(rgb_image, "temp_rgb.png")
|
| 448 |
+
# temp_measurements_path = await save_upload_file(measurements_json, "temp_measurements.json")
|
| 449 |
+
# temp_left_path = await save_upload_file(rgb_left_image, "temp_left.png")
|
| 450 |
+
# temp_right_path = await save_upload_file(rgb_right_image, "temp_right.png")
|
| 451 |
+
# temp_center_path = await save_upload_file(rgb_center_image, "temp_center.png")
|
| 452 |
+
# temp_lidar_path = await save_upload_file(lidar_data, "temp_lidar.npy")
|
| 453 |
+
|
| 454 |
+
# try:
|
| 455 |
+
# target_point_list = json.loads(target_point)
|
| 456 |
+
# except json.JSONDecodeError:
|
| 457 |
+
# raise HTTPException(status_code=400, detail="Invalid JSON format for target_point.")
|
| 458 |
+
|
| 459 |
+
# try:
|
| 460 |
+
# # استدعاء دالة النموذج مباشرة بالمسارات المؤقتة
|
| 461 |
+
# # لا نحتاج لـ model_from_state لأننا سنقوم بتحميل النموذج مباشرة
|
| 462 |
+
# dashboard_pil, commands_dict = run_single_frame(
|
| 463 |
+
# model_from_state=None, # سيتم تحميل النموذج الافتراضي داخل الدالة
|
| 464 |
+
# rgb_image_path=temp_rgb_path,
|
| 465 |
+
# rgb_left_image_path=temp_left_path,
|
| 466 |
+
# rgb_right_image_path=temp_right_path,
|
| 467 |
+
# rgb_center_image_path=temp_center_path,
|
| 468 |
+
# lidar_image_path=temp_lidar_path,
|
| 469 |
+
# measurements_path=temp_measurements_path,
|
| 470 |
+
# target_point_list=target_point_list
|
| 471 |
+
# )
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
# # --- ✅ التعديل هنا ---
|
| 475 |
+
# # تحويل صورة PIL إلى بيانات ثنائية في الذاكرة
|
| 476 |
+
# buffered = io.BytesIO()
|
| 477 |
+
# dashboard_pil.save(buffered, format="PNG")
|
| 478 |
+
# # تشفير البيانات الثنائية إلى نص Base64
|
| 479 |
+
# img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 480 |
+
|
| 481 |
+
# print("✅ Model execution successful. Returning commands and Base64 image.")
|
| 482 |
+
|
| 483 |
+
# # إرجاع كائن JSON يحتوي على كل من الأوامر والصورة المشفرة
|
| 484 |
+
# return {
|
| 485 |
+
# "control_commands": commands_dict,
|
| 486 |
+
# "dashboard_image_base64": img_str
|
| 487 |
+
# }
|
| 488 |
+
|
| 489 |
+
# # # FastAPI لا يمكنه إرجاع كائن PIL مباشرة، يجب تحويله
|
| 490 |
+
# # # يمكننا إعادته كـ Base64 أو حفظه وإرجاع مساره
|
| 491 |
+
# # # للتبسيط، سنرجع فقط أوامر التحكم
|
| 492 |
+
# # print("✅ Model execution successful. Returning control commands.")
|
| 493 |
+
# # return commands_dict
|
| 494 |
+
|
| 495 |
+
# except gr.Error as e:
|
| 496 |
+
# # تحويل أخطاء Gradio إلى أخطاء HTTP
|
| 497 |
+
# raise HTTPException(status_code=400, detail=str(e))
|
| 498 |
+
# except Exception as e:
|
| 499 |
+
# print(traceback.format_exc())
|
| 500 |
+
# raise HTTPException(status_code=500, detail=f"An internal server error occurred: {e}")
|
| 501 |
+
# finally:
|
| 502 |
+
# # ✅ تنظيف الملفات المؤقتة بعد الاستخدام
|
| 503 |
+
# for path in [temp_rgb_path, temp_measurements_path, temp_left_path, temp_right_path, temp_center_path, temp_lidar_path]:
|
| 504 |
+
# if path and os.path.exists(path):
|
| 505 |
+
# os.remove(path)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
# # ==============================================================================
|
| 509 |
+
# # 4. تعريف واجهة Gradio (لا تغيير)
|
| 510 |
+
# # ==============================================================================
|
| 511 |
+
# available_models = find_available_models()
|
| 512 |
+
# with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), css=".gradio-container {max-width: 95% !important;}") as demo:
|
| 513 |
+
# # ... (كل كود واجهة Gradio يبقى كما هو تمامًا) ...
|
| 514 |
+
# model_state = gr.State(value=None)
|
| 515 |
+
# gr.Markdown("# 🚗 محاكاة القيادة الذاتية باستخدام Interfuser")
|
| 516 |
+
# gr.Markdown("مرحباً بك في واجهة اختبار نموذج Interfuser. اتبع الخطوات أدناه لتشغيل المحاكاة على إطار واحد.")
|
| 517 |
+
# with gr.Row():
|
| 518 |
+
# with gr.Column(scale=1):
|
| 519 |
+
# with gr.Group():
|
| 520 |
+
# gr.Markdown("## ⚙️ الخطوة 1: اختر النموذج")
|
| 521 |
+
# with gr.Row():
|
| 522 |
+
# model_selector = gr.Dropdown(label="النماذج المتاحة", choices=available_models, value=available_models[0] if available_models else "لم يتم العثور على نماذج")
|
| 523 |
+
# status_textbox = gr.Textbox(label="حالة النموذج", interactive=False)
|
| 524 |
+
# with gr.Group():
|
| 525 |
+
# gr.Markdown("## 🗂️ الخطوة 2: ارفع ملفات السيناريو")
|
| 526 |
+
# with gr.Group():
|
| 527 |
+
# gr.Markdown("**(مطلوب)**")
|
| 528 |
+
# api_rgb_image_path = gr.File(label="صورة الكاميرا الأمامية (RGB)", type="filepath")
|
| 529 |
+
# api_measurements_path = gr.File(label="ملف القياسات (JSON)", type="filepath")
|
| 530 |
+
# with gr.Accordion("📷 مدخلات اختيارية (كاميرات ومستشعرات إضافية)", open=False):
|
| 531 |
+
# api_rgb_left_image_path = gr.File(label="كاميرا اليسار (RGB)", type="filepath")
|
| 532 |
+
# api_rgb_right_image_path = gr.File(label="كاميرا اليمين (RGB)", type="filepath")
|
| 533 |
+
# api_rgb_center_image_path = gr.File(label="كاميرا الوسط (RGB)", type="filepath")
|
| 534 |
+
# api_lidar_image_path = gr.File(label="بيانات الليدار (NPY)", type="filepath")
|
| 535 |
+
# api_target_point_list = gr.JSON(label="📍 النقطة المستهدفة (x, y)", value=[0.0, 100.0])
|
| 536 |
+
# api_run_button = gr.Button("🚀 شغل المحاكاة", variant="primary", scale=2)
|
| 537 |
+
# with gr.Group():
|
| 538 |
+
# gr.Markdown("### ✨ أمثلة جاهزة")
|
| 539 |
+
# gr.Markdown("انقر على مثال لتعبئة الحقول تلقائياً (يتطلب وجود مجلد `examples`).")
|
| 540 |
+
# gr.Examples(examples=[[os.path.join(EXAMPLES_DIR, "sample1", "rgb.jpg"), os.path.join(EXAMPLES_DIR, "sample1", "measurements.json")], [os.path.join(EXAMPLES_DIR, "sample2", "rgb.jpg"), os.path.join(EXAMPLES_DIR, "sample2", "measurements.json")]], inputs=[api_rgb_image_path, api_measurements_path], label="اختر سيناريو اختبار")
|
| 541 |
+
# with gr.Column(scale=2):
|
| 542 |
+
# with gr.Group():
|
| 543 |
+
# gr.Markdown("## 📊 الخطوة 3: شاهد النتائج")
|
| 544 |
+
# api_output_image = gr.Image(label="لوحة التحكم المرئية (Dashboard)", type="pil", interactive=False)
|
| 545 |
+
# api_control_json = gr.JSON(label="أوامر التحكم (JSON)")
|
| 546 |
+
# if available_models:
|
| 547 |
+
# demo.load(fn=load_model, inputs=model_selector, outputs=[model_state, status_textbox])
|
| 548 |
+
# model_selector.change(fn=load_model, inputs=model_selector, outputs=[model_state, status_textbox])
|
| 549 |
+
# api_run_button.click(fn=run_single_frame, inputs=[model_state, api_rgb_image_path, api_rgb_left_image_path, api_rgb_right_image_path, api_rgb_center_image_path, api_lidar_image_path, api_measurements_path, api_target_point_list], outputs=[api_output_image, api_control_json], api_name="run_single_frame")
|
| 550 |
+
|
| 551 |
+
# # ✅ ==============================================================================
|
| 552 |
+
# # ✅ 5. تركيب واجهة Gradio على تطبيق FastAPI
|
| 553 |
+
# # ✅ ==============================================================================
|
| 554 |
+
# # هذه هي الخطوة السحرية التي تدمج العالمين معًا.
|
| 555 |
+
# # app = gr.mount_ публіk(app, demo, path="/")
|
| 556 |
+
# app = gr.mount_gradio_app(app, demo, path="/")
|
| 557 |
+
|
| 558 |
+
# # ✅ ==============================================================================
|
| 559 |
+
# # ✅ 6. تشغيل الخادم المدمج (نقطة الدخول)
|
| 560 |
+
# # ✅ ==============================================================================
|
| 561 |
+
|
| 562 |
+
# # هذا الجزء يخبر السكربت أنه عند تشغيله مباشرة،
|
| 563 |
+
# # يجب أن يقوم بتشغيل تطبيق FastAPI باستخدام خادم uvicorn.
|
| 564 |
+
# if __name__ == "__main__":
|
| 565 |
+
# import uvicorn
|
| 566 |
+
# # Hugging Face Spaces يتوقع أن يعمل التطبيق على المنفذ 7860
|
| 567 |
+
# # و host="0.0.0.0" يجعله متاحًا للوصول من خارج الحاوية (container)
|
| 568 |
+
# uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 569 |
+
|
| 570 |
+
# app.py (النسخة النهائية المدمجة مع توثيق FastAPI)
|
| 571 |
+
|
| 572 |
+
# -------------------------------------------------
|
| 573 |
+
##-- 1. إضافة الاستيرادات اللازمة للتوثيق
|
| 574 |
+
# -------------------------------------------------
|
| 575 |
import os
|
| 576 |
import json
|
| 577 |
import traceback
|
|
|
|
| 581 |
from PIL import Image
|
| 582 |
import io
|
| 583 |
import base64
|
|
|
|
| 584 |
import cv2
|
| 585 |
import math
|
| 586 |
+
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
|
| 587 |
+
from pydantic import BaseModel, Field
|
| 588 |
+
from typing import List, Dict
|
| 589 |
|
| 590 |
# --- استيراد من الملفات المنظمة في مشروعك ---
|
| 591 |
from model import build_interfuser_model
|
|
|
|
| 595 |
ensure_rgb, WAYPOINT_SCALE_FACTOR, T1_FUTURE_TIME, T2_FUTURE_TIME
|
| 596 |
)
|
| 597 |
|
| 598 |
+
# -------------------------------------------------
|
| 599 |
+
##-- 2. تعريف تطبيق FastAPI مع وصف عام
|
| 600 |
+
# -------------------------------------------------
|
| 601 |
+
app = FastAPI(
|
| 602 |
+
title="API لمحاكاة القيادة الذاتية (Interfuser)",
|
| 603 |
+
description="""
|
| 604 |
+
واجهة برمجة تطبيقات مخصصة للتحكم في نموذج Interfuser.
|
| 605 |
+
|
| 606 |
+
يحتوي هذا التطبيق على:
|
| 607 |
+
- **واجهة رسومية (UI)** على المسار الرئيسي (`/`) للتفاعل البصري.
|
| 608 |
+
- **واجهة برمجية (API)** على المسار (`/api/predict_flutter`) مخصصة للتطبيقات مثل فلاتر.
|
| 609 |
+
- **توثيق تفاعلي** على المسار (`/docs`).
|
| 610 |
+
""",
|
| 611 |
+
version="1.1.0"
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
# -------------------------------------------------
|
| 615 |
+
##-- 3. تعريف هياكل البيانات (Schemas) للمدخلات والمخرجات
|
| 616 |
+
# -------------------------------------------------
|
| 617 |
+
class ControlCommands(BaseModel):
|
| 618 |
+
steer: float = Field(..., example=-0.61, description="قيمة التوجيه (Steering). تتراوح بين -1 (يسار) و 1 (يمين).")
|
| 619 |
+
throttle: float = Field(..., example=0.75, description="قيمة التسارع (Throttle). تتراوح بين 0 و 1.")
|
| 620 |
+
brake: bool = Field(..., example=False, description="هل يجب الضغط على المكابح (Brake)؟")
|
| 621 |
+
|
| 622 |
+
class PredictionResponse(BaseModel):
|
| 623 |
+
control_commands: ControlCommands = Field(..., description="كائن يحتوي على أوامر التحكم المتوقعة.")
|
| 624 |
+
dashboard_image_base64: str = Field(..., description="صورة لوحة التحكم كـ نص مشفر بصيغة Base64.")
|
| 625 |
|
| 626 |
# ==============================================================================
|
| 627 |
# 1. إعدادات ومسارات النماذج (لا تغيير)
|
| 628 |
# ==============================================================================
|
| 629 |
+
# ... (هذا الجزء يبقى كما هو تمامًا) ...
|
| 630 |
WEIGHTS_DIR = "model"
|
| 631 |
EXAMPLES_DIR = "examples"
|
| 632 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
| 633 |
MODELS_SPECIFIC_CONFIGS = {
|
| 634 |
"interfuser_baseline": { "rgb_backbone_name": "r50", "embed_dim": 256, "direct_concat": True },
|
| 635 |
"interfuser_lightweight": { "rgb_backbone_name": "r26", "embed_dim": 128, "enc_depth": 4, "dec_depth": 4, "direct_concat": True }
|
| 636 |
}
|
|
|
|
| 637 |
def find_available_models():
|
| 638 |
if not os.path.isdir(WEIGHTS_DIR): return []
|
| 639 |
return [f.replace(".pth", "") for f in os.listdir(WEIGHTS_DIR) if f.endswith(".pth")]
|
|
|
|
| 641 |
# ==============================================================================
|
| 642 |
# 2. الدوال الأساسية (لا تغيير)
|
| 643 |
# ==============================================================================
|
| 644 |
+
# ... (دالة load_model ودالة run_single_frame تبقيان كما هما تمامًا) ...
|
|
|
|
| 645 |
def load_model(model_name: str):
|
| 646 |
+
if not model_name or "لم يتم" in model_name: return None, "الرجاء اختيار نموذج صالح."
|
|
|
|
|
|
|
| 647 |
weights_path = os.path.join(WEIGHTS_DIR, f"{model_name}.pth")
|
| 648 |
print(f"Building model: '{model_name}'")
|
| 649 |
model_config = MODELS_SPECIFIC_CONFIGS.get(model_name, {})
|
|
|
|
| 655 |
state_dic = torch.load(weights_path, map_location=device, weights_only=True)
|
| 656 |
model.load_state_dict(state_dic)
|
| 657 |
print(f"تم تحميل أوزان النموذج '{model_name}' بنجاح.")
|
| 658 |
+
except Exception as e: gr.Warning(f"فشل تحميل الأوزان للنموذج '{model_name}': {e}.")
|
|
|
|
| 659 |
model.to(device)
|
| 660 |
model.eval()
|
| 661 |
return model, f"تم تحميل نموذج: {model_name}"
|
| 662 |
|
| 663 |
+
def run_single_frame(model_from_state, rgb_image_path, rgb_left_image_path, rgb_right_image_path, rgb_center_image_path, lidar_image_path, measurements_path, target_point_list):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 664 |
if model_from_state is None:
|
| 665 |
print("API session detected or model not loaded. Loading default model...")
|
| 666 |
available_models = find_available_models()
|
|
|
|
| 668 |
model_to_use, _ = load_model(available_models[0])
|
| 669 |
else:
|
| 670 |
model_to_use = model_from_state
|
| 671 |
+
if model_to_use is None: raise gr.Error("فشل تحميل النموذج. تحقق من السجلات (Logs).")
|
|
|
|
|
|
|
|
|
|
| 672 |
try:
|
| 673 |
+
if not (rgb_image_path and measurements_path): raise gr.Error("الرجاء توفير الصورة الأمامية وملف القياسات على الأقل.")
|
| 674 |
+
try: rgb_image_pil = Image.open(rgb_image_path).convert("RGB")
|
| 675 |
+
except Exception as e: raise gr.Error(f"فشل تحميل صورة الكاميرا الأمامية. تأكد من أن الملف صحيح. الخطأ: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 676 |
def load_optional_image(path, default_image):
|
| 677 |
if path:
|
| 678 |
try: return Image.open(path).convert("RGB")
|
|
|
|
| 687 |
if lidar_array.max() > 0: lidar_array = (lidar_array / lidar_array.max()) * 255.0
|
| 688 |
lidar_pil = Image.fromarray(lidar_array.astype(np.uint8)).convert('RGB')
|
| 689 |
except Exception as e: raise gr.Error(f"فشل تحميل ملف الليدار (.npy). تأكد من أن الملف صحيح. الخطأ: {e}")
|
| 690 |
+
else: lidar_pil = Image.fromarray(np.zeros((112, 112, 3), dtype=np.uint8))
|
|
|
|
| 691 |
try:
|
| 692 |
with open(measurements_path, 'r') as f: m_dict = json.load(f)
|
| 693 |
except Exception as e: raise gr.Error(f"فشل تحميل أو قراءة ملف القياسات (.json). تأكد من أنه بصيغة صحيحة. الخطأ: {e}")
|
|
|
|
| 726 |
print(traceback.format_exc())
|
| 727 |
raise gr.Error(f"حدث خطأ غير متوقع أثناء معالجة الإطار: {e}")
|
| 728 |
|
| 729 |
+
# -------------------------------------------------
|
| 730 |
+
##-- 4. تعديل نقطة النهاية المخصصة (API Endpoint) بالتوثيق
|
| 731 |
+
# -------------------------------------------------
|
| 732 |
+
@app.post(
|
| 733 |
+
"/api/predict_flutter",
|
| 734 |
+
tags=["Flutter API"],
|
| 735 |
+
summary="التنبؤ بأوامر القيادة لإطار واحد",
|
| 736 |
+
description="""
|
| 737 |
+
يقوم هذا الـ Endpoint بمعالجة بيانات إطار واحد من مستشعرات السيارة (صور، قياسات)
|
| 738 |
+
ويتنبأ بأوامر التحكم اللازمة (التوجيه، التسارع، المكابح)، بالإضافة إلى إرجاع
|
| 739 |
+
صورة لوحة التحكم البصرية (Dashboard).
|
| 740 |
+
""",
|
| 741 |
+
response_model=PredictionResponse, # استخدام نموذج المخرجات المحدد
|
| 742 |
+
responses={
|
| 743 |
+
400: {"description": "خطأ في مدخلات العميل (مثل JSON غير صالح)"},
|
| 744 |
+
422: {"description": "خطأ في التحقق من صحة البيانات (مثل ملف مطلوب مفقود)"},
|
| 745 |
+
500: {"description": "خطأ داخلي في الخادم أثناء معالجة النموذج"},
|
| 746 |
+
}
|
| 747 |
+
)
|
| 748 |
async def flutter_predict_endpoint(
|
| 749 |
+
rgb_image: UploadFile = File(..., description="صورة الكاميرا الأمامية بصيغة PNG أو JPG."),
|
| 750 |
+
measurements_json: UploadFile = File(..., description="ملف القياسات الحالي بصيغة JSON."),
|
| 751 |
+
target_point: str = Form(
|
| 752 |
+
default='[0.0, 100.0]',
|
| 753 |
+
description="النقطة المستهدفة كـ JSON string. مثال: '[50.0, 20.0]'"
|
| 754 |
+
),
|
| 755 |
+
rgb_left_image: UploadFile = File(None, description="صورة اختيارية من كاميرا اليسار."),
|
| 756 |
+
rgb_right_image: UploadFile = File(None, description="صورة اختيارية من كاميرا اليمين."),
|
| 757 |
+
rgb_center_image: UploadFile = File(None, description="صورة اختيارية من كاميرا الوسط."),
|
| 758 |
+
lidar_data: UploadFile = File(None, description="ملف بيانات الليدار الاختياري بصيغة .npy."),
|
| 759 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 760 |
print("✅ Custom API endpoint /api/predict_flutter called!")
|
| 761 |
|
|
|
|
| 762 |
async def save_upload_file(upload_file: UploadFile, destination: str):
|
| 763 |
if not upload_file: return None
|
| 764 |
try:
|
| 765 |
+
with open(destination, "wb") as f: f.write(await upload_file.read())
|
|
|
|
| 766 |
return destination
|
| 767 |
+
except Exception as e: raise HTTPException(status_code=500, detail=f"Could not save file: {e}")
|
|
|
|
| 768 |
|
|
|
|
| 769 |
temp_rgb_path = await save_upload_file(rgb_image, "temp_rgb.png")
|
| 770 |
temp_measurements_path = await save_upload_file(measurements_json, "temp_measurements.json")
|
| 771 |
temp_left_path = await save_upload_file(rgb_left_image, "temp_left.png")
|
|
|
|
| 773 |
temp_center_path = await save_upload_file(rgb_center_image, "temp_center.png")
|
| 774 |
temp_lidar_path = await save_upload_file(lidar_data, "temp_lidar.npy")
|
| 775 |
|
| 776 |
+
try: target_point_list = json.loads(target_point)
|
| 777 |
+
except json.JSONDecodeError: raise HTTPException(status_code=400, detail="Invalid JSON format for target_point.")
|
|
|
|
|
|
|
| 778 |
|
| 779 |
try:
|
|
|
|
|
|
|
| 780 |
dashboard_pil, commands_dict = run_single_frame(
|
| 781 |
+
model_from_state=None, rgb_image_path=temp_rgb_path, rgb_left_image_path=temp_left_path,
|
| 782 |
+
rgb_right_image_path=temp_right_path, rgb_center_image_path=temp_center_path,
|
| 783 |
+
lidar_image_path=temp_lidar_path, measurements_path=temp_measurements_path,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 784 |
target_point_list=target_point_list
|
| 785 |
)
|
| 786 |
+
|
|
|
|
|
|
|
|
|
|
| 787 |
buffered = io.BytesIO()
|
| 788 |
dashboard_pil.save(buffered, format="PNG")
|
|
|
|
| 789 |
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 790 |
|
| 791 |
print("✅ Model execution successful. Returning commands and Base64 image.")
|
| 792 |
|
| 793 |
+
# التأكد من أن الرد يتبع هيكل Pydantic المحدد
|
| 794 |
+
return PredictionResponse(
|
| 795 |
+
control_commands=ControlCommands(**commands_dict),
|
| 796 |
+
dashboard_image_base64=img_str
|
| 797 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 798 |
except gr.Error as e:
|
|
|
|
| 799 |
raise HTTPException(status_code=400, detail=str(e))
|
| 800 |
except Exception as e:
|
| 801 |
print(traceback.format_exc())
|
| 802 |
raise HTTPException(status_code=500, detail=f"An internal server error occurred: {e}")
|
| 803 |
finally:
|
|
|
|
| 804 |
for path in [temp_rgb_path, temp_measurements_path, temp_left_path, temp_right_path, temp_center_path, temp_lidar_path]:
|
| 805 |
if path and os.path.exists(path):
|
| 806 |
os.remove(path)
|
| 807 |
|
|
|
|
| 808 |
# ==============================================================================
|
| 809 |
+
# 5. تعريف واجهة Gradio (لا تغيير)
|
| 810 |
# ==============================================================================
|
| 811 |
+
# ... (هذا الجزء يبقى كما هو تمامًا) ...
|
| 812 |
available_models = find_available_models()
|
| 813 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), css=".gradio-container {max-width: 95% !important;}") as demo:
|
|
|
|
| 814 |
model_state = gr.State(value=None)
|
| 815 |
gr.Markdown("# 🚗 محاكاة القيادة الذاتية باستخدام Interfuser")
|
| 816 |
gr.Markdown("مرحباً بك في واجهة اختبار نموذج Interfuser. اتبع الخطوات أدناه لتشغيل المحاكاة على إطار واحد.")
|
|
|
|
| 848 |
model_selector.change(fn=load_model, inputs=model_selector, outputs=[model_state, status_textbox])
|
| 849 |
api_run_button.click(fn=run_single_frame, inputs=[model_state, api_rgb_image_path, api_rgb_left_image_path, api_rgb_right_image_path, api_rgb_center_image_path, api_lidar_image_path, api_measurements_path, api_target_point_list], outputs=[api_output_image, api_control_json], api_name="run_single_frame")
|
| 850 |
|
| 851 |
+
# ==============================================================================
|
| 852 |
+
# 6. تركيب واجهة Gradio على تطبيق FastAPI
|
| 853 |
+
# ==============================================================================
|
|
|
|
|
|
|
| 854 |
app = gr.mount_gradio_app(app, demo, path="/")
|
| 855 |
|
| 856 |
+
# ==============================================================================
|
| 857 |
+
# 7. تشغيل الخادم المدمج (نقطة الدخول)
|
| 858 |
+
# ==============================================================================
|
|
|
|
|
|
|
|
|
|
| 859 |
if __name__ == "__main__":
|
| 860 |
import uvicorn
|
|
|
|
|
|
|
| 861 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|