Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234562 unmodified lines910111213141516171819202122232425262728292 unmodified lines32333435363738394041424344454647484950515253545512 unmodified lines686970717273744 unmodified lines798081828384856 unmodified lines92939495969798991001 unmodified line10210310410510610710810911011111211 unmodified lines12412512612712812913030 unmodified lines1611621631641651661673 unmodified lines17117217317417517617728 unmodified lines20620720820921021121211 unmodified lines22422522622722822923034 unmodified lines26526626726826927027127227327427527627727827928028113 unmodified lines2952962972982993003011 unmodified line30330430530630730830931031131231331422 unmodified lines337338339340341342343344345346347348"""Đếm xe qua line - Deploy lên Hugging Face Spaces với Gradio"""import osimport tempfileimport cv22 unmodified linesimport supervision as svfrom ultralytics import YOLO# Cấu hình mặc định cho tối ưuDEFAULT_MAX_FRAME_SIZE = 640 # Giới hạn kích thước khung hình đưa vào YOLODEFAULT_DETECT_EVERY_N_FRAMES = 2 # Chỉ detect mỗi N frame để giảm tải CPU# Load model (yolov8n nhẹ cho CPU miễn phí)model = YOLO("yolov8n.pt")CLASS_NAMES_DICT = model.model.namesSELECTED_CLASS_NAMES = ['person', 'bus', 'motorcycle', 'car', 'truck']SELECTED_CLASS_IDS = [{value: key for key, value in CLASS_NAMES_DICT.items()}[name]for name in SELECTED_CLASS_NAMES]# Annotators (tạo 1 lần, dùng lại)box_annotator = sv.BoxAnnotator(thickness=4)label_annotator = sv.LabelAnnotator(text_thickness=2, text_scale=1.5, text_color=sv.Color.BLACK)trace_annotator = sv.TraceAnnotator(thickness=4, trace_length=50)2 unmodified linesuse_resize: bool = True,max_frame_size: int = DEFAULT_MAX_FRAME_SIZE,detect_every_n: int = DEFAULT_DETECT_EVERY_N_FRAMES,line_orientation: str = "Ngang", # "Ngang" | "Dọc"):"""Xử lý video: đếm xe qua line và trả về video đã annotate.Các tham số tối ưu và cấu hình được truyền từ UI:- use_resize: có resize khung hình trước khi detect hay không- max_frame_size: cạnh dài tối đa sau resize- detect_every_n: chỉ detect mỗi N frame (1 = detect mọi frame)- line_orientation: "Ngang" hoặc "Dọc""""if video_path is None:return None# Gradio Video có thể trả về dict với key "path"if isinstance(video_path, dict):video_path = video_path.get("path", video_path)# Lấy thông tin video (dùng cho tracker)video_info = sv.VideoInfo.from_video_path(video_path)byte_tracker = sv.ByteTrack(12 unmodified linesdef callback(frame: np.ndarray, index: int) -> np.ndarray:nonlocal previous_positions, class_counts, crossed_ids# Đảm bảo giá trị hợp lệif max_frame_size is None or max_frame_size <= 0:max_size = DEFAULT_MAX_FRAME_SIZEelse:4 unmodified lineselse:detect_every = int(detect_every_n)# Resize khung hình trước khi đưa vào YOLO để giảm tải (nếu bật)fh_orig, fw_orig = frame.shape[:2]if use_resize:scale = min(1.0, max_size / max(fh_orig, fw_orig))6 unmodified lineselse:frame_infer = frame# Tính lại kích thước sau khi resizefh, fw = frame_infer.shape[:2]# Vị trí line theo hướng người dùng chọnif line_orientation == "Dọc":line_pos = int(fw * 0.5)is_horizontal = False1 unmodified lineline_pos = int(fh * 0.5)is_horizontal = True# Bỏ qua một số frame để giảm số lần detectif detect_every > 1 and index % detect_every != 0:annotator_frame = frame_infer.copy()# Vẽ line đếm theo cấu hìnhif is_horizontal:cv2.line(annotator_frame,11 unmodified lines2,)# Khung tổng đếm (dùng class_counts hiện tại)box_w, box_h = 280, 50 + len(SELECTED_CLASS_NAMES) * 28x0, y0 = fw - box_w - 20, 2030 unmodified linesdetections = detections[np.isin(detections.class_id, SELECTED_CLASS_IDS)]detections = byte_tracker.update_with_detections(detections)# Đếm theo loại khi qua lineif detections.tracker_id is not None:xyxy = detections.xyxyfor i in range(len(detections)):3 unmodified linescx = (xyxy[i, 0] + xyxy[i, 2]) / 2cy = (xyxy[i, 1] + xyxy[i, 3]) / 2# Toạ độ 1D dùng để kiểm tra qua line (y nếu line ngang, x nếu line dọc)curr_coord = cy if is_horizontal else cxif tid in previous_positions:28 unmodified linesscene=annotator_frame, detections=detections, labels=labels)# Vẽ line đếm theo cấu hìnhif is_horizontal:cv2.line(annotator_frame,11 unmodified lines2,)# Khung tổng đếmbox_w, box_h = 280, 50 + len(SELECTED_CLASS_NAMES) * 28x0, y0 = fw - box_w - 20, 2034 unmodified linesreturn output_path# Gradio UIwith gr.Blocks(title="Đếm xe qua line", theme=gr.themes.Soft(primary_hue="blue", secondary_hue="gray")) as demo:# Header đẹp hơn + thông tin sinh viênwith gr.Row():gr.Markdown("""<div style="display:flex;flex-direction:column;gap:4px;"><h1 style="margin-bottom:4px;">🚗 Đếm xe qua line (YOLOv8 + ByteTrack)</h1><p style="margin:0;font-size:16px;color:#4b5563;">Dự án: Đếm đối tượng qua line (Horizonal / Vertical) dùng YOLOv8 + ByteTrack.</p><p style="margin:0;font-size:14px;color:#6b7280;">Thực hiện: <strong>Trần Hải Nam - 223332840</strong></p>13 unmodified lineswith gr.Column(scale=1):gr.Markdown("### ✅ Kết quả đã xử lý\n""Hiển thị tracking, line đếm và thống kê số lượng theo lớp.")video_output = gr.Video(label="Video đã xử lý")1 unmodified linewith gr.Accordion("⚙️ Tùy chọn nâng cao", open=False):with gr.Row():use_resize = gr.Checkbox(value=True, label="Giảm kích thước khung hình trước khi detect")line_orientation = gr.Radio(choices=["Ngang", "Dọc"],value="Ngang",label="Hướng line đếm",)with gr.Row():max_frame_size = gr.Slider(22 unmodified lines"""---### ℹ️ Gợi ý sử dụng- Mặc định line đếm nằm **ngang** ở giữa khung hình (50% chiều cao).- Có thể chuyển sang line **dọc** trong phần _"Tùy chọn nâng cao"_.- Với CPU miễn phí (Hugging Face Spaces), nên:- Dùng video **ngắn** (< 30 giây).- Tăng `Detect mỗi N frame` nếu muốn xử lý nhanh hơn.- Model sử dụng: **YOLOv8n** (phiên bản nhẹ, phù hợp CPU).""")1232 unmodified lines678910111213141516171819202122232 unmodified lines262728293031323334353637383912 unmodified lines5253545556574 unmodified lines6263646566676 unmodified lines747576777879801 unmodified line82838485868788899011 unmodified lines10210310410510610730 unmodified lines1381391401411421433 unmodified lines14714814915015115228 unmodified lines18118218318418518611 unmodified lines19819920020120220334 unmodified lines23823924024124224324424524624724824913 unmodified lines2632642652662672682691 unmodified line27127227327427527627727827928028128222 unmodified lines305306307308309310311312313314315316import osimport tempfileimport cv22 unmodified linesimport supervision as svfrom ultralytics import YOLODEFAULT_MAX_FRAME_SIZE = 640DEFAULT_DETECT_EVERY_N_FRAMES = 2model = YOLO("yolov8n.pt")CLASS_NAMES_DICT = model.model.namesSELECTED_CLASS_NAMES = ['car', 'truck', 'bus', 'motorcycle', ]SELECTED_CLASS_IDS = [{value: key for key, value in CLASS_NAMES_DICT.items()}[name]for name in SELECTED_CLASS_NAMES]box_annotator = sv.BoxAnnotator(thickness=4)label_annotator = sv.LabelAnnotator(text_thickness=2, text_scale=1.5, text_color=sv.Color.BLACK)trace_annotator = sv.TraceAnnotator(thickness=4, trace_length=50)2 unmodified linesuse_resize: bool = True,max_frame_size: int = DEFAULT_MAX_FRAME_SIZE,detect_every_n: int = DEFAULT_DETECT_EVERY_N_FRAMES,line_orientation: str = "Ngang",):if video_path is None:return Noneif isinstance(video_path, dict):video_path = video_path.get("path", video_path)video_info = sv.VideoInfo.from_video_path(video_path)byte_tracker = sv.ByteTrack(12 unmodified linesdef callback(frame: np.ndarray, index: int) -> np.ndarray:nonlocal previous_positions, class_counts, crossed_idsif max_frame_size is None or max_frame_size <= 0:max_size = DEFAULT_MAX_FRAME_SIZEelse:4 unmodified lineselse:detect_every = int(detect_every_n)fh_orig, fw_orig = frame.shape[:2]if use_resize:scale = min(1.0, max_size / max(fh_orig, fw_orig))6 unmodified lineselse:frame_infer = framefh, fw = frame_infer.shape[:2]if line_orientation == "Dọc":line_pos = int(fw * 0.5)is_horizontal = False1 unmodified lineline_pos = int(fh * 0.5)is_horizontal = Trueif detect_every > 1 and index % detect_every != 0:annotator_frame = frame_infer.copy()if is_horizontal:cv2.line(annotator_frame,11 unmodified lines2,)box_w, box_h = 280, 50 + len(SELECTED_CLASS_NAMES) * 28x0, y0 = fw - box_w - 20, 2030 unmodified linesdetections = detections[np.isin(detections.class_id, SELECTED_CLASS_IDS)]detections = byte_tracker.update_with_detections(detections)if detections.tracker_id is not None:xyxy = detections.xyxyfor i in range(len(detections)):3 unmodified linescx = (xyxy[i, 0] + xyxy[i, 2]) / 2cy = (xyxy[i, 1] + xyxy[i, 3]) / 2curr_coord = cy if is_horizontal else cxif tid in previous_positions:28 unmodified linesscene=annotator_frame, detections=detections, labels=labels)if is_horizontal:cv2.line(annotator_frame,11 unmodified lines2,)box_w, box_h = 280, 50 + len(SELECTED_CLASS_NAMES) * 28x0, y0 = fw - box_w - 20, 2034 unmodified linesreturn output_pathwith gr.Blocks(title="Nhận dạng phương tiện giao thông", theme=gr.themes.Soft(primary_hue="blue", secondary_hue="gray")) as demo:with gr.Row():gr.Markdown("""<div style="display:flex;flex-direction:column;gap:4px;"><h1 style="margin-bottom:4px;">🚗 Nhận diện phương tiện giao thông (YOLOv8 + ByteTrack)</h1><p style="margin:0;font-size:14px;color:#6b7280;">Thực hiện: <strong>Trần Hải Nam - 223332840</strong></p>13 unmodified lineswith gr.Column(scale=1):gr.Markdown("### ✅ Kết quả đã xử lý\n""Hiển thị và thống kê số lượng theo lớp.")video_output = gr.Video(label="Video đã xử lý")1 unmodified linewith gr.Accordion("⚙️ Tùy chọn nâng cao", open=False):with gr.Row():use_resize = gr.Checkbox(value=True, label="Giảm kích thước khung hình trước khi nhận dạng")line_orientation = gr.Radio(choices=["Ngang", "Dọc"],value="Ngang",label="Hướng phương tiện di chuyển",)with gr.Row():max_frame_size = gr.Slider(22 unmodified lines"""---### ℹ️ Gợi ý sử dụng- Mặc định hướng phương tiện di chuyển để nhận dạng là nằm **ngang** ở giữa khung hình (50% chiều cao).- Có thể chuyển sang hướng **dọc** trong phần _"Tùy chọn nâng cao"_.- Vì sử dụng CPU, nên:- Dùng video **ngắn** (< 30 giây).- Tăng `Detect mỗi N frame` nếu muốn xử lý nhanh hơn.- Model sử dụng: **YOLOv8n**.""")
app.py+13-45