firgiawann commited on
Commit
01fb043
·
verified ·
1 Parent(s): 9668442

Refactor to classification sections and confusion matrix image

Browse files
Files changed (3) hide show
  1. README.md +14 -6
  2. app.py +216 -275
  3. requirements.txt +4 -0
README.md CHANGED
@@ -35,13 +35,14 @@ Membangun aplikasi yang dapat:
35
  - jumlah presensi,
36
  - status validasi.
37
 
38
- ## Evaluasi Manual (Confusion Matrix)
39
 
40
- Aplikasi menyediakan panel evaluasi manual:
41
- - setelah inferensi, pilih label aktual (`Sesuai` / `Tidak sesuai`),
42
- - klik **Update Confusion Matrix**,
43
- - panel menampilkan **gambar confusion matrix** (bukan tabel teks) dengan nilai `TP`, `FP`, `FN`, `TN`,
44
- - metrik `Accuracy`, `Precision`, `Recall`, dan `F1-Score` dihitung langsung di panel rumus.
 
45
 
46
  ## Struktur File yang Diharapkan
47
 
@@ -85,6 +86,13 @@ Buka URL lokal yang muncul di terminal (default Gradio).
85
  - `HF_MODEL_FILE` (opsional)
86
  4. Space akan build otomatis dan menjalankan `app.py`.
87
 
 
 
 
 
 
 
 
88
  ## Catatan
89
 
90
  - Fitur utama saat ini fokus pada inferensi gambar.
 
35
  - jumlah presensi,
36
  - status validasi.
37
 
38
+ ## Evaluasi Klasifikasi (Confusion Matrix Image)
39
 
40
+ Aplikasi menyediakan evaluasi batch otomatis:
41
+ - upload ZIP berisi gambar evaluasi,
42
+ - upload CSV ground truth (filename, presensi, actual_label),
43
+ - sistem menjalankan klasifikasi untuk semua sampel,
44
+ - output confusion matrix ditampilkan sebagai **gambar heatmap**,
45
+ - metrik Accuracy, Precision, Recall, dan F1-Score dihitung otomatis.
46
 
47
  ## Struktur File yang Diharapkan
48
 
 
86
  - `HF_MODEL_FILE` (opsional)
87
  4. Space akan build otomatis dan menjalankan `app.py`.
88
 
89
+ ## Format CSV Evaluasi
90
+
91
+ Contoh kolom yang didukung:
92
+ - `filename` (atau `file`/`image`)
93
+ - `presensi` (atau `attendance`)
94
+ - `actual_label` (atau `label`/`ground_truth`) berisi `Sesuai` atau `Tidak sesuai`
95
+
96
  ## Catatan
97
 
98
  - Fitur utama saat ini fokus pada inferensi gambar.
app.py CHANGED
@@ -1,22 +1,25 @@
 
1
  import os
 
 
2
  from functools import lru_cache
3
- from typing import Any, Dict, Tuple
4
 
5
  import cv2
6
  import gradio as gr
 
7
  import numpy as np
 
 
8
  from huggingface_hub import hf_hub_download
 
9
  from ultralytics import YOLO
10
 
11
 
12
- CM_INIT = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
13
 
14
 
15
  def resolve_model_path() -> str:
16
- """Resolve YOLO model path from local file or Hugging Face Hub.
17
-
18
- Default lokal: yolov8n.pt (sementara sebelum tersedia best.pt).
19
- """
20
  model_env = os.getenv("MODEL_PATH", "").strip()
21
  base_dir = os.path.dirname(__file__)
22
  if model_env:
@@ -24,13 +27,10 @@ def resolve_model_path() -> str:
24
  return model_env
25
  raise FileNotFoundError(f"MODEL_PATH tidak valid: {model_env}")
26
 
27
- local_candidates = [
28
- os.path.join(base_dir, "yolov8n.pt"),
29
- os.path.join(base_dir, "best.pt"),
30
- ]
31
- for candidate_path in local_candidates:
32
- if os.path.exists(candidate_path):
33
- return candidate_path
34
 
35
  hf_repo = os.getenv("HF_MODEL_REPO", "").strip()
36
  hf_file = os.getenv("HF_MODEL_FILE", "yolov8n.pt").strip()
@@ -38,134 +38,20 @@ def resolve_model_path() -> str:
38
  return hf_hub_download(repo_id=hf_repo, filename=hf_file)
39
 
40
  raise FileNotFoundError(
41
- "Model tidak ditemukan. Simpan file 'yolov8n.pt' di root project "
42
- "atau set environment MODEL_PATH. "
43
- "Opsional fallback Hugging Face Hub: set HF_MODEL_REPO dan HF_MODEL_FILE."
44
  )
45
 
46
 
47
  @lru_cache(maxsize=1)
48
  def load_model() -> YOLO:
49
- model_path = resolve_model_path()
50
- return YOLO(model_path)
51
-
52
-
53
- def format_summary(detected_count: int, attendance_count: int, status: str) -> str:
54
- return (
55
- f"Jumlah terdeteksi: {detected_count}\n"
56
- f"Jumlah presensi: {attendance_count}\n"
57
- f"Status validasi: {status}"
58
- )
59
 
60
 
61
  def _safe_div(num: float, den: float) -> float:
62
  return 0.0 if den == 0 else num / den
63
 
64
 
65
- def compute_metrics(tp: int, fp: int, fn: int, tn: int) -> Dict[str, float]:
66
- total = tp + fp + fn + tn
67
- accuracy = _safe_div(tp + tn, total)
68
- precision = _safe_div(tp, tp + fp)
69
- recall = _safe_div(tp, tp + fn)
70
- f1 = _safe_div(2 * precision * recall, precision + recall)
71
- return {
72
- "accuracy": accuracy,
73
- "precision": precision,
74
- "recall": recall,
75
- "f1": f1,
76
- }
77
-
78
-
79
- def render_metrics_markdown(cm_state: Dict[str, int]) -> str:
80
- tp = int(cm_state.get("tp", 0))
81
- fp = int(cm_state.get("fp", 0))
82
- fn = int(cm_state.get("fn", 0))
83
- tn = int(cm_state.get("tn", 0))
84
- m = compute_metrics(tp, fp, fn, tn)
85
- total = tp + fp + fn + tn
86
- return (
87
- "### Perhitungan Rumus\n"
88
- f"- **Accuracy** = (TP + TN) / (TP + FP + FN + TN) = ({tp}+{tn})/{total} = **{m['accuracy']:.4f}**\n"
89
- f"- **Precision** = TP / (TP + FP) = {tp}/({tp + fp}) = **{m['precision']:.4f}**\n"
90
- f"- **Recall** = TP / (TP + FN) = {tp}/({tp + fn}) = **{m['recall']:.4f}**\n"
91
- f"- **F1-Score** = 2 x (Precision x Recall) / (Precision + Recall) = **{m['f1']:.4f}**\n"
92
- )
93
-
94
-
95
- def draw_confusion_matrix_image(cm_state: Dict[str, int]) -> np.ndarray:
96
- tp = int(cm_state.get("tp", 0))
97
- fp = int(cm_state.get("fp", 0))
98
- fn = int(cm_state.get("fn", 0))
99
- tn = int(cm_state.get("tn", 0))
100
-
101
- canvas = np.full((520, 860, 3), 246, dtype=np.uint8)
102
- cv2.putText(
103
- canvas,
104
- "Confusion Matrix (Visual)",
105
- (245, 45),
106
- cv2.FONT_HERSHEY_SIMPLEX,
107
- 0.9,
108
- (35, 35, 35),
109
- 2,
110
- cv2.LINE_AA,
111
- )
112
-
113
- start_x, start_y, cell = 300, 130, 145
114
- cv2.putText(canvas, "Prediksi", (365, 95), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (40, 40, 40), 2, cv2.LINE_AA)
115
- cv2.putText(canvas, "Sesuai", (330, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (55, 55, 55), 2, cv2.LINE_AA)
116
- cv2.putText(canvas, "Tidak sesuai", (450, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (55, 55, 55), 2, cv2.LINE_AA)
117
- cv2.putText(canvas, "Aktual", (220, 285), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (40, 40, 40), 2, cv2.LINE_AA)
118
- cv2.putText(canvas, "Sesuai", (235, 205), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (55, 55, 55), 2, cv2.LINE_AA)
119
- cv2.putText(canvas, "Tidak sesuai", (170, 350), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (55, 55, 55), 2, cv2.LINE_AA)
120
-
121
- cells = [
122
- ("TP", tp, (198, 239, 206), 0, 0),
123
- ("FN", fn, (225, 229, 255), 0, 1),
124
- ("FP", fp, (197, 220, 255), 1, 0),
125
- ("TN", tn, (205, 251, 243), 1, 1),
126
- ]
127
- for label, value, color, row, col in cells:
128
- x1 = start_x + col * cell
129
- y1 = start_y + row * cell
130
- x2 = x1 + cell
131
- y2 = y1 + cell
132
- cv2.rectangle(canvas, (x1, y1), (x2, y2), color, -1)
133
- cv2.rectangle(canvas, (x1, y1), (x2, y2), (70, 70, 70), 2)
134
- cv2.putText(
135
- canvas,
136
- label,
137
- (x1 + 50, y1 + 62),
138
- cv2.FONT_HERSHEY_SIMPLEX,
139
- 1.0,
140
- (25, 25, 25),
141
- 2,
142
- cv2.LINE_AA,
143
- )
144
- cv2.putText(
145
- canvas,
146
- str(value),
147
- (x1 + 62, y1 + 108),
148
- cv2.FONT_HERSHEY_SIMPLEX,
149
- 1.0,
150
- (15, 15, 15),
151
- 2,
152
- cv2.LINE_AA,
153
- )
154
-
155
- total = tp + fp + fn + tn
156
- cv2.putText(
157
- canvas,
158
- f"Total Sampel: {total}",
159
- (318, 450),
160
- cv2.FONT_HERSHEY_SIMPLEX,
161
- 0.75,
162
- (45, 45, 45),
163
- 2,
164
- cv2.LINE_AA,
165
- )
166
- return cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
167
-
168
-
169
  def _resolve_person_class_id(result: Any) -> int:
170
  names = getattr(result, "names", {})
171
  if isinstance(names, dict):
@@ -179,184 +65,239 @@ def _resolve_person_class_id(result: Any) -> int:
179
  return 0
180
 
181
 
182
- def run_attendance_validation(
183
- image: np.ndarray, attendance_count: float, conf_threshold: float
184
- ) -> Tuple[np.ndarray, str, str]:
185
  if image is None:
186
- raise ValueError("Silakan unggah gambar atau gunakan kamera terlebih dahulu.")
187
-
188
- try:
189
- target_attendance = int(attendance_count)
190
- except (TypeError, ValueError):
191
- target_attendance = 0
192
-
193
  model = load_model()
194
- image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
195
- results = model.predict(source=image_bgr, conf=conf_threshold, verbose=False)
196
- result = results[0]
197
-
198
- person_class_id = _resolve_person_class_id(result)
199
- classes = result.boxes.cls.cpu().numpy() if result.boxes is not None else np.array([])
200
- detected_count = int(np.sum(classes == person_class_id))
201
 
202
- annotated_bgr = result.plot()
203
- annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)
204
 
205
- status = "Sesuai" if detected_count == target_attendance else "Tidak sesuai"
206
- summary = format_summary(detected_count, target_attendance, status)
207
- return annotated_rgb, summary, status
208
 
209
 
210
- def update_confusion_matrix(
211
- cm_state: Dict[str, int], predicted_label: str, actual_label: str
212
- ) -> Tuple[Dict[str, int], np.ndarray, str, str]:
213
- state = dict(cm_state or CM_INIT)
214
-
215
- if predicted_label not in ("Sesuai", "Tidak sesuai"):
216
- return (
217
- state,
218
- draw_confusion_matrix_image(state),
219
- render_metrics_markdown(state),
220
- "Lakukan validasi gambar terlebih dahulu sebelum update confusion matrix.",
221
- )
222
-
223
- if actual_label == "Sesuai" and predicted_label == "Sesuai":
224
- state["tp"] += 1
225
- elif actual_label == "Sesuai" and predicted_label == "Tidak sesuai":
226
- state["fn"] += 1
227
- elif actual_label == "Tidak sesuai" and predicted_label == "Sesuai":
228
- state["fp"] += 1
229
- else:
230
- state["tn"] += 1
231
-
232
- return (
233
- state,
234
- draw_confusion_matrix_image(state),
235
- render_metrics_markdown(state),
236
- "Confusion matrix berhasil diperbarui.",
237
- )
238
-
239
-
240
- def reset_confusion_matrix() -> Tuple[Dict[str, int], np.ndarray, str, str]:
241
- state = dict(CM_INIT)
242
- return (
243
- state,
244
- draw_confusion_matrix_image(state),
245
- render_metrics_markdown(state),
246
- "Confusion matrix direset ke nol.",
247
- )
248
-
249
-
250
- def run_inference_ui(
251
  image: np.ndarray, attendance_count: float, conf_threshold: float
252
- ) -> Tuple[np.ndarray, str, str]:
253
  try:
254
- return run_attendance_validation(image, attendance_count, conf_threshold)
 
 
 
 
 
 
 
 
 
 
 
 
255
  except Exception as err:
256
  summary = (
257
  "Proses gagal.\n"
258
  f"Detail: {err}\n\n"
259
  "Tips:\n"
260
- "1) Pastikan file model tersedia (yolov8n.pt atau MODEL_PATH).\n"
261
- "2) Jika menggunakan Hugging Face Hub, set HF_MODEL_REPO dan HF_MODEL_FILE."
262
  )
263
- return image, summary, ""
264
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
 
266
- def run_video_validation_stub(video_path: str) -> None:
267
- """
268
- Extension point for future video attendance pipeline.
269
- This project intentionally keeps image inference as the primary feature.
270
- """
271
- raise NotImplementedError(
272
- f"Video pipeline belum diimplementasikan. Input diterima: {video_path}"
 
 
 
 
 
 
 
 
 
 
273
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
 
275
 
276
  CUSTOM_CSS = """
277
- .container {max-width: 1200px !important; margin: auto;}
278
- .app-title {text-align: center; margin-bottom: 6px;}
279
- .app-subtitle {text-align: center; color: #4a5568; margin-top: 0;}
280
  """
281
 
282
 
283
- with gr.Blocks(css=CUSTOM_CSS, title="Validasi Kehadiran Mahasiswa - YOLOv8") as demo:
284
  gr.HTML(
285
  """
286
- <h1 class="app-title">Validasi Kehadiran Mahasiswa Berbasis YOLOv8</h1>
287
- <p class="app-subtitle">
288
- Implementasi klasifikasi kehadiran dalam ruang kelas berbasis citra secara real-time (demo riset).
289
  </p>
290
  """
291
  )
292
 
293
- cm_state = gr.State(dict(CM_INIT))
294
- predicted_label_state = gr.State("")
295
-
296
- with gr.Row():
297
- with gr.Column(scale=2):
298
- image_input = gr.Image(
299
- label="Input Gambar Kelas",
300
- type="numpy",
301
- sources=["upload", "webcam"],
302
- )
303
- attendance_input = gr.Number(
304
- label="Jumlah Presensi",
305
- value=0,
306
- precision=0,
307
- minimum=0,
308
- )
309
- conf_input = gr.Slider(
310
- minimum=0.1,
311
- maximum=1.0,
312
- value=0.25,
313
- step=0.05,
314
- label="Confidence Threshold",
315
- )
316
- run_btn = gr.Button("Proses Validasi", variant="primary")
317
-
318
- output_image = gr.Image(label="Hasil Deteksi (Bounding Box)", type="numpy")
319
- output_summary = gr.Textbox(
320
- label="Ringkasan Validasi",
321
- lines=5,
322
- interactive=False,
323
- )
324
-
325
- with gr.Column(scale=2):
326
- gr.Markdown("### Evaluasi Manual")
327
- actual_label_input = gr.Radio(
328
- choices=["Sesuai", "Tidak sesuai"],
329
- value="Sesuai",
330
- label="Label Aktual Sampel",
331
- )
332
- update_cm_btn = gr.Button("Update Confusion Matrix")
333
- reset_cm_btn = gr.Button("Reset Confusion Matrix")
334
- eval_status = gr.Markdown("Silakan proses gambar terlebih dahulu.")
335
- with gr.Row():
336
- cm_image = gr.Image(
337
- label="Confusion Matrix (Gambar)",
338
- type="numpy",
339
- value=draw_confusion_matrix_image(CM_INIT),
340
- interactive=False,
341
- )
342
- metrics_panel = gr.Markdown(render_metrics_markdown(CM_INIT))
343
 
344
  run_btn.click(
345
- fn=run_inference_ui,
346
  inputs=[image_input, attendance_input, conf_input],
347
- outputs=[output_image, output_summary, predicted_label_state],
348
- )
349
-
350
- update_cm_btn.click(
351
- fn=update_confusion_matrix,
352
- inputs=[cm_state, predicted_label_state, actual_label_input],
353
- outputs=[cm_state, cm_image, metrics_panel, eval_status],
354
  )
355
 
356
- reset_cm_btn.click(
357
- fn=reset_confusion_matrix,
358
- inputs=[],
359
- outputs=[cm_state, cm_image, metrics_panel, eval_status],
360
  )
361
 
362
 
 
1
+ import io
2
  import os
3
+ import tempfile
4
+ import zipfile
5
  from functools import lru_cache
6
+ from typing import Any, Dict, List, Tuple
7
 
8
  import cv2
9
  import gradio as gr
10
+ import matplotlib.pyplot as plt
11
  import numpy as np
12
+ import pandas as pd
13
+ import seaborn as sns
14
  from huggingface_hub import hf_hub_download
15
+ from sklearn.metrics import confusion_matrix
16
  from ultralytics import YOLO
17
 
18
 
19
+ CLASS_NAMES = ["Sesuai", "Tidak sesuai"]
20
 
21
 
22
  def resolve_model_path() -> str:
 
 
 
 
23
  model_env = os.getenv("MODEL_PATH", "").strip()
24
  base_dir = os.path.dirname(__file__)
25
  if model_env:
 
27
  return model_env
28
  raise FileNotFoundError(f"MODEL_PATH tidak valid: {model_env}")
29
 
30
+ for candidate in ("yolov8n.pt", "best.pt"):
31
+ local_path = os.path.join(base_dir, candidate)
32
+ if os.path.exists(local_path):
33
+ return local_path
 
 
 
34
 
35
  hf_repo = os.getenv("HF_MODEL_REPO", "").strip()
36
  hf_file = os.getenv("HF_MODEL_FILE", "yolov8n.pt").strip()
 
38
  return hf_hub_download(repo_id=hf_repo, filename=hf_file)
39
 
40
  raise FileNotFoundError(
41
+ "Model tidak ditemukan. Simpan 'yolov8n.pt' (atau best.pt) di root project, "
42
+ "atau set MODEL_PATH / HF_MODEL_REPO."
 
43
  )
44
 
45
 
46
  @lru_cache(maxsize=1)
47
  def load_model() -> YOLO:
48
+ return YOLO(resolve_model_path())
 
 
 
 
 
 
 
 
 
49
 
50
 
51
  def _safe_div(num: float, den: float) -> float:
52
  return 0.0 if den == 0 else num / den
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def _resolve_person_class_id(result: Any) -> int:
56
  names = getattr(result, "names", {})
57
  if isinstance(names, dict):
 
65
  return 0
66
 
67
 
68
+ def infer_image(image: np.ndarray, conf_threshold: float) -> Tuple[np.ndarray, int]:
 
 
69
  if image is None:
70
+ raise ValueError("Silakan unggah gambar atau gunakan kamera.")
 
 
 
 
 
 
71
  model = load_model()
72
+ bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
73
+ result = model.predict(source=bgr, conf=conf_threshold, verbose=False)[0]
74
+ person_id = _resolve_person_class_id(result)
75
+ cls = result.boxes.cls.cpu().numpy() if result.boxes is not None else np.array([])
76
+ detected_count = int(np.sum(cls == person_id))
77
+ annotated = cv2.cvtColor(result.plot(), cv2.COLOR_BGR2RGB)
78
+ return annotated, detected_count
79
 
 
 
80
 
81
+ def classify_status(detected_count: int, attendance_count: int) -> str:
82
+ return "Sesuai" if detected_count == attendance_count else "Tidak sesuai"
 
83
 
84
 
85
+ def run_single_validation(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  image: np.ndarray, attendance_count: float, conf_threshold: float
87
+ ) -> Tuple[np.ndarray, str]:
88
  try:
89
+ attendance = int(attendance_count)
90
+ except (TypeError, ValueError):
91
+ attendance = 0
92
+
93
+ try:
94
+ annotated, detected = infer_image(image, conf_threshold)
95
+ status = classify_status(detected, attendance)
96
+ summary = (
97
+ f"Jumlah terdeteksi: {detected}\n"
98
+ f"Jumlah presensi: {attendance}\n"
99
+ f"Status klasifikasi: {status}"
100
+ )
101
+ return annotated, summary
102
  except Exception as err:
103
  summary = (
104
  "Proses gagal.\n"
105
  f"Detail: {err}\n\n"
106
  "Tips:\n"
107
+ "1) Pastikan model tersedia (yolov8n.pt atau MODEL_PATH).\n"
108
+ "2) Jika model dari HF Hub, set HF_MODEL_REPO dan HF_MODEL_FILE."
109
  )
110
+ return image, summary
111
+
112
+
113
+ def draw_confusion_matrix_image(cm: np.ndarray) -> np.ndarray:
114
+ sns.set_style("white")
115
+ fig, ax = plt.subplots(figsize=(6.2, 4.8))
116
+ sns.heatmap(
117
+ cm,
118
+ annot=True,
119
+ fmt="d",
120
+ cmap="Blues",
121
+ cbar=True,
122
+ xticklabels=CLASS_NAMES,
123
+ yticklabels=CLASS_NAMES,
124
+ linewidths=0.5,
125
+ linecolor="white",
126
+ ax=ax,
127
+ )
128
+ ax.set_title("Confusion Matrix", fontsize=12, pad=10)
129
+ ax.set_xlabel("Predicted label")
130
+ ax.set_ylabel("True label")
131
+ plt.xticks(rotation=30, ha="right")
132
+ plt.yticks(rotation=0)
133
+ plt.tight_layout()
134
+
135
+ buf = io.BytesIO()
136
+ fig.savefig(buf, format="png", dpi=150)
137
+ plt.close(fig)
138
+ buf.seek(0)
139
+ data = np.frombuffer(buf.read(), dtype=np.uint8)
140
+ img_bgr = cv2.imdecode(data, cv2.IMREAD_COLOR)
141
+ return cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
142
+
143
+
144
+ def _normalize_actual_label(value: str) -> str:
145
+ v = str(value).strip().lower()
146
+ if v in ("sesuai", "match", "1", "true"):
147
+ return "Sesuai"
148
+ return "Tidak sesuai"
149
+
150
+
151
+ def _get_col(df: pd.DataFrame, options: List[str]) -> str:
152
+ lower_map = {c.lower(): c for c in df.columns}
153
+ for opt in options:
154
+ if opt.lower() in lower_map:
155
+ return lower_map[opt.lower()]
156
+ raise ValueError(f"Kolom tidak ditemukan. Butuh salah satu dari: {options}")
157
+
158
+
159
+ def evaluate_classification_batch(
160
+ image_zip_path: str, csv_path: str, conf_threshold: float
161
+ ) -> Tuple[np.ndarray, str, pd.DataFrame]:
162
+ if not image_zip_path or not csv_path:
163
+ raise ValueError("Upload ZIP gambar dan CSV evaluasi terlebih dahulu.")
164
+
165
+ df = pd.read_csv(csv_path)
166
+ fname_col = _get_col(df, ["filename", "file", "image", "image_name"])
167
+ pres_col = _get_col(df, ["presensi", "attendance", "attendance_count"])
168
+ actual_col = _get_col(df, ["actual_label", "label", "ground_truth", "aktual"])
169
+
170
+ y_true: List[str] = []
171
+ y_pred: List[str] = []
172
+ rows: List[Dict[str, Any]] = []
173
+
174
+ with tempfile.TemporaryDirectory() as tmpdir:
175
+ with zipfile.ZipFile(image_zip_path, "r") as zf:
176
+ zf.extractall(tmpdir)
177
+
178
+ for _, row in df.iterrows():
179
+ fname = str(row[fname_col]).strip()
180
+ attendance = int(row[pres_col])
181
+ actual = _normalize_actual_label(row[actual_col])
182
+ img_path = os.path.join(tmpdir, fname)
183
+ img = cv2.imread(img_path)
184
+ if img is None:
185
+ continue
186
+ rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
187
+ _, detected = infer_image(rgb, conf_threshold)
188
+ pred = classify_status(detected, attendance)
189
+
190
+ y_true.append(actual)
191
+ y_pred.append(pred)
192
+ rows.append(
193
+ {
194
+ "filename": fname,
195
+ "detected_count": detected,
196
+ "attendance_count": attendance,
197
+ "actual_label": actual,
198
+ "predicted_label": pred,
199
+ }
200
+ )
201
 
202
+ if len(y_true) == 0:
203
+ raise ValueError("Tidak ada sampel valid yang berhasil diproses.")
204
+
205
+ cm = confusion_matrix(y_true, y_pred, labels=CLASS_NAMES)
206
+ cm_img = draw_confusion_matrix_image(cm)
207
+ tn, fp, fn, tp = cm.ravel() if cm.size == 4 else (0, 0, 0, 0)
208
+ acc = _safe_div(tp + tn, tp + tn + fp + fn)
209
+ prec = _safe_div(tp, tp + fp)
210
+ rec = _safe_div(tp, tp + fn)
211
+ f1 = _safe_div(2 * prec * rec, prec + rec)
212
+ metrics = (
213
+ "### Hasil Evaluasi Klasifikasi\n"
214
+ f"- Jumlah sampel: **{len(y_true)}**\n"
215
+ f"- Accuracy: **{acc:.4f}**\n"
216
+ f"- Precision (Sesuai): **{prec:.4f}**\n"
217
+ f"- Recall (Sesuai): **{rec:.4f}**\n"
218
+ f"- F1-Score (Sesuai): **{f1:.4f}**\n"
219
  )
220
+ return cm_img, metrics, pd.DataFrame(rows)
221
+
222
+
223
+ def run_batch_ui(
224
+ image_zip: Any, csv_file: Any, conf_threshold: float
225
+ ) -> Tuple[np.ndarray, str, pd.DataFrame]:
226
+ try:
227
+ zip_path = image_zip.name if image_zip is not None else ""
228
+ csv_path = csv_file.name if csv_file is not None else ""
229
+ return evaluate_classification_batch(zip_path, csv_path, conf_threshold)
230
+ except Exception as err:
231
+ empty = pd.DataFrame(
232
+ columns=[
233
+ "filename",
234
+ "detected_count",
235
+ "attendance_count",
236
+ "actual_label",
237
+ "predicted_label",
238
+ ]
239
+ )
240
+ msg = f"Evaluasi batch gagal: {err}"
241
+ blank = np.full((420, 620, 3), 245, dtype=np.uint8)
242
+ cv2.putText(blank, "Confusion Matrix belum tersedia", (95, 210), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (80, 80, 80), 2)
243
+ return blank, msg, empty
244
 
245
 
246
  CUSTOM_CSS = """
247
+ .container {max-width: 1100px !important; margin: auto;}
248
+ .section-box {padding: 14px; border: 1px solid #d7dee8; border-radius: 10px; background: #ffffff;}
 
249
  """
250
 
251
 
252
+ with gr.Blocks(css=CUSTOM_CSS, title="Klasifikasi Kehadiran Mahasiswa - YOLOv8") as demo:
253
  gr.HTML(
254
  """
255
+ <h1 style="text-align:center;margin-bottom:4px;">Klasifikasi Kehadiran Mahasiswa Berbasis YOLOv8</h1>
256
+ <p style="text-align:center;color:#4a5568;margin-top:0;">
257
+ Metode klasifikasi biner: <b>Sesuai</b> jika jumlah terdeteksi = jumlah presensi, selain itu <b>Tidak sesuai</b>.
258
  </p>
259
  """
260
  )
261
 
262
+ with gr.Column(elem_classes=["section-box"]):
263
+ gr.Markdown("## Section 1 - Validasi Satu Gambar")
264
+ image_input = gr.Image(
265
+ label="Input Gambar Kelas",
266
+ type="numpy",
267
+ sources=["upload", "webcam"],
268
+ )
269
+ attendance_input = gr.Number(label="Jumlah Presensi", value=0, precision=0, minimum=0)
270
+ conf_input = gr.Slider(0.1, 1.0, value=0.25, step=0.05, label="Confidence Threshold")
271
+ run_btn = gr.Button("Proses Klasifikasi", variant="primary")
272
+ output_image = gr.Image(label="Hasil Deteksi", type="numpy")
273
+ output_summary = gr.Textbox(label="Ringkasan", lines=5, interactive=False)
274
+
275
+ with gr.Column(elem_classes=["section-box"]):
276
+ gr.Markdown("## Section 2 - Evaluasi Batch Klasifikasi")
277
+ gr.Markdown(
278
+ "Upload **ZIP gambar** dan **CSV evaluasi**.\n"
279
+ "Kolom CSV yang didukung:\n"
280
+ "- nama file gambar: `filename`/`file`/`image`\n"
281
+ "- jumlah presensi: `presensi`/`attendance`\n"
282
+ "- label aktual: `actual_label`/`label`/`ground_truth` (`Sesuai` atau `Tidak sesuai`)"
283
+ )
284
+ image_zip = gr.File(label="ZIP Gambar Evaluasi", file_types=[".zip"])
285
+ csv_file = gr.File(label="CSV Ground Truth", file_types=[".csv"])
286
+ eval_btn = gr.Button("Jalankan Evaluasi", variant="secondary")
287
+ cm_image = gr.Image(label="Confusion Matrix (Image)", type="numpy")
288
+ eval_metrics = gr.Markdown("Metrik evaluasi akan tampil di sini.")
289
+ eval_table = gr.Dataframe(label="Detail Prediksi per Sampel")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
 
291
  run_btn.click(
292
+ fn=run_single_validation,
293
  inputs=[image_input, attendance_input, conf_input],
294
+ outputs=[output_image, output_summary],
 
 
 
 
 
 
295
  )
296
 
297
+ eval_btn.click(
298
+ fn=run_batch_ui,
299
+ inputs=[image_zip, csv_file, conf_input],
300
+ outputs=[cm_image, eval_metrics, eval_table],
301
  )
302
 
303
 
requirements.txt CHANGED
@@ -3,3 +3,7 @@ ultralytics>=8.2.0
3
  opencv-python-headless>=4.10.0.84
4
  huggingface_hub>=0.23.0
5
  numpy>=1.26.0
 
 
 
 
 
3
  opencv-python-headless>=4.10.0.84
4
  huggingface_hub>=0.23.0
5
  numpy>=1.26.0
6
+ pandas>=2.2.0
7
+ scikit-learn>=1.5.0
8
+ matplotlib>=3.8.0
9
+ seaborn>=0.13.0