Update app.py
Browse files
app.py
CHANGED
|
@@ -1,20 +1,21 @@
|
|
| 1 |
"""
|
| 2 |
-
ArchNemix Controller Space v1.
|
| 3 |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
Orchestrates 12 backend HuggingFace Spaces in a staged pipeline:
|
| 5 |
|
| 6 |
-
TTS (Γ
|
| 7 |
|
| 8 |
Pipeline stages β user can re-run any stage independently:
|
| 9 |
1. TTS β text β audio (saved to HF dataset)
|
| 10 |
2. Align β audio β word timestamps (saved to HF dataset)
|
| 11 |
-
3. Video β audio + subtitles β MP4 (
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
|
|
|
| 15 |
|
| 16 |
HF Secrets required:
|
| 17 |
-
APP_KEY β must match all
|
| 18 |
HF_TOKEN β write access to your pipeline dataset
|
| 19 |
HF_DATASET β e.g. "YourOrg/archnemix-pipelines"
|
| 20 |
"""
|
|
@@ -30,7 +31,7 @@ from typing import Dict, Any, Optional, Tuple
|
|
| 30 |
import httpx
|
| 31 |
from fastapi import FastAPI, HTTPException, Request
|
| 32 |
from fastapi.middleware.cors import CORSMiddleware
|
| 33 |
-
from fastapi.responses import JSONResponse, Response
|
| 34 |
from pydantic import BaseModel
|
| 35 |
|
| 36 |
from dataset import DatasetStore
|
|
@@ -84,7 +85,7 @@ FFMPEG_SPACES = [
|
|
| 84 |
]
|
| 85 |
|
| 86 |
non_used_spaces = [
|
| 87 |
-
"https://archnemix-ffmpeg-polyglot-ffmpeg-rust.hf.space",
|
| 88 |
]
|
| 89 |
|
| 90 |
ALL_SPACES: Dict[str, list] = {
|
|
@@ -117,8 +118,8 @@ class StageStatus:
|
|
| 117 |
# IN-MEMORY STATE
|
| 118 |
# =============================================================================
|
| 119 |
|
| 120 |
-
pipelines:
|
| 121 |
-
status_cache:
|
| 122 |
|
| 123 |
# =============================================================================
|
| 124 |
# REQUEST / RESPONSE MODELS
|
|
@@ -154,7 +155,7 @@ class VideoSubmitRequest(BaseModel):
|
|
| 154 |
|
| 155 |
app = FastAPI(
|
| 156 |
title="ArchNemix Controller v1",
|
| 157 |
-
version="1.
|
| 158 |
docs_url="/docs",
|
| 159 |
redoc_url=None,
|
| 160 |
)
|
|
@@ -259,7 +260,6 @@ async def _status_loop():
|
|
| 259 |
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 260 |
for r in results:
|
| 261 |
if isinstance(r, dict):
|
| 262 |
-
# preserve any in-flight reservations made since last check
|
| 263 |
existing = status_cache.get(r["url"], {})
|
| 264 |
r["_reserved"] = existing.get("_reserved", 0)
|
| 265 |
status_cache[r["url"]] = r
|
|
@@ -316,7 +316,6 @@ async def _pick(stype: str) -> Optional[str]:
|
|
| 316 |
|
| 317 |
for url in urls:
|
| 318 |
c = status_cache.get(url, {})
|
| 319 |
-
# skip spaces we know are offline
|
| 320 |
if c and not c.get("online", True):
|
| 321 |
continue
|
| 322 |
|
|
@@ -325,12 +324,10 @@ async def _pick(stype: str) -> Optional[str]:
|
|
| 325 |
waiting = c.get("waiting", 0)
|
| 326 |
reserved = c.get("_reserved", 0)
|
| 327 |
load = running + waiting + reserved
|
| 328 |
-
# skip if truly full (no room even in queue)
|
| 329 |
if load >= FFMPEG_QUEUE_DEPTH:
|
| 330 |
continue
|
| 331 |
else:
|
| 332 |
reserved = c.get("_reserved", 0)
|
| 333 |
-
# for mfa/qwen/tts: 0 = free, 1 = busy
|
| 334 |
load = (0 if c.get("can_submit", True) else 1) + reserved
|
| 335 |
if load >= 1:
|
| 336 |
continue
|
|
@@ -339,7 +336,6 @@ async def _pick(stype: str) -> Optional[str]:
|
|
| 339 |
best_load = load
|
| 340 |
best_url = url
|
| 341 |
|
| 342 |
-
# live fallback if cache gave us nothing usable
|
| 343 |
if best_url is None:
|
| 344 |
results = await asyncio.gather(*[_check_one(url, stype) for url in urls])
|
| 345 |
for r in results:
|
|
@@ -366,20 +362,18 @@ async def _pick(stype: str) -> Optional[str]:
|
|
| 366 |
best_load = load
|
| 367 |
best_url = url
|
| 368 |
|
| 369 |
-
# optimistic reservation β increment counter so next concurrent pick
|
| 370 |
-
# sees this space as one slot more loaded before the cache refreshes
|
| 371 |
if best_url and best_url in status_cache:
|
| 372 |
c = status_cache[best_url]
|
| 373 |
c["_reserved"] = c.get("_reserved", 0) + 1
|
| 374 |
if stype == "ffmpeg":
|
| 375 |
total = c.get("running", 0) + c.get("waiting", 0) + c["_reserved"]
|
| 376 |
-
c["can_submit"]
|
| 377 |
-
c["queue_full"]
|
| 378 |
c["slot_available"] = c.get("running", 0) == 0
|
| 379 |
else:
|
| 380 |
-
c["can_submit"]
|
| 381 |
c["slot_available"] = False
|
| 382 |
-
c["queue_full"]
|
| 383 |
|
| 384 |
return best_url
|
| 385 |
|
|
@@ -401,8 +395,6 @@ def _new_pipeline(config: PipelineStartRequest) -> Dict[str, Any]:
|
|
| 401 |
"pipeline_id": pid,
|
| 402 |
"created_at": datetime.utcnow().isoformat(),
|
| 403 |
"last_active": datetime.utcnow().isoformat(),
|
| 404 |
-
# finalized = True means the client acknowledged receipt of the
|
| 405 |
-
# finished video. The watchdog must never touch a finalized pipeline.
|
| 406 |
"finalized": False,
|
| 407 |
"config": {
|
| 408 |
"text": config.text,
|
|
@@ -420,9 +412,11 @@ def _new_pipeline(config: PipelineStartRequest) -> Dict[str, Any]:
|
|
| 420 |
Stage.VIDEO: _blank_stage(),
|
| 421 |
},
|
| 422 |
"assets": {
|
| 423 |
-
"audio_url":
|
| 424 |
-
"timestamps_url":
|
| 425 |
-
|
|
|
|
|
|
|
| 426 |
},
|
| 427 |
}
|
| 428 |
|
|
@@ -480,12 +474,11 @@ async def _poll_backend_stage(p: Dict, stage: str) -> None:
|
|
| 480 |
pid = p["pipeline_id"]
|
| 481 |
|
| 482 |
try:
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
)
|
| 489 |
except Exception as e:
|
| 490 |
logger.warning(f"Poll error {pid}/{stage}: {e}")
|
| 491 |
return
|
|
@@ -557,14 +550,32 @@ async def _finalise_stage(p: Dict, stage: str, url: str, jid: str, slim_data: Di
|
|
| 557 |
|
| 558 |
logger.info(f"Pipeline {pid[:8]} Align done β {ts_url}")
|
| 559 |
|
|
|
|
| 560 |
elif stage == Stage.VIDEO:
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
|
| 567 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
|
| 569 |
s["status"] = StageStatus.DONE
|
| 570 |
s["completed_at"] = datetime.utcnow().isoformat()
|
|
@@ -749,7 +760,7 @@ async def _submit_video(p: Dict, subtitles_ass: str, background: str, duration:
|
|
| 749 |
if not backend_url:
|
| 750 |
return JSONResponse(status_code=503, content={
|
| 751 |
"error": "all_video_busy",
|
| 752 |
-
"detail": "All
|
| 753 |
"retry_after": 120,
|
| 754 |
})
|
| 755 |
|
|
@@ -821,9 +832,11 @@ def _pipeline_view(p: Dict) -> Dict:
|
|
| 821 |
"finalized": p.get("finalized", False),
|
| 822 |
"stages": stages,
|
| 823 |
"assets": {
|
| 824 |
-
"audio_url":
|
| 825 |
-
"timestamps_url":
|
| 826 |
-
|
|
|
|
|
|
|
| 827 |
},
|
| 828 |
"next_actions": _next_actions(p),
|
| 829 |
}
|
|
@@ -896,7 +909,7 @@ async def startup():
|
|
| 896 |
asyncio.create_task(_status_loop())
|
| 897 |
asyncio.create_task(_cleanup_loop())
|
| 898 |
asyncio.create_task(_frontend_heartbeat_watchdog())
|
| 899 |
-
logger.info("ArchNemix Controller v1.
|
| 900 |
|
| 901 |
|
| 902 |
async def _frontend_heartbeat_watchdog():
|
|
@@ -906,9 +919,6 @@ async def _frontend_heartbeat_watchdog():
|
|
| 906 |
|
| 907 |
for pid, p in list(pipelines.items()):
|
| 908 |
|
| 909 |
-
# ββ GUARD: never touch a pipeline the client has already finalised.
|
| 910 |
-
# The client called /finalize after downloading the video, so we
|
| 911 |
-
# know the job completed successfully β the silence is intentional.
|
| 912 |
if p.get("finalized"):
|
| 913 |
continue
|
| 914 |
|
|
@@ -918,7 +928,6 @@ async def _frontend_heartbeat_watchdog():
|
|
| 918 |
|
| 919 |
silence = (now - last_hb).total_seconds()
|
| 920 |
|
| 921 |
-
# ββ Permanent abandon: client gone for a long time, delete everything ββ
|
| 922 |
if silence >= FRONTEND_HEARTBEAT_GRACE + 200:
|
| 923 |
logger.warning(f"Pipeline {pid[:8]} silent {silence:.0f}s β permanent abandon")
|
| 924 |
try:
|
|
@@ -929,7 +938,6 @@ async def _frontend_heartbeat_watchdog():
|
|
| 929 |
pipeline_heartbeats.pop(pid, None)
|
| 930 |
continue
|
| 931 |
|
| 932 |
-
# ββ Short silence: cancel any running backend job ββββββββββββββββββ
|
| 933 |
elif silence >= FRONTEND_HEARTBEAT_GRACE:
|
| 934 |
running_stage = next(
|
| 935 |
(name for name, s in p["stages"].items() if s["status"] == StageStatus.RUNNING),
|
|
@@ -972,18 +980,17 @@ async def shutdown():
|
|
| 972 |
async def root():
|
| 973 |
return {
|
| 974 |
"name": "ArchNemix Controller",
|
| 975 |
-
"version": "1.
|
| 976 |
"endpoints": {
|
| 977 |
-
"POST /pipeline/start":
|
| 978 |
-
"GET /pipeline/{id}":
|
| 979 |
-
"POST /pipeline/{id}/rerun/tts":
|
| 980 |
-
"POST /pipeline/{id}/align":
|
| 981 |
-
"POST /pipeline/{id}/rerun/align":
|
| 982 |
-
"POST /pipeline/{id}/video":
|
| 983 |
-
"POST /pipeline/{id}/rerun/video":
|
| 984 |
-
"POST /pipeline/{id}/finalize":
|
| 985 |
-
"GET /
|
| 986 |
-
"GET /status": "Live slot availability for all spaces",
|
| 987 |
},
|
| 988 |
}
|
| 989 |
|
|
@@ -1047,8 +1054,9 @@ async def rerun_tts(pipeline_id: str, req: RerunTTSRequest):
|
|
| 1047 |
|
| 1048 |
p["stages"][Stage.ALIGN] = _blank_stage()
|
| 1049 |
p["stages"][Stage.VIDEO] = _blank_stage()
|
| 1050 |
-
p["assets"]["timestamps_url"]
|
| 1051 |
-
p["assets"]["
|
|
|
|
| 1052 |
|
| 1053 |
err = await _submit_tts(p, p["config"]["text"], p["config"]["voice"], p["config"]["rate"])
|
| 1054 |
if err:
|
|
@@ -1106,7 +1114,8 @@ async def rerun_align(pipeline_id: str, req: AlignSubmitRequest):
|
|
| 1106 |
if req.aligner_type is not None: p["config"]["aligner_type"] = req.aligner_type
|
| 1107 |
|
| 1108 |
p["stages"][Stage.VIDEO] = _blank_stage()
|
| 1109 |
-
p["assets"]["
|
|
|
|
| 1110 |
|
| 1111 |
aligner_type = p["config"].get("aligner_type", "mfa")
|
| 1112 |
backend_type = await _submit_align(p, p["config"]["language"], p["config"]["pass_number"], aligner_type)
|
|
@@ -1136,10 +1145,9 @@ async def submit_video(pipeline_id: str, req: VideoSubmitRequest):
|
|
| 1136 |
return err
|
| 1137 |
|
| 1138 |
return JSONResponse({
|
| 1139 |
-
"pipeline_id":
|
| 1140 |
-
"status":
|
| 1141 |
-
"
|
| 1142 |
-
"message": "Video job submitted. Poll /pipeline/{id} every 5s.",
|
| 1143 |
})
|
| 1144 |
|
| 1145 |
|
|
@@ -1155,29 +1163,24 @@ async def rerun_video(pipeline_id: str, req: VideoSubmitRequest):
|
|
| 1155 |
if req.background is not None: p["config"]["background"] = req.background
|
| 1156 |
if req.duration is not None: p["config"]["duration"] = req.duration
|
| 1157 |
|
|
|
|
|
|
|
|
|
|
| 1158 |
err = await _submit_video(p, req.subtitles_ass, p["config"]["background"], p["config"]["duration"])
|
| 1159 |
if err:
|
| 1160 |
return err
|
| 1161 |
|
| 1162 |
return JSONResponse({
|
| 1163 |
-
"pipeline_id":
|
| 1164 |
-
"status":
|
| 1165 |
-
"
|
| 1166 |
-
"message": "Video re-submitted. Poll /pipeline/{id} every 5s.",
|
| 1167 |
})
|
| 1168 |
|
| 1169 |
|
| 1170 |
@app.post("/pipeline/{pipeline_id}/finalize")
|
| 1171 |
async def finalize_pipeline(pipeline_id: str):
|
| 1172 |
-
"""
|
| 1173 |
-
Called by the frontend immediately after it receives the completed video.
|
| 1174 |
-
Marks the pipeline as finalized (immunises it from the watchdog) and
|
| 1175 |
-
deletes intermediate assets (audio + timestamps) from the dataset,
|
| 1176 |
-
leaving only video.mp4.
|
| 1177 |
-
"""
|
| 1178 |
p = pipelines.get(pipeline_id)
|
| 1179 |
if not p:
|
| 1180 |
-
# Pipeline already expired from memory β that's fine, nothing to do.
|
| 1181 |
return {"ok": True, "pipeline_id": pipeline_id, "note": "pipeline_not_in_memory"}
|
| 1182 |
|
| 1183 |
if p.get("finalized"):
|
|
@@ -1189,57 +1192,30 @@ async def finalize_pipeline(pipeline_id: str):
|
|
| 1189 |
"detail": "Cannot finalize a pipeline whose video stage has not completed.",
|
| 1190 |
})
|
| 1191 |
|
| 1192 |
-
# Mark immediately so the watchdog skips it from this tick onward.
|
| 1193 |
p["finalized"] = True
|
| 1194 |
-
|
| 1195 |
-
# Stop heartbeats from affecting this pipeline.
|
| 1196 |
pipeline_heartbeats.pop(pipeline_id, None)
|
| 1197 |
|
| 1198 |
-
#
|
| 1199 |
asyncio.create_task(_run_delete_intermediates(pipeline_id))
|
| 1200 |
|
| 1201 |
-
logger.info(f"Pipeline {pipeline_id[:8]} finalized
|
| 1202 |
|
| 1203 |
return {
|
| 1204 |
-
"ok":
|
| 1205 |
-
"pipeline_id":
|
| 1206 |
-
"
|
|
|
|
| 1207 |
}
|
| 1208 |
|
| 1209 |
|
| 1210 |
async def _run_delete_intermediates(pipeline_id: str):
|
| 1211 |
-
"""Background task: delete audio + timestamps, keep video.mp4."""
|
| 1212 |
try:
|
| 1213 |
await store().delete_intermediates(pipeline_id)
|
| 1214 |
except Exception as e:
|
| 1215 |
logger.error(f"delete_intermediates failed for {pipeline_id[:8]}: {e}")
|
| 1216 |
|
| 1217 |
|
| 1218 |
-
|
| 1219 |
-
async def download_video(pipeline_id: str):
|
| 1220 |
-
p = _pipeline_or_404(pipeline_id)
|
| 1221 |
-
|
| 1222 |
-
video_url = p["assets"].get("video_url")
|
| 1223 |
-
if not video_url:
|
| 1224 |
-
raise HTTPException(400, {
|
| 1225 |
-
"error": "video_not_ready",
|
| 1226 |
-
"detail": "Video has not completed yet. Poll /pipeline/{id} first.",
|
| 1227 |
-
})
|
| 1228 |
-
|
| 1229 |
-
try:
|
| 1230 |
-
r = await http().get(video_url, timeout=120.0, follow_redirects=True)
|
| 1231 |
-
r.raise_for_status()
|
| 1232 |
-
except Exception as e:
|
| 1233 |
-
raise HTTPException(503, {"error": "video_fetch_failed", "detail": str(e)})
|
| 1234 |
-
|
| 1235 |
-
return Response(
|
| 1236 |
-
content=r.content,
|
| 1237 |
-
media_type="video/mp4",
|
| 1238 |
-
headers={
|
| 1239 |
-
"Content-Disposition": f'attachment; filename="archnemix-{pipeline_id[:8]}.mp4"',
|
| 1240 |
-
"Cache-Control": "no-cache",
|
| 1241 |
-
},
|
| 1242 |
-
)
|
| 1243 |
|
| 1244 |
|
| 1245 |
@app.get("/status")
|
|
|
|
| 1 |
"""
|
| 2 |
+
ArchNemix Controller Space v1.2
|
| 3 |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
Orchestrates 12 backend HuggingFace Spaces in a staged pipeline:
|
| 5 |
|
| 6 |
+
TTS (Γ4) β Aligner/Qwen (Γ8) β FFmpeg (Γ1)
|
| 7 |
|
| 8 |
Pipeline stages β user can re-run any stage independently:
|
| 9 |
1. TTS β text β audio (saved to HF dataset)
|
| 10 |
2. Align β audio β word timestamps (saved to HF dataset)
|
| 11 |
+
3. Video β audio + subtitles β MP4 (served directly from FFmpeg space)
|
| 12 |
|
| 13 |
+
Video is never stored in the dataset or downloaded by the controller.
|
| 14 |
+
FFmpeg space returns stream_url + download_url, controller passes them
|
| 15 |
+
straight to the frontend. Browser talks to FFmpeg space directly.
|
| 16 |
|
| 17 |
HF Secrets required:
|
| 18 |
+
APP_KEY β must match all FFmpeg spaces
|
| 19 |
HF_TOKEN β write access to your pipeline dataset
|
| 20 |
HF_DATASET β e.g. "YourOrg/archnemix-pipelines"
|
| 21 |
"""
|
|
|
|
| 31 |
import httpx
|
| 32 |
from fastapi import FastAPI, HTTPException, Request
|
| 33 |
from fastapi.middleware.cors import CORSMiddleware
|
| 34 |
+
from fastapi.responses import JSONResponse, Response, RedirectResponse
|
| 35 |
from pydantic import BaseModel
|
| 36 |
|
| 37 |
from dataset import DatasetStore
|
|
|
|
| 85 |
]
|
| 86 |
|
| 87 |
non_used_spaces = [
|
| 88 |
+
"https://archnemix-ffmpeg-polyglot-ffmpeg-rust.hf.space",
|
| 89 |
]
|
| 90 |
|
| 91 |
ALL_SPACES: Dict[str, list] = {
|
|
|
|
| 118 |
# IN-MEMORY STATE
|
| 119 |
# =============================================================================
|
| 120 |
|
| 121 |
+
pipelines: Dict[str, Dict[str, Any]] = {}
|
| 122 |
+
status_cache: Dict[str, Dict[str, Any]] = {}
|
| 123 |
|
| 124 |
# =============================================================================
|
| 125 |
# REQUEST / RESPONSE MODELS
|
|
|
|
| 155 |
|
| 156 |
app = FastAPI(
|
| 157 |
title="ArchNemix Controller v1",
|
| 158 |
+
version="1.2.0",
|
| 159 |
docs_url="/docs",
|
| 160 |
redoc_url=None,
|
| 161 |
)
|
|
|
|
| 260 |
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 261 |
for r in results:
|
| 262 |
if isinstance(r, dict):
|
|
|
|
| 263 |
existing = status_cache.get(r["url"], {})
|
| 264 |
r["_reserved"] = existing.get("_reserved", 0)
|
| 265 |
status_cache[r["url"]] = r
|
|
|
|
| 316 |
|
| 317 |
for url in urls:
|
| 318 |
c = status_cache.get(url, {})
|
|
|
|
| 319 |
if c and not c.get("online", True):
|
| 320 |
continue
|
| 321 |
|
|
|
|
| 324 |
waiting = c.get("waiting", 0)
|
| 325 |
reserved = c.get("_reserved", 0)
|
| 326 |
load = running + waiting + reserved
|
|
|
|
| 327 |
if load >= FFMPEG_QUEUE_DEPTH:
|
| 328 |
continue
|
| 329 |
else:
|
| 330 |
reserved = c.get("_reserved", 0)
|
|
|
|
| 331 |
load = (0 if c.get("can_submit", True) else 1) + reserved
|
| 332 |
if load >= 1:
|
| 333 |
continue
|
|
|
|
| 336 |
best_load = load
|
| 337 |
best_url = url
|
| 338 |
|
|
|
|
| 339 |
if best_url is None:
|
| 340 |
results = await asyncio.gather(*[_check_one(url, stype) for url in urls])
|
| 341 |
for r in results:
|
|
|
|
| 362 |
best_load = load
|
| 363 |
best_url = url
|
| 364 |
|
|
|
|
|
|
|
| 365 |
if best_url and best_url in status_cache:
|
| 366 |
c = status_cache[best_url]
|
| 367 |
c["_reserved"] = c.get("_reserved", 0) + 1
|
| 368 |
if stype == "ffmpeg":
|
| 369 |
total = c.get("running", 0) + c.get("waiting", 0) + c["_reserved"]
|
| 370 |
+
c["can_submit"] = total < FFMPEG_QUEUE_DEPTH
|
| 371 |
+
c["queue_full"] = total >= FFMPEG_QUEUE_DEPTH
|
| 372 |
c["slot_available"] = c.get("running", 0) == 0
|
| 373 |
else:
|
| 374 |
+
c["can_submit"] = False
|
| 375 |
c["slot_available"] = False
|
| 376 |
+
c["queue_full"] = True
|
| 377 |
|
| 378 |
return best_url
|
| 379 |
|
|
|
|
| 395 |
"pipeline_id": pid,
|
| 396 |
"created_at": datetime.utcnow().isoformat(),
|
| 397 |
"last_active": datetime.utcnow().isoformat(),
|
|
|
|
|
|
|
| 398 |
"finalized": False,
|
| 399 |
"config": {
|
| 400 |
"text": config.text,
|
|
|
|
| 412 |
Stage.VIDEO: _blank_stage(),
|
| 413 |
},
|
| 414 |
"assets": {
|
| 415 |
+
"audio_url": None, # HF dataset
|
| 416 |
+
"timestamps_url": None, # HF dataset
|
| 417 |
+
# ββ video lives on the FFmpeg space, never in the dataset ββββββββββ
|
| 418 |
+
"video_download_url": None, # direct download URL from FFmpeg space
|
| 419 |
+
"video_stream_url": None, # direct stream URL from FFmpeg space
|
| 420 |
},
|
| 421 |
}
|
| 422 |
|
|
|
|
| 474 |
pid = p["pipeline_id"]
|
| 475 |
|
| 476 |
try:
|
| 477 |
+
r = await http().get(
|
| 478 |
+
f"{url}/job/{jid}",
|
| 479 |
+
params={"slim": "true"} if stage != Stage.VIDEO else {},
|
| 480 |
+
timeout=HTTP_TIMEOUT,
|
| 481 |
+
)
|
|
|
|
| 482 |
except Exception as e:
|
| 483 |
logger.warning(f"Poll error {pid}/{stage}: {e}")
|
| 484 |
return
|
|
|
|
| 550 |
|
| 551 |
logger.info(f"Pipeline {pid[:8]} Align done β {ts_url}")
|
| 552 |
|
| 553 |
+
# ββ VIDEO β controller never downloads or stores the video bytes ββββββ
|
| 554 |
elif stage == Stage.VIDEO:
|
| 555 |
+
# slim_data already has status="completed" and the URLs because
|
| 556 |
+
# the FFmpeg space now returns them in the regular poll response.
|
| 557 |
+
# We just read them out β no extra HTTP call needed.
|
| 558 |
+
raw_download = slim_data.get("download_url", f"/download/{jid}")
|
| 559 |
+
raw_stream = slim_data.get("stream_url", f"/stream/{jid}")
|
| 560 |
+
|
| 561 |
+
# Make absolute if the space returned relative paths
|
| 562 |
+
download_url = (
|
| 563 |
+
raw_download if raw_download.startswith("http")
|
| 564 |
+
else f"{url}{raw_download}"
|
| 565 |
+
)
|
| 566 |
+
stream_url = (
|
| 567 |
+
raw_stream if raw_stream.startswith("http")
|
| 568 |
+
else f"{url}{raw_stream}"
|
| 569 |
+
)
|
| 570 |
|
| 571 |
+
p["assets"]["video_download_url"] = download_url
|
| 572 |
+
p["assets"]["video_stream_url"] = stream_url
|
| 573 |
+
|
| 574 |
+
logger.info(
|
| 575 |
+
f"Pipeline {pid[:8]} Video done β "
|
| 576 |
+
f"download={download_url} stream={stream_url}"
|
| 577 |
+
)
|
| 578 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 579 |
|
| 580 |
s["status"] = StageStatus.DONE
|
| 581 |
s["completed_at"] = datetime.utcnow().isoformat()
|
|
|
|
| 760 |
if not backend_url:
|
| 761 |
return JSONResponse(status_code=503, content={
|
| 762 |
"error": "all_video_busy",
|
| 763 |
+
"detail": "All video spaces are busy. Try again in ~2 min.",
|
| 764 |
"retry_after": 120,
|
| 765 |
})
|
| 766 |
|
|
|
|
| 832 |
"finalized": p.get("finalized", False),
|
| 833 |
"stages": stages,
|
| 834 |
"assets": {
|
| 835 |
+
"audio_url": p["assets"]["audio_url"],
|
| 836 |
+
"timestamps_url": p["assets"]["timestamps_url"],
|
| 837 |
+
# frontend uses these two directly β no /download proxy needed
|
| 838 |
+
"video_download_url": p["assets"]["video_download_url"],
|
| 839 |
+
"video_stream_url": p["assets"]["video_stream_url"],
|
| 840 |
},
|
| 841 |
"next_actions": _next_actions(p),
|
| 842 |
}
|
|
|
|
| 909 |
asyncio.create_task(_status_loop())
|
| 910 |
asyncio.create_task(_cleanup_loop())
|
| 911 |
asyncio.create_task(_frontend_heartbeat_watchdog())
|
| 912 |
+
logger.info("ArchNemix Controller v1.2 ready.")
|
| 913 |
|
| 914 |
|
| 915 |
async def _frontend_heartbeat_watchdog():
|
|
|
|
| 919 |
|
| 920 |
for pid, p in list(pipelines.items()):
|
| 921 |
|
|
|
|
|
|
|
|
|
|
| 922 |
if p.get("finalized"):
|
| 923 |
continue
|
| 924 |
|
|
|
|
| 928 |
|
| 929 |
silence = (now - last_hb).total_seconds()
|
| 930 |
|
|
|
|
| 931 |
if silence >= FRONTEND_HEARTBEAT_GRACE + 200:
|
| 932 |
logger.warning(f"Pipeline {pid[:8]} silent {silence:.0f}s β permanent abandon")
|
| 933 |
try:
|
|
|
|
| 938 |
pipeline_heartbeats.pop(pid, None)
|
| 939 |
continue
|
| 940 |
|
|
|
|
| 941 |
elif silence >= FRONTEND_HEARTBEAT_GRACE:
|
| 942 |
running_stage = next(
|
| 943 |
(name for name, s in p["stages"].items() if s["status"] == StageStatus.RUNNING),
|
|
|
|
| 980 |
async def root():
|
| 981 |
return {
|
| 982 |
"name": "ArchNemix Controller",
|
| 983 |
+
"version": "1.2.0",
|
| 984 |
"endpoints": {
|
| 985 |
+
"POST /pipeline/start": "Start new pipeline (submits TTS immediately)",
|
| 986 |
+
"GET /pipeline/{id}": "Poll pipeline state + per-stage status",
|
| 987 |
+
"POST /pipeline/{id}/rerun/tts": "Re-run TTS only (new text/voice/rate optional)",
|
| 988 |
+
"POST /pipeline/{id}/align": "Submit alignment (uses completed TTS audio)",
|
| 989 |
+
"POST /pipeline/{id}/rerun/align": "Re-run alignment only",
|
| 990 |
+
"POST /pipeline/{id}/video": "Submit video (uses completed TTS audio + subtitles_ass from frontend)",
|
| 991 |
+
"POST /pipeline/{id}/rerun/video": "Re-run video only",
|
| 992 |
+
"POST /pipeline/{id}/finalize": "Mark pipeline complete β deletes dataset intermediates",
|
| 993 |
+
"GET /status": "Live slot availability for all spaces",
|
|
|
|
| 994 |
},
|
| 995 |
}
|
| 996 |
|
|
|
|
| 1054 |
|
| 1055 |
p["stages"][Stage.ALIGN] = _blank_stage()
|
| 1056 |
p["stages"][Stage.VIDEO] = _blank_stage()
|
| 1057 |
+
p["assets"]["timestamps_url"] = None
|
| 1058 |
+
p["assets"]["video_download_url"] = None
|
| 1059 |
+
p["assets"]["video_stream_url"] = None
|
| 1060 |
|
| 1061 |
err = await _submit_tts(p, p["config"]["text"], p["config"]["voice"], p["config"]["rate"])
|
| 1062 |
if err:
|
|
|
|
| 1114 |
if req.aligner_type is not None: p["config"]["aligner_type"] = req.aligner_type
|
| 1115 |
|
| 1116 |
p["stages"][Stage.VIDEO] = _blank_stage()
|
| 1117 |
+
p["assets"]["video_download_url"] = None
|
| 1118 |
+
p["assets"]["video_stream_url"] = None
|
| 1119 |
|
| 1120 |
aligner_type = p["config"].get("aligner_type", "mfa")
|
| 1121 |
backend_type = await _submit_align(p, p["config"]["language"], p["config"]["pass_number"], aligner_type)
|
|
|
|
| 1145 |
return err
|
| 1146 |
|
| 1147 |
return JSONResponse({
|
| 1148 |
+
"pipeline_id": pipeline_id,
|
| 1149 |
+
"status": "video_running",
|
| 1150 |
+
"message": "Video job submitted. Poll /pipeline/{id} every 5s.",
|
|
|
|
| 1151 |
})
|
| 1152 |
|
| 1153 |
|
|
|
|
| 1163 |
if req.background is not None: p["config"]["background"] = req.background
|
| 1164 |
if req.duration is not None: p["config"]["duration"] = req.duration
|
| 1165 |
|
| 1166 |
+
p["assets"]["video_download_url"] = None
|
| 1167 |
+
p["assets"]["video_stream_url"] = None
|
| 1168 |
+
|
| 1169 |
err = await _submit_video(p, req.subtitles_ass, p["config"]["background"], p["config"]["duration"])
|
| 1170 |
if err:
|
| 1171 |
return err
|
| 1172 |
|
| 1173 |
return JSONResponse({
|
| 1174 |
+
"pipeline_id": pipeline_id,
|
| 1175 |
+
"status": "video_running",
|
| 1176 |
+
"message": "Video re-submitted. Poll /pipeline/{id} every 5s.",
|
|
|
|
| 1177 |
})
|
| 1178 |
|
| 1179 |
|
| 1180 |
@app.post("/pipeline/{pipeline_id}/finalize")
|
| 1181 |
async def finalize_pipeline(pipeline_id: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1182 |
p = pipelines.get(pipeline_id)
|
| 1183 |
if not p:
|
|
|
|
| 1184 |
return {"ok": True, "pipeline_id": pipeline_id, "note": "pipeline_not_in_memory"}
|
| 1185 |
|
| 1186 |
if p.get("finalized"):
|
|
|
|
| 1192 |
"detail": "Cannot finalize a pipeline whose video stage has not completed.",
|
| 1193 |
})
|
| 1194 |
|
|
|
|
| 1195 |
p["finalized"] = True
|
|
|
|
|
|
|
| 1196 |
pipeline_heartbeats.pop(pipeline_id, None)
|
| 1197 |
|
| 1198 |
+
# Only delete audio + timestamps from dataset β video was never there
|
| 1199 |
asyncio.create_task(_run_delete_intermediates(pipeline_id))
|
| 1200 |
|
| 1201 |
+
logger.info(f"Pipeline {pipeline_id[:8]} finalized.")
|
| 1202 |
|
| 1203 |
return {
|
| 1204 |
+
"ok": True,
|
| 1205 |
+
"pipeline_id": pipeline_id,
|
| 1206 |
+
"video_download_url": p["assets"].get("video_download_url"),
|
| 1207 |
+
"video_stream_url": p["assets"].get("video_stream_url"),
|
| 1208 |
}
|
| 1209 |
|
| 1210 |
|
| 1211 |
async def _run_delete_intermediates(pipeline_id: str):
|
|
|
|
| 1212 |
try:
|
| 1213 |
await store().delete_intermediates(pipeline_id)
|
| 1214 |
except Exception as e:
|
| 1215 |
logger.error(f"delete_intermediates failed for {pipeline_id[:8]}: {e}")
|
| 1216 |
|
| 1217 |
|
| 1218 |
+
# /download endpoint removed β frontend uses video_download_url directly
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1219 |
|
| 1220 |
|
| 1221 |
@app.get("/status")
|