File size: 11,574 Bytes
15433af
 
 
 
 
 
 
 
 
 
 
 
 
a37d0db
15433af
 
a37d0db
15433af
 
 
 
a37d0db
15433af
 
a37d0db
 
15433af
 
 
 
 
 
a37d0db
15433af
 
 
 
 
a37d0db
15433af
 
 
 
a37d0db
15433af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a37d0db
15433af
 
 
 
 
 
 
 
 
 
 
 
 
7112c74
 
 
15433af
7112c74
 
 
 
 
15433af
 
7112c74
 
 
 
 
 
 
15433af
 
7112c74
15433af
 
 
 
 
 
 
 
 
 
a37d0db
15433af
 
 
 
 
7112c74
15433af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a37d0db
 
15433af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a37d0db
 
15433af
 
 
 
 
 
 
 
 
 
 
 
 
a37d0db
 
 
15433af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab737b3
15433af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab737b3
15433af
 
 
 
 
 
 
 
 
 
ab737b3
15433af
 
 
 
 
 
 
 
ab737b3
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""

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,
)