Aly Hassan Kamel
Update app.py
7112c74 verified
Raw History Blame Contribute Delete
11.6 kB
"""
Smart Mall Vehicle Analytics System
=====================================
Gradio app for Hugging Face Spaces.
Pipeline:
1. Input: single image OR video file
2. EfficientNetV2 -> car brand / model / price segment (HF_CAR_CLASSIFIER_REPO)
3. YOLOv11n plate detector -> plate bounding box (HF_PLATE_DETECTOR_REPO)
4. YOLOv11n char OCR -> Arabic letters + digits (HF_CHAR_OCR_REPO)
5. Scorer -> plate prestige + purchasing power
"""
import logging
import os
import tempfile
import cv2
import gradio as gr
import numpy as np
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
# Read repos from env (set as Space Secrets)
HF_TOKEN = os.getenv("HF_TOKEN", "")
HF_PLATE_DETECTOR_REPO = os.getenv("HF_PLATE_DETECTOR_REPO", "alyhassankamel/egyptian_license_plate_detector")
HF_CHAR_OCR_REPO = os.getenv("HF_CHAR_OCR_REPO", "alyhassankamel/egyptian-license-plate-ocr")
HF_CAR_CLASSIFIER_REPO = os.getenv("HF_CAR_CLASSIFIER_REPO", "PatrickBLB/egyptian_cars_recognition_computer_vision_model")
CONF_THRESHOLD = float(os.getenv("CONF_THRESHOLD", "0.25"))
MODEL_DIR = "/tmp/models"
os.makedirs(MODEL_DIR, exist_ok=True)
# ---------- Model downloader --------------------------------------------------
def download_model(repo_id: str, filename: str, dest_name: str) -> str | None:
local_path = os.path.join(MODEL_DIR, dest_name)
if os.path.exists(local_path):
return local_path
try:
from huggingface_hub import hf_hub_download
logger.info(f"Downloading {filename} from {repo_id} ...")
path = hf_hub_download(
repo_id=repo_id,
filename=filename,
token=HF_TOKEN or None,
local_dir=MODEL_DIR,
local_dir_use_symlinks=False,
)
# hf_hub_download may save to a subfolder - copy to flat path
import shutil
if os.path.abspath(path) != os.path.abspath(local_path):
shutil.copy2(path, local_path)
logger.info(f"Saved to {local_path}")
return local_path
except Exception as e:
logger.error(f"Failed to download {filename} from {repo_id}: {e}")
return None
# ---------- Lazy pipeline singleton ------------------------------------------
_pipeline = None
def get_pipeline():
global _pipeline
if _pipeline is not None:
return _pipeline
import traceback
logger.info("=" * 60)
logger.info("Initializing pipeline (first request)...")
logger.info(f"HF_TOKEN set : {'YES' if HF_TOKEN else 'NO <-- THIS IS THE PROBLEM'}")
logger.info(f"PLATE DETECTOR REPO: {HF_PLATE_DETECTOR_REPO}")
logger.info(f"CHAR OCR REPO : {HF_CHAR_OCR_REPO}")
logger.info(f"CAR CLASSIFIER REPO: {HF_CAR_CLASSIFIER_REPO}")
logger.info("=" * 60)
plate_path = download_model(HF_PLATE_DETECTOR_REPO, "best.pt", "plate_detector.pt")
logger.info(f"Plate detector path: {plate_path}")
ocr_path = download_model(HF_CHAR_OCR_REPO, "best.pt", "char_ocr.pt")
logger.info(f"OCR path : {ocr_path}")
clf_path = download_model(HF_CAR_CLASSIFIER_REPO, "best.pt", "car_classifier.pt")
logger.info(f"Classifier path : {clf_path}")
if not plate_path or not ocr_path:
logger.error("FAILED: One or more required models could not be downloaded. See errors above.")
return None
# Tell config where the downloaded files are
os.environ["PLATE_DETECTOR_MODEL_PATH"] = plate_path
os.environ["CHAR_OCR_MODEL_PATH"] = ocr_path
os.environ["CAR_CLASSIFIER_MODEL_PATH"] = clf_path or ""
os.environ["CONF_THRESHOLD"] = str(CONF_THRESHOLD)
os.environ["HF_TOKEN"] = HF_TOKEN
os.environ["HF_CAR_CLASSIFIER_REPO"] = HF_CAR_CLASSIFIER_REPO
try:
from app.pipeline.coordinator import LPRPipeline
_pipeline = LPRPipeline()
logger.info("Pipeline ready")
except Exception as e:
logger.error(f"Pipeline init failed: {e}")
logger.error(traceback.format_exc())
_pipeline = None
return _pipeline
# ---------- Frame utilities ---------------------------------------------------
def sharpness(frame: np.ndarray) -> float:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
return cv2.Laplacian(gray, cv2.CV_64F).var()
def extract_best_frames(video_path: str, max_frames: int = 5) -> list[np.ndarray]:
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return []
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
window = max(1, total // max_frames)
best = []
for w in range(max_frames):
start = w * window
end = min(start + window, total)
candidates = []
for idx in range(start, end, max(1, (end - start) // 5)):
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
ret, frame = cap.read()
if ret:
candidates.append((sharpness(frame), frame))
if candidates:
candidates.sort(key=lambda x: x[0], reverse=True)
best.append(candidates[0][1])
cap.release()
return best
# ---------- Drawing & formatting ---------------------------------------------
def draw_detections(image_bgr: np.ndarray, detections: list[dict]) -> np.ndarray:
out = image_bgr.copy()
for i, det in enumerate(detections):
x1, y1, x2, y2 = [int(v) for v in det["bbox"]]
cv2.rectangle(out, (x1, y1), (x2, y2), (0, 220, 80), 3)
label = f"#{i+1} {det['plate_string']}"
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2)
cv2.rectangle(out, (x1, max(0, y1 - th - 10)), (x1 + tw + 6, y1), (0, 220, 80), -1)
cv2.putText(out, label, (x1 + 3, max(th, y1 - 5)),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2)
return out
def format_results(detections: list[dict], frame_index: int | None = None) -> str:
if not detections:
return "No license plates detected."
lines = []
if frame_index is not None:
lines.append(f"Frame #{frame_index + 1}\n")
for i, det in enumerate(detections):
segment = det["segment"].title() if det["segment"] != "unknown" else "Unknown"
brand = det.get("car_brand", "unknown").title()
model = det.get("car_model", "unknown").title()
vehicle = f"{brand} {model}".strip() or "Unknown"
price = det.get("estimated_price")
price_str = f"EGP {price:,.0f}" if price else "N/A"
lines.append(
f"-- Detection #{i+1} --\n"
f"Plate Text : {det['plate_string']}\n"
f"Digits : {det['digits']}\n"
f"Letters : {det['letters']}\n"
f"Vehicle : {vehicle}\n"
f"Segment : {segment} (score: {det['segment_score']:.2f})\n"
f"Est. Price : {price_str}\n"
f"Plate Prestige : {det['plate_score']:.2f}\n"
f"Purchasing Power : {det['purchasing_power']:.2f}\n"
)
return "\n".join(lines)
# ---------- Inference ---------------------------------------------------------
def process_image(image: np.ndarray):
if image is None:
return None, "No image provided."
pipeline = get_pipeline()
if pipeline is None:
return image, "Pipeline failed to initialize. Check HF_TOKEN and model repos."
bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
result = pipeline.process(bgr)
if not result["success"]:
return image, f"Pipeline error: {result.get('error', 'Unknown')}"
if result["num_plates"] == 0:
return image, "No license plates detected."
annotated = cv2.cvtColor(draw_detections(bgr, result["detections"]), cv2.COLOR_BGR2RGB)
return annotated, format_results(result["detections"])
def process_video(video_path: str):
if not video_path:
return [], "No video provided."
pipeline = get_pipeline()
if pipeline is None:
return [], "Pipeline failed to initialize. Check HF_TOKEN and model repos."
frames = extract_best_frames(video_path, max_frames=5)
if not frames:
return [], "Could not read frames from video."
annotated_frames, all_text = [], []
for i, frame_bgr in enumerate(frames):
result = pipeline.process(frame_bgr)
rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
if not result["success"] or result["num_plates"] == 0:
annotated_frames.append(rgb)
all_text.append(f"Frame #{i+1}: No plates detected.")
continue
annotated_frames.append(cv2.cvtColor(draw_detections(frame_bgr, result["detections"]), cv2.COLOR_BGR2RGB))
all_text.append(format_results(result["detections"], frame_index=i))
return annotated_frames, "\n\n".join(all_text)
# ---------- Gradio UI ---------------------------------------------------------
CSS = """
#title { text-align:center; font-size:2rem; font-weight:800; margin-bottom:.2rem; }
#subtitle { text-align:center; color:#888; margin-bottom:1.5rem; }
.mono { font-family:'Courier New',monospace; font-size:.88rem; }
"""
with gr.Blocks(title="Smart Mall Vehicle Analytics") as demo:
gr.HTML("<h1 id='title'>Smart Mall Vehicle Analytics</h1>")
gr.HTML(
"<p id='subtitle'>Upload a <b>car image</b> or <b>video clip</b> — "
"get license plate, car model, segment, price estimate and purchasing power score.</p>"
)
with gr.Tabs():
with gr.TabItem("Image"):
with gr.Row():
with gr.Column(scale=1):
img_input = gr.Image(type="numpy", label="Upload Vehicle Photo")
img_btn = gr.Button("Analyze", variant="primary", size="lg")
with gr.Column(scale=1):
img_output = gr.Image(type="numpy", label="Annotated Result")
img_text = gr.Textbox(label="Detection Details", lines=16,
elem_classes=["mono"])
img_btn.click(fn=process_image, inputs=img_input, outputs=[img_output, img_text])
with gr.TabItem("Video"):
with gr.Row():
with gr.Column(scale=1):
vid_input = gr.Video(label="Upload Video Clip")
vid_btn = gr.Button("Analyze", variant="primary", size="lg")
with gr.Column(scale=1):
vid_gallery = gr.Gallery(label="Annotated Frames", columns=2, height="auto")
vid_text = gr.Textbox(label="Detection Details (all frames)", lines=20,
elem_classes=["mono"])
vid_btn.click(fn=process_video, inputs=vid_input, outputs=[vid_gallery, vid_text])
gr.HTML(
"<div style='text-align:center;margin-top:1rem;color:#666;font-size:.8rem'>"
"YOLOv11n Plate Detector · YOLOv11n Arabic OCR · EfficientNetV2 Car Classifier"
"</div>"
)
demo.launch(
server_name="0.0.0.0",
theme=gr.themes.Base(primary_hue="emerald", neutral_hue="slate",
font=gr.themes.GoogleFont("DM Sans")),
css=CSS,
)