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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import json
|
| 4 |
+
import traceback
|
| 5 |
+
from uuid import uuid4
|
| 6 |
+
|
| 7 |
+
# --- FastAPI & Web server imports ---
|
| 8 |
+
import uvicorn
|
| 9 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException, Security, Depends
|
| 10 |
+
from fastapi.security import APIKeyHeader
|
| 11 |
+
from fastapi.responses import JSONResponse
|
| 12 |
+
|
| 13 |
+
# --- ML & Data processing imports ---
|
| 14 |
+
import torch
|
| 15 |
+
from PIL import Image
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
# --- استيراد من ملفات المشروع الخاصة بك ---
|
| 19 |
+
try:
|
| 20 |
+
from model import build_interfuser_model
|
| 21 |
+
from logic import (
|
| 22 |
+
transform, InterfuserController, ControllerConfig,
|
| 23 |
+
Tracker, WAYPOINT_SCALE_FACTOR
|
| 24 |
+
)
|
| 25 |
+
except ImportError as e:
|
| 26 |
+
print(f"Error importing from project files: {e}")
|
| 27 |
+
print("Please ensure model.py and logic.py are in the same directory.")
|
| 28 |
+
exit()
|
| 29 |
+
|
| 30 |
+
# ==============================================================================
|
| 31 |
+
# 1. إعدادات الخادم، النموذج، والأمان
|
| 32 |
+
# ==============================================================================
|
| 33 |
+
app = FastAPI(
|
| 34 |
+
title="Interfuser Driving API (Secure & Stateful)",
|
| 35 |
+
description="An API for driving commands with session management and API key authentication.",
|
| 36 |
+
version="2.0.0"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# --- تحميل النموذج (يتم مرة واحدة عند بدء التشغيل) ---
|
| 40 |
+
MODEL_NAME = "interfuser_baseline"
|
| 41 |
+
WEIGHTS_PATH = os.path.join("weights", f"{MODEL_NAME}.pth")
|
| 42 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 43 |
+
MODEL_CONFIG = {
|
| 44 |
+
"rgb_backbone_name": "r50", "embed_dim": 256, "direct_concat": True,
|
| 45 |
+
'get': lambda key, default: MODEL_CONFIG.get(key, default)
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
print(f"Loading model '{MODEL_NAME}' on device '{DEVICE}'...")
|
| 49 |
+
if not os.path.exists(WEIGHTS_PATH):
|
| 50 |
+
raise FileNotFoundError(f"Weights file not found at: {WEIGHTS_PATH}")
|
| 51 |
+
|
| 52 |
+
model = build_interfuser_model(MODEL_CONFIG)
|
| 53 |
+
model.load_state_dict(torch.load(WEIGHTS_PATH, map_location=DEVICE))
|
| 54 |
+
model.to(DEVICE)
|
| 55 |
+
model.eval()
|
| 56 |
+
print("✅ Model loaded successfully!")
|
| 57 |
+
|
| 58 |
+
# --- إدارة الجلسات والأمان ---
|
| 59 |
+
SESSIONS = {} # قاموس لتخزين حالات الجلسات: {session_id: Tracker}
|
| 60 |
+
API_KEY_NAME = "X-API-KEY"
|
| 61 |
+
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
|
| 62 |
+
|
| 63 |
+
# في تطبيق حقيقي، يجب أن تكون هذه المفاتيح في متغيرات بيئة أو خدمة إدارة أسرار
|
| 64 |
+
VALID_API_KEYS = {
|
| 65 |
+
"your-super-secret-key-for-flutter-app", # مفتاح لتطبيق فلاتر
|
| 66 |
+
"a-different-key-for-testing" # مفتاح آخر للاختبار
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
async def get_api_key(api_key: str = Security(api_key_header)):
|
| 70 |
+
"""تبعية للتحقق من أن مفتاح الـ API صالح."""
|
| 71 |
+
if api_key in VALID_API_KEYS:
|
| 72 |
+
return api_key
|
| 73 |
+
else:
|
| 74 |
+
raise HTTPException(
|
| 75 |
+
status_code=403, detail="Could not validate credentials or missing API Key"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# ==============================================================================
|
| 80 |
+
# 2. تعريف نقاط نهاية الـ API (Endpoints)
|
| 81 |
+
# ==============================================================================
|
| 82 |
+
|
| 83 |
+
# --- حماية جميع نقاط النهاية باستخدام التبعية ---
|
| 84 |
+
# أي طلب لأي نقطة نهاية أدناه يجب أن يجتاز get_api_key أولاً
|
| 85 |
+
app.dependency_overrides[get_api_key] = get_api_key
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@app.post("/sessions/create", summary="Create a new tracking session")
|
| 89 |
+
async def create_session(api_key: str = Depends(get_api_key)):
|
| 90 |
+
"""
|
| 91 |
+
ينشئ جلسة تتبع جديدة ويعيد معرفًا فريدًا لها.
|
| 92 |
+
هذه هي الخطوة الأولى قبل إرسال بيانات الإطارات.
|
| 93 |
+
"""
|
| 94 |
+
session_id = str(uuid4())
|
| 95 |
+
SESSIONS[session_id] = {"tracker": Tracker(), "frame_count": 0}
|
| 96 |
+
print(f"New session created: {session_id}")
|
| 97 |
+
return JSONResponse(content={"session_id": session_id})
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@app.post("/predict/{session_id}", summary="Run a single frame prediction for a session")
|
| 101 |
+
async def predict(
|
| 102 |
+
session_id: str,
|
| 103 |
+
rgb_image: UploadFile = File(..., description="Front-facing RGB camera image."),
|
| 104 |
+
measurements_json: UploadFile = File(..., description="JSON file with vehicle measurements."),
|
| 105 |
+
api_key: str = Depends(get_api_key)
|
| 106 |
+
):
|
| 107 |
+
"""
|
| 108 |
+
يشغل التنبؤ لإطار واحد ضمن جلسة موجودة.
|
| 109 |
+
يستخدم الـ Tracker المستمر الخاص بالجلسة لتتبع الأجسام عبر الزمن.
|
| 110 |
+
"""
|
| 111 |
+
if session_id not in SESSIONS:
|
| 112 |
+
raise HTTPException(status_code=404, detail="Session not found. Please create a new session.")
|
| 113 |
+
|
| 114 |
+
session_data = SESSIONS[session_id]
|
| 115 |
+
tracker = session_data["tracker"]
|
| 116 |
+
session_data["frame_count"] += 1
|
| 117 |
+
current_frame = session_data["frame_count"]
|
| 118 |
+
|
| 119 |
+
try:
|
| 120 |
+
# --- قراءة ومعالجة المدخلات ---
|
| 121 |
+
image_bytes = await rgb_image.read()
|
| 122 |
+
measurements_string = await measurements_json.read()
|
| 123 |
+
rgb_pil = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 124 |
+
m_dict = json.loads(measurements_string)
|
| 125 |
+
|
| 126 |
+
# --- تجهيز التنسورات للنموذج ---
|
| 127 |
+
front_tensor = transform(rgb_pil).unsqueeze(0).to(DEVICE)
|
| 128 |
+
dummy_tensor = torch.zeros_like(front_tensor)
|
| 129 |
+
measurements_tensor = torch.tensor([[
|
| 130 |
+
m_dict.get(k, 0.0) for k in ['x', 'y', 'theta', 'speed', 'steer', 'throttle', 'brake', 'command', 'is_junction', 'should_brake']
|
| 131 |
+
]], dtype=torch.float32).to(DEVICE)
|
| 132 |
+
target_point_tensor = torch.tensor([[0.0, 100.0]], dtype=torch.float32).to(DEVICE)
|
| 133 |
+
|
| 134 |
+
inputs = {
|
| 135 |
+
'rgb': front_tensor, 'rgb_left': dummy_tensor, 'rgb_right': dummy_tensor,
|
| 136 |
+
'rgb_center': dummy_tensor, 'lidar': dummy_tensor,
|
| 137 |
+
'measurements': measurements_tensor, 'target_point': target_point_tensor
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
# --- تشغيل النموذج والتحكم ---
|
| 141 |
+
with torch.no_grad():
|
| 142 |
+
outputs = model(inputs)
|
| 143 |
+
traffic, waypoints, is_junction, traffic_light, stop_sign, _ = outputs
|
| 144 |
+
|
| 145 |
+
traffic_np = traffic[0].detach().cpu().numpy().reshape(20, 20, -1)
|
| 146 |
+
waypoints_np = waypoints[0].detach().cpu().numpy() * WAYPOINT_SCALE_FACTOR
|
| 147 |
+
|
| 148 |
+
pos = [m_dict.get('x', 0.0), m_dict.get('y', 0.0)]
|
| 149 |
+
theta = m_dict.get('theta', 0.0)
|
| 150 |
+
|
| 151 |
+
# استخدام Tracker المستمر الخاص بالجلسة
|
| 152 |
+
updated_traffic = tracker.update_and_predict(traffic_np.copy(), pos, theta, current_frame)
|
| 153 |
+
|
| 154 |
+
controller = InterfuserController(ControllerConfig())
|
| 155 |
+
steer, throttle, brake, _ = controller.run_step(
|
| 156 |
+
m_dict.get('speed', 5.0), waypoints_np, is_junction.sigmoid()[0,1].item(),
|
| 157 |
+
traffic_light.sigmoid()[0,0].item(), stop_sign.sigmoid()[0,1].item(), updated_traffic
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# --- بناء وإرجاع الاستجابة ---
|
| 161 |
+
control_commands = {"steer": float(steer), "throttle": float(throttle), "brake": bool(brake)}
|
| 162 |
+
return JSONResponse(content={"status": "success", "control_commands": control_commands})
|
| 163 |
+
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print(traceback.format_exc())
|
| 166 |
+
raise HTTPException(status_code=500, detail=f"An internal error occurred: {str(e)}")
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@app.delete("/sessions/{session_id}", summary="Delete a tracking session")
|
| 170 |
+
async def delete_session(session_id: str, api_key: str = Depends(get_api_key)):
|
| 171 |
+
"""
|
| 172 |
+
يحذف جلسة تتبع لتحرير الموارد على الخادم.
|
| 173 |
+
"""
|
| 174 |
+
if session_id in SESSIONS:
|
| 175 |
+
del SESSIONS[session_id]
|
| 176 |
+
print(f"Session deleted: {session_id}")
|
| 177 |
+
return JSONResponse(content={"message": "Session deleted successfully."})
|
| 178 |
+
raise HTTPException(status_code=404, detail="Session not found.")
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
# ==============================================================================
|
| 182 |
+
# 3. نقطة بداية تشغيل الخادم
|
| 183 |
+
# ==============================================================================
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
print("--- Interfuser API Server ---")
|
| 186 |
+
print("API documentation will be available at http://127.0.0.1:8000/docs")
|
| 187 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|