TPPKN2000 commited on
Commit
f94290f
·
verified ·
1 Parent(s): 3f3f522

Upload 5 files

Browse files
Files changed (5) hide show
  1. README.md +84 -9
  2. app.py +167 -0
  3. gitattributes +1 -0
  4. inference.py +91 -0
  5. requirements.txt +6 -0
README.md CHANGED
@@ -1,15 +1,90 @@
1
  ---
2
- title: Object Detection Application
3
- emoji: 🐢
4
- colorFrom: green
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 6.26.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
- license: mit
12
- short_description: Something like a practical application for object detection
13
  ---
14
 
15
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Traffic & Person Detection Demo
3
+ emoji: 🚦
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: "5.4.0"
 
8
  app_file: app.py
9
  pinned: false
 
 
10
  ---
11
 
12
+ # Phát hiện người & phương tiện giao thông đô thị (Gradio + ZeroGPU)
13
+
14
+ Demo web app cho đồ án Statistical Machine Learning — so sánh 3 kiến trúc
15
+ object detection (Faster R-CNN / YOLOv8 / RT-DETR) trên subset 6 lớp của
16
+ PASCAL VOC 07+12: `person, bicycle, car, motorbike, bus, train`.
17
+
18
+ Chọn model ở dropdown, upload ảnh, xem kết quả detect trực tiếp — chạy trên
19
+ **ZeroGPU** (HF Spaces cấp GPU thật, tạm thời, chỉ trong lúc gọi hàm
20
+ `detect()`).
21
+
22
+ ## Cách deploy lên Hugging Face Spaces
23
+
24
+ 1. Tạo Space mới tại https://huggingface.co/new-space:
25
+ - SDK: **Gradio**
26
+ - Hardware: **ZeroGPU** (mục "Space hardware" khi tạo, hoặc đổi sau ở
27
+ Settings > Hardware — cần tài khoản đã bật ZeroGPU / là Pro hoặc tổ
28
+ chức có quyền dùng ZeroGPU).
29
+
30
+ 2. Clone Space repo về máy, copy **toàn bộ** nội dung thư mục này vào —
31
+ chú ý copy cả file ẩn `.gitattributes` (dùng `cp -r source/. dest/`
32
+ hoặc `cp -a`, **không** dùng `cp source/* dest/` vì dấu `*` không khớp
33
+ file bắt đầu bằng dấu chấm, dễ bị thiếu file này).
34
+
35
+ 3. **Thêm 3 file weight vào `weights/`** — xem hướng dẫn chi tiết trong
36
+ `weights/README.md` (tên file + đường dẫn lấy từ Colab phải đúng chính
37
+ xác, mỗi model có cấu trúc thư mục output khác nhau).
38
+
39
+ 4. Kiểm tra `.gitattributes` đã có mặt và đúng nội dung TRƯỚC khi add file
40
+ weight (bắt buộc để git-lfs nhận diện `.pt` là file lớn):
41
+ ```bash
42
+ cat .gitattributes
43
+ # phải in ra: *.pt filter=lfs diff=lfs merge=lfs -text
44
+ ```
45
+
46
+ 5. Push lên Space:
47
+ ```bash
48
+ git lfs install # nếu máy bạn chưa cài git-lfs
49
+ git add .gitattributes # add file này TRƯỚC hoặc CÙNG LÚC với các .pt
50
+ git add .
51
+ git commit -m "add model weights + gradio app"
52
+ git push
53
+ ```
54
+
55
+ 6. Đợi Space build xong (vài phút, xem log ở tab "Logs"), sau đó có link
56
+ public dạng `https://huggingface.co/spaces/<username>/<space-name>`.
57
+
58
+ ## Chạy thử local trước khi deploy (khuyến khích)
59
+
60
+ ```bash
61
+ pip install -r requirements.txt
62
+ python app.py
63
+ ```
64
+ Mở link `http://127.0.0.1:7860` mà Gradio in ra. `@spaces.GPU` tự động
65
+ fallback về chạy bình thường (CPU, hoặc GPU nếu máy bạn có) khi không nằm
66
+ trong môi trường HF Spaces thật, nên test local không cần lo về ZeroGPU.
67
+
68
+ Nếu thiếu file weight nào, app vẫn chạy được bình thường — chỉ ẩn model đó
69
+ khỏi dropdown thay vì crash, nên bạn có thể test dần từng model một khi có
70
+ weight.
71
+
72
+ ## Ghi chú thiết kế (ZeroGPU)
73
+
74
+ - Model được load lên **CPU** ngay khi app khởi động (`get_detector()`,
75
+ cache lại để không load lại từ đĩa mỗi lần đổi model). GPU thật chỉ được
76
+ HF Spaces cấp phát **bên trong** hàm `detect()` (đánh dấu
77
+ `@spaces.GPU(duration=30)`) và thu hồi ngay sau khi hàm trả kết quả —
78
+ đây là cơ chế ZeroGPU: chia sẻ GPU vật lý cho nhiều Space, mỗi lần gọi có
79
+ thể rơi vào GPU khác nhau, nên không giữ model cố định trên 1 device cụ
80
+ thể giữa các lần gọi.
81
+ - `requirements.txt` dùng torch bản CUDA đầy đủ (không dùng bản CPU-only
82
+ như bản Streamlit trước) vì ZeroGPU cần torch có hỗ trợ CUDA thật khi GPU
83
+ được cấp.
84
+ - Faster R-CNN dùng `min_size=600, max_size=1000` khi load lại (khớp với
85
+ cấu hình train được khuyến nghị ở Pha B) — nếu bạn train Faster R-CNN với
86
+ `--min_size/--max_size` khác, sửa lại 2 giá trị này trong
87
+ `inference.py::FasterRCNNDetector.__init__` cho khớp.
88
+ - `duration=30` trong `@spaces.GPU(duration=30)` là số giây tối đa mỗi lần
89
+ gọi được giữ GPU — 30s dư sức cho 1 ảnh, có thể giảm nếu muốn xếp hàng ít
90
+ hơn khi nhiều người dùng cùng lúc.
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ app.py — Gradio demo (ZeroGPU) cho đồ án "Phát hiện người và phương tiện
3
+ giao thông phục vụ giám sát an ninh đô thị".
4
+
5
+ Cho phép chọn 1 trong 3 model (Faster R-CNN / YOLOv8 / RT-DETR) để chạy detect
6
+ trên ảnh do người dùng upload. Model nào chưa có file weight trong weights/
7
+ sẽ tự động bị loại khỏi dropdown (kèm cảnh báo), thay vì làm sập app.
8
+
9
+ ZeroGPU: models được load lên CPU lúc khởi động app (không cần GPU), chỉ
10
+ thực sự dùng GPU bên trong hàm `detect()` được đánh dấu @spaces.GPU -- đây
11
+ là hàm duy nhất HF Spaces cấp phát GPU thật (H200 slice) khi được gọi, và
12
+ thu hồi ngay sau khi hàm return. Xem: https://huggingface.co/docs/hub/spaces-zerogpu
13
+
14
+ Cách thêm weight: xem weights/README.md
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import time
19
+ from pathlib import Path
20
+
21
+ import gradio as gr
22
+ import spaces
23
+ import torch
24
+ from PIL import Image, ImageDraw, ImageFont
25
+
26
+ from inference import FasterRCNNDetector, UltralyticsDetector, VOC_CLASSES
27
+
28
+ WEIGHTS_DIR = Path(__file__).parent / "weights"
29
+
30
+ MODEL_CONFIGS = {
31
+ "Faster R-CNN (ResNet50-FPN v2)": {
32
+ "file": WEIGHTS_DIR / "faster_rcnn_best.pt",
33
+ "kind": "faster_rcnn",
34
+ "paper": "Ren et al., NeurIPS 2015",
35
+ },
36
+ "YOLOv8s": {
37
+ "file": WEIGHTS_DIR / "yolov8_best.pt",
38
+ "kind": "yolo",
39
+ "paper": "Ultralytics (YOLO lineage, Redmon et al.)",
40
+ },
41
+ "RT-DETR-L": {
42
+ "file": WEIGHTS_DIR / "rtdetr_best.pt",
43
+ "kind": "rtdetr",
44
+ "paper": "Lv et al., 2023 — DETRs Beat YOLOs on Real-Time Object Detection",
45
+ },
46
+ }
47
+
48
+ # fixed color per class so the same class always looks the same across models
49
+ COLORS = {
50
+ "person": "#e6194b",
51
+ "bicycle": "#3cb44b",
52
+ "car": "#4363d8",
53
+ "motorbike": "#f58231",
54
+ "bus": "#911eb4",
55
+ "train": "#42d4f4",
56
+ }
57
+
58
+ _detector_cache: dict[str, object] = {}
59
+
60
+
61
+ def get_detector(model_name: str):
62
+ """Lazily construct + cache each detector (on CPU) the first time it's
63
+ selected, so switching models in the dropdown doesn't reload from disk
64
+ every single click."""
65
+ if model_name not in _detector_cache:
66
+ cfg = MODEL_CONFIGS[model_name]
67
+ if cfg["kind"] == "faster_rcnn":
68
+ _detector_cache[model_name] = FasterRCNNDetector(str(cfg["file"]))
69
+ else:
70
+ _detector_cache[model_name] = UltralyticsDetector(str(cfg["file"]), family=cfg["kind"])
71
+ return _detector_cache[model_name]
72
+
73
+
74
+ def draw_boxes(image: Image.Image, detections: list[dict]) -> Image.Image:
75
+ img = image.copy().convert("RGB")
76
+ draw = ImageDraw.Draw(img)
77
+ try:
78
+ font = ImageFont.load_default(size=16)
79
+ except TypeError:
80
+ font = ImageFont.load_default() # older Pillow without `size` kwarg
81
+
82
+ for det in detections:
83
+ x1, y1, x2, y2 = det["box"]
84
+ color = COLORS.get(det["label"], "#ffffff")
85
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=3)
86
+ text = f'{det["label"]} {det["score"]:.2f}'
87
+ text_bbox = draw.textbbox((x1, y1), text, font=font)
88
+ text_h = text_bbox[3] - text_bbox[1]
89
+ draw.rectangle([x1, y1 - text_h - 4, text_bbox[2] + 4, y1], fill=color)
90
+ draw.text((x1 + 2, y1 - text_h - 3), text, fill="white", font=font)
91
+ return img
92
+
93
+
94
+ @spaces.GPU(duration=30)
95
+ def detect(model_name: str, image: Image.Image, conf_thresh: float):
96
+ if image is None:
97
+ return None, [], "⬆️ Hãy tải ảnh lên trước."
98
+ if not model_name:
99
+ return None, [], "⚠️ Chưa có model nào khả dụng (thiếu file weight)."
100
+
101
+ detector = get_detector(model_name)
102
+
103
+ device = "cuda" if torch.cuda.is_available() else "cpu"
104
+ start = time.time()
105
+ detections = detector.predict(image, conf_thresh=conf_thresh, device=device)
106
+ elapsed_ms = (time.time() - start) * 1000
107
+
108
+ annotated = draw_boxes(image, detections)
109
+ table = [
110
+ [d["label"], round(d["score"], 3), ", ".join(f"{v:.0f}" for v in d["box"])]
111
+ for d in sorted(detections, key=lambda d: -d["score"])
112
+ ]
113
+ info = f"⏱️ Thời gian inference: {elapsed_ms:.0f} ms | 🎯 Số đối tượng phát hiện: {len(detections)}"
114
+ if not detections:
115
+ info += "\n\nKhông phát hiện đối tượng nào ở ngưỡng confidence hiện tại — thử giảm ngưỡng."
116
+ return annotated, table, info
117
+
118
+
119
+ available_models = [name for name, cfg in MODEL_CONFIGS.items() if cfg["file"].exists()]
120
+ missing_models = [name for name, cfg in MODEL_CONFIGS.items() if not cfg["file"].exists()]
121
+
122
+ with gr.Blocks(title="Traffic & Person Detection") as demo:
123
+ gr.Markdown("# 🚦 Phát hiện người & phương tiện giao thông đô thị")
124
+ gr.Markdown(
125
+ "Đồ án Statistical Machine Learning — so sánh Faster R-CNN / YOLOv8 / RT-DETR "
126
+ "trên subset 6 lớp của PASCAL VOC (`person, bicycle, car, motorbike, bus, train`). "
127
+ "Chạy trên ZeroGPU."
128
+ )
129
+
130
+ if not available_models:
131
+ gr.Markdown(
132
+ "### ⚠️ Chưa có file weight nào trong `weights/`.\n"
133
+ "Xem `weights/README.md` để biết cách thêm model."
134
+ )
135
+ else:
136
+ if missing_models:
137
+ gr.Markdown("⚠️ Model chưa sẵn sàng (thiếu file weight): " + ", ".join(missing_models))
138
+
139
+ with gr.Row():
140
+ with gr.Column(scale=1):
141
+ model_dd = gr.Dropdown(
142
+ choices=available_models, value=available_models[0], label="Chọn model"
143
+ )
144
+ paper_md = gr.Markdown(f"📄 {MODEL_CONFIGS[available_models[0]]['paper']}")
145
+ conf_slider = gr.Slider(0.05, 0.95, value=0.5, step=0.05, label="Ngưỡng confidence")
146
+ image_in = gr.Image(type="pil", label="Ảnh đầu vào")
147
+ btn = gr.Button("Detect", variant="primary")
148
+ gr.Markdown("6 lớp: " + ", ".join(VOC_CLASSES))
149
+
150
+ with gr.Column(scale=1):
151
+ image_out = gr.Image(label="Kết quả")
152
+ info_out = gr.Markdown()
153
+ table_out = gr.Dataframe(
154
+ headers=["Lớp", "Confidence", "Box (x1, y1, x2, y2)"],
155
+ label="Chi tiết",
156
+ )
157
+
158
+ model_dd.change(
159
+ fn=lambda name: f"📄 {MODEL_CONFIGS[name]['paper']}",
160
+ inputs=model_dd,
161
+ outputs=paper_md,
162
+ )
163
+ btn.click(fn=detect, inputs=[model_dd, image_in, conf_slider], outputs=[image_out, table_out, info_out])
164
+ image_in.change(fn=detect, inputs=[model_dd, image_in, conf_slider], outputs=[image_out, table_out, info_out])
165
+
166
+ if __name__ == "__main__":
167
+ demo.launch()
gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.pt filter=lfs diff=lfs merge=lfs -text
inference.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ inference.py
3
+ Unified detector interface so app.py doesn't need to know the differences
4
+ between torchvision (Faster R-CNN) and ultralytics (YOLOv8 / RT-DETR) APIs.
5
+
6
+ Every detector's .predict(pil_image, conf_thresh, device) returns the SAME
7
+ format: [{"box": [x1, y1, x2, y2], "label": str, "score": float}, ...]
8
+
9
+ ZeroGPU note: models are constructed on CPU and stay there at rest -- HF
10
+ Spaces' ZeroGPU only attaches a real GPU for the duration of a function
11
+ decorated with @spaces.GPU (see app.py). `device` is therefore passed into
12
+ predict() per-call rather than fixed at construction time, since a different
13
+ physical GPU may be assigned on each call.
14
+
15
+ IMPORTANT: VOC_CLASSES order below MUST exactly match the order used during
16
+ training (data_prep/xml_utils.py::VOC_CLASSES) -- Faster R-CNN's output label
17
+ indices (1..6, 0=background) are positional and carry no class names in the
18
+ checkpoint itself, unlike YOLOv8/RT-DETR (via ultralytics) which embed class
19
+ names in the .pt file directly.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import torch
24
+ from torchvision.models.detection import fasterrcnn_resnet50_fpn_v2
25
+ from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
26
+ from torchvision.transforms import functional as TF
27
+
28
+ VOC_CLASSES = ["person", "bicycle", "car", "motorbike", "bus", "train"]
29
+
30
+
31
+ class FasterRCNNDetector:
32
+ def __init__(self, weights_path: str, min_size: int = 600, max_size: int = 1000):
33
+ model = fasterrcnn_resnet50_fpn_v2(weights=None, min_size=min_size, max_size=max_size)
34
+ in_features = model.roi_heads.box_predictor.cls_score.in_features
35
+ model.roi_heads.box_predictor = FastRCNNPredictor(in_features, len(VOC_CLASSES) + 1) # +1 background
36
+ state = torch.load(weights_path, map_location="cpu")
37
+ model.load_state_dict(state)
38
+ model.eval()
39
+ self.model = model # stays on CPU until predict() moves it inside a GPU-allocated call
40
+
41
+ @torch.no_grad()
42
+ def predict(self, pil_image, conf_thresh: float = 0.5, device: str = "cpu") -> list[dict]:
43
+ self.model.to(device)
44
+ img_t = TF.pil_to_tensor(pil_image)
45
+ img_t = TF.convert_image_dtype(img_t, torch.float32).to(device)
46
+ output = self.model([img_t])[0]
47
+
48
+ boxes = output["boxes"].detach().cpu().numpy()
49
+ labels = output["labels"].detach().cpu().numpy()
50
+ scores = output["scores"].detach().cpu().numpy()
51
+
52
+ results = []
53
+ for box, label, score in zip(boxes, labels, scores):
54
+ if score < conf_thresh:
55
+ continue
56
+ results.append({
57
+ "box": [float(v) for v in box],
58
+ "label": VOC_CLASSES[label - 1], # label 0 is background, never predicted as a box
59
+ "score": float(score),
60
+ })
61
+ return results
62
+
63
+
64
+ class UltralyticsDetector:
65
+ """Shared wrapper for YOLOv8 and RT-DETR -- both are exposed through the
66
+ same ultralytics `Model` API (.predict()), just different constructor
67
+ classes. Class names are read from the checkpoint itself (no need for
68
+ VOC_CLASSES here), so this stays correct even if training class order
69
+ ever changes independently of the Faster R-CNN pipeline.
70
+ """
71
+
72
+ def __init__(self, weights_path: str, family: str):
73
+ if family == "yolo":
74
+ from ultralytics import YOLO
75
+ self.model = YOLO(weights_path)
76
+ elif family == "rtdetr":
77
+ from ultralytics import RTDETR
78
+ self.model = RTDETR(weights_path)
79
+ else:
80
+ raise ValueError(f"unknown family: {family}")
81
+
82
+ def predict(self, pil_image, conf_thresh: float = 0.5, device: str = "cpu") -> list[dict]:
83
+ result = self.model.predict(pil_image, conf=conf_thresh, device=device, verbose=False)[0]
84
+ names = result.names
85
+ out = []
86
+ for box in result.boxes:
87
+ xyxy = box.xyxy[0].tolist()
88
+ cls_id = int(box.cls[0])
89
+ score = float(box.conf[0])
90
+ out.append({"box": xyxy, "label": names[cls_id], "score": score})
91
+ return out
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio>=4.36
2
+ spaces>=0.28
3
+ torch
4
+ torchvision
5
+ ultralytics>=8.2
6
+ pillow>=10.0