firgiawann commited on
Commit
bde5ebe
·
verified ·
1 Parent(s): 183f29b

Update 39 show latest training artifacts from artifact repo

Browse files
Files changed (3) hide show
  1. CHANGELOG.md +6 -0
  2. README.md +3 -0
  3. app.py +108 -18
CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
  # Changelog
2
 
 
 
 
 
 
 
3
  ## Update ke-38 - 2026-05-02
4
  - Cegah Space melakukan commit runtime ke repo Space yang sama secara default.
5
  - Tambah guard `HF_ALLOW_SPACE_RUNTIME_COMMITS` untuk menghindari rebuild otomatis yang menyebabkan HTTP 503 setelah training.
 
1
  # Changelog
2
 
3
+ ## Update ke-39 - 2026-05-02
4
+ - Tambah repo artefak training terpisah melalui `HF_ARTIFACT_REPO`.
5
+ - Panel training sekarang mengambil ulang grafik, confusion matrix, `results.csv`, log, dan summary terakhir dari repo artefak saat Space rebuild.
6
+ - Sync artefak training diarahkan ke repo artefak jika tersedia, sehingga data terakhir tetap tampil tanpa memicu rebuild Space yang sama.
7
+ - Minor update dinaikkan ke-39.
8
+
9
  ## Update ke-38 - 2026-05-02
10
  - Cegah Space melakukan commit runtime ke repo Space yang sama secara default.
11
  - Tambah guard `HF_ALLOW_SPACE_RUNTIME_COMMITS` untuk menghindari rebuild otomatis yang menyebabkan HTTP 503 setelah training.
README.md CHANGED
@@ -104,6 +104,8 @@ Opsional environment variable:
104
  - `HF_TOKEN` - token untuk upload otomatis saat training selesai
105
  - `HF_DETECTION_DIR` - folder khusus di repo HF untuk auto-save hasil deteksi (default: `space_detection_archive`)
106
  - `HF_TRAINING_DIR` - folder khusus di repo HF untuk auto-save artefak training (default: `space_training_archive`)
 
 
107
  - `HF_AUTOSYNC_ENABLED` - aktif/nonaktif auto-sync file repo (`true/false`)
108
  - `HF_AUTOSYNC_LOCAL_ONLY` - default `true`, artinya autosync hanya jalan dari lokal
109
  - `HF_AUTOSYNC_REALTIME` - default `false`; jika `true` baru watcher realtime aktif
@@ -132,6 +134,7 @@ Catatan auto-save hasil training:
132
  - Proses training juga langsung menyalin grafik YOLO `results.png` menjadi PNG permanen saat training selesai, sehingga tidak bergantung pada refresh browser.
133
  - Jika koneksi browser terputus saat training, artefak tetap aman setelah proses training selesai dan sync ke repo berhasil. Jika container berhenti sebelum training selesai, artefak final memang belum sempat dibuat.
134
  - Pseudo-label dari dataset tanpa label `.txt` dapat memakan waktu di CPU Space karena semua gambar harus diproses YOLOv8n sebelum epoch dimulai.
 
135
 
136
  Catatan auto-sync update file repo:
137
  - Default `HF_AUTOSYNC_ENABLED=false`, jadi tidak ada sync repo saat startup/runtime.
 
104
  - `HF_TOKEN` - token untuk upload otomatis saat training selesai
105
  - `HF_DETECTION_DIR` - folder khusus di repo HF untuk auto-save hasil deteksi (default: `space_detection_archive`)
106
  - `HF_TRAINING_DIR` - folder khusus di repo HF untuk auto-save artefak training (default: `space_training_archive`)
107
+ - `HF_ARTIFACT_REPO` - repo dataset/model terpisah untuk menyimpan dan menampilkan ulang artefak training terakhir (contoh: `KLP2-PCD/KLP2-training-artifacts`)
108
+ - `HF_ARTIFACT_REPO_TYPE` - tipe repo artefak, default `dataset`
109
  - `HF_AUTOSYNC_ENABLED` - aktif/nonaktif auto-sync file repo (`true/false`)
110
  - `HF_AUTOSYNC_LOCAL_ONLY` - default `true`, artinya autosync hanya jalan dari lokal
111
  - `HF_AUTOSYNC_REALTIME` - default `false`; jika `true` baru watcher realtime aktif
 
134
  - Proses training juga langsung menyalin grafik YOLO `results.png` menjadi PNG permanen saat training selesai, sehingga tidak bergantung pada refresh browser.
135
  - Jika koneksi browser terputus saat training, artefak tetap aman setelah proses training selesai dan sync ke repo berhasil. Jika container berhenti sebelum training selesai, artefak final memang belum sempat dibuat.
136
  - Pseudo-label dari dataset tanpa label `.txt` dapat memakan waktu di CPU Space karena semua gambar harus diproses YOLOv8n sebelum epoch dimulai.
137
+ - Panel training akan mengambil ulang data terakhir dari `HF_ARTIFACT_REPO` saat Space rebuild, sehingga metrik dan grafik terakhir tetap tampil di UI.
138
 
139
  Catatan auto-sync update file repo:
140
  - Default `HF_AUTOSYNC_ENABLED=false`, jadi tidak ada sync repo saat startup/runtime.
app.py CHANGED
@@ -24,7 +24,7 @@ from ultralytics import YOLO
24
  CM_INIT = {"tp": 0, "fp": 0, "fn": 0, "tn": 0, "person": 0, "not_person": 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", "38")
28
 
29
 
30
  # Gradio/Spaces can trigger noisy asyncio cleanup traces ("Invalid file descriptor: -1")
@@ -1220,17 +1220,18 @@ def save_training_summary(paths: Dict[str, Path], state: Dict[str, Any], rows_co
1220
  return str(paths["summary"])
1221
 
1222
 
1223
- def sync_training_artifacts_to_hf(
1224
  run_name: str,
1225
  results_csv: Path | None,
1226
  log_file: Path | None,
1227
  chart_file: Path | None,
1228
  confusion_matrix_file: Path | None,
1229
  summary_file: Path | None,
1230
- ) -> str:
1231
- hf_repo = os.getenv("HF_MODEL_REPO", "").strip()
1232
- hf_repo_type = os.getenv("HF_MODEL_REPO_TYPE", "space").strip() or "space"
1233
- hf_token = os.getenv("HF_TOKEN", "").strip() or None
 
1234
  repo_dir = os.getenv("HF_TRAINING_DIR", "space_training_archive").strip().strip("/")
1235
  run_name = run_name or datetime.now().strftime("training_%Y%m%d_%H%M%S")
1236
 
@@ -1565,14 +1566,97 @@ def _tail_log(path: Path, max_chars: int = 12000) -> str:
1565
  return text[-max_chars:]
1566
 
1567
 
1568
- def _safe_results_csv_path(state: Dict[str, Any]) -> Path | None:
1569
- raw = (state.get("results_csv") or "").strip() if isinstance(state, dict) else ""
1570
- if not raw:
1571
- return None
1572
- p = Path(raw)
1573
- if p.exists() and p.is_file():
1574
- return p
1575
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1576
 
1577
 
1578
  def _training_status_md(state: Dict[str, Any], rows_count: int) -> str:
@@ -1600,10 +1684,16 @@ def _training_status_md(state: Dict[str, Any], rows_count: int) -> str:
1600
 
1601
  def poll_training_status() -> Tuple[str, Any, Any, Any, Any, np.ndarray, Any, np.ndarray, str, str]:
1602
  try:
1603
- base_dir = Path(__file__).resolve().parent
1604
- paths = _train_paths(base_dir)
1605
- state = _read_status(paths["status"])
1606
- log_text = _tail_log(paths["log"])
 
 
 
 
 
 
1607
 
1608
  results_csv = _safe_results_csv_path(state)
1609
  rows = _read_results_rows(results_csv) if results_csv is not None else []
 
24
  CM_INIT = {"tp": 0, "fp": 0, "fn": 0, "tn": 0, "person": 0, "not_person": 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", "39")
28
 
29
 
30
  # Gradio/Spaces can trigger noisy asyncio cleanup traces ("Invalid file descriptor: -1")
 
1220
  return str(paths["summary"])
1221
 
1222
 
1223
+ def sync_training_artifacts_to_hf(
1224
  run_name: str,
1225
  results_csv: Path | None,
1226
  log_file: Path | None,
1227
  chart_file: Path | None,
1228
  confusion_matrix_file: Path | None,
1229
  summary_file: Path | None,
1230
+ ) -> str:
1231
+ artifact_repo, artifact_repo_type, artifact_token = _artifact_repo_config()
1232
+ hf_repo = artifact_repo or os.getenv("HF_MODEL_REPO", "").strip()
1233
+ hf_repo_type = artifact_repo_type if artifact_repo else (os.getenv("HF_MODEL_REPO_TYPE", "space").strip() or "space")
1234
+ hf_token = artifact_token
1235
  repo_dir = os.getenv("HF_TRAINING_DIR", "space_training_archive").strip().strip("/")
1236
  run_name = run_name or datetime.now().strftime("training_%Y%m%d_%H%M%S")
1237
 
 
1566
  return text[-max_chars:]
1567
 
1568
 
1569
+ def _safe_results_csv_path(state: Dict[str, Any]) -> Path | None:
1570
+ raw = (state.get("results_csv") or "").strip() if isinstance(state, dict) else ""
1571
+ if not raw:
1572
+ return None
1573
+ p = Path(raw)
1574
+ if p.exists() and p.is_file():
1575
+ return p
1576
+ return None
1577
+
1578
+
1579
+ def _artifact_repo_config() -> Tuple[str, str, str | None]:
1580
+ repo = (
1581
+ os.getenv("HF_ARTIFACT_REPO", "").strip()
1582
+ or os.getenv("HF_TRAINING_ARTIFACT_REPO", "").strip()
1583
+ )
1584
+ repo_type = os.getenv("HF_ARTIFACT_REPO_TYPE", "dataset").strip() or "dataset"
1585
+ token = os.getenv("HF_TOKEN", "").strip() or None
1586
+ return repo, repo_type, token
1587
+
1588
+
1589
+ def _download_hf_file(
1590
+ repo_id: str,
1591
+ repo_type: str,
1592
+ token: str | None,
1593
+ filename: str,
1594
+ destination: Path,
1595
+ ) -> bool:
1596
+ try:
1597
+ downloaded = hf_hub_download(
1598
+ repo_id=repo_id,
1599
+ repo_type=repo_type,
1600
+ filename=filename,
1601
+ token=token,
1602
+ )
1603
+ destination.parent.mkdir(parents=True, exist_ok=True)
1604
+ shutil.copy2(downloaded, destination)
1605
+ return True
1606
+ except Exception:
1607
+ return False
1608
+
1609
+
1610
+ def hydrate_latest_training_artifacts(paths: Dict[str, Path]) -> Dict[str, Any]:
1611
+ repo_id, repo_type, token = _artifact_repo_config()
1612
+ if not repo_id:
1613
+ return {}
1614
+
1615
+ artifact_dir = paths["artifact_dir"]
1616
+ latest_results = artifact_dir / "results_latest.csv"
1617
+ latest_log = artifact_dir / "training_latest.log"
1618
+
1619
+ _download_hf_file(
1620
+ repo_id,
1621
+ repo_type,
1622
+ token,
1623
+ "training_outputs/training_curve_latest.png",
1624
+ paths["chart"],
1625
+ )
1626
+ _download_hf_file(
1627
+ repo_id,
1628
+ repo_type,
1629
+ token,
1630
+ "training_outputs/confusion_matrix_latest.png",
1631
+ paths["train_cm"],
1632
+ )
1633
+ if paths["summary"].exists() is False:
1634
+ _download_hf_file(
1635
+ repo_id,
1636
+ repo_type,
1637
+ token,
1638
+ "training_outputs/training_summary_latest.json",
1639
+ paths["summary"],
1640
+ )
1641
+
1642
+ state = _read_status(paths["summary"])
1643
+ run_name = str(state.get("run_name", "")).strip()
1644
+ if run_name and run_name != "-":
1645
+ base = f"space_training_archive/{run_name}"
1646
+ _download_hf_file(repo_id, repo_type, token, f"{base}/results.csv", latest_results)
1647
+ _download_hf_file(repo_id, repo_type, token, f"{base}/training.log", latest_log)
1648
+
1649
+ if latest_results.exists() and latest_results.is_file():
1650
+ state["results_csv"] = str(latest_results)
1651
+ if state.get("status") in {"running", "", None}:
1652
+ state["status"] = "done"
1653
+ state["stage"] = "latest_artifact"
1654
+ if latest_log.exists() and latest_log.is_file() and not paths["log"].exists():
1655
+ shutil.copy2(latest_log, paths["log"])
1656
+ if state:
1657
+ state["artifacts_sync_msg"] = f"Ditampilkan dari repo artefak: {repo_id}"
1658
+ _write_status(paths["status"], state)
1659
+ return state
1660
 
1661
 
1662
  def _training_status_md(state: Dict[str, Any], rows_count: int) -> str:
 
1684
 
1685
  def poll_training_status() -> Tuple[str, Any, Any, Any, Any, np.ndarray, Any, np.ndarray, str, str]:
1686
  try:
1687
+ base_dir = Path(__file__).resolve().parent
1688
+ paths = _train_paths(base_dir)
1689
+ state = _read_status(paths["status"])
1690
+ if not state and (
1691
+ not paths["chart"].exists()
1692
+ or not paths["train_cm"].exists()
1693
+ or not paths["summary"].exists()
1694
+ ):
1695
+ state = hydrate_latest_training_artifacts(paths)
1696
+ log_text = _tail_log(paths["log"])
1697
 
1698
  results_csv = _safe_results_csv_path(state)
1699
  rows = _read_results_rows(results_csv) if results_csv is not None else []