Update app.py
Browse files
app.py
CHANGED
|
@@ -76,7 +76,7 @@ def _get_model(conf: float, iou: float):
|
|
| 76 |
except Exception as e:
|
| 77 |
last_err = e
|
| 78 |
if _model is None:
|
| 79 |
-
_model_err = f"Model load failed. Last error: {last_err}"
|
| 80 |
if _model_err:
|
| 81 |
raise RuntimeError(_model_err)
|
| 82 |
_model.overrides["conf"] = float(conf)
|
|
@@ -166,74 +166,118 @@ def _save_pdf(title: str, summary: str, counts: Dict[str, int], annotated_image_
|
|
| 166 |
return out_path
|
| 167 |
|
| 168 |
# =========================
|
| 169 |
-
# INFERENCE
|
| 170 |
# =========================
|
| 171 |
-
def
|
| 172 |
-
if image is None:
|
| 173 |
-
return None, [], "No image provided.", None, None
|
| 174 |
-
cv2 = _lazy_cv2()
|
| 175 |
-
model = _get_model(conf, iou)
|
| 176 |
-
results = model.predict(image, imgsz=960, verbose=False)
|
| 177 |
-
r = results[0]
|
| 178 |
-
rows = _results_to_rows(results)
|
| 179 |
-
annotated = r.plot() # BGR ndarray
|
| 180 |
-
counts = _count_by_class(rows)
|
| 181 |
-
summary = "Detections: " + (", ".join(f"{k}: {v}" for k, v in counts.items()) if rows else "none")
|
| 182 |
-
tmp_img = os.path.join(tempfile.gettempdir(), f"annotated_{int(time.time())}.jpg")
|
| 183 |
try:
|
| 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 |
try:
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
if not ok:
|
| 212 |
-
break
|
| 213 |
-
frames += 1
|
| 214 |
-
if frames > int(max_frames):
|
| 215 |
-
break
|
| 216 |
-
results = model.predict(frame, imgsz=960, verbose=False)
|
| 217 |
-
r = results[0]
|
| 218 |
-
for row in _results_to_rows(results):
|
| 219 |
-
totals[row["class"]] = totals.get(row["class"], 0) + 1
|
| 220 |
-
annotated = r.plot()
|
| 221 |
-
writer.write(annotated)
|
| 222 |
-
finally:
|
| 223 |
-
cap.release()
|
| 224 |
-
writer.release()
|
| 225 |
-
summary = "Detections (frame-wise tallies): " + (", ".join(f"{k}: {v}" for k, v in totals.items()) if totals else "none")
|
| 226 |
-
tally_rows = [{"class": k, "count": v} for k, v in sorted(totals.items())]
|
| 227 |
-
csv_path = _save_csv(tally_rows)
|
| 228 |
-
return out_path, totals, summary, csv_path
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
| 234 |
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
# =========================
|
| 239 |
# UI (local embedded samples)
|
|
@@ -259,9 +303,10 @@ If they’re missing, you can still upload your own.
|
|
| 259 |
# ---------- IMAGE ----------
|
| 260 |
with gr.TabItem("Image"):
|
| 261 |
with gr.Row():
|
|
|
|
| 262 |
image_in = gr.Image(
|
| 263 |
value=EMBED_IMG if os.path.exists(EMBED_IMG) else None,
|
| 264 |
-
type="filepath",
|
| 265 |
label="Input Image (embedded or upload)"
|
| 266 |
)
|
| 267 |
with gr.Column():
|
|
@@ -285,11 +330,8 @@ If they’re missing, you can still upload your own.
|
|
| 285 |
pdf_img_path = gr.File(label="PDF Report", interactive=False)
|
| 286 |
annotated_tmp_img_path = gr.State(value=None)
|
| 287 |
|
| 288 |
-
def _run_img(image, conf, iou):
|
| 289 |
-
return detect_image(image, conf, iou)
|
| 290 |
-
|
| 291 |
run_img.click(
|
| 292 |
-
fn=
|
| 293 |
inputs=[image_in, conf_img, iou_img],
|
| 294 |
outputs=[image_out, table_out, msg_img, csv_img_path, annotated_tmp_img_path],
|
| 295 |
)
|
|
@@ -328,25 +370,14 @@ If they’re missing, you can still upload your own.
|
|
| 328 |
pdf_vid_btn = gr.Button("Generate PDF Report")
|
| 329 |
pdf_vid_path = gr.File(label="PDF Report", interactive=False)
|
| 330 |
|
| 331 |
-
def _run_vid(vpath, conf, iou, maxf):
|
| 332 |
-
out_path, counts, summary, csv_path = detect_video(vpath, conf, iou, int(maxf))
|
| 333 |
-
return out_path, json.dumps(counts or {}, ensure_ascii=False, indent=2), summary, csv_path
|
| 334 |
-
|
| 335 |
run_vid.click(
|
| 336 |
-
fn=
|
| 337 |
inputs=[video_in, conf_vid, iou_vid, max_frames],
|
| 338 |
outputs=[video_out, counts_text, msg_vid, csv_vid_path],
|
| 339 |
)
|
| 340 |
|
| 341 |
-
def _export_pdf_vid(summary: str, counts_json_str: str):
|
| 342 |
-
try:
|
| 343 |
-
counts = json.loads(counts_json_str) if counts_json_str else {}
|
| 344 |
-
except Exception:
|
| 345 |
-
counts = {}
|
| 346 |
-
return export_pdf_vid(summary, counts)
|
| 347 |
-
|
| 348 |
pdf_vid_btn.click(
|
| 349 |
-
fn=
|
| 350 |
inputs=[msg_vid, counts_text],
|
| 351 |
outputs=[pdf_vid_path],
|
| 352 |
)
|
|
|
|
| 76 |
except Exception as e:
|
| 77 |
last_err = e
|
| 78 |
if _model is None:
|
| 79 |
+
_model_err = f"Model load failed. Tried {len(MODEL_CANDIDATES)} candidate(s). Last error: {last_err}"
|
| 80 |
if _model_err:
|
| 81 |
raise RuntimeError(_model_err)
|
| 82 |
_model.overrides["conf"] = float(conf)
|
|
|
|
| 166 |
return out_path
|
| 167 |
|
| 168 |
# =========================
|
| 169 |
+
# INFERENCE (SAFE WRAPPERS)
|
| 170 |
# =========================
|
| 171 |
+
def detect_image_safe(image, conf: float, iou: float):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
try:
|
| 173 |
+
if image is None:
|
| 174 |
+
return None, [], "⚠️ No image provided.", None, None
|
| 175 |
+
cv2 = _lazy_cv2()
|
| 176 |
+
|
| 177 |
+
# If the component is type="filepath", it sends a string path.
|
| 178 |
+
# If type="numpy", it sends an array. Ultralytics handles both,
|
| 179 |
+
# but we’ll keep it robust either way.
|
| 180 |
+
model = _get_model(conf, iou)
|
| 181 |
+
results = model.predict(image, imgsz=960, verbose=False)
|
| 182 |
+
r = results[0]
|
| 183 |
+
rows = _results_to_rows(results)
|
| 184 |
+
annotated = r.plot() # BGR ndarray
|
| 185 |
+
counts = _count_by_class(rows)
|
| 186 |
+
summary = "Detections: " + (", ".join(f"{k}: {v}" for k, v in counts.items()) if rows else "none")
|
| 187 |
+
|
| 188 |
+
tmp_img = os.path.join(tempfile.gettempdir(), f"annotated_{int(time.time())}.jpg")
|
| 189 |
+
try:
|
| 190 |
+
cv2.imwrite(tmp_img, annotated)
|
| 191 |
+
except Exception:
|
| 192 |
+
tmp_img = None
|
| 193 |
+
|
| 194 |
+
csv_path = _save_csv(rows)
|
| 195 |
+
|
| 196 |
+
# Convert BGR->RGB for display if ndarray
|
| 197 |
+
try:
|
| 198 |
+
if hasattr(annotated, "shape") and len(annotated.shape) == 3:
|
| 199 |
+
annotated = annotated[:, :, ::-1]
|
| 200 |
+
except Exception:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
return annotated, rows, summary, csv_path, tmp_img
|
| 204 |
+
|
| 205 |
+
except Exception as e:
|
| 206 |
+
# Return error in the summary field instead of crashing
|
| 207 |
+
return None, [], f"❌ Error during image detection: {e}", None, None
|
| 208 |
+
|
| 209 |
+
def detect_video_safe(video_path: str, conf: float, iou: float, max_frames: int = 300):
|
| 210 |
try:
|
| 211 |
+
if not video_path:
|
| 212 |
+
return None, "{}", "⚠️ No video provided.", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
+
cv2 = _lazy_cv2()
|
| 215 |
+
model = _get_model(conf, iou)
|
| 216 |
+
|
| 217 |
+
cap = cv2.VideoCapture(video_path)
|
| 218 |
+
if not cap.isOpened():
|
| 219 |
+
return None, "{}", "❌ Failed to open video.", None
|
| 220 |
|
| 221 |
+
fps = cap.get(cv2.CAP_PROP_FPS) or 24.0
|
| 222 |
+
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 1280)
|
| 223 |
+
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 720)
|
| 224 |
+
|
| 225 |
+
writer, out_path = _write_video(os.path.join(tempfile.gettempdir(), f"annotated_{int(time.time())}"), fps, w, h)
|
| 226 |
+
if writer is None or (hasattr(writer, "isOpened") and not writer.isOpened()):
|
| 227 |
+
cap.release()
|
| 228 |
+
return None, "{}", "❌ Video writer could not open. Try another format/resolution.", None
|
| 229 |
+
|
| 230 |
+
totals: Dict[str, int] = {}
|
| 231 |
+
frames = 0
|
| 232 |
+
try:
|
| 233 |
+
while True:
|
| 234 |
+
ok, frame = cap.read()
|
| 235 |
+
if not ok:
|
| 236 |
+
break
|
| 237 |
+
frames += 1
|
| 238 |
+
if frames > int(max_frames):
|
| 239 |
+
break
|
| 240 |
+
|
| 241 |
+
results = model.predict(frame, imgsz=960, verbose=False)
|
| 242 |
+
r = results[0]
|
| 243 |
+
|
| 244 |
+
for row in _results_to_rows(results):
|
| 245 |
+
totals[row["class"]] = totals.get(row["class"], 0) + 1
|
| 246 |
+
|
| 247 |
+
annotated = r.plot()
|
| 248 |
+
writer.write(annotated)
|
| 249 |
+
finally:
|
| 250 |
+
cap.release()
|
| 251 |
+
writer.release()
|
| 252 |
+
|
| 253 |
+
summary = "Detections (frame-wise tallies): " + (", ".join(f"{k}: {v}" for k, v in totals.items()) if totals else "none")
|
| 254 |
+
tally_rows = [{"class": k, "count": v} for k, v in sorted(totals.items())]
|
| 255 |
+
csv_path = _save_csv(tally_rows)
|
| 256 |
+
counts_json = json.dumps(totals or {}, ensure_ascii=False, indent=2)
|
| 257 |
+
|
| 258 |
+
return out_path, counts_json, summary, csv_path
|
| 259 |
+
|
| 260 |
+
except Exception as e:
|
| 261 |
+
return None, "{}", f"❌ Error during video detection: {e}", None
|
| 262 |
+
|
| 263 |
+
def export_pdf_img(summary: str, table_rows: List[dict], annotated_tmp_jpg: Optional[str]):
|
| 264 |
+
try:
|
| 265 |
+
counts = _count_by_class(table_rows or [])
|
| 266 |
+
return _save_pdf("UAV Detector — Image Report", summary or "No summary.", counts,
|
| 267 |
+
annotated_tmp_jpg if annotated_tmp_jpg and os.path.exists(annotated_tmp_jpg) else None)
|
| 268 |
+
except Exception as e:
|
| 269 |
+
# Create a tiny report that just contains the error
|
| 270 |
+
return _save_pdf("UAV Detector — Image Report", f"❌ PDF export error: {e}", {}, None)
|
| 271 |
+
|
| 272 |
+
def export_pdf_vid(summary: str, counts_json: str):
|
| 273 |
+
try:
|
| 274 |
+
counts = json.loads(counts_json) if counts_json else {}
|
| 275 |
+
except Exception:
|
| 276 |
+
counts = {}
|
| 277 |
+
try:
|
| 278 |
+
return _save_pdf("UAV Detector — Video Report", summary or "No summary.", counts or {}, None)
|
| 279 |
+
except Exception as e:
|
| 280 |
+
return _save_pdf("UAV Detector — Video Report", f"❌ PDF export error: {e}", {}, None)
|
| 281 |
|
| 282 |
# =========================
|
| 283 |
# UI (local embedded samples)
|
|
|
|
| 303 |
# ---------- IMAGE ----------
|
| 304 |
with gr.TabItem("Image"):
|
| 305 |
with gr.Row():
|
| 306 |
+
# Use type="filepath" so embedded path loads directly. Uploads also pass a path.
|
| 307 |
image_in = gr.Image(
|
| 308 |
value=EMBED_IMG if os.path.exists(EMBED_IMG) else None,
|
| 309 |
+
type="filepath",
|
| 310 |
label="Input Image (embedded or upload)"
|
| 311 |
)
|
| 312 |
with gr.Column():
|
|
|
|
| 330 |
pdf_img_path = gr.File(label="PDF Report", interactive=False)
|
| 331 |
annotated_tmp_img_path = gr.State(value=None)
|
| 332 |
|
|
|
|
|
|
|
|
|
|
| 333 |
run_img.click(
|
| 334 |
+
fn=detect_image_safe,
|
| 335 |
inputs=[image_in, conf_img, iou_img],
|
| 336 |
outputs=[image_out, table_out, msg_img, csv_img_path, annotated_tmp_img_path],
|
| 337 |
)
|
|
|
|
| 370 |
pdf_vid_btn = gr.Button("Generate PDF Report")
|
| 371 |
pdf_vid_path = gr.File(label="PDF Report", interactive=False)
|
| 372 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
run_vid.click(
|
| 374 |
+
fn=detect_video_safe,
|
| 375 |
inputs=[video_in, conf_vid, iou_vid, max_frames],
|
| 376 |
outputs=[video_out, counts_text, msg_vid, csv_vid_path],
|
| 377 |
)
|
| 378 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
pdf_vid_btn.click(
|
| 380 |
+
fn=export_pdf_vid,
|
| 381 |
inputs=[msg_vid, counts_text],
|
| 382 |
outputs=[pdf_vid_path],
|
| 383 |
)
|