Apply article revision: person vs background evaluation, saved detection artifacts, separate input-output layout (update 23)
Browse files- CHANGELOG.md +7 -0
- README.md +12 -11
- app.py +141 -63
CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
| 1 |
# Changelog
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
## Update ke-22 - 2026-04-15
|
| 4 |
- Tambah status tahap training lebih jelas: `preparing_dataset` lalu `training`.
|
| 5 |
- Saat tombol training ditekan, log langsung menulis `Preparing dataset...` agar terlihat proses benar-benar dimulai.
|
|
|
|
| 1 |
# Changelog
|
| 2 |
|
| 3 |
+
## Update ke-23 - 2026-04-21
|
| 4 |
+
- Layout input dan output dipisah per baris/section, tidak lagi dalam satu baris yang sama.
|
| 5 |
+
- Evaluasi diubah dari `Sesuai/Tidak Sesuai` menjadi klasifikasi `Person` vs `Not Person/Background`.
|
| 6 |
+
- Hasil deteksi kini disimpan ke `evaluation_outputs/` sebagai gambar anotasi dan log `detection_log.csv`.
|
| 7 |
+
- Output training menampilkan file `results.csv` lokal agar grafik/akurasi dapat ditinjau kembali.
|
| 8 |
+
- Minor update dinaikkan ke-23.
|
| 9 |
+
|
| 10 |
## Update ke-22 - 2026-04-15
|
| 11 |
- Tambah status tahap training lebih jelas: `preparing_dataset` lalu `training`.
|
| 12 |
- Saat tombol training ditekan, log langsung menulis `Preparing dataset...` agar terlihat proses benar-benar dimulai.
|
README.md
CHANGED
|
@@ -8,12 +8,12 @@ python_version: "3.10"
|
|
| 8 |
app_file: app.py
|
| 9 |
---
|
| 10 |
|
| 11 |
-
# Pengecekan dan Klasifikasi
|
| 12 |
|
| 13 |
Versi ini difokuskan untuk tahap awal:
|
| 14 |
- pengecekan gambar kelas,
|
| 15 |
- deteksi objek `person`,
|
| 16 |
-
- klasifikasi sederhana
|
| 17 |
|
| 18 |
## Tujuan Fitur Saat Ini
|
| 19 |
|
|
@@ -22,12 +22,9 @@ Versi ini difokuskan untuk tahap awal:
|
|
| 22 |
3. Tampilkan hasil:
|
| 23 |
- gambar teranotasi bounding box,
|
| 24 |
- jumlah person terdeteksi,
|
| 25 |
-
-
|
| 26 |
-
- validasi `Sesuai` / `Tidak Sesuai`,
|
| 27 |
- confusion matrix dan rumus evaluasi,
|
| 28 |
-
-
|
| 29 |
-
- `Ada Mahasiswa` jika jumlah terdeteksi > 0
|
| 30 |
-
- `Tidak Ada Mahasiswa` jika jumlah terdeteksi = 0
|
| 31 |
- grafik hasil pengecekan.
|
| 32 |
4. Setelah proses cek, confusion matrix dan rumus evaluasi diperbarui otomatis berdasarkan label aktual yang dipilih.
|
| 33 |
|
|
@@ -41,8 +38,9 @@ Versi ini difokuskan untuk tahap awal:
|
|
| 41 |
- tombol proses
|
| 42 |
- **Section 2 - Hasil Processing**
|
| 43 |
- hasil gambar deteksi
|
| 44 |
-
- ringkasan klasifikasi
|
| 45 |
- grafik jumlah person terdeteksi
|
|
|
|
| 46 |
- **Menu Training** (accordion)
|
| 47 |
- membaca dataset dari `dataset/train` dan `dataset/test`
|
| 48 |
- jika label `.txt` YOLO belum ada, bisa aktifkan pseudo-label
|
|
@@ -51,13 +49,14 @@ Versi ini difokuskan untuk tahap awal:
|
|
| 51 |
- terminal training live untuk progres epoch
|
| 52 |
- grafik training otomatis (loss, precision, recall, mAP per epoch)
|
| 53 |
- output model terbaik selalu di-overwrite ke `best.pt` setiap training selesai
|
|
|
|
| 54 |
- jika env Hugging Face diisi, `best.pt` otomatis di-sync ke repo HF
|
| 55 |
|
| 56 |
Catatan:
|
| 57 |
-
-
|
| 58 |
-
-
|
| 59 |
-
- input jumlah presensi belum digunakan pada versi ini.
|
| 60 |
- UI otomatis menyesuaikan mode gelap perangkat (dark mode).
|
|
|
|
| 61 |
|
| 62 |
## File Penting
|
| 63 |
|
|
@@ -67,6 +66,8 @@ Catatan:
|
|
| 67 |
- `.gitignore` - aturan ignore
|
| 68 |
- `CHANGELOG.md` - riwayat update (termasuk nomor update)
|
| 69 |
- `skills/update-tracking/SKILL.md` - panduan konsistensi versi & format update
|
|
|
|
|
|
|
| 70 |
|
| 71 |
## Tracking Versi
|
| 72 |
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# Pengecekan dan Klasifikasi Person Berbasis YOLOv8
|
| 12 |
|
| 13 |
Versi ini difokuskan untuk tahap awal:
|
| 14 |
- pengecekan gambar kelas,
|
| 15 |
- deteksi objek `person`,
|
| 16 |
+
- klasifikasi sederhana `person` vs `not person/background`.
|
| 17 |
|
| 18 |
## Tujuan Fitur Saat Ini
|
| 19 |
|
|
|
|
| 22 |
3. Tampilkan hasil:
|
| 23 |
- gambar teranotasi bounding box,
|
| 24 |
- jumlah person terdeteksi,
|
| 25 |
+
- kelas prediksi evaluasi `Person` / `Not Person/Background`,
|
|
|
|
| 26 |
- confusion matrix dan rumus evaluasi,
|
| 27 |
+
- arsip evaluasi lokal (gambar hasil + CSV),
|
|
|
|
|
|
|
| 28 |
- grafik hasil pengecekan.
|
| 29 |
4. Setelah proses cek, confusion matrix dan rumus evaluasi diperbarui otomatis berdasarkan label aktual yang dipilih.
|
| 30 |
|
|
|
|
| 38 |
- tombol proses
|
| 39 |
- **Section 2 - Hasil Processing**
|
| 40 |
- hasil gambar deteksi
|
| 41 |
+
- ringkasan klasifikasi `person` vs `not person/background`
|
| 42 |
- grafik jumlah person terdeteksi
|
| 43 |
+
- file gambar evaluasi dan file CSV evaluasi lokal
|
| 44 |
- **Menu Training** (accordion)
|
| 45 |
- membaca dataset dari `dataset/train` dan `dataset/test`
|
| 46 |
- jika label `.txt` YOLO belum ada, bisa aktifkan pseudo-label
|
|
|
|
| 49 |
- terminal training live untuk progres epoch
|
| 50 |
- grafik training otomatis (loss, precision, recall, mAP per epoch)
|
| 51 |
- output model terbaik selalu di-overwrite ke `best.pt` setiap training selesai
|
| 52 |
+
- file `results.csv` training tersedia sebagai arsip metrik lokal
|
| 53 |
- jika env Hugging Face diisi, `best.pt` otomatis di-sync ke repo HF
|
| 54 |
|
| 55 |
Catatan:
|
| 56 |
+
- evaluasi dilakukan pada kelas `Person` dan `Not Person/Background`.
|
| 57 |
+
- hasil confidence rendah/tinggi dapat diamati melalui slider confidence dan arsip CSV evaluasi.
|
|
|
|
| 58 |
- UI otomatis menyesuaikan mode gelap perangkat (dark mode).
|
| 59 |
+
- output gambar dapat diperbesar melalui file hasil evaluasi yang tersimpan.
|
| 60 |
|
| 61 |
## File Penting
|
| 62 |
|
|
|
|
| 66 |
- `.gitignore` - aturan ignore
|
| 67 |
- `CHANGELOG.md` - riwayat update (termasuk nomor update)
|
| 68 |
- `skills/update-tracking/SKILL.md` - panduan konsistensi versi & format update
|
| 69 |
+
- `evaluation_outputs/` - arsip hasil deteksi untuk evaluasi artikel
|
| 70 |
+
- `runs_train/` - hasil training dan grafik/metrik YOLO
|
| 71 |
|
| 72 |
## Tracking Versi
|
| 73 |
|
app.py
CHANGED
|
@@ -11,7 +11,6 @@ import subprocess
|
|
| 11 |
from datetime import datetime
|
| 12 |
from functools import lru_cache
|
| 13 |
from pathlib import Path
|
| 14 |
-
from threading import Thread
|
| 15 |
from typing import Any, Dict, Tuple
|
| 16 |
|
| 17 |
import cv2
|
|
@@ -23,9 +22,9 @@ from huggingface_hub import CommitOperationAdd, CommitOperationDelete, HfApi, hf
|
|
| 23 |
from ultralytics import YOLO
|
| 24 |
|
| 25 |
CM_INIT = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
|
| 26 |
-
EVAL_CLASSES = ["
|
| 27 |
APP_VERSION = os.getenv("APP_VERSION", "v0.9.0")
|
| 28 |
-
APP_MINOR_UPDATE = os.getenv("APP_MINOR_UPDATE", "
|
| 29 |
|
| 30 |
|
| 31 |
# Gradio/Spaces can trigger noisy asyncio cleanup traces ("Invalid file descriptor: -1")
|
|
@@ -192,8 +191,62 @@ def classify_presence(detected_count: int) -> str:
|
|
| 192 |
return "Ada Mahasiswa" if detected_count > 0 else "Tidak Ada Mahasiswa"
|
| 193 |
|
| 194 |
|
| 195 |
-
def
|
| 196 |
-
return "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
|
| 199 |
def draw_detection_chart(detected: int) -> np.ndarray:
|
|
@@ -222,11 +275,11 @@ def draw_detection_chart(detected: int) -> np.ndarray:
|
|
| 222 |
return cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
|
| 223 |
|
| 224 |
|
| 225 |
-
def draw_compare_chart(detected_before: int, detected_after: int
|
| 226 |
fig, ax = plt.subplots(figsize=(6.2, 3.4))
|
| 227 |
-
labels = ["YOLOv8n", "Best.pt"
|
| 228 |
-
values = [detected_before, detected_after
|
| 229 |
-
bars = ax.bar(labels, values, color=["#2b6cb0", "#805ad5"
|
| 230 |
ax.set_title("Perbandingan Sebelum vs Sesudah Training")
|
| 231 |
ax.set_ylabel("Jumlah")
|
| 232 |
for b in bars:
|
|
@@ -262,48 +315,61 @@ def _merge_annotated_images(left: np.ndarray, right: np.ndarray) -> np.ndarray:
|
|
| 262 |
def run_check_and_classify(
|
| 263 |
image: np.ndarray,
|
| 264 |
conf_threshold: float,
|
| 265 |
-
attendance_count: float,
|
| 266 |
model_choice: str,
|
| 267 |
inference_mode: str,
|
| 268 |
annotation_style: str,
|
| 269 |
-
) -> Tuple[np.ndarray, str, np.ndarray, str, str]:
|
| 270 |
try:
|
| 271 |
-
attendance = int(attendance_count)
|
| 272 |
if inference_mode == "Bandingkan (YOLOv8n vs Best.pt)":
|
| 273 |
ann_before, det_before = infer_image(image, conf_threshold, "YOLOv8n", annotation_style)
|
| 274 |
ann_after, det_after = infer_image(image, conf_threshold, "Best.pt", annotation_style)
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
presence_before = classify_presence(det_before)
|
| 278 |
-
presence_after = classify_presence(det_after)
|
| 279 |
combined = _merge_annotated_images(ann_before, ann_after)
|
| 280 |
-
chart = draw_compare_chart(det_before, det_after
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
summary = (
|
| 282 |
"### Ringkasan Perbandingan Model\n"
|
| 283 |
-
f"-
|
| 284 |
-
f"- **YOLOv8n**: terdeteksi={det_before},
|
| 285 |
-
f"- **Best.pt**: terdeteksi={det_after},
|
| 286 |
-
"- Catatan evaluasi:
|
| 287 |
)
|
| 288 |
-
pred_md = f"Label prediksi
|
| 289 |
-
return combined, summary, chart,
|
| 290 |
|
| 291 |
annotated, detected = infer_image(image, conf_threshold, model_choice, annotation_style)
|
| 292 |
status_presence = classify_presence(detected)
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
summary = (
|
| 295 |
-
"### Ringkasan Hasil
|
| 296 |
f"- Jumlah objek `person` terdeteksi: **{detected}**\n"
|
| 297 |
-
f"- Jumlah presensi (input testing): **{attendance}**\n"
|
| 298 |
f"- Klasifikasi keberadaan: **{status_presence}**\n"
|
| 299 |
-
f"-
|
|
|
|
| 300 |
f"- Model digunakan: **{model_choice}**\n"
|
| 301 |
f"- Gaya anotasi: **{annotation_style}**\n"
|
| 302 |
-
"- Label objek: **person 1, person 2, ...**"
|
|
|
|
| 303 |
)
|
| 304 |
chart = draw_detection_chart(detected)
|
| 305 |
-
pred_md = f"Label prediksi
|
| 306 |
-
return annotated, summary, chart,
|
| 307 |
except Exception as err:
|
| 308 |
summary = (
|
| 309 |
"### Ringkasan Hasil Pengolahan Citra\n"
|
|
@@ -320,7 +386,7 @@ def run_check_and_classify(
|
|
| 320 |
(80, 80, 80),
|
| 321 |
2,
|
| 322 |
)
|
| 323 |
-
return image, summary, blank, "", "Label prediksi
|
| 324 |
|
| 325 |
|
| 326 |
def toggle_model_selector(mode: str):
|
|
@@ -380,6 +446,7 @@ def render_metric_markdown(cm_state: Dict[str, int]) -> str:
|
|
| 380 |
f1 = _safe_div(2 * prec * rec, prec + rec)
|
| 381 |
return (
|
| 382 |
"### Evaluasi dan Rumus\n"
|
|
|
|
| 383 |
f"- Accuracy = (TP+TN)/(TP+FP+FN+TN) = ({tp}+{tn})/({tp+fp+fn+tn}) = **{acc:.4f}**\n"
|
| 384 |
f"- Precision = TP/(TP+FP) = {tp}/({tp+fp}) = **{prec:.4f}**\n"
|
| 385 |
f"- Recall = TP/(TP+FN) = {tp}/({tp+fn}) = **{rec:.4f}**\n"
|
|
@@ -399,11 +466,11 @@ def update_evaluation(
|
|
| 399 |
"Jalankan deteksi terlebih dahulu agar label prediksi tersedia.",
|
| 400 |
)
|
| 401 |
|
| 402 |
-
if actual_label == "
|
| 403 |
state["tp"] += 1
|
| 404 |
-
elif actual_label == "
|
| 405 |
state["fn"] += 1
|
| 406 |
-
elif actual_label == "
|
| 407 |
state["fp"] += 1
|
| 408 |
else:
|
| 409 |
state["tn"] += 1
|
|
@@ -982,7 +1049,7 @@ def _training_status_md(state: Dict[str, Any], rows_count: int) -> str:
|
|
| 982 |
return f"Status training: **{status}** \nRun: `{run_name}`"
|
| 983 |
|
| 984 |
|
| 985 |
-
def poll_training_status() -> Tuple[str, Any, np.ndarray, str]:
|
| 986 |
try:
|
| 987 |
base_dir = Path(__file__).resolve().parent
|
| 988 |
paths = _train_paths(base_dir)
|
|
@@ -1005,11 +1072,13 @@ def poll_training_status() -> Tuple[str, Any, np.ndarray, str]:
|
|
| 1005 |
_write_status(paths["status"], state)
|
| 1006 |
|
| 1007 |
best_file = str(paths["best"]) if paths["best"].exists() else None
|
| 1008 |
-
|
|
|
|
| 1009 |
except Exception as err:
|
| 1010 |
return (
|
| 1011 |
f"Monitor training error: {err}",
|
| 1012 |
None,
|
|
|
|
| 1013 |
_make_info_image("Monitor training error.\nSilakan klik Refresh Status Training."),
|
| 1014 |
"Status training: **Error monitor**",
|
| 1015 |
)
|
|
@@ -1021,7 +1090,7 @@ def run_training(
|
|
| 1021 |
batch: float,
|
| 1022 |
use_pseudo_if_missing: bool,
|
| 1023 |
pseudo_conf: float,
|
| 1024 |
-
) -> Tuple[str, Any, np.ndarray, str]:
|
| 1025 |
base_dir = Path(__file__).resolve().parent
|
| 1026 |
paths = _train_paths(base_dir)
|
| 1027 |
current = _read_status(paths["status"])
|
|
@@ -1243,8 +1312,9 @@ with gr.Blocks(title="Pengecekan dan Klasifikasi Mahasiswa - YOLOv8") as demo:
|
|
| 1243 |
"## Metodologi Penelitian\n"
|
| 1244 |
"1. **Akuisisi Data**: input gambar kelas dari upload atau kamera.\n"
|
| 1245 |
"2. **Deteksi Objek (YOLOv8)**: sistem mendeteksi objek kelas `person`.\n"
|
| 1246 |
-
"3. **Klasifikasi
|
| 1247 |
-
"4. **
|
|
|
|
| 1248 |
)
|
| 1249 |
|
| 1250 |
with gr.Column(elem_classes=["section-box"]):
|
|
@@ -1259,18 +1329,10 @@ with gr.Blocks(title="Pengecekan dan Klasifikasi Mahasiswa - YOLOv8") as demo:
|
|
| 1259 |
value="YOLOv8n",
|
| 1260 |
label="Pilih Model",
|
| 1261 |
)
|
| 1262 |
-
|
| 1263 |
-
|
| 1264 |
-
|
| 1265 |
-
|
| 1266 |
-
sources=["upload", "webcam"],
|
| 1267 |
-
)
|
| 1268 |
-
output_image = gr.Image(label="Output Tahap 2 - Hasil Deteksi YOLOv8", type="numpy")
|
| 1269 |
-
attendance_input = gr.Number(
|
| 1270 |
-
label="Input Jumlah Presensi (Untuk Testing Validasi)",
|
| 1271 |
-
value=0,
|
| 1272 |
-
precision=0,
|
| 1273 |
-
minimum=0,
|
| 1274 |
)
|
| 1275 |
conf_input = gr.Slider(0.1, 1.0, value=0.25, step=0.05, label="Parameter Confidence (Deteksi)")
|
| 1276 |
with gr.Accordion("Advanced Options", open=False, elem_classes=["advanced-box"]):
|
|
@@ -1283,18 +1345,25 @@ with gr.Blocks(title="Pengecekan dan Klasifikasi Mahasiswa - YOLOv8") as demo:
|
|
| 1283 |
run_btn = gr.Button("Jalankan Deteksi dan Klasifikasi", variant="primary")
|
| 1284 |
|
| 1285 |
with gr.Column(elem_classes=["section-box"]):
|
| 1286 |
-
gr.Markdown("## Tahap
|
| 1287 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1288 |
comparison_chart = gr.Image(label="Visualisasi Jumlah Person Terdeteksi", type="numpy")
|
| 1289 |
-
predicted_label_md = gr.Markdown("Label prediksi
|
|
|
|
|
|
|
| 1290 |
|
| 1291 |
with gr.Column(elem_classes=["section-box"]):
|
| 1292 |
-
gr.Markdown("## Tahap
|
| 1293 |
cm_state = gr.State(dict(CM_INIT))
|
| 1294 |
predicted_state = gr.State("")
|
| 1295 |
actual_label = gr.Radio(
|
| 1296 |
choices=EVAL_CLASSES,
|
| 1297 |
-
value="
|
| 1298 |
label="Label Aktual (untuk evaluasi/testing)",
|
| 1299 |
)
|
| 1300 |
with gr.Row():
|
|
@@ -1310,7 +1379,7 @@ with gr.Blocks(title="Pengecekan dan Klasifikasi Mahasiswa - YOLOv8") as demo:
|
|
| 1310 |
metric_md = gr.Markdown(render_metric_markdown(CM_INIT))
|
| 1311 |
|
| 1312 |
with gr.Column(elem_classes=["section-box"]):
|
| 1313 |
-
with gr.Accordion("Tahap
|
| 1314 |
gr.Markdown(
|
| 1315 |
"Training akan membaca dataset dari `dataset/train` dan `dataset/test`.\n"
|
| 1316 |
"Jika label `.txt` belum ada, aktifkan pseudo-label agar proses tetap jalan.\n"
|
|
@@ -1341,11 +1410,20 @@ with gr.Blocks(title="Pengecekan dan Klasifikasi Mahasiswa - YOLOv8") as demo:
|
|
| 1341 |
value=_make_info_image("Grafik training akan tampil di sini."),
|
| 1342 |
)
|
| 1343 |
best_model_file = gr.File(label="best.pt hasil training")
|
|
|
|
| 1344 |
|
| 1345 |
run_btn_evt = run_btn.click(
|
| 1346 |
fn=run_check_and_classify,
|
| 1347 |
-
inputs=[image_input, conf_input,
|
| 1348 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1349 |
)
|
| 1350 |
run_btn_evt.then(
|
| 1351 |
fn=update_evaluation,
|
|
@@ -1367,25 +1445,25 @@ with gr.Blocks(title="Pengecekan dan Klasifikasi Mahasiswa - YOLOv8") as demo:
|
|
| 1367 |
train_btn.click(
|
| 1368 |
fn=run_training,
|
| 1369 |
inputs=[train_epochs, train_imgsz, train_batch, use_pseudo, pseudo_conf],
|
| 1370 |
-
outputs=[train_log, best_model_file, train_curve, train_status_md],
|
| 1371 |
)
|
| 1372 |
refresh_train_btn.click(
|
| 1373 |
fn=poll_training_status,
|
| 1374 |
inputs=[],
|
| 1375 |
-
outputs=[train_log, best_model_file, train_curve, train_status_md],
|
| 1376 |
queue=False,
|
| 1377 |
)
|
| 1378 |
demo.load(
|
| 1379 |
fn=poll_training_status,
|
| 1380 |
inputs=[],
|
| 1381 |
-
outputs=[train_log, best_model_file, train_curve, train_status_md],
|
| 1382 |
queue=False,
|
| 1383 |
)
|
| 1384 |
train_timer = gr.Timer(value=2.0)
|
| 1385 |
train_timer.tick(
|
| 1386 |
fn=poll_training_status,
|
| 1387 |
inputs=[],
|
| 1388 |
-
outputs=[train_log, best_model_file, train_curve, train_status_md],
|
| 1389 |
queue=False,
|
| 1390 |
)
|
| 1391 |
|
|
|
|
| 11 |
from datetime import datetime
|
| 12 |
from functools import lru_cache
|
| 13 |
from pathlib import Path
|
|
|
|
| 14 |
from typing import Any, Dict, Tuple
|
| 15 |
|
| 16 |
import cv2
|
|
|
|
| 22 |
from ultralytics import YOLO
|
| 23 |
|
| 24 |
CM_INIT = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
|
| 25 |
+
EVAL_CLASSES = ["Person", "Not Person/Background"]
|
| 26 |
APP_VERSION = os.getenv("APP_VERSION", "v0.9.0")
|
| 27 |
+
APP_MINOR_UPDATE = os.getenv("APP_MINOR_UPDATE", "23")
|
| 28 |
|
| 29 |
|
| 30 |
# Gradio/Spaces can trigger noisy asyncio cleanup traces ("Invalid file descriptor: -1")
|
|
|
|
| 191 |
return "Ada Mahasiswa" if detected_count > 0 else "Tidak Ada Mahasiswa"
|
| 192 |
|
| 193 |
|
| 194 |
+
def classify_person_vs_background(detected_count: int) -> str:
|
| 195 |
+
return "Person" if detected_count > 0 else "Not Person/Background"
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _evaluation_paths(base_dir: Path) -> Dict[str, Path]:
|
| 199 |
+
eval_dir = base_dir / "evaluation_outputs"
|
| 200 |
+
eval_dir.mkdir(parents=True, exist_ok=True)
|
| 201 |
+
return {
|
| 202 |
+
"dir": eval_dir,
|
| 203 |
+
"csv": eval_dir / "detection_log.csv",
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def save_detection_artifacts(
|
| 208 |
+
annotated_image: np.ndarray,
|
| 209 |
+
model_choice: str,
|
| 210 |
+
inference_mode: str,
|
| 211 |
+
conf_threshold: float,
|
| 212 |
+
predicted_label: str,
|
| 213 |
+
detected_count: int,
|
| 214 |
+
) -> Tuple[str | None, str | None]:
|
| 215 |
+
base_dir = Path(__file__).resolve().parent
|
| 216 |
+
paths = _evaluation_paths(base_dir)
|
| 217 |
+
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 218 |
+
image_path = paths["dir"] / f"detection_{ts}.png"
|
| 219 |
+
bgr = cv2.cvtColor(annotated_image, cv2.COLOR_RGB2BGR)
|
| 220 |
+
cv2.imwrite(str(image_path), bgr)
|
| 221 |
+
|
| 222 |
+
csv_path = paths["csv"]
|
| 223 |
+
write_header = not csv_path.exists()
|
| 224 |
+
with csv_path.open("a", encoding="utf-8", newline="") as f:
|
| 225 |
+
writer = csv.writer(f)
|
| 226 |
+
if write_header:
|
| 227 |
+
writer.writerow(
|
| 228 |
+
[
|
| 229 |
+
"timestamp",
|
| 230 |
+
"model_choice",
|
| 231 |
+
"inference_mode",
|
| 232 |
+
"confidence_threshold",
|
| 233 |
+
"predicted_label",
|
| 234 |
+
"detected_count",
|
| 235 |
+
"saved_image",
|
| 236 |
+
]
|
| 237 |
+
)
|
| 238 |
+
writer.writerow(
|
| 239 |
+
[
|
| 240 |
+
datetime.now().isoformat(),
|
| 241 |
+
model_choice,
|
| 242 |
+
inference_mode,
|
| 243 |
+
f"{conf_threshold:.2f}",
|
| 244 |
+
predicted_label,
|
| 245 |
+
detected_count,
|
| 246 |
+
str(image_path),
|
| 247 |
+
]
|
| 248 |
+
)
|
| 249 |
+
return str(image_path), str(csv_path)
|
| 250 |
|
| 251 |
|
| 252 |
def draw_detection_chart(detected: int) -> np.ndarray:
|
|
|
|
| 275 |
return cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
|
| 276 |
|
| 277 |
|
| 278 |
+
def draw_compare_chart(detected_before: int, detected_after: int) -> np.ndarray:
|
| 279 |
fig, ax = plt.subplots(figsize=(6.2, 3.4))
|
| 280 |
+
labels = ["YOLOv8n", "Best.pt"]
|
| 281 |
+
values = [detected_before, detected_after]
|
| 282 |
+
bars = ax.bar(labels, values, color=["#2b6cb0", "#805ad5"])
|
| 283 |
ax.set_title("Perbandingan Sebelum vs Sesudah Training")
|
| 284 |
ax.set_ylabel("Jumlah")
|
| 285 |
for b in bars:
|
|
|
|
| 315 |
def run_check_and_classify(
|
| 316 |
image: np.ndarray,
|
| 317 |
conf_threshold: float,
|
|
|
|
| 318 |
model_choice: str,
|
| 319 |
inference_mode: str,
|
| 320 |
annotation_style: str,
|
| 321 |
+
) -> Tuple[str | np.ndarray, str, np.ndarray, str, str, str | None, str | None]:
|
| 322 |
try:
|
|
|
|
| 323 |
if inference_mode == "Bandingkan (YOLOv8n vs Best.pt)":
|
| 324 |
ann_before, det_before = infer_image(image, conf_threshold, "YOLOv8n", annotation_style)
|
| 325 |
ann_after, det_after = infer_image(image, conf_threshold, "Best.pt", annotation_style)
|
| 326 |
+
pred_before = classify_person_vs_background(det_before)
|
| 327 |
+
pred_after = classify_person_vs_background(det_after)
|
|
|
|
|
|
|
| 328 |
combined = _merge_annotated_images(ann_before, ann_after)
|
| 329 |
+
chart = draw_compare_chart(det_before, det_after)
|
| 330 |
+
saved_image_path, saved_csv_path = save_detection_artifacts(
|
| 331 |
+
combined,
|
| 332 |
+
model_choice="Best.pt",
|
| 333 |
+
inference_mode=inference_mode,
|
| 334 |
+
conf_threshold=conf_threshold,
|
| 335 |
+
predicted_label=pred_after,
|
| 336 |
+
detected_count=det_after,
|
| 337 |
+
)
|
| 338 |
summary = (
|
| 339 |
"### Ringkasan Perbandingan Model\n"
|
| 340 |
+
f"- Confidence threshold: **{conf_threshold:.2f}**\n"
|
| 341 |
+
f"- **YOLOv8n**: person terdeteksi={det_before}, prediksi kelas={pred_before}\n"
|
| 342 |
+
f"- **Best.pt**: person terdeteksi={det_after}, prediksi kelas={pred_after}\n"
|
| 343 |
+
"- Catatan evaluasi: confusion matrix memakai prediksi **Best.pt** terhadap label aktual manual."
|
| 344 |
)
|
| 345 |
+
pred_md = f"Label prediksi evaluasi (Best.pt): **{pred_after}**"
|
| 346 |
+
return saved_image_path or combined, summary, chart, pred_after, pred_md, saved_image_path, saved_csv_path
|
| 347 |
|
| 348 |
annotated, detected = infer_image(image, conf_threshold, model_choice, annotation_style)
|
| 349 |
status_presence = classify_presence(detected)
|
| 350 |
+
predicted_label = classify_person_vs_background(detected)
|
| 351 |
+
saved_image_path, saved_csv_path = save_detection_artifacts(
|
| 352 |
+
annotated,
|
| 353 |
+
model_choice=model_choice,
|
| 354 |
+
inference_mode=inference_mode,
|
| 355 |
+
conf_threshold=conf_threshold,
|
| 356 |
+
predicted_label=predicted_label,
|
| 357 |
+
detected_count=detected,
|
| 358 |
+
)
|
| 359 |
summary = (
|
| 360 |
+
"### Ringkasan Hasil Deteksi dan Klasifikasi\n"
|
| 361 |
f"- Jumlah objek `person` terdeteksi: **{detected}**\n"
|
|
|
|
| 362 |
f"- Klasifikasi keberadaan: **{status_presence}**\n"
|
| 363 |
+
f"- Kelas prediksi evaluasi: **{predicted_label}**\n"
|
| 364 |
+
f"- Confidence threshold: **{conf_threshold:.2f}**\n"
|
| 365 |
f"- Model digunakan: **{model_choice}**\n"
|
| 366 |
f"- Gaya anotasi: **{annotation_style}**\n"
|
| 367 |
+
"- Label objek: **person 1, person 2, ...**\n"
|
| 368 |
+
f"- Arsip evaluasi lokal: **{saved_csv_path or '-'}**"
|
| 369 |
)
|
| 370 |
chart = draw_detection_chart(detected)
|
| 371 |
+
pred_md = f"Label prediksi evaluasi: **{predicted_label}**"
|
| 372 |
+
return saved_image_path or annotated, summary, chart, predicted_label, pred_md, saved_image_path, saved_csv_path
|
| 373 |
except Exception as err:
|
| 374 |
summary = (
|
| 375 |
"### Ringkasan Hasil Pengolahan Citra\n"
|
|
|
|
| 386 |
(80, 80, 80),
|
| 387 |
2,
|
| 388 |
)
|
| 389 |
+
return image, summary, blank, "", "Label prediksi evaluasi: **-**", None, None
|
| 390 |
|
| 391 |
|
| 392 |
def toggle_model_selector(mode: str):
|
|
|
|
| 446 |
f1 = _safe_div(2 * prec * rec, prec + rec)
|
| 447 |
return (
|
| 448 |
"### Evaluasi dan Rumus\n"
|
| 449 |
+
"- Kelas positif evaluasi: **Person**\n"
|
| 450 |
f"- Accuracy = (TP+TN)/(TP+FP+FN+TN) = ({tp}+{tn})/({tp+fp+fn+tn}) = **{acc:.4f}**\n"
|
| 451 |
f"- Precision = TP/(TP+FP) = {tp}/({tp+fp}) = **{prec:.4f}**\n"
|
| 452 |
f"- Recall = TP/(TP+FN) = {tp}/({tp+fn}) = **{rec:.4f}**\n"
|
|
|
|
| 466 |
"Jalankan deteksi terlebih dahulu agar label prediksi tersedia.",
|
| 467 |
)
|
| 468 |
|
| 469 |
+
if actual_label == "Person" and predicted_label == "Person":
|
| 470 |
state["tp"] += 1
|
| 471 |
+
elif actual_label == "Person" and predicted_label == "Not Person/Background":
|
| 472 |
state["fn"] += 1
|
| 473 |
+
elif actual_label == "Not Person/Background" and predicted_label == "Person":
|
| 474 |
state["fp"] += 1
|
| 475 |
else:
|
| 476 |
state["tn"] += 1
|
|
|
|
| 1049 |
return f"Status training: **{status}** \nRun: `{run_name}`"
|
| 1050 |
|
| 1051 |
|
| 1052 |
+
def poll_training_status() -> Tuple[str, Any, Any, np.ndarray, str]:
|
| 1053 |
try:
|
| 1054 |
base_dir = Path(__file__).resolve().parent
|
| 1055 |
paths = _train_paths(base_dir)
|
|
|
|
| 1072 |
_write_status(paths["status"], state)
|
| 1073 |
|
| 1074 |
best_file = str(paths["best"]) if paths["best"].exists() else None
|
| 1075 |
+
metrics_file = str(results_csv) if results_csv is not None else None
|
| 1076 |
+
return log_text, best_file, metrics_file, chart, _training_status_md(state, len(rows))
|
| 1077 |
except Exception as err:
|
| 1078 |
return (
|
| 1079 |
f"Monitor training error: {err}",
|
| 1080 |
None,
|
| 1081 |
+
None,
|
| 1082 |
_make_info_image("Monitor training error.\nSilakan klik Refresh Status Training."),
|
| 1083 |
"Status training: **Error monitor**",
|
| 1084 |
)
|
|
|
|
| 1090 |
batch: float,
|
| 1091 |
use_pseudo_if_missing: bool,
|
| 1092 |
pseudo_conf: float,
|
| 1093 |
+
) -> Tuple[str, Any, Any, np.ndarray, str]:
|
| 1094 |
base_dir = Path(__file__).resolve().parent
|
| 1095 |
paths = _train_paths(base_dir)
|
| 1096 |
current = _read_status(paths["status"])
|
|
|
|
| 1312 |
"## Metodologi Penelitian\n"
|
| 1313 |
"1. **Akuisisi Data**: input gambar kelas dari upload atau kamera.\n"
|
| 1314 |
"2. **Deteksi Objek (YOLOv8)**: sistem mendeteksi objek kelas `person`.\n"
|
| 1315 |
+
"3. **Klasifikasi Evaluasi**: citra diklasifikasikan menjadi `Person` atau `Not Person/Background`.\n"
|
| 1316 |
+
"4. **Arsip Evaluasi**: hasil deteksi disimpan ke file lokal untuk bahan analisis artikel.\n"
|
| 1317 |
+
"5. **Pengembangan Model**: menu training untuk pembaruan bobot model (`best.pt`)."
|
| 1318 |
)
|
| 1319 |
|
| 1320 |
with gr.Column(elem_classes=["section-box"]):
|
|
|
|
| 1329 |
value="YOLOv8n",
|
| 1330 |
label="Pilih Model",
|
| 1331 |
)
|
| 1332 |
+
image_input = gr.Image(
|
| 1333 |
+
label="Input Gambar Kelas (Upload/Kamera)",
|
| 1334 |
+
type="numpy",
|
| 1335 |
+
sources=["upload", "webcam"],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1336 |
)
|
| 1337 |
conf_input = gr.Slider(0.1, 1.0, value=0.25, step=0.05, label="Parameter Confidence (Deteksi)")
|
| 1338 |
with gr.Accordion("Advanced Options", open=False, elem_classes=["advanced-box"]):
|
|
|
|
| 1345 |
run_btn = gr.Button("Jalankan Deteksi dan Klasifikasi", variant="primary")
|
| 1346 |
|
| 1347 |
with gr.Column(elem_classes=["section-box"]):
|
| 1348 |
+
gr.Markdown("## Tahap 2 - Hasil Deteksi dan Klasifikasi", elem_classes=["section-title"])
|
| 1349 |
+
output_image = gr.Image(
|
| 1350 |
+
label="Output Hasil Deteksi YOLOv8",
|
| 1351 |
+
type="filepath",
|
| 1352 |
+
show_download_button=True,
|
| 1353 |
+
)
|
| 1354 |
+
class_result_md = gr.Markdown("Ringkasan hasil deteksi akan tampil di sini.")
|
| 1355 |
comparison_chart = gr.Image(label="Visualisasi Jumlah Person Terdeteksi", type="numpy")
|
| 1356 |
+
predicted_label_md = gr.Markdown("Label prediksi evaluasi: **-**")
|
| 1357 |
+
saved_detection_file = gr.File(label="File Gambar Hasil Evaluasi")
|
| 1358 |
+
evaluation_csv_file = gr.File(label="Log CSV Evaluasi Lokal")
|
| 1359 |
|
| 1360 |
with gr.Column(elem_classes=["section-box"]):
|
| 1361 |
+
gr.Markdown("## Tahap 3 - Evaluasi (Confusion Matrix + Rumus)", elem_classes=["section-title"])
|
| 1362 |
cm_state = gr.State(dict(CM_INIT))
|
| 1363 |
predicted_state = gr.State("")
|
| 1364 |
actual_label = gr.Radio(
|
| 1365 |
choices=EVAL_CLASSES,
|
| 1366 |
+
value="Person",
|
| 1367 |
label="Label Aktual (untuk evaluasi/testing)",
|
| 1368 |
)
|
| 1369 |
with gr.Row():
|
|
|
|
| 1379 |
metric_md = gr.Markdown(render_metric_markdown(CM_INIT))
|
| 1380 |
|
| 1381 |
with gr.Column(elem_classes=["section-box"]):
|
| 1382 |
+
with gr.Accordion("Tahap 4 - Pengembangan Model (Training)", open=False):
|
| 1383 |
gr.Markdown(
|
| 1384 |
"Training akan membaca dataset dari `dataset/train` dan `dataset/test`.\n"
|
| 1385 |
"Jika label `.txt` belum ada, aktifkan pseudo-label agar proses tetap jalan.\n"
|
|
|
|
| 1410 |
value=_make_info_image("Grafik training akan tampil di sini."),
|
| 1411 |
)
|
| 1412 |
best_model_file = gr.File(label="best.pt hasil training")
|
| 1413 |
+
training_metrics_file = gr.File(label="results.csv / Metrik Training Lokal")
|
| 1414 |
|
| 1415 |
run_btn_evt = run_btn.click(
|
| 1416 |
fn=run_check_and_classify,
|
| 1417 |
+
inputs=[image_input, conf_input, model_choice, inference_mode, annotation_style],
|
| 1418 |
+
outputs=[
|
| 1419 |
+
output_image,
|
| 1420 |
+
class_result_md,
|
| 1421 |
+
comparison_chart,
|
| 1422 |
+
predicted_state,
|
| 1423 |
+
predicted_label_md,
|
| 1424 |
+
saved_detection_file,
|
| 1425 |
+
evaluation_csv_file,
|
| 1426 |
+
],
|
| 1427 |
)
|
| 1428 |
run_btn_evt.then(
|
| 1429 |
fn=update_evaluation,
|
|
|
|
| 1445 |
train_btn.click(
|
| 1446 |
fn=run_training,
|
| 1447 |
inputs=[train_epochs, train_imgsz, train_batch, use_pseudo, pseudo_conf],
|
| 1448 |
+
outputs=[train_log, best_model_file, training_metrics_file, train_curve, train_status_md],
|
| 1449 |
)
|
| 1450 |
refresh_train_btn.click(
|
| 1451 |
fn=poll_training_status,
|
| 1452 |
inputs=[],
|
| 1453 |
+
outputs=[train_log, best_model_file, training_metrics_file, train_curve, train_status_md],
|
| 1454 |
queue=False,
|
| 1455 |
)
|
| 1456 |
demo.load(
|
| 1457 |
fn=poll_training_status,
|
| 1458 |
inputs=[],
|
| 1459 |
+
outputs=[train_log, best_model_file, training_metrics_file, train_curve, train_status_md],
|
| 1460 |
queue=False,
|
| 1461 |
)
|
| 1462 |
train_timer = gr.Timer(value=2.0)
|
| 1463 |
train_timer.tick(
|
| 1464 |
fn=poll_training_status,
|
| 1465 |
inputs=[],
|
| 1466 |
+
outputs=[train_log, best_model_file, training_metrics_file, train_curve, train_status_md],
|
| 1467 |
queue=False,
|
| 1468 |
)
|
| 1469 |
|