Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
ArchNemix Controller Space v1.
|
| 3 |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
Orchestrates 12 backend HuggingFace Spaces in a staged pipeline:
|
| 5 |
|
|
@@ -149,7 +149,7 @@ class VideoSubmitRequest(BaseModel):
|
|
| 149 |
|
| 150 |
app = FastAPI(
|
| 151 |
title="ArchNemix Controller v1",
|
| 152 |
-
version="1.
|
| 153 |
docs_url="/docs",
|
| 154 |
redoc_url=None,
|
| 155 |
)
|
|
@@ -182,11 +182,10 @@ def store() -> DatasetStore:
|
|
| 182 |
return _store
|
| 183 |
|
| 184 |
# =============================================================================
|
| 185 |
-
# SAFE JSON HELPER
|
| 186 |
# =============================================================================
|
| 187 |
|
| 188 |
def _safe_json(r: httpx.Response) -> Any:
|
| 189 |
-
"""Parse response JSON safely. Returns a dict with error info if body is empty or invalid JSON."""
|
| 190 |
try:
|
| 191 |
return r.json()
|
| 192 |
except Exception:
|
|
@@ -281,7 +280,7 @@ def _status_summary() -> Dict[str, Any]:
|
|
| 281 |
"spaces": spaces,
|
| 282 |
}
|
| 283 |
|
| 284 |
-
aligner_free
|
| 285 |
aligner_total = out["mfa"]["total"] + out["qwen"]["total"]
|
| 286 |
out["aligners"] = {
|
| 287 |
"free": aligner_free,
|
|
@@ -295,53 +294,40 @@ def _status_summary() -> Dict[str, Any]:
|
|
| 295 |
# =============================================================================
|
| 296 |
|
| 297 |
async def _pick(stype: str) -> Optional[str]:
|
| 298 |
-
"""Pick the space with the fewest running+queued jobs."""
|
| 299 |
urls = ALL_SPACES[stype]
|
| 300 |
-
|
| 301 |
-
# First check cache for quick answer
|
| 302 |
-
best_url = None
|
| 303 |
best_load = float('inf')
|
| 304 |
-
|
| 305 |
for url in urls:
|
| 306 |
c = status_cache.get(url, {})
|
| 307 |
if not c.get("online") or not c.get("worker_ready", True):
|
| 308 |
continue
|
| 309 |
-
|
| 310 |
if stype == "ffmpeg":
|
| 311 |
-
|
| 312 |
-
running = c.get("running", 1)
|
| 313 |
-
waiting = c.get("waiting", 1)
|
| 314 |
-
load = running + waiting
|
| 315 |
else:
|
| 316 |
-
# MFA/Qwen use can_submit (True = no running, no queued)
|
| 317 |
-
# Convert to load: 0 if can_submit, else at least 1
|
| 318 |
load = 0 if c.get("can_submit") else 1
|
| 319 |
-
|
| 320 |
if load < best_load:
|
| 321 |
best_load = load
|
| 322 |
-
best_url
|
| 323 |
-
|
| 324 |
if best_url:
|
| 325 |
return best_url
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
best_url = None
|
| 330 |
best_load = float('inf')
|
| 331 |
-
|
| 332 |
for r in results:
|
| 333 |
if not isinstance(r, dict) or not r.get("online") or not r.get("worker_ready", True):
|
| 334 |
continue
|
| 335 |
-
|
| 336 |
if stype == "ffmpeg":
|
| 337 |
load = r.get("running", 1) + r.get("waiting", 1)
|
| 338 |
else:
|
| 339 |
load = 0 if r.get("can_submit") else 1
|
| 340 |
-
|
| 341 |
if load < best_load:
|
| 342 |
best_load = load
|
| 343 |
-
best_url
|
| 344 |
-
|
| 345 |
return best_url
|
| 346 |
|
| 347 |
|
|
@@ -362,6 +348,9 @@ def _new_pipeline(config: PipelineStartRequest) -> Dict[str, Any]:
|
|
| 362 |
"pipeline_id": pid,
|
| 363 |
"created_at": datetime.utcnow().isoformat(),
|
| 364 |
"last_active": datetime.utcnow().isoformat(),
|
|
|
|
|
|
|
|
|
|
| 365 |
"config": {
|
| 366 |
"text": config.text,
|
| 367 |
"voice": config.voice,
|
|
@@ -465,12 +454,12 @@ async def _poll_backend_stage(p: Dict, stage: str) -> None:
|
|
| 465 |
s["completed_at"] = datetime.utcnow().isoformat()
|
| 466 |
|
| 467 |
elif bk_status in ("running", "queued", "processing"):
|
| 468 |
-
s["progress"] = data.get("progress",
|
| 469 |
-
s["chunks_done"] = data.get("chunks_done",
|
| 470 |
-
s["chunks_total"] = data.get("chunks_total",
|
| 471 |
-
s["elapsed_s"] = data.get("elapsed_s",
|
| 472 |
s["estimated_remaining_s"] = data.get("estimated_remaining_s", s.get("estimated_remaining_s"))
|
| 473 |
-
s["message"] = data.get("message",
|
| 474 |
if "encode_stats" in data:
|
| 475 |
s["encode_stats"] = data["encode_stats"]
|
| 476 |
|
|
@@ -595,7 +584,6 @@ async def _submit_align(
|
|
| 595 |
"detail": "TTS stage has not completed yet. Complete TTS first.",
|
| 596 |
})
|
| 597 |
|
| 598 |
-
# Fetch audio β include HF token if URL is on huggingface.co
|
| 599 |
try:
|
| 600 |
headers = {}
|
| 601 |
if HF_TOKEN and "huggingface.co" in audio_url:
|
|
@@ -661,7 +649,6 @@ async def _submit_align(
|
|
| 661 |
"retry_after": 20,
|
| 662 |
})
|
| 663 |
if r.status_code != 200:
|
| 664 |
-
# FIXED: use _safe_json so empty body from Rust panic doesn't crash controller
|
| 665 |
raise HTTPException(r.status_code, _safe_json(r))
|
| 666 |
|
| 667 |
data = r.json()
|
|
@@ -676,7 +663,6 @@ async def _submit_align(
|
|
| 676 |
s["error"] = None
|
| 677 |
|
| 678 |
logger.info(f"Pipeline {pid[:8]}: Alignment submitted to {backend_type.upper()} ({backend_url})")
|
| 679 |
-
|
| 680 |
return backend_type
|
| 681 |
|
| 682 |
|
|
@@ -779,6 +765,7 @@ def _pipeline_view(p: Dict) -> Dict:
|
|
| 779 |
return {
|
| 780 |
"pipeline_id": p["pipeline_id"],
|
| 781 |
"created_at": p["created_at"],
|
|
|
|
| 782 |
"stages": stages,
|
| 783 |
"assets": {
|
| 784 |
"audio_url": p["assets"]["audio_url"],
|
|
@@ -830,7 +817,7 @@ async def _cleanup_loop():
|
|
| 830 |
pipelines.pop(pid, None)
|
| 831 |
pipeline_heartbeats.pop(pid, None)
|
| 832 |
if expired:
|
| 833 |
-
logger.info(f"Purged {len(expired)} expired pipelines.")
|
| 834 |
|
| 835 |
# =============================================================================
|
| 836 |
# STARTUP / SHUTDOWN
|
|
@@ -856,7 +843,7 @@ async def startup():
|
|
| 856 |
asyncio.create_task(_status_loop())
|
| 857 |
asyncio.create_task(_cleanup_loop())
|
| 858 |
asyncio.create_task(_frontend_heartbeat_watchdog())
|
| 859 |
-
logger.info("ArchNemix Controller v1.
|
| 860 |
|
| 861 |
|
| 862 |
async def _frontend_heartbeat_watchdog():
|
|
@@ -865,14 +852,22 @@ async def _frontend_heartbeat_watchdog():
|
|
| 865 |
now = datetime.utcnow()
|
| 866 |
|
| 867 |
for pid, p in list(pipelines.items()):
|
| 868 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 869 |
if last_hb is None:
|
| 870 |
last_hb = datetime.fromisoformat(p["created_at"])
|
| 871 |
|
| 872 |
silence = (now - last_hb).total_seconds()
|
| 873 |
|
|
|
|
| 874 |
if silence >= FRONTEND_HEARTBEAT_GRACE + 200:
|
| 875 |
-
logger.warning(f"Pipeline {pid[:8]} silent {silence:.0f}s β
|
| 876 |
try:
|
| 877 |
await store().delete_pipeline(pid)
|
| 878 |
except Exception as e:
|
|
@@ -881,6 +876,7 @@ async def _frontend_heartbeat_watchdog():
|
|
| 881 |
pipeline_heartbeats.pop(pid, None)
|
| 882 |
continue
|
| 883 |
|
|
|
|
| 884 |
elif silence >= FRONTEND_HEARTBEAT_GRACE:
|
| 885 |
running_stage = next(
|
| 886 |
(name for name, s in p["stages"].items() if s["status"] == StageStatus.RUNNING),
|
|
@@ -923,17 +919,18 @@ async def shutdown():
|
|
| 923 |
async def root():
|
| 924 |
return {
|
| 925 |
"name": "ArchNemix Controller",
|
| 926 |
-
"version": "1.
|
| 927 |
"endpoints": {
|
| 928 |
-
"POST /pipeline/start":
|
| 929 |
-
"GET /pipeline/{id}":
|
| 930 |
-
"POST /pipeline/{id}/rerun/tts":
|
| 931 |
-
"POST /pipeline/{id}/align":
|
| 932 |
-
"POST /pipeline/{id}/rerun/align":
|
| 933 |
-
"POST /pipeline/{id}/video":
|
| 934 |
-
"POST /pipeline/{id}/rerun/video":
|
| 935 |
-
"
|
| 936 |
-
"GET /
|
|
|
|
| 937 |
},
|
| 938 |
}
|
| 939 |
|
|
@@ -1117,6 +1114,54 @@ async def rerun_video(pipeline_id: str, req: VideoSubmitRequest):
|
|
| 1117 |
})
|
| 1118 |
|
| 1119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1120 |
@app.get("/download/{pipeline_id}")
|
| 1121 |
async def download_video(pipeline_id: str):
|
| 1122 |
p = _pipeline_or_404(pipeline_id)
|
|
|
|
| 1 |
"""
|
| 2 |
+
ArchNemix Controller Space v1.1
|
| 3 |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
Orchestrates 12 backend HuggingFace Spaces in a staged pipeline:
|
| 5 |
|
|
|
|
| 149 |
|
| 150 |
app = FastAPI(
|
| 151 |
title="ArchNemix Controller v1",
|
| 152 |
+
version="1.1.0",
|
| 153 |
docs_url="/docs",
|
| 154 |
redoc_url=None,
|
| 155 |
)
|
|
|
|
| 182 |
return _store
|
| 183 |
|
| 184 |
# =============================================================================
|
| 185 |
+
# SAFE JSON HELPER
|
| 186 |
# =============================================================================
|
| 187 |
|
| 188 |
def _safe_json(r: httpx.Response) -> Any:
|
|
|
|
| 189 |
try:
|
| 190 |
return r.json()
|
| 191 |
except Exception:
|
|
|
|
| 280 |
"spaces": spaces,
|
| 281 |
}
|
| 282 |
|
| 283 |
+
aligner_free = out["mfa"]["free"] + out["qwen"]["free"]
|
| 284 |
aligner_total = out["mfa"]["total"] + out["qwen"]["total"]
|
| 285 |
out["aligners"] = {
|
| 286 |
"free": aligner_free,
|
|
|
|
| 294 |
# =============================================================================
|
| 295 |
|
| 296 |
async def _pick(stype: str) -> Optional[str]:
|
|
|
|
| 297 |
urls = ALL_SPACES[stype]
|
| 298 |
+
best_url = None
|
|
|
|
|
|
|
| 299 |
best_load = float('inf')
|
| 300 |
+
|
| 301 |
for url in urls:
|
| 302 |
c = status_cache.get(url, {})
|
| 303 |
if not c.get("online") or not c.get("worker_ready", True):
|
| 304 |
continue
|
|
|
|
| 305 |
if stype == "ffmpeg":
|
| 306 |
+
load = c.get("running", 1) + c.get("waiting", 1)
|
|
|
|
|
|
|
|
|
|
| 307 |
else:
|
|
|
|
|
|
|
| 308 |
load = 0 if c.get("can_submit") else 1
|
|
|
|
| 309 |
if load < best_load:
|
| 310 |
best_load = load
|
| 311 |
+
best_url = url
|
| 312 |
+
|
| 313 |
if best_url:
|
| 314 |
return best_url
|
| 315 |
+
|
| 316 |
+
results = await asyncio.gather(*[_check_one(url, stype) for url in urls])
|
| 317 |
+
best_url = None
|
|
|
|
| 318 |
best_load = float('inf')
|
| 319 |
+
|
| 320 |
for r in results:
|
| 321 |
if not isinstance(r, dict) or not r.get("online") or not r.get("worker_ready", True):
|
| 322 |
continue
|
|
|
|
| 323 |
if stype == "ffmpeg":
|
| 324 |
load = r.get("running", 1) + r.get("waiting", 1)
|
| 325 |
else:
|
| 326 |
load = 0 if r.get("can_submit") else 1
|
|
|
|
| 327 |
if load < best_load:
|
| 328 |
best_load = load
|
| 329 |
+
best_url = r["url"]
|
| 330 |
+
|
| 331 |
return best_url
|
| 332 |
|
| 333 |
|
|
|
|
| 348 |
"pipeline_id": pid,
|
| 349 |
"created_at": datetime.utcnow().isoformat(),
|
| 350 |
"last_active": datetime.utcnow().isoformat(),
|
| 351 |
+
# finalized = True means the client acknowledged receipt of the
|
| 352 |
+
# finished video. The watchdog must never touch a finalized pipeline.
|
| 353 |
+
"finalized": False,
|
| 354 |
"config": {
|
| 355 |
"text": config.text,
|
| 356 |
"voice": config.voice,
|
|
|
|
| 454 |
s["completed_at"] = datetime.utcnow().isoformat()
|
| 455 |
|
| 456 |
elif bk_status in ("running", "queued", "processing"):
|
| 457 |
+
s["progress"] = data.get("progress", s.get("progress", 0))
|
| 458 |
+
s["chunks_done"] = data.get("chunks_done", s.get("chunks_done", 0))
|
| 459 |
+
s["chunks_total"] = data.get("chunks_total", s.get("chunks_total", 0))
|
| 460 |
+
s["elapsed_s"] = data.get("elapsed_s", s.get("elapsed_s"))
|
| 461 |
s["estimated_remaining_s"] = data.get("estimated_remaining_s", s.get("estimated_remaining_s"))
|
| 462 |
+
s["message"] = data.get("message", s.get("message", ""))
|
| 463 |
if "encode_stats" in data:
|
| 464 |
s["encode_stats"] = data["encode_stats"]
|
| 465 |
|
|
|
|
| 584 |
"detail": "TTS stage has not completed yet. Complete TTS first.",
|
| 585 |
})
|
| 586 |
|
|
|
|
| 587 |
try:
|
| 588 |
headers = {}
|
| 589 |
if HF_TOKEN and "huggingface.co" in audio_url:
|
|
|
|
| 649 |
"retry_after": 20,
|
| 650 |
})
|
| 651 |
if r.status_code != 200:
|
|
|
|
| 652 |
raise HTTPException(r.status_code, _safe_json(r))
|
| 653 |
|
| 654 |
data = r.json()
|
|
|
|
| 663 |
s["error"] = None
|
| 664 |
|
| 665 |
logger.info(f"Pipeline {pid[:8]}: Alignment submitted to {backend_type.upper()} ({backend_url})")
|
|
|
|
| 666 |
return backend_type
|
| 667 |
|
| 668 |
|
|
|
|
| 765 |
return {
|
| 766 |
"pipeline_id": p["pipeline_id"],
|
| 767 |
"created_at": p["created_at"],
|
| 768 |
+
"finalized": p.get("finalized", False),
|
| 769 |
"stages": stages,
|
| 770 |
"assets": {
|
| 771 |
"audio_url": p["assets"]["audio_url"],
|
|
|
|
| 817 |
pipelines.pop(pid, None)
|
| 818 |
pipeline_heartbeats.pop(pid, None)
|
| 819 |
if expired:
|
| 820 |
+
logger.info(f"Purged {len(expired)} expired pipelines from memory.")
|
| 821 |
|
| 822 |
# =============================================================================
|
| 823 |
# STARTUP / SHUTDOWN
|
|
|
|
| 843 |
asyncio.create_task(_status_loop())
|
| 844 |
asyncio.create_task(_cleanup_loop())
|
| 845 |
asyncio.create_task(_frontend_heartbeat_watchdog())
|
| 846 |
+
logger.info("ArchNemix Controller v1.1 ready.")
|
| 847 |
|
| 848 |
|
| 849 |
async def _frontend_heartbeat_watchdog():
|
|
|
|
| 852 |
now = datetime.utcnow()
|
| 853 |
|
| 854 |
for pid, p in list(pipelines.items()):
|
| 855 |
+
|
| 856 |
+
# ββ GUARD: never touch a pipeline the client has already finalised.
|
| 857 |
+
# The client called /finalize after downloading the video, so we
|
| 858 |
+
# know the job completed successfully β the silence is intentional.
|
| 859 |
+
if p.get("finalized"):
|
| 860 |
+
continue
|
| 861 |
+
|
| 862 |
+
last_hb = pipeline_heartbeats.get(pid)
|
| 863 |
if last_hb is None:
|
| 864 |
last_hb = datetime.fromisoformat(p["created_at"])
|
| 865 |
|
| 866 |
silence = (now - last_hb).total_seconds()
|
| 867 |
|
| 868 |
+
# ββ Permanent abandon: client gone for a long time, delete everything ββ
|
| 869 |
if silence >= FRONTEND_HEARTBEAT_GRACE + 200:
|
| 870 |
+
logger.warning(f"Pipeline {pid[:8]} silent {silence:.0f}s β permanent abandon")
|
| 871 |
try:
|
| 872 |
await store().delete_pipeline(pid)
|
| 873 |
except Exception as e:
|
|
|
|
| 876 |
pipeline_heartbeats.pop(pid, None)
|
| 877 |
continue
|
| 878 |
|
| 879 |
+
# ββ Short silence: cancel any running backend job ββββββββββββββββββ
|
| 880 |
elif silence >= FRONTEND_HEARTBEAT_GRACE:
|
| 881 |
running_stage = next(
|
| 882 |
(name for name, s in p["stages"].items() if s["status"] == StageStatus.RUNNING),
|
|
|
|
| 919 |
async def root():
|
| 920 |
return {
|
| 921 |
"name": "ArchNemix Controller",
|
| 922 |
+
"version": "1.1.0",
|
| 923 |
"endpoints": {
|
| 924 |
+
"POST /pipeline/start": "Start new pipeline (submits TTS immediately)",
|
| 925 |
+
"GET /pipeline/{id}": "Poll pipeline state + per-stage status",
|
| 926 |
+
"POST /pipeline/{id}/rerun/tts": "Re-run TTS only (new text/voice/rate optional)",
|
| 927 |
+
"POST /pipeline/{id}/align": "Submit alignment (uses completed TTS audio)",
|
| 928 |
+
"POST /pipeline/{id}/rerun/align": "Re-run alignment only",
|
| 929 |
+
"POST /pipeline/{id}/video": "Submit video (uses completed TTS audio + subtitles_ass from frontend)",
|
| 930 |
+
"POST /pipeline/{id}/rerun/video": "Re-run video only",
|
| 931 |
+
"POST /pipeline/{id}/finalize": "Mark pipeline complete β deletes intermediates, keeps video",
|
| 932 |
+
"GET /download/{id}": "Download completed video (proxied from dataset)",
|
| 933 |
+
"GET /status": "Live slot availability for all spaces",
|
| 934 |
},
|
| 935 |
}
|
| 936 |
|
|
|
|
| 1114 |
})
|
| 1115 |
|
| 1116 |
|
| 1117 |
+
@app.post("/pipeline/{pipeline_id}/finalize")
|
| 1118 |
+
async def finalize_pipeline(pipeline_id: str):
|
| 1119 |
+
"""
|
| 1120 |
+
Called by the frontend immediately after it receives the completed video.
|
| 1121 |
+
Marks the pipeline as finalized (immunises it from the watchdog) and
|
| 1122 |
+
deletes intermediate assets (audio + timestamps) from the dataset,
|
| 1123 |
+
leaving only video.mp4.
|
| 1124 |
+
"""
|
| 1125 |
+
p = pipelines.get(pipeline_id)
|
| 1126 |
+
if not p:
|
| 1127 |
+
# Pipeline already expired from memory β that's fine, nothing to do.
|
| 1128 |
+
return {"ok": True, "pipeline_id": pipeline_id, "note": "pipeline_not_in_memory"}
|
| 1129 |
+
|
| 1130 |
+
if p.get("finalized"):
|
| 1131 |
+
return {"ok": True, "pipeline_id": pipeline_id, "note": "already_finalized"}
|
| 1132 |
+
|
| 1133 |
+
if p["stages"][Stage.VIDEO]["status"] != StageStatus.DONE:
|
| 1134 |
+
raise HTTPException(400, {
|
| 1135 |
+
"error": "video_not_done",
|
| 1136 |
+
"detail": "Cannot finalize a pipeline whose video stage has not completed.",
|
| 1137 |
+
})
|
| 1138 |
+
|
| 1139 |
+
# Mark immediately so the watchdog skips it from this tick onward.
|
| 1140 |
+
p["finalized"] = True
|
| 1141 |
+
|
| 1142 |
+
# Stop heartbeats from affecting this pipeline.
|
| 1143 |
+
pipeline_heartbeats.pop(pipeline_id, None)
|
| 1144 |
+
|
| 1145 |
+
# Delete intermediates in the background β don't make the client wait.
|
| 1146 |
+
asyncio.create_task(_run_delete_intermediates(pipeline_id))
|
| 1147 |
+
|
| 1148 |
+
logger.info(f"Pipeline {pipeline_id[:8]} finalized β intermediates scheduled for deletion.")
|
| 1149 |
+
|
| 1150 |
+
return {
|
| 1151 |
+
"ok": True,
|
| 1152 |
+
"pipeline_id": pipeline_id,
|
| 1153 |
+
"video_url": p["assets"].get("video_url"),
|
| 1154 |
+
}
|
| 1155 |
+
|
| 1156 |
+
|
| 1157 |
+
async def _run_delete_intermediates(pipeline_id: str):
|
| 1158 |
+
"""Background task: delete audio + timestamps, keep video.mp4."""
|
| 1159 |
+
try:
|
| 1160 |
+
await store().delete_intermediates(pipeline_id)
|
| 1161 |
+
except Exception as e:
|
| 1162 |
+
logger.error(f"delete_intermediates failed for {pipeline_id[:8]}: {e}")
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
@app.get("/download/{pipeline_id}")
|
| 1166 |
async def download_video(pipeline_id: str):
|
| 1167 |
p = _pipeline_or_404(pipeline_id)
|