firgiawann commited on
Commit
b066dd6
·
verified ·
1 Parent(s): 633942d

Background training with reconnect-safe status/log polling (update 18)

Browse files
Files changed (3) hide show
  1. CHANGELOG.md +6 -0
  2. README.md +2 -0
  3. app.py +222 -84
CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
  # Changelog
2
 
 
 
 
 
 
 
3
  ## Update ke-17 - 2026-04-15
4
  - Tambah `Advanced Options` pada inferensi: pilih gaya anotasi `Border + Label` atau `Label saja`.
5
  - Opsi anotasi berlaku untuk semua model (YOLOv8n, Best.pt, dan mode perbandingan).
 
1
  # Changelog
2
 
3
+ ## Update ke-18 - 2026-04-15
4
+ - Training diubah ke mode background process (`subprocess`) sehingga tetap berjalan di server walau koneksi client terputus.
5
+ - Ditambah monitor status training (`Status training`, `Refresh Status Training`) + polling otomatis tiap 2 detik saat UI terbuka.
6
+ - Saat reconnect, UI membaca `training_status.json` dan `training.log` sehingga progres terakhir tetap terlihat.
7
+ - Minor update dinaikkan ke-18.
8
+
9
  ## Update ke-17 - 2026-04-15
10
  - Tambah `Advanced Options` pada inferensi: pilih gaya anotasi `Border + Label` atau `Label saja`.
11
  - Opsi anotasi berlaku untuk semua model (YOLOv8n, Best.pt, dan mode perbandingan).
README.md CHANGED
@@ -46,6 +46,8 @@ Versi ini difokuskan untuk tahap awal:
46
  - **Menu Training** (accordion)
47
  - membaca dataset dari `dataset/train` dan `dataset/test`
48
  - 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
 
46
  - **Menu Training** (accordion)
47
  - membaca dataset dari `dataset/train` dan `dataset/test`
48
  - jika label `.txt` YOLO belum ada, bisa aktifkan pseudo-label
49
+ - training dijalankan di background process (server-side)
50
+ - progres bisa dipantau kembali setelah reconnect (status + log + grafik)
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
app.py CHANGED
@@ -5,6 +5,7 @@ import asyncio
5
  import fnmatch
6
  import time
7
  import csv
 
8
  import sys
9
  import subprocess
10
  from datetime import datetime
@@ -24,7 +25,7 @@ from ultralytics import YOLO
24
  CM_INIT = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
25
  EVAL_CLASSES = ["Sesuai", "Tidak Sesuai"]
26
  APP_VERSION = os.getenv("APP_VERSION", "v0.9.0")
27
- APP_MINOR_UPDATE = os.getenv("APP_MINOR_UPDATE", "17")
28
 
29
 
30
  # Gradio/Spaces can trigger noisy asyncio cleanup traces ("Invalid file descriptor: -1")
@@ -896,60 +897,205 @@ def start_repo_autosync(root: Path) -> str:
896
  )
897
 
898
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899
  def run_training(
900
  epochs: float,
901
  imgsz: float,
902
  batch: float,
903
  use_pseudo_if_missing: bool,
904
  pseudo_conf: float,
905
- ) -> Any:
906
- logs: list[str] = []
907
-
908
- def push(msg: str):
909
- ts = datetime.now().strftime("%H:%M:%S")
910
- logs.append(f"[{ts}] {msg}")
 
 
911
 
912
  try:
913
- push("Persiapan dataset training dimulai...")
914
- yield "\n".join(logs), None, _make_info_image("Training belum dimulai.")
915
-
916
- base_dir = Path(__file__).resolve().parent
917
  dataset_root = base_dir / "dataset"
918
  data_yaml, prep_info = _prepare_training_dataset(
919
  dataset_root=dataset_root,
920
  use_pseudo_if_missing=use_pseudo_if_missing,
921
  pseudo_conf=float(pseudo_conf),
922
  )
923
- push(prep_info)
924
 
925
  model_path = str(base_dir / "yolov8n.pt") if (base_dir / "yolov8n.pt").exists() else resolve_model_path("YOLOv8n")
926
  run_name = f"classroom_train_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
927
  project_dir = base_dir / "runs_train"
928
  save_dir = project_dir / run_name
929
  results_csv = save_dir / "results.csv"
930
- push(f"Training start: model={Path(model_path).name}, epochs={int(epochs)}, imgsz={int(imgsz)}, batch={int(batch)}")
931
- push(f"Run dir: {save_dir}")
932
- yield "\n".join(logs[-120:]), None, _make_info_image("Training berjalan...\nLog dan grafik akan diperbarui otomatis.")
 
933
 
934
  train_code = r"""
935
- import os
 
 
936
  from ultralytics import YOLO
937
-
938
- model = YOLO(os.environ["TRAIN_MODEL_PATH"])
939
- res = model.train(
940
- data=os.environ["TRAIN_DATA_YAML"],
941
- epochs=int(os.environ["TRAIN_EPOCHS"]),
942
- imgsz=int(os.environ["TRAIN_IMGSZ"]),
943
- batch=int(os.environ["TRAIN_BATCH"]),
944
- device="cpu",
945
- project=os.environ["TRAIN_PROJECT_DIR"],
946
- name=os.environ["TRAIN_RUN_NAME"],
947
- exist_ok=False,
948
- verbose=True,
949
- )
950
- print("TRAIN_SAVE_DIR=" + str(res.save_dir), flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
951
  """
952
  env = os.environ.copy()
 
953
  env["TRAIN_MODEL_PATH"] = str(model_path)
954
  env["TRAIN_DATA_YAML"] = str(data_yaml)
955
  env["TRAIN_EPOCHS"] = str(int(epochs))
@@ -957,63 +1103,42 @@ print("TRAIN_SAVE_DIR=" + str(res.save_dir), flush=True)
957
  env["TRAIN_BATCH"] = str(int(batch))
958
  env["TRAIN_PROJECT_DIR"] = str(project_dir)
959
  env["TRAIN_RUN_NAME"] = run_name
960
-
961
- proc = subprocess.Popen(
962
- [sys.executable, "-u", "-c", train_code],
963
- stdout=subprocess.PIPE,
964
- stderr=subprocess.STDOUT,
965
- text=True,
966
- encoding="utf-8",
967
- errors="replace",
968
- env=env,
969
- )
970
-
971
- last_seen_epoch = -1
972
- save_dir = save_dir
973
- if proc.stdout is not None:
974
- for raw_line in proc.stdout:
975
- line = raw_line.strip()
976
- if line:
977
- push(line)
978
- if line.startswith("TRAIN_SAVE_DIR="):
979
- save_dir = Path(line.split("=", 1)[1].strip())
980
- results_csv = save_dir / "results.csv"
981
- rows = _read_results_rows(results_csv)
982
- if rows:
983
- epoch_val = _to_float(rows[-1].get("epoch", ""))
984
- epoch_now = int(epoch_val) + 1 if epoch_val is not None else len(rows)
985
- if epoch_now > last_seen_epoch:
986
- last_seen_epoch = epoch_now
987
- push(f"Progress epoch: {epoch_now}/{int(epochs)}")
988
- yield "\n".join(logs[-250:]), None, plot_training_curves(results_csv)
989
-
990
- rc = proc.wait()
991
- if rc != 0:
992
- raise RuntimeError(
993
- f"Training process exit code {rc}. "
994
- "Lihat log terminal training untuk detail error."
995
  )
996
 
997
- best_pt = save_dir / "weights" / "best.pt"
998
- best_out = base_dir / "best.pt"
999
- hf_sync_msg = "HF sync dilewati: best.pt tidak ditemukan di output training."
1000
- if best_pt.exists():
1001
- shutil.copy2(best_pt, best_out)
1002
- load_model.cache_clear()
1003
- hf_sync_msg = sync_best_to_hf(best_out)
1004
-
1005
- final_chart = plot_training_curves(results_csv)
1006
- push("Training selesai.")
1007
- push(f"best.pt aktif: {best_out if best_out.exists() else best_pt}")
1008
- push(hf_sync_msg)
1009
- push("Lanjut inferensi: pilih model Best.pt atau mode perbandingan.")
1010
- yield "\n".join(logs[-250:]), str(best_out) if best_out.exists() else None, final_chart
1011
- return
1012
  except Exception as err:
1013
- yield f"Training gagal: {err}", None, _make_info_image(
1014
- "Training gagal.\nPeriksa struktur dataset/train, dataset/test, dan label."
 
 
 
 
 
 
1015
  )
1016
- return
1017
 
1018
 
1019
  CUSTOM_CSS = """
@@ -1152,6 +1277,8 @@ with gr.Blocks(title="Pengecekan dan Klasifikasi Mahasiswa - YOLOv8") as demo:
1152
  label="Confidence pseudo-label",
1153
  )
1154
  train_btn = gr.Button("Mulai Training", variant="primary")
 
 
1155
  train_log = gr.Textbox(label="Terminal Training (Live)", lines=14, interactive=False)
1156
  train_curve = gr.Image(
1157
  label="Grafik Training (Loss, Precision/Recall, mAP per Epoch)",
@@ -1185,7 +1312,18 @@ with gr.Blocks(title="Pengecekan dan Klasifikasi Mahasiswa - YOLOv8") as demo:
1185
  train_btn.click(
1186
  fn=run_training,
1187
  inputs=[train_epochs, train_imgsz, train_batch, use_pseudo, pseudo_conf],
1188
- outputs=[train_log, best_model_file, train_curve],
 
 
 
 
 
 
 
 
 
 
 
1189
  )
1190
 
1191
  gr.HTML(
 
5
  import fnmatch
6
  import time
7
  import csv
8
+ import json
9
  import sys
10
  import subprocess
11
  from datetime import datetime
 
25
  CM_INIT = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
26
  EVAL_CLASSES = ["Sesuai", "Tidak Sesuai"]
27
  APP_VERSION = os.getenv("APP_VERSION", "v0.9.0")
28
+ APP_MINOR_UPDATE = os.getenv("APP_MINOR_UPDATE", "18")
29
 
30
 
31
  # Gradio/Spaces can trigger noisy asyncio cleanup traces ("Invalid file descriptor: -1")
 
897
  )
898
 
899
 
900
+ def _train_paths(base_dir: Path) -> Dict[str, Path]:
901
+ return {
902
+ "status": base_dir / "training_status.json",
903
+ "log": base_dir / "training.log",
904
+ "best": base_dir / "best.pt",
905
+ }
906
+
907
+
908
+ def _write_status(path: Path, payload: Dict[str, Any]) -> None:
909
+ tmp = path.with_suffix(".tmp")
910
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
911
+ tmp.replace(path)
912
+
913
+
914
+ def _read_status(path: Path) -> Dict[str, Any]:
915
+ if not path.exists():
916
+ return {}
917
+ try:
918
+ return json.loads(path.read_text(encoding="utf-8"))
919
+ except Exception:
920
+ return {}
921
+
922
+
923
+ def _is_pid_running(pid: int) -> bool:
924
+ if pid <= 0:
925
+ return False
926
+ try:
927
+ os.kill(pid, 0)
928
+ return True
929
+ except Exception:
930
+ return False
931
+
932
+
933
+ def _tail_log(path: Path, max_chars: int = 12000) -> str:
934
+ if not path.exists():
935
+ return "Belum ada log training."
936
+ text = path.read_text(encoding="utf-8", errors="replace")
937
+ if len(text) <= max_chars:
938
+ return text
939
+ return text[-max_chars:]
940
+
941
+
942
+ def _training_status_md(state: Dict[str, Any], rows_count: int) -> str:
943
+ if not state:
944
+ return "Status training: **Idle**"
945
+ status = state.get("status", "unknown")
946
+ run_name = state.get("run_name", "-")
947
+ if status == "running":
948
+ return f"Status training: **Running** \nRun: `{run_name}` \nEpoch tercatat: **{rows_count}**"
949
+ if status == "done":
950
+ return f"Status training: **Selesai** \nRun: `{run_name}`"
951
+ if status == "failed":
952
+ err = state.get("error", "-")
953
+ return f"Status training: **Gagal** \nRun: `{run_name}` \nError: `{err}`"
954
+ return f"Status training: **{status}** \nRun: `{run_name}`"
955
+
956
+
957
+ def poll_training_status() -> Tuple[str, Any, np.ndarray, str]:
958
+ base_dir = Path(__file__).resolve().parent
959
+ paths = _train_paths(base_dir)
960
+ state = _read_status(paths["status"])
961
+ log_text = _tail_log(paths["log"])
962
+
963
+ results_csv = Path(state["results_csv"]) if state.get("results_csv") else Path("")
964
+ rows = _read_results_rows(results_csv) if results_csv.exists() else []
965
+ chart = plot_training_curves(results_csv) if results_csv.exists() else _make_info_image(
966
+ "Grafik training belum tersedia."
967
+ )
968
+
969
+ if state.get("status") == "running":
970
+ pid = int(state.get("pid", 0) or 0)
971
+ if not _is_pid_running(pid):
972
+ # Fallback jika proses selesai tapi status belum ter-update.
973
+ state["status"] = "done" if paths["best"].exists() else "failed"
974
+ if state["status"] == "failed" and not state.get("error"):
975
+ state["error"] = "Proses berhenti tanpa status akhir."
976
+ _write_status(paths["status"], state)
977
+
978
+ best_file = str(paths["best"]) if paths["best"].exists() else None
979
+ return log_text, best_file, chart, _training_status_md(state, len(rows))
980
+
981
+
982
  def run_training(
983
  epochs: float,
984
  imgsz: float,
985
  batch: float,
986
  use_pseudo_if_missing: bool,
987
  pseudo_conf: float,
988
+ ) -> Tuple[str, Any, np.ndarray, str]:
989
+ base_dir = Path(__file__).resolve().parent
990
+ paths = _train_paths(base_dir)
991
+ current = _read_status(paths["status"])
992
+ if current.get("status") == "running":
993
+ pid = int(current.get("pid", 0) or 0)
994
+ if _is_pid_running(pid):
995
+ return poll_training_status()
996
 
997
  try:
 
 
 
 
998
  dataset_root = base_dir / "dataset"
999
  data_yaml, prep_info = _prepare_training_dataset(
1000
  dataset_root=dataset_root,
1001
  use_pseudo_if_missing=use_pseudo_if_missing,
1002
  pseudo_conf=float(pseudo_conf),
1003
  )
 
1004
 
1005
  model_path = str(base_dir / "yolov8n.pt") if (base_dir / "yolov8n.pt").exists() else resolve_model_path("YOLOv8n")
1006
  run_name = f"classroom_train_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
1007
  project_dir = base_dir / "runs_train"
1008
  save_dir = project_dir / run_name
1009
  results_csv = save_dir / "results.csv"
1010
+
1011
+ with paths["log"].open("a", encoding="utf-8") as lf:
1012
+ lf.write(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Start training {run_name}\n")
1013
+ lf.write(f"{prep_info}\n")
1014
 
1015
  train_code = r"""
1016
+ import os, json, shutil
1017
+ from datetime import datetime
1018
+ from pathlib import Path
1019
  from ultralytics import YOLO
1020
+ from huggingface_hub import HfApi
1021
+
1022
+ def write_status(path, payload):
1023
+ p = Path(path)
1024
+ tmp = p.with_suffix(".tmp")
1025
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
1026
+ tmp.replace(p)
1027
+
1028
+ status_path = os.environ["TRAIN_STATUS_PATH"]
1029
+ base_dir = Path(os.environ["TRAIN_BASE_DIR"])
1030
+ run_name = os.environ["TRAIN_RUN_NAME"]
1031
+ save_dir = Path(os.environ["TRAIN_SAVE_DIR"])
1032
+ results_csv = save_dir / "results.csv"
1033
+
1034
+ state = {
1035
+ "status": "running",
1036
+ "run_name": run_name,
1037
+ "pid": os.getpid(),
1038
+ "save_dir": str(save_dir),
1039
+ "results_csv": str(results_csv),
1040
+ "started_at": datetime.now().isoformat(),
1041
+ }
1042
+ write_status(status_path, state)
1043
+
1044
+ try:
1045
+ model = YOLO(os.environ["TRAIN_MODEL_PATH"])
1046
+ res = model.train(
1047
+ data=os.environ["TRAIN_DATA_YAML"],
1048
+ epochs=int(os.environ["TRAIN_EPOCHS"]),
1049
+ imgsz=int(os.environ["TRAIN_IMGSZ"]),
1050
+ batch=int(os.environ["TRAIN_BATCH"]),
1051
+ device="cpu",
1052
+ project=os.environ["TRAIN_PROJECT_DIR"],
1053
+ name=run_name,
1054
+ exist_ok=False,
1055
+ verbose=True,
1056
+ )
1057
+ final_save = Path(str(res.save_dir))
1058
+ best_pt = final_save / "weights" / "best.pt"
1059
+ best_out = base_dir / "best.pt"
1060
+ hf_sync_msg = "HF sync dilewati: best.pt tidak ditemukan."
1061
+ if best_pt.exists():
1062
+ shutil.copy2(best_pt, best_out)
1063
+ hf_repo = os.getenv("HF_MODEL_REPO", "").strip()
1064
+ hf_file = os.getenv("HF_MODEL_FILE", "best.pt").strip() or "best.pt"
1065
+ hf_repo_type = os.getenv("HF_MODEL_REPO_TYPE", "space").strip() or "space"
1066
+ hf_token = os.getenv("HF_TOKEN", "").strip() or None
1067
+ if hf_repo:
1068
+ api = HfApi(token=hf_token)
1069
+ api.upload_file(
1070
+ path_or_fileobj=str(best_out),
1071
+ path_in_repo=hf_file,
1072
+ repo_id=hf_repo,
1073
+ repo_type=hf_repo_type,
1074
+ commit_message=f"Auto-update {hf_file} ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')})",
1075
+ )
1076
+ hf_sync_msg = f"HF sync sukses: {hf_repo} ({hf_repo_type}) -> {hf_file}"
1077
+
1078
+ state.update({
1079
+ "status": "done",
1080
+ "ended_at": datetime.now().isoformat(),
1081
+ "save_dir": str(final_save),
1082
+ "results_csv": str(final_save / "results.csv"),
1083
+ "best_path": str(best_out if best_out.exists() else best_pt),
1084
+ "hf_sync_msg": hf_sync_msg,
1085
+ })
1086
+ write_status(status_path, state)
1087
+ print("TRAIN_DONE", flush=True)
1088
+ except Exception as e:
1089
+ state.update({
1090
+ "status": "failed",
1091
+ "ended_at": datetime.now().isoformat(),
1092
+ "error": str(e),
1093
+ })
1094
+ write_status(status_path, state)
1095
+ print("TRAIN_FAILED: " + str(e), flush=True)
1096
  """
1097
  env = os.environ.copy()
1098
+ env["TRAIN_BASE_DIR"] = str(base_dir)
1099
  env["TRAIN_MODEL_PATH"] = str(model_path)
1100
  env["TRAIN_DATA_YAML"] = str(data_yaml)
1101
  env["TRAIN_EPOCHS"] = str(int(epochs))
 
1103
  env["TRAIN_BATCH"] = str(int(batch))
1104
  env["TRAIN_PROJECT_DIR"] = str(project_dir)
1105
  env["TRAIN_RUN_NAME"] = run_name
1106
+ env["TRAIN_SAVE_DIR"] = str(save_dir)
1107
+ env["TRAIN_STATUS_PATH"] = str(paths["status"])
1108
+
1109
+ with paths["log"].open("a", encoding="utf-8") as lf:
1110
+ proc = subprocess.Popen(
1111
+ [sys.executable, "-u", "-c", train_code],
1112
+ stdout=lf,
1113
+ stderr=subprocess.STDOUT,
1114
+ cwd=str(base_dir),
1115
+ env=env,
1116
+ start_new_session=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1117
  )
1118
 
1119
+ _write_status(
1120
+ paths["status"],
1121
+ {
1122
+ "status": "running",
1123
+ "run_name": run_name,
1124
+ "pid": proc.pid,
1125
+ "save_dir": str(save_dir),
1126
+ "results_csv": str(results_csv),
1127
+ "started_at": datetime.now().isoformat(),
1128
+ },
1129
+ )
1130
+ return poll_training_status()
 
 
 
1131
  except Exception as err:
1132
+ _write_status(
1133
+ paths["status"],
1134
+ {
1135
+ "status": "failed",
1136
+ "run_name": "-",
1137
+ "error": str(err),
1138
+ "ended_at": datetime.now().isoformat(),
1139
+ },
1140
  )
1141
+ return poll_training_status()
1142
 
1143
 
1144
  CUSTOM_CSS = """
 
1277
  label="Confidence pseudo-label",
1278
  )
1279
  train_btn = gr.Button("Mulai Training", variant="primary")
1280
+ refresh_train_btn = gr.Button("Refresh Status Training")
1281
+ train_status_md = gr.Markdown("Status training: **Idle**")
1282
  train_log = gr.Textbox(label="Terminal Training (Live)", lines=14, interactive=False)
1283
  train_curve = gr.Image(
1284
  label="Grafik Training (Loss, Precision/Recall, mAP per Epoch)",
 
1312
  train_btn.click(
1313
  fn=run_training,
1314
  inputs=[train_epochs, train_imgsz, train_batch, use_pseudo, pseudo_conf],
1315
+ outputs=[train_log, best_model_file, train_curve, train_status_md],
1316
+ )
1317
+ refresh_train_btn.click(
1318
+ fn=poll_training_status,
1319
+ inputs=[],
1320
+ outputs=[train_log, best_model_file, train_curve, train_status_md],
1321
+ )
1322
+ demo.load(
1323
+ fn=poll_training_status,
1324
+ inputs=[],
1325
+ outputs=[train_log, best_model_file, train_curve, train_status_md],
1326
+ every=2,
1327
  )
1328
 
1329
  gr.HTML(