firgiawann commited on
Commit
9f3d5c5
·
verified ·
1 Parent(s): 307fc65

Restructure sections: results in section 2 and add training section

Browse files
Files changed (2) hide show
  1. README.md +15 -0
  2. app.py +136 -58
README.md CHANGED
@@ -44,6 +44,21 @@ Aplikasi menyediakan evaluasi batch otomatis:
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
 
49
  - `app.py` - aplikasi Gradio untuk Spaces
 
44
  - output confusion matrix ditampilkan sebagai **gambar heatmap**,
45
  - metrik Accuracy, Precision, Recall, dan F1-Score dihitung otomatis.
46
 
47
+ ## Struktur UI (Vertical Sections)
48
+
49
+ - **Section 1 - Input & Proses**
50
+ - upload/kamera gambar, input presensi, parameter confidence, tombol proses klasifikasi
51
+ - input evaluasi batch (ZIP gambar + CSV ground truth)
52
+ - **Section 2 - Hasil Processing**
53
+ - hasil klasifikasi
54
+ - grafik perbandingan (terdeteksi vs presensi)
55
+ - confusion matrix image
56
+ - metrik evaluasi batch
57
+ - **Section 3 - Training**
58
+ - upload ZIP dataset YOLO
59
+ - set path `data.yaml`, epochs, image size
60
+ - jalankan training dan ambil `best.pt` jika tersedia
61
+
62
  ## Struktur File yang Diharapkan
63
 
64
  - `app.py` - aplikasi Gradio untuk Spaces
app.py CHANGED
@@ -2,6 +2,7 @@ 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
 
@@ -82,9 +83,29 @@ 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):
@@ -94,20 +115,22 @@ def run_single_validation(
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:
@@ -158,7 +181,7 @@ def _get_col(df: pd.DataFrame, options: List[str]) -> str:
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
 
@@ -169,7 +192,6 @@ def evaluate_classification_batch(
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:
@@ -186,18 +208,8 @@ def evaluate_classification_batch(
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.")
@@ -210,41 +222,92 @@ def evaluate_classification_batch(
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
 
@@ -254,13 +317,13 @@ with gr.Blocks(css=CUSTOM_CSS, title="Klasifikasi Kehadiran Mahasiswa - YOLOv8")
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
  with gr.Row():
265
  image_input = gr.Image(
266
  label="Upload/Kamera - Gambar Kelas",
@@ -268,37 +331,52 @@ with gr.Blocks(css=CUSTOM_CSS, title="Klasifikasi Kehadiran Mahasiswa - YOLOv8")
268
  sources=["upload", "webcam"],
269
  )
270
  output_image = gr.Image(label="Hasil Proses (Dekat Upload)", type="numpy")
271
- output_summary = gr.Textbox(label="Ringkasan", lines=5, interactive=False)
272
  attendance_input = gr.Number(label="Jumlah Presensi", value=0, precision=0, minimum=0)
273
  conf_input = gr.Slider(0.1, 1.0, value=0.25, step=0.05, label="Confidence Threshold")
274
  run_btn = gr.Button("Proses Klasifikasi", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
275
 
276
  with gr.Column(elem_classes=["section-box"]):
277
- gr.Markdown("## Section 2 - Evaluasi Batch Klasifikasi")
278
  gr.Markdown(
279
- "Upload **ZIP gambar** dan **CSV evaluasi**.\n"
280
- "Kolom CSV yang didukung:\n"
281
- "- nama file gambar: `filename`/`file`/`image`\n"
282
- "- jumlah presensi: `presensi`/`attendance`\n"
283
- "- label aktual: `actual_label`/`label`/`ground_truth` (`Sesuai` atau `Tidak sesuai`)"
284
  )
285
- image_zip = gr.File(label="ZIP Gambar Evaluasi", file_types=[".zip"])
286
- csv_file = gr.File(label="CSV Ground Truth", file_types=[".csv"])
287
- eval_btn = gr.Button("Jalankan Evaluasi", variant="secondary")
288
- cm_image = gr.Image(label="Confusion Matrix (Image)", type="numpy")
289
- eval_metrics = gr.Markdown("Metrik evaluasi akan tampil di sini.")
290
- eval_table = gr.Dataframe(label="Detail Prediksi per Sampel")
 
 
291
 
292
  run_btn.click(
293
  fn=run_single_validation,
294
  inputs=[image_input, attendance_input, conf_input],
295
- outputs=[output_image, output_summary],
296
  )
297
 
298
  eval_btn.click(
299
  fn=run_batch_ui,
300
  inputs=[image_zip, csv_file, conf_input],
301
- outputs=[cm_image, eval_metrics, eval_table],
 
 
 
 
 
 
302
  )
303
 
304
 
 
2
  import os
3
  import tempfile
4
  import zipfile
5
+ from datetime import datetime
6
  from functools import lru_cache
7
  from typing import Any, Dict, List, Tuple
8
 
 
83
  return "Sesuai" if detected_count == attendance_count else "Tidak sesuai"
84
 
85
 
86
+ def draw_single_comparison_chart(detected: int, attendance: int) -> np.ndarray:
87
+ fig, ax = plt.subplots(figsize=(5.0, 3.2))
88
+ labels = ["Terdeteksi", "Presensi"]
89
+ values = [detected, attendance]
90
+ bars = ax.bar(labels, values, color=["#2b6cb0", "#2f855a"])
91
+ ax.set_title("Grafik Perbandingan")
92
+ ax.set_ylabel("Jumlah")
93
+ for b in bars:
94
+ ax.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.05, str(int(b.get_height())), ha="center", va="bottom")
95
+ plt.tight_layout()
96
+
97
+ buf = io.BytesIO()
98
+ fig.savefig(buf, format="png", dpi=140)
99
+ plt.close(fig)
100
+ buf.seek(0)
101
+ data = np.frombuffer(buf.read(), dtype=np.uint8)
102
+ img_bgr = cv2.imdecode(data, cv2.IMREAD_COLOR)
103
+ return cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
104
+
105
+
106
  def run_single_validation(
107
  image: np.ndarray, attendance_count: float, conf_threshold: float
108
+ ) -> Tuple[np.ndarray, str, np.ndarray]:
109
  try:
110
  attendance = int(attendance_count)
111
  except (TypeError, ValueError):
 
115
  annotated, detected = infer_image(image, conf_threshold)
116
  status = classify_status(detected, attendance)
117
  summary = (
118
+ "### Hasil Klasifikasi\n"
119
+ f"- Jumlah terdeteksi: **{detected}**\n"
120
+ f"- Jumlah presensi: **{attendance}**\n"
121
+ f"- Status klasifikasi: **{status}**"
122
  )
123
+ chart = draw_single_comparison_chart(detected, attendance)
124
+ return annotated, summary, chart
125
  except Exception as err:
126
  summary = (
127
+ "### Hasil Klasifikasi\n"
128
+ f"Proses gagal: {err}\n\n"
129
+ "Tips: pastikan model tersedia (`yolov8n.pt` atau MODEL_PATH)."
 
 
130
  )
131
+ blank = np.full((320, 500, 3), 245, dtype=np.uint8)
132
+ cv2.putText(blank, "Grafik belum tersedia", (120, 165), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (80, 80, 80), 2)
133
+ return image, summary, blank
134
 
135
 
136
  def draw_confusion_matrix_image(cm: np.ndarray) -> np.ndarray:
 
181
 
182
  def evaluate_classification_batch(
183
  image_zip_path: str, csv_path: str, conf_threshold: float
184
+ ) -> Tuple[np.ndarray, str]:
185
  if not image_zip_path or not csv_path:
186
  raise ValueError("Upload ZIP gambar dan CSV evaluasi terlebih dahulu.")
187
 
 
192
 
193
  y_true: List[str] = []
194
  y_pred: List[str] = []
 
195
 
196
  with tempfile.TemporaryDirectory() as tmpdir:
197
  with zipfile.ZipFile(image_zip_path, "r") as zf:
 
208
  rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
209
  _, detected = infer_image(rgb, conf_threshold)
210
  pred = classify_status(detected, attendance)
 
211
  y_true.append(actual)
212
  y_pred.append(pred)
 
 
 
 
 
 
 
 
 
213
 
214
  if len(y_true) == 0:
215
  raise ValueError("Tidak ada sampel valid yang berhasil diproses.")
 
222
  rec = _safe_div(tp, tp + fn)
223
  f1 = _safe_div(2 * prec * rec, prec + rec)
224
  metrics = (
225
+ "### Hasil Evaluasi Batch\n"
226
  f"- Jumlah sampel: **{len(y_true)}**\n"
227
  f"- Accuracy: **{acc:.4f}**\n"
228
  f"- Precision (Sesuai): **{prec:.4f}**\n"
229
  f"- Recall (Sesuai): **{rec:.4f}**\n"
230
+ f"- F1-Score (Sesuai): **{f1:.4f}**"
231
  )
232
+ return cm_img, metrics
233
 
234
 
235
+ def run_batch_ui(image_zip: Any, csv_file: Any, conf_threshold: float) -> Tuple[np.ndarray, str]:
 
 
236
  try:
237
  zip_path = image_zip.name if image_zip is not None else ""
238
  csv_path = csv_file.name if csv_file is not None else ""
239
  return evaluate_classification_batch(zip_path, csv_path, conf_threshold)
240
  except Exception as err:
241
+ msg = f"### Hasil Evaluasi Batch\nEvaluasi batch gagal: {err}"
 
 
 
 
 
 
 
 
 
242
  blank = np.full((420, 620, 3), 245, dtype=np.uint8)
243
  cv2.putText(blank, "Confusion Matrix belum tersedia", (95, 210), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (80, 80, 80), 2)
244
+ return blank, msg
245
+
246
+
247
+ def _find_yaml(root_dir: str, yaml_name_or_path: str) -> str:
248
+ candidate = os.path.join(root_dir, yaml_name_or_path)
249
+ if os.path.exists(candidate):
250
+ return candidate
251
+
252
+ target_name = os.path.basename(yaml_name_or_path)
253
+ for base, _, files in os.walk(root_dir):
254
+ for f in files:
255
+ if f == target_name:
256
+ return os.path.join(base, f)
257
+ raise FileNotFoundError(f"File YAML dataset tidak ditemukan: {yaml_name_or_path}")
258
+
259
+
260
+ def run_training_ui(
261
+ dataset_zip: Any, data_yaml: str, epochs: float, imgsz: float
262
+ ) -> Tuple[str, str]:
263
+ if dataset_zip is None:
264
+ return "Training gagal: upload ZIP dataset terlebih dahulu.", None
265
+
266
+ try:
267
+ dataset_path = dataset_zip.name
268
+ base_dir = os.path.dirname(__file__)
269
+ train_workspace = os.path.join(base_dir, "training_data", datetime.now().strftime("%Y%m%d_%H%M%S"))
270
+ os.makedirs(train_workspace, exist_ok=True)
271
+
272
+ with zipfile.ZipFile(dataset_path, "r") as zf:
273
+ zf.extractall(train_workspace)
274
+
275
+ yaml_path = _find_yaml(train_workspace, data_yaml.strip() or "data.yaml")
276
+ base_model = os.path.join(base_dir, "yolov8n.pt")
277
+ if not os.path.exists(base_model):
278
+ base_model = resolve_model_path()
279
+
280
+ train_model = YOLO(base_model)
281
+ results = train_model.train(
282
+ data=yaml_path,
283
+ epochs=int(epochs),
284
+ imgsz=int(imgsz),
285
+ project=os.path.join(base_dir, "runs_train"),
286
+ name="space_train",
287
+ exist_ok=True,
288
+ device="cpu",
289
+ verbose=False,
290
+ )
291
+
292
+ save_dir = str(results.save_dir)
293
+ best_path = os.path.join(save_dir, "weights", "best.pt")
294
+ if not os.path.exists(best_path):
295
+ best_path = None
296
+
297
+ msg = (
298
+ "Training selesai.\n"
299
+ f"- Dataset workspace: `{train_workspace}`\n"
300
+ f"- data.yaml: `{yaml_path}`\n"
301
+ f"- Output run: `{save_dir}`\n"
302
+ f"- best.pt: `{best_path}`"
303
+ )
304
+ return msg, best_path
305
+ except Exception as err:
306
+ return f"Training gagal: {err}", None
307
 
308
 
309
  CUSTOM_CSS = """
310
+ .container {max-width: 1120px !important; margin: auto;}
311
  .section-box {padding: 14px; border: 1px solid #d7dee8; border-radius: 10px; background: #ffffff;}
312
  """
313
 
 
317
  """
318
  <h1 style="text-align:center;margin-bottom:4px;">Klasifikasi Kehadiran Mahasiswa Berbasis YOLOv8</h1>
319
  <p style="text-align:center;color:#4a5568;margin-top:0;">
320
+ Status <b>Sesuai</b> jika jumlah terdeteksi = jumlah presensi, selain itu <b>Tidak sesuai</b>.
321
  </p>
322
  """
323
  )
324
 
325
  with gr.Column(elem_classes=["section-box"]):
326
+ gr.Markdown("## Section 1 - Input & Proses")
327
  with gr.Row():
328
  image_input = gr.Image(
329
  label="Upload/Kamera - Gambar Kelas",
 
331
  sources=["upload", "webcam"],
332
  )
333
  output_image = gr.Image(label="Hasil Proses (Dekat Upload)", type="numpy")
 
334
  attendance_input = gr.Number(label="Jumlah Presensi", value=0, precision=0, minimum=0)
335
  conf_input = gr.Slider(0.1, 1.0, value=0.25, step=0.05, label="Confidence Threshold")
336
  run_btn = gr.Button("Proses Klasifikasi", variant="primary")
337
+ gr.Markdown("### Input Evaluasi Batch")
338
+ image_zip = gr.File(label="ZIP Gambar Evaluasi", file_types=[".zip"])
339
+ csv_file = gr.File(label="CSV Ground Truth", file_types=[".csv"])
340
+ eval_btn = gr.Button("Jalankan Evaluasi Batch", variant="secondary")
341
+
342
+ with gr.Column(elem_classes=["section-box"]):
343
+ gr.Markdown("## Section 2 - Hasil Processing")
344
+ class_result_md = gr.Markdown("Hasil klasifikasi akan tampil di sini.")
345
+ comparison_chart = gr.Image(label="Grafik Klasifikasi", type="numpy")
346
+ cm_image = gr.Image(label="Confusion Matrix", type="numpy")
347
+ eval_metrics = gr.Markdown("Metrik evaluasi batch akan tampil di sini.")
348
 
349
  with gr.Column(elem_classes=["section-box"]):
350
+ gr.Markdown("## Section 3 - Training")
351
  gr.Markdown(
352
+ "Upload ZIP dataset YOLO lalu jalankan training. "
353
+ "Isi `data.yaml` sesuai nama/path file YAML di dalam ZIP."
 
 
 
354
  )
355
+ train_zip = gr.File(label="ZIP Dataset Training", file_types=[".zip"])
356
+ train_yaml = gr.Textbox(label="Path data.yaml di dalam ZIP", value="data.yaml")
357
+ with gr.Row():
358
+ train_epochs = gr.Number(label="Epochs", value=20, precision=0, minimum=1)
359
+ train_imgsz = gr.Number(label="Image Size", value=640, precision=0, minimum=64)
360
+ train_btn = gr.Button("Mulai Training", variant="primary")
361
+ train_log = gr.Textbox(label="Log Training", lines=7, interactive=False)
362
+ train_best = gr.File(label="Download best.pt (jika tersedia)")
363
 
364
  run_btn.click(
365
  fn=run_single_validation,
366
  inputs=[image_input, attendance_input, conf_input],
367
+ outputs=[output_image, class_result_md, comparison_chart],
368
  )
369
 
370
  eval_btn.click(
371
  fn=run_batch_ui,
372
  inputs=[image_zip, csv_file, conf_input],
373
+ outputs=[cm_image, eval_metrics],
374
+ )
375
+
376
+ train_btn.click(
377
+ fn=run_training_ui,
378
+ inputs=[train_zip, train_yaml, train_epochs, train_imgsz],
379
+ outputs=[train_log, train_best],
380
  )
381
 
382