Add model selector, attendance testing input, confusion matrix and metric formulas
Browse files- README.md +3 -0
- app.py +189 -24
- requirements.txt +1 -0
README.md
CHANGED
|
@@ -22,6 +22,9 @@ Versi ini difokuskan untuk tahap awal:
|
|
| 22 |
3. Tampilkan hasil:
|
| 23 |
- gambar teranotasi bounding box,
|
| 24 |
- jumlah person terdeteksi,
|
|
|
|
|
|
|
|
|
|
| 25 |
- status klasifikasi:
|
| 26 |
- `Ada Mahasiswa` jika jumlah terdeteksi > 0
|
| 27 |
- `Tidak Ada Mahasiswa` jika jumlah terdeteksi = 0
|
|
|
|
| 22 |
3. Tampilkan hasil:
|
| 23 |
- gambar teranotasi bounding box,
|
| 24 |
- jumlah person terdeteksi,
|
| 25 |
+
- input jumlah presensi (testing),
|
| 26 |
+
- validasi `Sesuai` / `Tidak Sesuai`,
|
| 27 |
+
- confusion matrix dan rumus evaluasi,
|
| 28 |
- status klasifikasi:
|
| 29 |
- `Ada Mahasiswa` jika jumlah terdeteksi > 0
|
| 30 |
- `Tidak Ada Mahasiswa` jika jumlah terdeteksi = 0
|
app.py
CHANGED
|
@@ -4,17 +4,21 @@ import shutil
|
|
| 4 |
from datetime import datetime
|
| 5 |
from functools import lru_cache
|
| 6 |
from pathlib import Path
|
| 7 |
-
from typing import Any, Tuple
|
| 8 |
|
| 9 |
import cv2
|
| 10 |
import gradio as gr
|
| 11 |
import matplotlib.pyplot as plt
|
| 12 |
import numpy as np
|
|
|
|
| 13 |
from huggingface_hub import hf_hub_download
|
| 14 |
from ultralytics import YOLO
|
| 15 |
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
|
|
|
| 18 |
model_env = os.getenv("MODEL_PATH", "").strip()
|
| 19 |
base_dir = os.path.dirname(__file__)
|
| 20 |
if model_env:
|
|
@@ -22,25 +26,35 @@ def resolve_model_path() -> str:
|
|
| 22 |
return model_env
|
| 23 |
raise FileNotFoundError(f"MODEL_PATH tidak valid: {model_env}")
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
for candidate in ("yolov8n.pt", "best.pt"):
|
| 26 |
-
|
| 27 |
-
if os.path.exists(
|
| 28 |
-
return
|
| 29 |
|
| 30 |
hf_repo = os.getenv("HF_MODEL_REPO", "").strip()
|
| 31 |
-
|
|
|
|
| 32 |
if hf_repo:
|
| 33 |
return hf_hub_download(repo_id=hf_repo, filename=hf_file)
|
| 34 |
|
| 35 |
raise FileNotFoundError(
|
| 36 |
-
"Model tidak ditemukan. Simpan 'yolov8n.pt'
|
| 37 |
"atau set MODEL_PATH / HF_MODEL_REPO."
|
| 38 |
)
|
| 39 |
|
| 40 |
|
| 41 |
-
@lru_cache(maxsize=
|
| 42 |
-
def load_model() -> YOLO:
|
| 43 |
-
return YOLO(resolve_model_path())
|
| 44 |
|
| 45 |
|
| 46 |
def _resolve_person_class_id(result: Any) -> int:
|
|
@@ -56,10 +70,10 @@ def _resolve_person_class_id(result: Any) -> int:
|
|
| 56 |
return 0
|
| 57 |
|
| 58 |
|
| 59 |
-
def infer_image(image: np.ndarray, conf_threshold: float) -> Tuple[np.ndarray, int]:
|
| 60 |
if image is None:
|
| 61 |
raise ValueError("Silakan unggah gambar atau gunakan kamera.")
|
| 62 |
-
model = load_model()
|
| 63 |
bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
|
| 64 |
result = model.predict(source=bgr, conf=conf_threshold, verbose=False)[0]
|
| 65 |
person_id = _resolve_person_class_id(result)
|
|
@@ -73,6 +87,10 @@ def classify_presence(detected_count: int) -> str:
|
|
| 73 |
return "Ada Mahasiswa" if detected_count > 0 else "Tidak Ada Mahasiswa"
|
| 74 |
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
def draw_detection_chart(detected: int) -> np.ndarray:
|
| 77 |
fig, ax = plt.subplots(figsize=(5.0, 3.2))
|
| 78 |
labels = ["Jumlah Person Terdeteksi"]
|
|
@@ -100,19 +118,24 @@ def draw_detection_chart(detected: int) -> np.ndarray:
|
|
| 100 |
|
| 101 |
|
| 102 |
def run_check_and_classify(
|
| 103 |
-
image: np.ndarray, conf_threshold: float
|
| 104 |
-
) -> Tuple[np.ndarray, str, np.ndarray]:
|
| 105 |
try:
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
| 108 |
summary = (
|
| 109 |
"### Ringkasan Hasil Pengolahan Citra\n"
|
| 110 |
f"- Jumlah objek `person` terdeteksi: **{detected}**\n"
|
| 111 |
-
f"-
|
| 112 |
-
"-
|
|
|
|
|
|
|
| 113 |
)
|
| 114 |
chart = draw_detection_chart(detected)
|
| 115 |
-
|
|
|
|
| 116 |
except Exception as err:
|
| 117 |
summary = (
|
| 118 |
"### Ringkasan Hasil Pengolahan Citra\n"
|
|
@@ -129,7 +152,105 @@ def run_check_and_classify(
|
|
| 129 |
(80, 80, 80),
|
| 130 |
2,
|
| 131 |
)
|
| 132 |
-
return image, summary, blank
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
|
| 135 |
def _iter_images(folder: Path) -> list[Path]:
|
|
@@ -149,7 +270,7 @@ def _label_candidates(img_path: Path) -> list[Path]:
|
|
| 149 |
|
| 150 |
|
| 151 |
def _write_pseudo_label(img_rgb: np.ndarray, label_path: Path, conf_threshold: float) -> int:
|
| 152 |
-
model = load_model()
|
| 153 |
h, w = img_rgb.shape[:2]
|
| 154 |
bgr = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)
|
| 155 |
result = model.predict(source=bgr, conf=conf_threshold, verbose=False)[0]
|
|
@@ -316,6 +437,11 @@ with gr.Blocks(css=CUSTOM_CSS, title="Pengecekan dan Klasifikasi Mahasiswa - YOL
|
|
| 316 |
|
| 317 |
with gr.Column(elem_classes=["section-box"]):
|
| 318 |
gr.Markdown("## Tahap 1 - Akuisisi Data", elem_classes=["section-title"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
with gr.Row():
|
| 320 |
image_input = gr.Image(
|
| 321 |
label="Input Gambar Kelas (Upload/Kamera)",
|
|
@@ -323,6 +449,12 @@ with gr.Blocks(css=CUSTOM_CSS, title="Pengecekan dan Klasifikasi Mahasiswa - YOL
|
|
| 323 |
sources=["upload", "webcam"],
|
| 324 |
)
|
| 325 |
output_image = gr.Image(label="Output Tahap 2 - Hasil Deteksi YOLOv8", type="numpy")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
conf_input = gr.Slider(0.1, 1.0, value=0.25, step=0.05, label="Parameter Confidence (Deteksi)")
|
| 327 |
run_btn = gr.Button("Jalankan Deteksi dan Klasifikasi", variant="primary")
|
| 328 |
|
|
@@ -330,9 +462,31 @@ with gr.Blocks(css=CUSTOM_CSS, title="Pengecekan dan Klasifikasi Mahasiswa - YOL
|
|
| 330 |
gr.Markdown("## Tahap 3 - Hasil Klasifikasi Kehadiran", elem_classes=["section-title"])
|
| 331 |
class_result_md = gr.Markdown("Ringkasan hasil klasifikasi akan tampil di sini.")
|
| 332 |
comparison_chart = gr.Image(label="Visualisasi Jumlah Person Terdeteksi", type="numpy")
|
|
|
|
| 333 |
|
| 334 |
with gr.Column(elem_classes=["section-box"]):
|
| 335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
gr.Markdown(
|
| 337 |
"Training akan membaca dataset dari `dataset/train` dan `dataset/test`.\n"
|
| 338 |
"Jika label `.txt` belum ada, aktifkan pseudo-label agar proses tetap jalan."
|
|
@@ -358,8 +512,19 @@ with gr.Blocks(css=CUSTOM_CSS, title="Pengecekan dan Klasifikasi Mahasiswa - YOL
|
|
| 358 |
|
| 359 |
run_btn.click(
|
| 360 |
fn=run_check_and_classify,
|
| 361 |
-
inputs=[image_input, conf_input],
|
| 362 |
-
outputs=[output_image, class_result_md, comparison_chart],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
)
|
| 364 |
|
| 365 |
train_btn.click(
|
|
|
|
| 4 |
from datetime import datetime
|
| 5 |
from functools import lru_cache
|
| 6 |
from pathlib import Path
|
| 7 |
+
from typing import Any, Dict, Tuple
|
| 8 |
|
| 9 |
import cv2
|
| 10 |
import gradio as gr
|
| 11 |
import matplotlib.pyplot as plt
|
| 12 |
import numpy as np
|
| 13 |
+
import seaborn as sns
|
| 14 |
from huggingface_hub import hf_hub_download
|
| 15 |
from ultralytics import YOLO
|
| 16 |
|
| 17 |
+
CM_INIT = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
|
| 18 |
+
EVAL_CLASSES = ["Sesuai", "Tidak Sesuai"]
|
| 19 |
|
| 20 |
+
|
| 21 |
+
def resolve_model_path(model_choice: str) -> str:
|
| 22 |
model_env = os.getenv("MODEL_PATH", "").strip()
|
| 23 |
base_dir = os.path.dirname(__file__)
|
| 24 |
if model_env:
|
|
|
|
| 26 |
return model_env
|
| 27 |
raise FileNotFoundError(f"MODEL_PATH tidak valid: {model_env}")
|
| 28 |
|
| 29 |
+
if model_choice == "Best.pt":
|
| 30 |
+
best_local = os.path.join(base_dir, "best.pt")
|
| 31 |
+
if os.path.exists(best_local):
|
| 32 |
+
return best_local
|
| 33 |
+
else:
|
| 34 |
+
yolo_local = os.path.join(base_dir, "yolov8n.pt")
|
| 35 |
+
if os.path.exists(yolo_local):
|
| 36 |
+
return yolo_local
|
| 37 |
+
|
| 38 |
for candidate in ("yolov8n.pt", "best.pt"):
|
| 39 |
+
p = os.path.join(base_dir, candidate)
|
| 40 |
+
if os.path.exists(p):
|
| 41 |
+
return p
|
| 42 |
|
| 43 |
hf_repo = os.getenv("HF_MODEL_REPO", "").strip()
|
| 44 |
+
default_hf = "best.pt" if model_choice == "Best.pt" else "yolov8n.pt"
|
| 45 |
+
hf_file = os.getenv("HF_MODEL_FILE", default_hf).strip()
|
| 46 |
if hf_repo:
|
| 47 |
return hf_hub_download(repo_id=hf_repo, filename=hf_file)
|
| 48 |
|
| 49 |
raise FileNotFoundError(
|
| 50 |
+
f"Model pilihan `{model_choice}` tidak ditemukan. Simpan 'yolov8n.pt' / 'best.pt' di root project, "
|
| 51 |
"atau set MODEL_PATH / HF_MODEL_REPO."
|
| 52 |
)
|
| 53 |
|
| 54 |
|
| 55 |
+
@lru_cache(maxsize=2)
|
| 56 |
+
def load_model(model_choice: str) -> YOLO:
|
| 57 |
+
return YOLO(resolve_model_path(model_choice))
|
| 58 |
|
| 59 |
|
| 60 |
def _resolve_person_class_id(result: Any) -> int:
|
|
|
|
| 70 |
return 0
|
| 71 |
|
| 72 |
|
| 73 |
+
def infer_image(image: np.ndarray, conf_threshold: float, model_choice: str) -> Tuple[np.ndarray, int]:
|
| 74 |
if image is None:
|
| 75 |
raise ValueError("Silakan unggah gambar atau gunakan kamera.")
|
| 76 |
+
model = load_model(model_choice)
|
| 77 |
bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
|
| 78 |
result = model.predict(source=bgr, conf=conf_threshold, verbose=False)[0]
|
| 79 |
person_id = _resolve_person_class_id(result)
|
|
|
|
| 87 |
return "Ada Mahasiswa" if detected_count > 0 else "Tidak Ada Mahasiswa"
|
| 88 |
|
| 89 |
|
| 90 |
+
def classify_match(detected_count: int, attendance_count: int) -> str:
|
| 91 |
+
return "Sesuai" if detected_count == attendance_count else "Tidak Sesuai"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
def draw_detection_chart(detected: int) -> np.ndarray:
|
| 95 |
fig, ax = plt.subplots(figsize=(5.0, 3.2))
|
| 96 |
labels = ["Jumlah Person Terdeteksi"]
|
|
|
|
| 118 |
|
| 119 |
|
| 120 |
def run_check_and_classify(
|
| 121 |
+
image: np.ndarray, conf_threshold: float, attendance_count: float, model_choice: str
|
| 122 |
+
) -> Tuple[np.ndarray, str, np.ndarray, str, str]:
|
| 123 |
try:
|
| 124 |
+
attendance = int(attendance_count)
|
| 125 |
+
annotated, detected = infer_image(image, conf_threshold, model_choice)
|
| 126 |
+
status_presence = classify_presence(detected)
|
| 127 |
+
status_match = classify_match(detected, attendance)
|
| 128 |
summary = (
|
| 129 |
"### Ringkasan Hasil Pengolahan Citra\n"
|
| 130 |
f"- Jumlah objek `person` terdeteksi: **{detected}**\n"
|
| 131 |
+
f"- Jumlah presensi (input testing): **{attendance}**\n"
|
| 132 |
+
f"- Klasifikasi keberadaan: **{status_presence}**\n"
|
| 133 |
+
f"- Validasi presensi: **{status_match}**\n"
|
| 134 |
+
f"- Model digunakan: **{model_choice}**"
|
| 135 |
)
|
| 136 |
chart = draw_detection_chart(detected)
|
| 137 |
+
pred_md = f"Label prediksi validasi: **{status_match}**"
|
| 138 |
+
return annotated, summary, chart, status_match, pred_md
|
| 139 |
except Exception as err:
|
| 140 |
summary = (
|
| 141 |
"### Ringkasan Hasil Pengolahan Citra\n"
|
|
|
|
| 152 |
(80, 80, 80),
|
| 153 |
2,
|
| 154 |
)
|
| 155 |
+
return image, summary, blank, "", "Label prediksi validasi: **-**"
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _safe_div(num: float, den: float) -> float:
|
| 159 |
+
return 0.0 if den == 0 else num / den
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def draw_confusion_matrix_from_state(cm_state: Dict[str, int]) -> np.ndarray:
|
| 163 |
+
tp = int(cm_state.get("tp", 0))
|
| 164 |
+
fp = int(cm_state.get("fp", 0))
|
| 165 |
+
fn = int(cm_state.get("fn", 0))
|
| 166 |
+
tn = int(cm_state.get("tn", 0))
|
| 167 |
+
cm = np.array([[tp, fn], [fp, tn]], dtype=int)
|
| 168 |
+
|
| 169 |
+
sns.set_style("white")
|
| 170 |
+
fig, ax = plt.subplots(figsize=(6.0, 4.6))
|
| 171 |
+
sns.heatmap(
|
| 172 |
+
cm,
|
| 173 |
+
annot=True,
|
| 174 |
+
fmt="d",
|
| 175 |
+
cmap="Blues",
|
| 176 |
+
cbar=True,
|
| 177 |
+
xticklabels=EVAL_CLASSES,
|
| 178 |
+
yticklabels=EVAL_CLASSES,
|
| 179 |
+
linewidths=0.5,
|
| 180 |
+
linecolor="white",
|
| 181 |
+
ax=ax,
|
| 182 |
+
)
|
| 183 |
+
ax.set_title("Confusion Matrix")
|
| 184 |
+
ax.set_xlabel("Prediksi")
|
| 185 |
+
ax.set_ylabel("Aktual")
|
| 186 |
+
plt.xticks(rotation=25, ha="right")
|
| 187 |
+
plt.yticks(rotation=0)
|
| 188 |
+
plt.tight_layout()
|
| 189 |
+
|
| 190 |
+
buf = io.BytesIO()
|
| 191 |
+
fig.savefig(buf, format="png", dpi=150)
|
| 192 |
+
plt.close(fig)
|
| 193 |
+
buf.seek(0)
|
| 194 |
+
data = np.frombuffer(buf.read(), dtype=np.uint8)
|
| 195 |
+
img_bgr = cv2.imdecode(data, cv2.IMREAD_COLOR)
|
| 196 |
+
return cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def render_metric_markdown(cm_state: Dict[str, int]) -> str:
|
| 200 |
+
tp = int(cm_state.get("tp", 0))
|
| 201 |
+
fp = int(cm_state.get("fp", 0))
|
| 202 |
+
fn = int(cm_state.get("fn", 0))
|
| 203 |
+
tn = int(cm_state.get("tn", 0))
|
| 204 |
+
acc = _safe_div(tp + tn, tp + fp + fn + tn)
|
| 205 |
+
prec = _safe_div(tp, tp + fp)
|
| 206 |
+
rec = _safe_div(tp, tp + fn)
|
| 207 |
+
f1 = _safe_div(2 * prec * rec, prec + rec)
|
| 208 |
+
return (
|
| 209 |
+
"### Evaluasi dan Rumus\n"
|
| 210 |
+
f"- Accuracy = (TP+TN)/(TP+FP+FN+TN) = ({tp}+{tn})/({tp+fp+fn+tn}) = **{acc:.4f}**\n"
|
| 211 |
+
f"- Precision = TP/(TP+FP) = {tp}/({tp+fp}) = **{prec:.4f}**\n"
|
| 212 |
+
f"- Recall = TP/(TP+FN) = {tp}/({tp+fn}) = **{rec:.4f}**\n"
|
| 213 |
+
f"- F1-Score = 2PR/(P+R) = **{f1:.4f}**"
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def update_evaluation(
|
| 218 |
+
cm_state: Dict[str, int], predicted_label: str, actual_label: str
|
| 219 |
+
) -> Tuple[Dict[str, int], np.ndarray, str, str]:
|
| 220 |
+
state = dict(cm_state or CM_INIT)
|
| 221 |
+
if predicted_label not in EVAL_CLASSES:
|
| 222 |
+
return (
|
| 223 |
+
state,
|
| 224 |
+
draw_confusion_matrix_from_state(state),
|
| 225 |
+
render_metric_markdown(state),
|
| 226 |
+
"Jalankan deteksi terlebih dahulu agar label prediksi tersedia.",
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
if actual_label == "Sesuai" and predicted_label == "Sesuai":
|
| 230 |
+
state["tp"] += 1
|
| 231 |
+
elif actual_label == "Sesuai" and predicted_label == "Tidak Sesuai":
|
| 232 |
+
state["fn"] += 1
|
| 233 |
+
elif actual_label == "Tidak Sesuai" and predicted_label == "Sesuai":
|
| 234 |
+
state["fp"] += 1
|
| 235 |
+
else:
|
| 236 |
+
state["tn"] += 1
|
| 237 |
+
|
| 238 |
+
return (
|
| 239 |
+
state,
|
| 240 |
+
draw_confusion_matrix_from_state(state),
|
| 241 |
+
render_metric_markdown(state),
|
| 242 |
+
"Confusion matrix berhasil diperbarui.",
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def reset_evaluation() -> Tuple[Dict[str, int], np.ndarray, str, str]:
|
| 247 |
+
state = dict(CM_INIT)
|
| 248 |
+
return (
|
| 249 |
+
state,
|
| 250 |
+
draw_confusion_matrix_from_state(state),
|
| 251 |
+
render_metric_markdown(state),
|
| 252 |
+
"Confusion matrix direset.",
|
| 253 |
+
)
|
| 254 |
|
| 255 |
|
| 256 |
def _iter_images(folder: Path) -> list[Path]:
|
|
|
|
| 270 |
|
| 271 |
|
| 272 |
def _write_pseudo_label(img_rgb: np.ndarray, label_path: Path, conf_threshold: float) -> int:
|
| 273 |
+
model = load_model("YOLOv8n")
|
| 274 |
h, w = img_rgb.shape[:2]
|
| 275 |
bgr = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)
|
| 276 |
result = model.predict(source=bgr, conf=conf_threshold, verbose=False)[0]
|
|
|
|
| 437 |
|
| 438 |
with gr.Column(elem_classes=["section-box"]):
|
| 439 |
gr.Markdown("## Tahap 1 - Akuisisi Data", elem_classes=["section-title"])
|
| 440 |
+
model_choice = gr.Dropdown(
|
| 441 |
+
choices=["YOLOv8n", "Best.pt"],
|
| 442 |
+
value="YOLOv8n",
|
| 443 |
+
label="Pilih Model",
|
| 444 |
+
)
|
| 445 |
with gr.Row():
|
| 446 |
image_input = gr.Image(
|
| 447 |
label="Input Gambar Kelas (Upload/Kamera)",
|
|
|
|
| 449 |
sources=["upload", "webcam"],
|
| 450 |
)
|
| 451 |
output_image = gr.Image(label="Output Tahap 2 - Hasil Deteksi YOLOv8", type="numpy")
|
| 452 |
+
attendance_input = gr.Number(
|
| 453 |
+
label="Input Jumlah Presensi (Untuk Testing Validasi)",
|
| 454 |
+
value=0,
|
| 455 |
+
precision=0,
|
| 456 |
+
minimum=0,
|
| 457 |
+
)
|
| 458 |
conf_input = gr.Slider(0.1, 1.0, value=0.25, step=0.05, label="Parameter Confidence (Deteksi)")
|
| 459 |
run_btn = gr.Button("Jalankan Deteksi dan Klasifikasi", variant="primary")
|
| 460 |
|
|
|
|
| 462 |
gr.Markdown("## Tahap 3 - Hasil Klasifikasi Kehadiran", elem_classes=["section-title"])
|
| 463 |
class_result_md = gr.Markdown("Ringkasan hasil klasifikasi akan tampil di sini.")
|
| 464 |
comparison_chart = gr.Image(label="Visualisasi Jumlah Person Terdeteksi", type="numpy")
|
| 465 |
+
predicted_label_md = gr.Markdown("Label prediksi validasi: **-**")
|
| 466 |
|
| 467 |
with gr.Column(elem_classes=["section-box"]):
|
| 468 |
+
gr.Markdown("## Tahap 4 - Evaluasi (Confusion Matrix + Rumus)", elem_classes=["section-title"])
|
| 469 |
+
cm_state = gr.State(dict(CM_INIT))
|
| 470 |
+
predicted_state = gr.State("")
|
| 471 |
+
actual_label = gr.Radio(
|
| 472 |
+
choices=EVAL_CLASSES,
|
| 473 |
+
value="Sesuai",
|
| 474 |
+
label="Label Aktual (untuk evaluasi/testing)",
|
| 475 |
+
)
|
| 476 |
+
with gr.Row():
|
| 477 |
+
update_eval_btn = gr.Button("Update Evaluasi", variant="secondary")
|
| 478 |
+
reset_eval_btn = gr.Button("Reset Evaluasi")
|
| 479 |
+
eval_status = gr.Markdown("Belum ada update evaluasi.")
|
| 480 |
+
cm_image = gr.Image(
|
| 481 |
+
label="Confusion Matrix",
|
| 482 |
+
value=draw_confusion_matrix_from_state(CM_INIT),
|
| 483 |
+
type="numpy",
|
| 484 |
+
interactive=False,
|
| 485 |
+
)
|
| 486 |
+
metric_md = gr.Markdown(render_metric_markdown(CM_INIT))
|
| 487 |
+
|
| 488 |
+
with gr.Column(elem_classes=["section-box"]):
|
| 489 |
+
with gr.Accordion("Tahap 5 - Pengembangan Model (Training)", open=False):
|
| 490 |
gr.Markdown(
|
| 491 |
"Training akan membaca dataset dari `dataset/train` dan `dataset/test`.\n"
|
| 492 |
"Jika label `.txt` belum ada, aktifkan pseudo-label agar proses tetap jalan."
|
|
|
|
| 512 |
|
| 513 |
run_btn.click(
|
| 514 |
fn=run_check_and_classify,
|
| 515 |
+
inputs=[image_input, conf_input, attendance_input, model_choice],
|
| 516 |
+
outputs=[output_image, class_result_md, comparison_chart, predicted_state, predicted_label_md],
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
update_eval_btn.click(
|
| 520 |
+
fn=update_evaluation,
|
| 521 |
+
inputs=[cm_state, predicted_state, actual_label],
|
| 522 |
+
outputs=[cm_state, cm_image, metric_md, eval_status],
|
| 523 |
+
)
|
| 524 |
+
reset_eval_btn.click(
|
| 525 |
+
fn=reset_evaluation,
|
| 526 |
+
inputs=[],
|
| 527 |
+
outputs=[cm_state, cm_image, metric_md, eval_status],
|
| 528 |
)
|
| 529 |
|
| 530 |
train_btn.click(
|
requirements.txt
CHANGED
|
@@ -4,3 +4,4 @@ opencv-python-headless>=4.10.0.84
|
|
| 4 |
huggingface_hub>=0.23.0
|
| 5 |
numpy>=1.26.0
|
| 6 |
matplotlib>=3.8.0
|
|
|
|
|
|
| 4 |
huggingface_hub>=0.23.0
|
| 5 |
numpy>=1.26.0
|
| 6 |
matplotlib>=3.8.0
|
| 7 |
+
seaborn>=0.13.0
|