Download app.py from YTShortMakerArchx/archnemix-controller: direct link, hf CLI and curl.
- Browser
- Download file 92.7 kB
-
https://huggingface.co/spaces/YTShortMakerArchx/archnemix-controller/resolve/main/app.py
- Command line
-
hf download hf://spaces/YTShortMakerArchx/archnemix-controller/app.py
-
curl -L -o app.py https://huggingface.co/spaces/YTShortMakerArchx/archnemix-controller/resolve/main/app.py
92.7 kB
"""
ArchNemix Controller Space v1.8
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ADDED: Enhanced error tracking with exact backend URL for each failed stage
ADDED: Detailed debugging information for pipeline failures
ADDED: Failure context including stage, backend URL, job ID, and error message
"""
import os
import uuid
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, Tuple, List
from enum import Enum
from dataclasses import dataclass, asdict, field
from collections import defaultdict
import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, Response, RedirectResponse, StreamingResponse
from pydantic import BaseModel
from dataset import DatasetStore
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s",
)
logger = logging.getLogger(__name__)
# =============================================================================
# CONFIGURATION
# =============================================================================
APP_KEY = os.getenv("APP_KEY", "")
HF_TOKEN = os.getenv("HF_TOKEN", "")
HF_DATASET = os.getenv("HF_DATASET", "")
HF_DATASET_2 = os.getenv("HF_DATASET_2", "")
ADMIN_KEY = os.getenv("ADMIN_KEY", "") # Secret key that bypasses rate limiting
pipeline_heartbeats: Dict[str, datetime] = {}
FRONTEND_HEARTBEAT_GRACE = 45
FFMPEG_QUEUE_DEPTH = 2
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ENHANCED ADMIN ANALYTICS STORAGE - v1.8
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@dataclass
class StageFailureDetail:
"""Detailed information about a stage failure"""
stage: str
backend_url: str
backend_type: str
job_id: str
error_message: str
error_type: str # e.g., "timeout", "backend_error", "save_failed", "user_cancelled"
submitted_at: Optional[datetime] = None
failed_at: datetime = field(default_factory=datetime.utcnow)
http_status: Optional[int] = None
response_body: Optional[str] = None
@dataclass
class JobAnalytics:
"""Track detailed analytics for a single job/pipeline"""
pipeline_id: str
created_at: datetime
user_ip: str # anonymized in logs
is_admin: bool
rate_limited: bool = False
# Stage tracking with backend details
tts_submitted_at: Optional[datetime] = None
tts_completed_at: Optional[datetime] = None
tts_status: str = "idle"
tts_error: Optional[str] = None
tts_backend: Optional[str] = None # Exact URL of backend space
tts_backend_type: Optional[str] = None
tts_job_id: Optional[str] = None
tts_failure_detail: Optional[StageFailureDetail] = None
align_submitted_at: Optional[datetime] = None
align_completed_at: Optional[datetime] = None
align_status: str = "idle"
align_error: Optional[str] = None
align_backend: Optional[str] = None # Exact URL of backend space
align_backend_type: Optional[str] = None
align_job_id: Optional[str] = None
align_failure_detail: Optional[StageFailureDetail] = None
video_submitted_at: Optional[datetime] = None
video_completed_at: Optional[datetime] = None
video_status: str = "idle"
video_error: Optional[str] = None
video_backend: Optional[str] = None # Exact URL of backend space
video_backend_type: Optional[str] = None
video_job_id: Optional[str] = None
video_storage_method: Optional[str] = None # "dataset" or "ffmpeg_fallback"
video_failure_detail: Optional[StageFailureDetail] = None
# Final outcome
final_status: str = "pending" # "success", "failed", "cancelled"
completed_at: Optional[datetime] = None
def to_dict(self) -> Dict:
d = asdict(self)
# Convert datetimes to ISO strings
for key, value in d.items():
if isinstance(value, datetime):
d[key] = value.isoformat()
elif isinstance(value, StageFailureDetail):
d[key] = {
"stage": value.stage,
"backend_url": value.backend_url,
"backend_type": value.backend_type,
"job_id": value.job_id,
"error_message": value.error_message,
"error_type": value.error_type,
"submitted_at": value.submitted_at.isoformat() if value.submitted_at else None,
"failed_at": value.failed_at.isoformat(),
"http_status": value.http_status,
"response_body": value.response_body[:500] if value.response_body else None, # Truncate long responses
}
return d
# Global analytics storage
analytics_storage: Dict[str, JobAnalytics] = {} # pipeline_id -> analytics
stage_failure_stats: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int))
# stage_failure_stats["tts"]["timeout"] = 5
# stage_failure_stats["tts"]["backend_error"] = 3
# Rate limiting storage
rate_limit_storage: Dict[str, list[datetime]] = {}
RATE_LIMIT_MAX_PER_HOUR = 10
RATE_LIMIT_WINDOW_HOURS = 1
ALLOWED_ORIGINS = [
"https://shortgenx.pages.dev",
"http://localhost:3000",
"http://127.0.0.1:3000",
"https://ytshortmakerarchx-archnemix-controller.hf.space",
]
TTS_SPACES = [
"https://archnemix-kokoro-tts-polyglot-kokoro-tts-rust.hf.space",
"https://Archnemix-Kokoro-TTS-Polyglot-kokoro-tts-GO.hf.space",
"https://Archnemix-Kokoro-TTS-Polyglot-kokorotts-python.hf.space",
"https://archnemix-kokoro-tts-polyglot-kokoro-tts-nodejs.hf.space",
]
MFA_SPACES = [
"https://montreal-forced-align-polygot-mfa-node-js.hf.space",
"https://montreal-forced-align-polygot-MFA-GO.hf.space",
"https://montreal-forced-align-polygot-MFA-RUST.hf.space",
"https://montreal-forced-align-polygot-MFA-python.hf.space",
]
QWEN_SPACES = [
"https://qwen-forced-aligner-polygot-qwenforcedaligner-nodejs.hf.space",
"https://qwen-forced-aligner-polygot-qwenforcedaligner-go.hf.space",
"https://Qwen-Forced-Aligner-polygot-Qwenforcedaligner-rust.hf.space",
"https://Qwen-Forced-Aligner-polygot-qwenforcedaligner-python.hf.space",
]
FFMPEG_SPACES = [
"https://archnemix-ffmpeg-polyglot-ffmpeg-rust.hf.space",
"https://archnemix-ffmpeg-polyglot-ffmpeg-nodejs.hf.space",
"https://archnemix-ffmpeg-polyglot-ffmpeg-GO.hf.space",
"https://archnemix-ffmpeg-polyglot-ffmpeg-python.hf.space",
]
non_used_spaces = [
"Currently None",
]
ALL_SPACES: Dict[str, list] = {
"tts": TTS_SPACES,
"mfa": MFA_SPACES,
"qwen": QWEN_SPACES,
"ffmpeg": FFMPEG_SPACES,
}
SESSION_TTL = 3600
STATUS_POLL_EVERY = 10
HTTP_TIMEOUT = 15.0
# =============================================================================
# STAGE CONSTANTS
# =============================================================================
class Stage:
TTS = "tts"
ALIGN = "align"
VIDEO = "video"
class StageStatus:
IDLE = "idle"
RUNNING = "running"
DONE = "done"
FAILED = "failed"
# =============================================================================
# IN-MEMORY STATE
# =============================================================================
pipelines: Dict[str, Dict[str, Any]] = {}
status_cache: Dict[str, Dict[str, Any]] = {}
# =============================================================================
# RATE LIMITING HELPERS
# =============================================================================
def _get_client_ip(request: Request) -> str:
"""
Extract real client IP from request.
Checks headers in order:
1. CF-Connecting-IP (Cloudflare)
2. X-Forwarded-For (standard proxy header)
3. request.client.host (direct connection)
"""
cf_ip = request.headers.get("CF-Connecting-IP")
if cf_ip:
return cf_ip.strip()
forwarded = request.headers.get("X-Forwarded-For")
if forwarded:
return forwarded.split(",")[0].strip()
return request.client.host if request.client else "unknown"
def _anonymize_ip(ip: str) -> str:
"""Anonymize IP for privacy in analytics (keep only first 3 octets)"""
parts = ip.split('.')
if len(parts) >= 3:
return f"{parts[0]}.{parts[1]}.{parts[2]}.xxx"
return "unknown"
def _is_admin_request(request: Request) -> bool:
"""Check if request has admin credentials via API key header."""
admin_header = request.headers.get("X-Admin-Key")
if ADMIN_KEY and admin_header and admin_header == ADMIN_KEY:
return True
return False
def _cleanup_old_timestamps(ip: str) -> None:
"""Remove timestamps older than RATE_LIMIT_WINDOW_HOURS from storage."""
if ip not in rate_limit_storage:
return
cutoff = datetime.utcnow() - timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
rate_limit_storage[ip] = [
ts for ts in rate_limit_storage[ip]
if ts > cutoff
]
if not rate_limit_storage[ip]:
del rate_limit_storage[ip]
def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
"""Check if IP has exceeded rate limit."""
_cleanup_old_timestamps(ip)
if ip not in rate_limit_storage:
return True, 0, 0
current_count = len(rate_limit_storage[ip])
if current_count >= RATE_LIMIT_MAX_PER_HOUR:
oldest_timestamp = min(rate_limit_storage[ip])
expires_at = oldest_timestamp + timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
seconds_until_expiry = int((expires_at - datetime.utcnow()).total_seconds())
return False, current_count, max(0, seconds_until_expiry)
return True, current_count, 0
def _record_request(ip: str) -> None:
"""Record a new pipeline start request for this IP."""
_cleanup_old_timestamps(ip)
if ip not in rate_limit_storage:
rate_limit_storage[ip] = []
rate_limit_storage[ip].append(datetime.utcnow())
# =============================================================================
# ENHANCED ANALYTICS HELPERS
# =============================================================================
def _record_stage_failure(
analytics: JobAnalytics,
stage: str,
backend_url: str,
backend_type: str,
job_id: str,
error_message: str,
error_type: str,
http_status: Optional[int] = None,
response_body: Optional[str] = None
):
"""Record detailed stage failure information"""
failure_detail = StageFailureDetail(
stage=stage,
backend_url=backend_url,
backend_type=backend_type,
job_id=job_id,
error_message=error_message,
error_type=error_type,
http_status=http_status,
response_body=response_body,
submitted_at=datetime.utcnow() if stage == "tts" else None
)
# Store failure detail in the appropriate stage
if stage == "tts":
analytics.tts_failure_detail = failure_detail
analytics.tts_error = error_message
analytics.tts_status = "failed"
elif stage == "align":
analytics.align_failure_detail = failure_detail
analytics.align_error = error_message
analytics.align_status = "failed"
elif stage == "video":
analytics.video_failure_detail = failure_detail
analytics.video_error = error_message
analytics.video_status = "failed"
# Update global failure stats
stage_failure_stats[stage][error_type] += 1
logger.error(
f"Pipeline {analytics.pipeline_id[:8]} {stage} failed on {backend_url} "
f"(job: {job_id}) - {error_type}: {error_message[:200]}"
)
def _get_analytics_summary() -> Dict:
"""Generate comprehensive analytics summary with backend breakdown"""
total_pipelines = len(analytics_storage)
if total_pipelines == 0:
return {
"total_pipelines": 0,
"message": "No analytics data available yet"
}
# Count by status
successful = sum(1 for a in analytics_storage.values() if a.final_status == "success")
failed = sum(1 for a in analytics_storage.values() if a.final_status == "failed")
cancelled = sum(1 for a in analytics_storage.values() if a.final_status == "cancelled")
pending = sum(1 for a in analytics_storage.values() if a.final_status == "pending")
# Count by user type
admin_users = sum(1 for a in analytics_storage.values() if a.is_admin)
normal_users = total_pipelines - admin_users
# Rate limit hits
rate_limited = sum(1 for a in analytics_storage.values() if a.rate_limited)
# Stage success rates
tts_success = sum(1 for a in analytics_storage.values() if a.tts_status == "done")
align_success = sum(1 for a in analytics_storage.values() if a.align_status == "done")
video_success = sum(1 for a in analytics_storage.values() if a.video_status == "done")
tts_failed = sum(1 for a in analytics_storage.values() if a.tts_status == "failed")
align_failed = sum(1 for a in analytics_storage.values() if a.align_status == "failed")
video_failed = sum(1 for a in analytics_storage.values() if a.video_status == "failed")
# Calculate average processing times
tts_times = []
for a in analytics_storage.values():
if a.tts_submitted_at and a.tts_completed_at:
duration = (a.tts_completed_at - a.tts_submitted_at).total_seconds()
tts_times.append(duration)
align_times = []
for a in analytics_storage.values():
if a.align_submitted_at and a.align_completed_at:
duration = (a.align_completed_at - a.align_submitted_at).total_seconds()
align_times.append(duration)
video_times = []
for a in analytics_storage.values():
if a.video_submitted_at and a.video_completed_at:
duration = (a.video_completed_at - a.video_submitted_at).total_seconds()
video_times.append(duration)
# Failure breakdown by stage and error type
failure_breakdown = {
"tts": dict(stage_failure_stats.get("tts", {})),
"align": dict(stage_failure_stats.get("align", {})),
"video": dict(stage_failure_stats.get("video", {})),
}
# Storage method stats
dataset_storage = sum(1 for a in analytics_storage.values() if a.video_storage_method == "dataset")
ffmpeg_fallback = sum(1 for a in analytics_storage.values() if a.video_storage_method == "ffmpeg_fallback")
# Backend usage statistics
backend_usage = defaultdict(int)
for a in analytics_storage.values():
if a.tts_backend:
backend_usage[a.tts_backend] += 1
if a.align_backend:
backend_usage[a.align_backend] += 1
if a.video_backend:
backend_usage[a.video_backend] += 1
# Backend failure rates
backend_failures = defaultdict(int)
backend_total_usage = defaultdict(int)
for a in analytics_storage.values():
if a.tts_backend:
backend_total_usage[a.tts_backend] += 1
if a.tts_status == "failed":
backend_failures[a.tts_backend] += 1
if a.align_backend:
backend_total_usage[a.align_backend] += 1
if a.align_status == "failed":
backend_failures[a.align_backend] += 1
if a.video_backend:
backend_total_usage[a.video_backend] += 1
if a.video_status == "failed":
backend_failures[a.video_backend] += 1
backend_stats = {}
for url in set(list(backend_total_usage.keys()) + list(backend_failures.keys())):
total = backend_total_usage.get(url, 0)
failed_count = backend_failures.get(url, 0)
backend_stats[url] = {
"total_uses": total,
"failures": failed_count,
"failure_rate": round(failed_count / total * 100, 1) if total > 0 else 0,
"backend_type": next(
(t for t, urls in ALL_SPACES.items() if url in urls),
"unknown"
)
}
return {
"total_pipelines": total_pipelines,
"successful": successful,
"failed": failed,
"cancelled": cancelled,
"pending": pending,
"success_rate": round(successful / total_pipelines * 100, 1) if total_pipelines > 0 else 0,
"users": {
"admin": admin_users,
"normal": normal_users,
"rate_limited": rate_limited,
},
"stage_success": {
"tts": {"success": tts_success, "failed": tts_failed, "rate": round(tts_success / (tts_success + tts_failed) * 100, 1) if (tts_success + tts_failed) > 0 else 0},
"align": {"success": align_success, "failed": align_failed, "rate": round(align_success / (align_success + align_failed) * 100, 1) if (align_success + align_failed) > 0 else 0},
"video": {"success": video_success, "failed": video_failed, "rate": round(video_success / (video_success + video_failed) * 100, 1) if (video_success + video_failed) > 0 else 0},
},
"avg_processing_time_seconds": {
"tts": round(sum(tts_times) / len(tts_times), 1) if tts_times else 0,
"align": round(sum(align_times) / len(align_times), 1) if align_times else 0,
"video": round(sum(video_times) / len(video_times), 1) if video_times else 0,
},
"failure_breakdown": failure_breakdown,
"video_storage": {
"dataset_primary": dataset_storage,
"ffmpeg_fallback": ffmpeg_fallback,
"fallback_rate": round(ffmpeg_fallback / (dataset_storage + ffmpeg_fallback) * 100, 1) if (dataset_storage + ffmpeg_fallback) > 0 else 0,
},
"backend_stats": backend_stats,
"time_range": {
"oldest": min((a.created_at for a in analytics_storage.values()), default=datetime.utcnow()).isoformat(),
"newest": max((a.created_at for a in analytics_storage.values()), default=datetime.utcnow()).isoformat(),
}
}
def _get_active_jobs() -> List[Dict]:
"""Get all currently running jobs with details"""
active_jobs = []
for pid, pipeline in pipelines.items():
running_stages = []
for stage_name in [Stage.TTS, Stage.ALIGN, Stage.VIDEO]:
s = pipeline["stages"][stage_name]
if s["status"] == StageStatus.RUNNING:
running_stages.append({
"stage": stage_name,
"backend_url": s.get("backend_url"),
"backend_job_id": s.get("backend_job_id"),
"submitted_at": s.get("submitted_at"),
"progress": s.get("progress", 0),
"message": s.get("message", ""),
})
if running_stages:
analytics = analytics_storage.get(pid)
active_jobs.append({
"pipeline_id": pid,
"created_at": pipeline["created_at"],
"running_stages": running_stages,
"user_ip": analytics.user_ip if analytics else "unknown",
"is_admin": analytics.is_admin if analytics else False,
})
return active_jobs
# =============================================================================
# RATE LIMIT CLEANUP LOOP
# =============================================================================
async def _rate_limit_cleanup_loop():
while True:
await asyncio.sleep(300)
cutoff = datetime.utcnow() - timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
cleaned_ips = 0
for ip in list(rate_limit_storage.keys()):
rate_limit_storage[ip] = [
ts for ts in rate_limit_storage[ip]
if ts > cutoff
]
if not rate_limit_storage[ip]:
del rate_limit_storage[ip]
cleaned_ips += 1
if cleaned_ips > 0:
logger.info(f"Rate limit cleanup: removed {cleaned_ips} expired IP entries")
# =============================================================================
# REQUEST / RESPONSE MODELS
# =============================================================================
class PipelineStartRequest(BaseModel):
text: str
voice: str = "male_high"
rate: float = 1.0
language: str = "English"
pass_number: int = 1
background: str = "mc1"
duration: Optional[float] = None
class RerunTTSRequest(BaseModel):
text: Optional[str] = None
voice: Optional[str] = None
rate: Optional[float] = None
class AlignSubmitRequest(BaseModel):
language: Optional[str] = None
pass_number: Optional[int] = None
aligner_type: Optional[str] = None
class VideoSubmitRequest(BaseModel):
subtitles_ass: str
background: Optional[str] = None
duration: Optional[float] = None
# =============================================================================
# FASTAPI APP
# =============================================================================
app = FastAPI(
title="ArchNemix Controller v1",
version="1.8.0",
docs_url="/docs",
redoc_url=None,
)
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["GET", "POST", "DELETE", "OPTIONS"],
allow_headers=["*"],
expose_headers=["X-Pipeline-ID", "X-Session-ID"],
)
@app.middleware("http")
async def enforce_cors_origin(request: Request, call_next):
"""
Extra security: Reject requests from non-allowed origins with clear error.
This complements CORS middleware for better security.
"""
origin = request.headers.get("origin")
# Allow requests with no origin (same-origin, API calls from servers)
if not origin:
response = await call_next(request)
return response
# Check if origin is in allowed list
is_allowed = origin in ALLOWED_ORIGINS
# Allow localhost development ports (any port)
if not is_allowed:
is_allowed = any(
origin.startswith(f"http://localhost:3000") or
origin.startswith(f"http://127.0.0.1:3000")
)
if not is_allowed:
logger.warning(f"[CORS SECURITY] Rejected request from unauthorized origin: {origin}")
return JSONResponse(
status_code=403,
content={
"error": "cors_origin_not_allowed",
"message": f"Origin '{origin}' is not allowed to access this service.",
"allowed_origins": ["shortgenx.pages.dev", "localhost:3000"]
}
)
response = await call_next(request)
return response
# =============================================================================
# HTTP CLIENT
# =============================================================================
_http: Optional[httpx.AsyncClient] = None
def http() -> httpx.AsyncClient:
return _http
# =============================================================================
# DATASET STORE
# =============================================================================
_store: Optional[DatasetStore] = None
def store() -> DatasetStore:
return _store
# =============================================================================
# SAFE JSON HELPER
# =============================================================================
def _safe_json(r: httpx.Response) -> Any:
try:
return r.json()
except Exception:
return {
"error": "backend_error",
"error_code": "EMPTY_RESPONSE",
"detail": r.text or f"Backend returned HTTP {r.status_code} with no body.",
}
# =============================================================================
# STATUS CACHE (keep all existing functions)
# =============================================================================
async def _check_one(url: str, stype: str) -> Dict[str, Any]:
dead = {
"url": url, "type": stype,
"online": False, "worker_ready": False,
"can_submit": False, "slot_available": False, "queue_full": True,
"running": 0, "waiting": 0,
"checked_at": datetime.utcnow().isoformat(),
}
try:
if stype in ("mfa", "qwen"):
r = await http().get(f"{url}/queue/status", timeout=5.0)
else:
r = await http().get(f"{url}/queue", timeout=5.0)
if r.status_code != 200:
return dead
d = r.json()
running = int(d.get("running", 0))
waiting = int(d.get("waiting", 0))
total = running + waiting
can_submit = bool(d.get("can_submit", total < 2))
slot_available = bool(d.get("slot_available", running == 0))
queue_full = bool(d.get("queue_full", total >= 2))
worker_ready = bool(d.get("worker_ready", True))
return {
"url": url, "type": stype, "online": True,
"worker_ready": worker_ready,
"can_submit": can_submit,
"slot_available": slot_available,
"queue_full": queue_full,
"running": running, "waiting": waiting,
"checked_at": datetime.utcnow().isoformat(),
}
except Exception as e:
logger.debug(f"Status check failed {url}: {e}")
return dead
async def _status_loop():
while True:
tasks = [
_check_one(url, stype)
for stype, urls in ALL_SPACES.items()
for url in urls
]
results = await asyncio.gather(*tasks, return_exceptions=True)
for r in results:
if isinstance(r, dict):
existing = status_cache.get(r["url"], {})
r["_reserved"] = existing.get("_reserved", 0)
status_cache[r["url"]] = r
await asyncio.sleep(STATUS_POLL_EVERY)
def _status_summary() -> Dict[str, Any]:
"""Enhanced status summary with queue info and separate MFA/Qwen stats"""
out: Dict[str, Any] = {}
for stype, urls in ALL_SPACES.items():
spaces = []
free = busy = 0
total_slots = 0
total_queue = 0
for url in urls:
c = status_cache.get(url, {
"online": False,
"can_submit": False,
"worker_ready": False,
"running": 0,
"waiting": 0,
})
running = c.get("running", 0)
waiting = c.get("waiting", 0)
depth = 2
available_slots = max(0, depth - (running + waiting))
queue_available = waiting < 1
spaces.append({
"url": url,
"online": c.get("online", False),
"can_submit": c.get("can_submit", False),
"worker_ready": c.get("worker_ready", False),
"running": running,
"waiting": waiting,
"available_slots": available_slots,
"queue_available": queue_available,
})
if c.get("can_submit"):
free += 1
total_slots += available_slots
else:
busy += 1
total_slots += available_slots
total_queue += waiting
out[stype] = {
"free": free,
"busy": busy,
"total": len(urls),
"all_busy": free == 0,
"total_slots": total_slots,
"total_queue": total_queue,
"spaces": spaces,
}
mfa_free = out["mfa"]["free"]
mfa_total = out["mfa"]["total"]
mfa_slots = out["mfa"]["total_slots"]
mfa_queue = out["mfa"]["total_queue"]
qwen_free = out["qwen"]["free"]
qwen_total = out["qwen"]["total"]
qwen_slots = out["qwen"]["total_slots"]
qwen_queue = out["qwen"]["total_queue"]
out["mfa_detailed"] = {
"free": mfa_free,
"busy": mfa_total - mfa_free,
"total": mfa_total,
"all_busy": mfa_free == 0,
"total_slots": mfa_slots,
"total_queue": mfa_queue,
}
out["qwen_detailed"] = {
"free": qwen_free,
"busy": qwen_total - qwen_free,
"total": qwen_total,
"all_busy": qwen_free == 0,
"total_slots": qwen_slots,
"total_queue": qwen_queue,
}
aligner_free = mfa_free + qwen_free
aligner_total = mfa_total + qwen_total
aligner_slots = mfa_slots + qwen_slots
aligner_queue = mfa_queue + qwen_queue
out["aligners"] = {
"free": aligner_free,
"busy": aligner_total - aligner_free,
"total": aligner_total,
"all_busy": aligner_free == 0,
"total_slots": aligner_slots,
"total_queue": aligner_queue,
}
return out
# =============================================================================
# SPACE PICKER (keep existing)
# =============================================================================
def _release_reservation(url: str):
if url and url in status_cache:
c = status_cache[url]
c["_reserved"] = max(0, c.get("_reserved", 1) - 1)
async def _pick(stype: str) -> Optional[str]:
urls = ALL_SPACES[stype]
best_url = None
best_load = float("inf")
depth = FFMPEG_QUEUE_DEPTH
for url in urls:
c = status_cache.get(url, {})
if c and not c.get("online", True):
continue
running = c.get("running", 0)
waiting = c.get("waiting", 0)
reserved = c.get("_reserved", 0)
load = running + waiting + reserved
if load >= depth:
continue
if load < best_load:
best_load = load
best_url = url
if best_url is None:
results = await asyncio.gather(*[_check_one(url, stype) for url in urls])
for r in results:
if isinstance(r, dict):
status_cache[r["url"]] = r
for url in urls:
c = status_cache.get(url, {})
if not c.get("online"):
continue
running = c.get("running", 0)
waiting = c.get("waiting", 0)
reserved = c.get("_reserved", 0)
load = running + waiting + reserved
if load >= depth:
continue
if load < best_load:
best_load = load
best_url = url
if best_url and best_url in status_cache:
c = status_cache[best_url]
c["_reserved"] = c.get("_reserved", 0) + 1
total = c.get("running", 0) + c.get("waiting", 0) + c["_reserved"]
c["can_submit"] = total < depth
c["queue_full"] = total >= depth
c["slot_available"] = c.get("running", 0) == 0
return best_url
async def _pick_aligner() -> Tuple[Optional[str], Optional[str]]:
for stype in ("mfa", "qwen"):
url = await _pick(stype)
if url:
return url, stype
return None, None
# =============================================================================
# PIPELINE HELPERS
# =============================================================================
def _new_pipeline(config: PipelineStartRequest) -> Dict[str, Any]:
pid = uuid.uuid4().hex
return {
"pipeline_id": pid,
"created_at": datetime.utcnow().isoformat(),
"last_active": datetime.utcnow().isoformat(),
"finalized": False,
"config": {
"text": config.text,
"voice": config.voice,
"rate": config.rate,
"language": config.language,
"pass_number": config.pass_number,
"background": config.background,
"duration": config.duration,
"aligner_type": "mfa",
},
"stages": {
Stage.TTS: _blank_stage(),
Stage.ALIGN: _blank_stage(),
Stage.VIDEO: _blank_stage(),
},
"assets": {
"audio_url": None,
"timestamps_url": None,
"video_url": None,
"video_download_url": None,
"video_stream_url": None,
},
}
def _blank_stage() -> Dict[str, Any]:
return {
"status": StageStatus.IDLE,
"backend_url": None,
"backend_job_id": None,
"backend_type": None,
"submitted_at": None,
"completed_at": None,
"error": None,
"progress": 0,
"chunks_done": 0,
"chunks_total": 0,
"elapsed_s": None,
"estimated_remaining_s": None,
"message": "",
"encode_stats": None,
}
def _touch(pid: str) -> Optional[Dict]:
p = pipelines.get(pid)
if p:
p["last_active"] = datetime.utcnow().isoformat()
return p
def _pipeline_or_404(pid: str) -> Dict:
p = _touch(pid)
if not p:
raise HTTPException(404, {
"error": "pipeline_not_found",
"detail": "Pipeline not found or expired. Start a new one.",
})
return p
def _client_id(pid: str) -> str:
return f"ctrl_{pid[:10]}"
# =============================================================================
# BACKEND JOB POLLER (with enhanced error tracking)
# =============================================================================
async def _poll_backend_stage(p: Dict, stage: str) -> None:
s = p["stages"][stage]
if s["status"] != StageStatus.RUNNING:
return
url = s["backend_url"]
jid = s["backend_job_id"]
pid = p["pipeline_id"]
analytics = analytics_storage.get(pid)
try:
r = await http().get(
f"{url}/job/{jid}",
params={"slim": "true"} if stage != Stage.VIDEO else {},
timeout=HTTP_TIMEOUT,
)
except httpx.TimeoutException as e:
logger.warning(f"Poll timeout {pid}/{stage}: {e}")
if analytics:
_record_stage_failure(
analytics, stage, url, s["backend_type"], jid,
f"Polling timeout after {HTTP_TIMEOUT}s",
"poll_timeout",
http_status=None
)
s["status"] = StageStatus.FAILED
s["error"] = f"Polling timeout: {e}"
return
except Exception as e:
logger.warning(f"Poll error {pid}/{stage}: {e}")
if analytics:
_record_stage_failure(
analytics, stage, url, s["backend_type"], jid,
str(e), "poll_error"
)
return
if r.status_code == 404:
s["status"] = StageStatus.FAILED
s["error"] = "Job expired on backend (5 min TTL). Please re-run this step."
if analytics:
_record_stage_failure(
analytics, stage, url, s["backend_type"], jid,
"Job expired on backend (5 min TTL)", "job_expired",
http_status=404
)
return
data = _safe_json(r)
bk_status = data.get("status", "unknown")
if bk_status == "completed":
await _finalise_stage(p, stage, url, jid, data)
elif bk_status in ("failed", "abandoned"):
error_msg = data.get("error", bk_status)
s["status"] = StageStatus.FAILED
s["error"] = error_msg
s["completed_at"] = datetime.utcnow().isoformat()
if analytics:
_record_stage_failure(
analytics, stage, url, s["backend_type"], jid,
error_msg, "backend_job_failed",
http_status=r.status_code,
response_body=str(data)[:500]
)
elif bk_status in ("running", "queued", "processing"):
s["progress"] = data.get("progress", s.get("progress", 0))
s["chunks_done"] = data.get("chunks_done", s.get("chunks_done", 0))
s["chunks_total"] = data.get("chunks_total", s.get("chunks_total", 0))
s["elapsed_s"] = data.get("elapsed_s", s.get("elapsed_s"))
s["estimated_remaining_s"] = data.get("estimated_remaining_s", s.get("estimated_remaining_s"))
s["message"] = data.get("message", s.get("message", ""))
if "encode_stats" in data:
s["encode_stats"] = data["encode_stats"]
async def _finalise_stage(p: Dict, stage: str, url: str, jid: str, slim_data: Dict):
pid = p["pipeline_id"]
s = p["stages"][stage]
analytics = analytics_storage.get(pid)
try:
if stage == Stage.TTS:
r = await http().get(f"{url}/job/{jid}", params={"slim": "false"}, timeout=30.0)
full = _safe_json(r)
audio_b64 = full.get("audio_base64", "")
timestamps = full.get("word_timestamps", [])
import base64, json
wav_bytes = base64.b64decode(audio_b64)
audio_url = await store().save(pid, "audio.wav", wav_bytes, content_type="audio/wav")
ts_bytes = json.dumps(timestamps).encode()
ts_url = await store().save(pid, "tts_timestamps.json", ts_bytes, content_type="application/json")
meta = {
"pipeline_id": pid,
"created_at": datetime.utcnow().isoformat() + "Z",
}
await store().save(pid, "meta.json", json.dumps(meta).encode(), content_type="application/json")
p["assets"]["audio_url"] = audio_url
p["assets"]["timestamps_url"] = ts_url
if analytics:
analytics.tts_completed_at = datetime.utcnow()
analytics.tts_status = "done"
analytics.tts_error = None
logger.info(f"Pipeline {pid[:8]} TTS done β {audio_url}")
elif stage == Stage.ALIGN:
r = await http().get(f"{url}/job/{jid}", params={"slim": "false"}, timeout=15.0)
full = _safe_json(r)
import json
timestamps = full.get("word_timestamps", [])
ts_bytes = json.dumps(timestamps).encode()
ts_url = await store().save(pid, "align_timestamps.json", ts_bytes, content_type="application/json")
p["assets"]["timestamps_url"] = ts_url
if analytics:
analytics.align_completed_at = datetime.utcnow()
analytics.align_status = "done"
analytics.align_error = None
logger.info(f"Pipeline {pid[:8]} Align done β {ts_url}")
elif stage == Stage.VIDEO:
raw_download = slim_data.get("download_url", f"/download/{jid}")
raw_stream = slim_data.get("stream_url", f"/stream/{jid}")
ffmpeg_download_url = (
raw_download if raw_download.startswith("http")
else f"{url}{raw_download}"
)
ffmpeg_stream_url = (
raw_stream if raw_stream.startswith("http")
else f"{url}{raw_stream}"
)
dataset_success = False
video_dataset_url = None
logger.info(f"Pipeline {pid[:8]}: Attempting to upload video to HF dataset...")
try:
headers = {"X-APP-KEY": APP_KEY} if APP_KEY else {}
video_response = await http().get(
ffmpeg_download_url,
headers=headers,
timeout=120.0,
follow_redirects=True
)
video_response.raise_for_status()
video_bytes = video_response.content
video_dataset_url = await store().save(
pid,
"video.mp4",
video_bytes,
content_type="video/mp4"
)
dataset_success = True
size_mb = len(video_bytes) / 1024 / 1024
logger.info(f"Pipeline {pid[:8]} Video uploaded to dataset successfully ({size_mb:.1f}MB)")
except Exception as dataset_err:
logger.warning(f"Pipeline {pid[:8]}: Dataset upload failed: {dataset_err}. Falling back to FFmpeg URLs.")
dataset_success = False
if dataset_success and video_dataset_url:
p["assets"]["video_url"] = video_dataset_url
p["assets"]["video_download_url"] = video_dataset_url
p["assets"]["video_stream_url"] = video_dataset_url
if analytics:
analytics.video_storage_method = "dataset"
else:
p["assets"]["video_url"] = None
p["assets"]["video_download_url"] = ffmpeg_download_url
p["assets"]["video_stream_url"] = ffmpeg_stream_url
if analytics:
analytics.video_storage_method = "ffmpeg_fallback"
if analytics:
analytics.video_completed_at = datetime.utcnow()
analytics.video_status = "done"
analytics.video_error = None
analytics.final_status = "success"
analytics.completed_at = datetime.utcnow()
s["status"] = StageStatus.DONE
s["completed_at"] = datetime.utcnow().isoformat()
except httpx.TimeoutException as e:
logger.exception(f"Finalise timeout {pid}/{stage}")
s["status"] = StageStatus.FAILED
s["error"] = f"Timeout during finalization: {e}"
if analytics:
_record_stage_failure(
analytics, stage, url, s["backend_type"], jid,
str(e), "finalize_timeout",
http_status=None
)
except Exception as e:
logger.exception(f"Finalise failed {pid}/{stage}")
s["status"] = StageStatus.FAILED
s["error"] = f"Failed to save result: {e}"
if analytics:
_record_stage_failure(
analytics, stage, url, s["backend_type"], jid,
str(e), "save_failed"
)
# =============================================================================
# STAGE SUBMISSION HELPERS (with enhanced error tracking)
# =============================================================================
async def _submit_tts(p: Dict, text: str, voice: str, rate: float) -> Optional[JSONResponse]:
pid = p["pipeline_id"]
analytics = analytics_storage.get(pid)
backend_url = await _pick("tts")
if not backend_url:
if analytics:
_record_stage_failure(
analytics, "tts", "N/A", "tts", "N/A",
"All TTS spaces are busy", "all_spaces_busy"
)
return JSONResponse(status_code=503, content={
"error": "all_tts_busy",
"detail": "All 4 TTS spaces are currently busy. Try again in ~20s.",
"retry_after": 20,
})
cid = _client_id(pid)
try:
r = await http().post(
f"{backend_url}/tts",
json={"text": text, "voice": voice, "rate": rate, "client_id": cid},
timeout=HTTP_TIMEOUT,
)
except httpx.TimeoutException as e:
if analytics:
_record_stage_failure(
analytics, "tts", backend_url, "tts", "N/A",
f"Submission timeout: {e}", "submission_timeout"
)
raise HTTPException(503, {"error": "backend_timeout", "detail": str(e)})
except httpx.RequestError as e:
if analytics:
_record_stage_failure(
analytics, "tts", backend_url, "tts", "N/A",
str(e), "request_error"
)
raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})
if r.status_code == 503:
if analytics:
_record_stage_failure(
analytics, "tts", backend_url, "tts", "N/A",
"Space became busy just before submission", "space_busy",
http_status=503
)
return JSONResponse(status_code=503, content={
"error": "all_tts_busy",
"detail": "TTS space became busy just before submission. Retry.",
"retry_after": 15,
})
if r.status_code != 200:
error_data = _safe_json(r)
if analytics:
_record_stage_failure(
analytics, "tts", backend_url, "tts", "N/A",
str(error_data), "backend_error",
http_status=r.status_code,
response_body=str(error_data)[:500]
)
raise HTTPException(r.status_code, error_data)
data = r.json()
jid = data["job_id"]
s = p["stages"][Stage.TTS]
s["status"] = StageStatus.RUNNING
s["backend_url"] = backend_url
s["backend_job_id"] = jid
s["backend_type"] = "tts"
s["submitted_at"] = datetime.utcnow().isoformat()
s["error"] = None
if analytics:
analytics.tts_submitted_at = datetime.utcnow()
analytics.tts_status = "running"
analytics.tts_backend = backend_url
analytics.tts_backend_type = "tts"
analytics.tts_job_id = jid
return None
async def _submit_align(
p: Dict,
language: str,
pass_number: int,
aligner_type: str = "mfa"
) -> str:
pid = p["pipeline_id"]
analytics = analytics_storage.get(pid)
audio_url = p["assets"].get("audio_url")
if not audio_url:
if analytics:
_record_stage_failure(
analytics, "align", "N/A", aligner_type, "N/A",
"TTS stage not completed", "tts_not_done"
)
raise HTTPException(400, {
"error": "no_audio",
"detail": "TTS stage has not completed yet. Complete TTS first.",
})
try:
headers = {}
if HF_TOKEN and "huggingface.co" in audio_url:
headers["Authorization"] = f"Bearer {HF_TOKEN}"
r = await http().get(audio_url, timeout=30.0, follow_redirects=True, headers=headers)
r.raise_for_status()
import base64
audio_b64 = base64.b64encode(r.content).decode()
except HTTPException:
raise
except Exception as e:
if analytics:
_record_stage_failure(
analytics, "align", "N/A", aligner_type, "N/A",
f"Failed to fetch audio: {e}", "audio_fetch_failed"
)
raise HTTPException(503, {"error": "audio_fetch_failed", "detail": str(e)})
backend_url = None
backend_type = None
if aligner_type == "qwen":
backend_url = await _pick("qwen")
if backend_url:
backend_type = "qwen"
else:
backend_url = await _pick("mfa")
if backend_url:
backend_type = "mfa"
logger.info(f"Pipeline {pid[:8]}: Qwen requested but full, using MFA fallback")
else:
backend_url = await _pick("mfa")
if backend_url:
backend_type = "mfa"
else:
backend_url = await _pick("qwen")
if backend_url:
backend_type = "qwen"
logger.info(f"Pipeline {pid[:8]}: MFA requested but full, using Qwen fallback")
if not backend_url:
if analytics:
_record_stage_failure(
analytics, "align", "N/A", aligner_type, "N/A",
"All aligner spaces are busy", "all_spaces_busy"
)
raise HTTPException(503, {
"error": "all_aligners_busy",
"detail": "All MFA and Qwen spaces are currently busy. Try again in ~30s.",
"retry_after": 30,
})
cid = _client_id(pid)
try:
r = await http().post(
f"{backend_url}/align",
json={
"audio_base64": audio_b64,
"text": p["config"]["text"],
"language": language,
"pass_number": pass_number,
"client_id": cid,
},
timeout=HTTP_TIMEOUT,
)
except httpx.TimeoutException as e:
if analytics:
_record_stage_failure(
analytics, "align", backend_url, backend_type, "N/A",
f"Submission timeout: {e}", "submission_timeout"
)
raise HTTPException(503, {"error": "backend_timeout", "detail": str(e)})
except httpx.RequestError as e:
if analytics:
_record_stage_failure(
analytics, "align", backend_url, backend_type, "N/A",
str(e), "request_error"
)
raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})
if r.status_code == 503:
if analytics:
_record_stage_failure(
analytics, "align", backend_url, backend_type, "N/A",
"Space became busy just before submission", "space_busy",
http_status=503
)
raise HTTPException(503, {
"error": "aligner_busy",
"detail": "Aligner became busy just before submission. Retry.",
"retry_after": 20,
})
if r.status_code != 200:
error_data = _safe_json(r)
if analytics:
_record_stage_failure(
analytics, "align", backend_url, backend_type, "N/A",
str(error_data), "backend_error",
http_status=r.status_code,
response_body=str(error_data)[:500]
)
raise HTTPException(r.status_code, error_data)
data = r.json()
jid = data["job_id"]
s = p["stages"][Stage.ALIGN]
s["status"] = StageStatus.RUNNING
s["backend_url"] = backend_url
s["backend_job_id"] = jid
s["backend_type"] = backend_type
s["submitted_at"] = datetime.utcnow().isoformat()
s["error"] = None
if analytics:
analytics.align_submitted_at = datetime.utcnow()
analytics.align_status = "running"
analytics.align_backend = backend_url
analytics.align_backend_type = backend_type
analytics.align_job_id = jid
logger.info(f"Pipeline {pid[:8]}: Alignment submitted to {backend_type.upper()} ({backend_url})")
return backend_type
async def _submit_video(p: Dict, subtitles_ass: str, background: str, duration: Optional[float]) -> Optional[JSONResponse]:
pid = p["pipeline_id"]
analytics = analytics_storage.get(pid)
if not APP_KEY:
if analytics:
_record_stage_failure(
analytics, "video", "N/A", "ffmpeg", "N/A",
"APP_KEY not configured", "config_error"
)
raise HTTPException(500, {
"error": "controller_misconfigured",
"detail": "APP_KEY secret not set on controller space.",
})
audio_url = p["assets"].get("audio_url")
if not audio_url:
if analytics:
_record_stage_failure(
analytics, "video", "N/A", "ffmpeg", "N/A",
"TTS not completed", "tts_not_done"
)
raise HTTPException(400, {"error": "no_audio", "detail": "TTS not completed yet."})
try:
headers = {}
if HF_TOKEN and "huggingface.co" in audio_url:
headers["Authorization"] = f"Bearer {HF_TOKEN}"
r = await http().get(audio_url, timeout=30.0, follow_redirects=True, headers=headers)
r.raise_for_status()
import base64
audio_b64 = base64.b64encode(r.content).decode()
except HTTPException:
raise
except Exception as e:
if analytics:
_record_stage_failure(
analytics, "video", "N/A", "ffmpeg", "N/A",
f"Failed to fetch audio: {e}", "audio_fetch_failed"
)
raise HTTPException(503, {"error": "audio_fetch_failed", "detail": str(e)})
backend_url = await _pick("ffmpeg")
if not backend_url:
if analytics:
_record_stage_failure(
analytics, "video", "N/A", "ffmpeg", "N/A",
"All video spaces are busy", "all_spaces_busy"
)
return JSONResponse(status_code=503, content={
"error": "all_video_busy",
"detail": "All video spaces are busy. Try again in ~2 min.",
"retry_after": 120,
})
cid = _client_id(pid)
try:
r = await http().post(
f"{backend_url}/generate",
json={
"audio_base64": audio_b64,
"subtitles_ass": subtitles_ass,
"background": background,
"duration": duration,
},
headers={"X-APP-KEY": APP_KEY, "X-Client-ID": cid},
timeout=30.0,
)
except httpx.TimeoutException as e:
if analytics:
_record_stage_failure(
analytics, "video", backend_url, "ffmpeg", "N/A",
f"Submission timeout: {e}", "submission_timeout"
)
raise HTTPException(503, {"error": "backend_timeout", "detail": str(e)})
except httpx.RequestError as e:
if analytics:
_record_stage_failure(
analytics, "video", backend_url, "ffmpeg", "N/A",
str(e), "request_error"
)
raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})
if r.status_code == 503:
if analytics:
_record_stage_failure(
analytics, "video", backend_url, "ffmpeg", "N/A",
"Space became busy just before submission", "space_busy",
http_status=503
)
return JSONResponse(status_code=503, content={
"error": "all_video_busy",
"detail": "Video space became busy just before submission. Retry.",
"retry_after": 60,
})
if r.status_code not in (200, 201):
error_data = _safe_json(r)
if analytics:
_record_stage_failure(
analytics, "video", backend_url, "ffmpeg", "N/A",
str(error_data), "backend_error",
http_status=r.status_code,
response_body=str(error_data)[:500]
)
raise HTTPException(r.status_code, error_data)
data = r.json()
jid = data["job_id"]
s = p["stages"][Stage.VIDEO]
s["status"] = StageStatus.RUNNING
s["backend_url"] = backend_url
s["backend_job_id"] = jid
s["backend_type"] = "ffmpeg"
s["submitted_at"] = datetime.utcnow().isoformat()
s["error"] = None
if analytics:
analytics.video_submitted_at = datetime.utcnow()
analytics.video_status = "running"
analytics.video_backend = backend_url
analytics.video_backend_type = "ffmpeg"
analytics.video_job_id = jid
return None
# =============================================================================
# PIPELINE VIEW HELPER
# =============================================================================
def _pipeline_view(p: Dict) -> Dict:
stages = {}
for stage_name, s in p["stages"].items():
stage_out = {
"status": s["status"],
"submitted_at": s["submitted_at"],
"completed_at": s["completed_at"],
"error": s["error"],
}
if s["status"] == StageStatus.RUNNING:
stage_out["backend_url"] = s.get("backend_url")
stage_out["backend_job_id"] = s.get("backend_job_id")
stage_out["backend_type"] = s.get("backend_type")
stage_out["progress"] = s.get("progress", 0)
stage_out["chunks_done"] = s.get("chunks_done", 0)
stage_out["chunks_total"] = s.get("chunks_total", 0)
stage_out["elapsed_s"] = s.get("elapsed_s")
stage_out["estimated_remaining_s"] = s.get("estimated_remaining_s")
stage_out["message"] = s.get("message", "")
if s.get("encode_stats"):
stage_out["encode_stats"] = s["encode_stats"]
stages[stage_name] = stage_out
return {
"pipeline_id": p["pipeline_id"],
"created_at": p["created_at"],
"finalized": p.get("finalized", False),
"stages": stages,
"assets": {
"audio_url": p["assets"]["audio_url"],
"timestamps_url": p["assets"]["timestamps_url"],
"video_url": p["assets"]["video_url"],
"video_download_url": p["assets"].get("video_download_url"),
"video_stream_url": p["assets"].get("video_stream_url"),
},
"next_actions": _next_actions(p),
}
def _next_actions(p: Dict) -> list:
actions = []
tts = p["stages"][Stage.TTS]["status"]
align = p["stages"][Stage.ALIGN]["status"]
video = p["stages"][Stage.VIDEO]["status"]
if tts == StageStatus.DONE:
actions.append("rerun_tts")
if align in (StageStatus.IDLE, StageStatus.FAILED):
actions.append("submit_align")
if tts == StageStatus.FAILED:
actions.append("rerun_tts")
if align == StageStatus.DONE:
actions.append("rerun_align")
if video in (StageStatus.IDLE, StageStatus.FAILED):
actions.append("submit_video")
if align == StageStatus.FAILED:
actions.append("rerun_align")
if video == StageStatus.DONE:
actions.append("download_video")
if video == StageStatus.FAILED:
actions.append("rerun_video")
return actions
# =============================================================================
# SESSION CLEANUP
# =============================================================================
async def _cleanup_loop():
while True:
await asyncio.sleep(120)
cutoff = datetime.utcnow() - timedelta(seconds=SESSION_TTL)
expired = [
pid for pid, p in list(pipelines.items())
if datetime.fromisoformat(p["last_active"]) < cutoff
]
for pid in expired:
pipelines.pop(pid, None)
pipeline_heartbeats.pop(pid, None)
if expired:
logger.info(f"Purged {len(expired)} expired pipelines from memory.")
# =============================================================================
# DATASET HEALTH CHECK
# =============================================================================
async def _check_dataset_reachability(repo: str, name: str) -> bool:
"""Check if a dataset repository is reachable and writable."""
if not repo:
logger.warning(f"Dataset {name}: not configured (empty repo name)")
return False
try:
from huggingface_hub import HfApi
import io
api = HfApi(token=HF_TOKEN)
try:
info = api.repo_info(repo_id=repo, repo_type="dataset")
logger.info(f"Dataset {name} ({repo}): β readable - found {info.id}")
except Exception as e:
logger.error(f"Dataset {name} ({repo}): β NOT readable - {e}")
return False
test_path = "_health_check.txt"
test_data = b"health check"
try:
api.upload_file(
path_or_fileobj=io.BytesIO(test_data),
path_in_repo=test_path,
repo_id=repo,
repo_type="dataset",
commit_message="Health check (will be deleted)",
)
logger.info(f"Dataset {name} ({repo}): β writable - test upload succeeded")
try:
api.delete_file(
path_in_repo=test_path,
repo_id=repo,
repo_type="dataset",
commit_message="Health check cleanup",
)
logger.info(f"Dataset {name} ({repo}): β test file cleaned up")
except Exception as cleanup_err:
logger.warning(f"Dataset {name} ({repo}): test file cleanup failed - {cleanup_err}")
return True
except Exception as write_err:
logger.error(f"Dataset {name} ({repo}): β NOT writable - {write_err}")
return False
except Exception as e:
logger.error(f"Dataset {name} ({repo}): β health check failed - {e}")
return False
# =============================================================================
# FRONTEND HEARTBEAT WATCHDOG
# =============================================================================
async def _frontend_heartbeat_watchdog():
while True:
await asyncio.sleep(15)
now = datetime.utcnow()
for pid, p in list(pipelines.items()):
if p.get("finalized"):
continue
last_hb = pipeline_heartbeats.get(pid)
if last_hb is None:
last_hb = datetime.fromisoformat(p["created_at"])
silence = (now - last_hb).total_seconds()
if silence >= FRONTEND_HEARTBEAT_GRACE + 200:
logger.warning(f"Pipeline {pid[:8]} silent {silence:.0f}s β permanent abandon")
try:
await store().delete_pipeline(pid)
except Exception as e:
logger.error(f"Failed to delete dataset assets for {pid[:8]}: {e}")
pipelines.pop(pid, None)
pipeline_heartbeats.pop(pid, None)
continue
elif silence >= FRONTEND_HEARTBEAT_GRACE:
running_stage = next(
(name for name, s in p["stages"].items() if s["status"] == StageStatus.RUNNING),
None
)
if not running_stage:
continue
s = p["stages"][running_stage]
url = s.get("backend_url")
jid = s.get("backend_job_id")
backend_type = s.get("backend_type")
logger.warning(f"Pipeline {pid[:8]} silent {silence:.0f}s β cancelling {running_stage} job {jid}")
if url and jid:
try:
if backend_type == "ffmpeg":
await http().delete(f"{url}/job/{jid}", headers={"X-APP-KEY": APP_KEY}, timeout=10.0)
else:
await http().post(f"{url}/cancel/{jid}", json={"client_id": _client_id(pid)}, timeout=10.0)
logger.info(f"Cancelled {running_stage} job {jid} on {url}")
except Exception as e:
logger.warning(f"Cancel request failed for {pid[:8]}: {e}")
s["status"] = StageStatus.FAILED
s["error"] = "Cancelled β client disconnected"
# Update analytics
analytics = analytics_storage.get(pid)
if analytics:
_record_stage_failure(
analytics, running_stage, url or "N/A", backend_type or "unknown", jid or "N/A",
"Cancelled β client disconnected", "client_disconnected"
)
# =============================================================================
# STARTUP / SHUTDOWN
# =============================================================================
@app.on_event("startup")
async def startup():
global _http, _store
if ADMIN_KEY:
logger.info(f"β ADMIN_KEY configured (rate limit bypass active for key holders)")
else:
logger.info("βΉ ADMIN_KEY not configured (rate limiting active for all users)")
logger.info("=" * 80)
logger.info("DATASET REACHABILITY CHECK (at space build/startup)")
logger.info("=" * 80)
if HF_TOKEN:
logger.info(f"β HF_TOKEN: configured (length={len(HF_TOKEN)})")
else:
logger.error("β HF_TOKEN: NOT configured β datasets will not work!")
if HF_DATASET:
logger.info(f"β HF_DATASET (primary) configured: {HF_DATASET}")
dataset1_ok = await _check_dataset_reachability(HF_DATASET, "PRIMARY")
else:
logger.error("β HF_DATASET (primary): NOT configured β no primary dataset!")
dataset1_ok = False
if HF_DATASET_2:
logger.info(f"β HF_DATASET_2 (secondary) configured: {HF_DATASET_2}")
dataset2_ok = await _check_dataset_reachability(HF_DATASET_2, "SECONDARY")
else:
logger.warning("β HF_DATASET_2 (secondary): NOT configured (will run in single-dataset mode)")
dataset2_ok = False
logger.info("=" * 80)
logger.info("DATASET STATUS SUMMARY:")
logger.info("-" * 80)
logger.info(f"PRIMARY dataset ({HF_DATASET or 'NOT SET'}): {'β READY' if dataset1_ok else 'β UNAVAILABLE'}")
if HF_DATASET_2:
logger.info(f"SECONDARY dataset ({HF_DATASET_2}): {'β READY' if dataset2_ok else 'β UNAVAILABLE'}")
logger.info("-" * 80)
if dataset1_ok and dataset2_ok:
logger.info("MODE: β DUAL-DATASET β Both datasets are operational")
elif dataset1_ok:
logger.warning("MODE: β DUAL-DATASET (DEGRADED) β Only primary dataset is operational")
elif dataset2_ok:
logger.warning("MODE: β DUAL-DATASET (DEGRADED) β Only secondary dataset is operational")
else:
logger.error("MODE: β DUAL-DATASET (FAILED) β Neither dataset is operational!")
else:
logger.info("-" * 80)
logger.info("MODE: β SINGLE-DATASET β Only primary dataset configured")
logger.info("=" * 80)
logger.info("Initializing HTTP client and DatasetStore...")
_http = httpx.AsyncClient(timeout=HTTP_TIMEOUT)
_store = DatasetStore(hf_token=HF_TOKEN, dataset_repo=HF_DATASET, dataset_repo_2=HF_DATASET_2)
init_tasks = [
_check_one(url, stype)
for stype, urls in ALL_SPACES.items()
for url in urls
]
results = await asyncio.gather(*init_tasks, return_exceptions=True)
for r in results:
if isinstance(r, dict):
status_cache[r["url"]] = r
asyncio.create_task(_status_loop())
asyncio.create_task(_cleanup_loop())
asyncio.create_task(_frontend_heartbeat_watchdog())
asyncio.create_task(_rate_limit_cleanup_loop())
logger.info("=" * 80)
logger.info(f"RATE LIMITING: {RATE_LIMIT_MAX_PER_HOUR} pipelines per IP per {RATE_LIMIT_WINDOW_HOURS}h")
if ADMIN_KEY:
logger.info("ADMIN BYPASS: Active β admin key holders bypass rate limits")
logger.info("ANALYTICS v1.8: Enhanced tracking with exact backend URLs and failure details")
logger.info("=" * 80)
logger.info("ArchNemix Controller v1.8 ready (enhanced debugging + backend failure tracking).")
@app.on_event("shutdown")
async def shutdown():
if _http:
await _http.aclose()
# =============================================================================
# ENDPOINTS
# =============================================================================
@app.get("/")
async def root():
return {
"name": "ArchNemix Controller",
"version": "1.8.0",
"endpoints": {
"POST /pipeline/start": "Start new pipeline (rate limited: 10/hour per IP, admin key bypass available)",
"GET /pipeline/{id}": "Poll pipeline state + per-stage status",
"POST /pipeline/{id}/rerun/tts": "Re-run TTS only (new text/voice/rate optional)",
"POST /pipeline/{id}/align": "Submit alignment (uses completed TTS audio)",
"POST /pipeline/{id}/rerun/align": "Re-run alignment only",
"POST /pipeline/{id}/video": "Submit video (uses completed TTS audio + subtitles_ass from frontend)",
"POST /pipeline/{id}/rerun/video": "Re-run video only",
"POST /pipeline/{id}/finalize": "Mark pipeline complete β deletes dataset intermediates",
"GET /status": "Live slot availability for all spaces",
"GET /capacity": "Current pipeline capacity usage",
"POST /pipeline/{id}/heartbeat": "Keep pipeline alive (prevents auto-cancel)",
"POST /pipeline/{id}/cancel/{stage}": "Cancel a running stage",
"GET /debug/dataset-routing/{id}": "Debug dataset routing logic",
"GET /debug/rate-limit-status": "Check rate limit status for current IP",
# Admin endpoints (require X-Admin-Key header)
"GET /admin/analytics": "π Comprehensive analytics summary with backend stats",
"GET /admin/active-jobs": "π List all currently running jobs with details",
"GET /admin/failures": "β Detailed failure breakdown with exact backend URLs",
"GET /admin/rate-limit-status": "β±οΈ Rate limit status for all IPs",
"GET /admin/pipeline/{id}/analytics": "π Analytics for specific pipeline with failure details",
"GET /admin/clear-analytics": "ποΈ Clear all analytics data",
},
"rate_limit": f"{RATE_LIMIT_MAX_PER_HOUR} pipelines per {RATE_LIMIT_WINDOW_HOURS} hour(s) per IP",
"admin_bypass": bool(ADMIN_KEY),
"analytics_enabled": True,
"analytics_version": "1.8",
"video_storage": "Dataset first (permanent), fallback to FFmpeg /tmp URLs (1-hour TTL) if upload fails",
}
@app.post("/pipeline/start")
async def start_pipeline(req: PipelineStartRequest, request: Request):
client_ip = _get_client_ip(request)
is_admin = _is_admin_request(request)
anonymized_ip = _anonymize_ip(client_ip)
rate_limited = False
if not is_admin:
allowed, current_count, retry_after = _check_rate_limit(client_ip)
if not allowed:
rate_limited = True
logger.warning(f"Rate limit exceeded for IP {anonymized_ip}")
return JSONResponse(status_code=429, content={
"error": "rate_limit_exceeded",
"detail": f"You have reached the limit of {RATE_LIMIT_MAX_PER_HOUR} videos per hour.",
"retry_after": retry_after,
})
active_count = sum(
1 for p in pipelines.values()
if any(
p["stages"][s]["status"] == StageStatus.RUNNING
for s in (Stage.TTS, Stage.ALIGN, Stage.VIDEO)
)
)
if active_count >= 8:
return JSONResponse(status_code=503, content={
"error": "at_capacity",
"detail": "All slots are currently busy. Try again in ~2 minutes.",
"retry_after": 120,
})
p = _new_pipeline(req)
pid = p["pipeline_id"]
pipelines[pid] = p
analytics = JobAnalytics(
pipeline_id=pid,
created_at=datetime.utcnow(),
user_ip=anonymized_ip,
is_admin=is_admin,
rate_limited=rate_limited,
)
analytics_storage[pid] = analytics
if not is_admin and not rate_limited:
_record_request(client_ip)
err = await _submit_tts(p, req.text, req.voice, req.rate)
if err:
analytics.tts_status = "failed"
analytics.tts_error = "All TTS spaces busy at submission"
analytics.final_status = "failed"
analytics.completed_at = datetime.utcnow()
_record_stage_failure(
analytics, "tts", "N/A", "tts", "N/A",
"All TTS spaces busy at submission", "all_spaces_busy"
)
p["stages"][Stage.TTS]["status"] = StageStatus.FAILED
p["stages"][Stage.TTS]["error"] = "All TTS spaces busy at submission time."
return JSONResponse(
status_code=503,
content={
"pipeline_id": pid,
"error": "all_tts_busy",
"detail": "All TTS spaces busy at submission time.",
"retry_after": 20,
"message": f"Pipeline created but TTS could not start. Retry with POST /pipeline/{pid}/rerun/tts",
},
headers={"X-Pipeline-ID": pid},
)
logger.info(
f"Pipeline {pid[:8]} started β TTS job {p['stages'][Stage.TTS]['backend_job_id']} "
f"(user: {'admin' if is_admin else 'normal'}, ip: {anonymized_ip})"
)
return JSONResponse(
{
"pipeline_id": pid,
"status": "tts_running",
"poll_url": f"/pipeline/{pid}",
"message": "TTS job submitted. Poll /pipeline/{id} every 2s.",
},
headers={"X-Pipeline-ID": pid},
)
@app.get("/pipeline/{pipeline_id}")
async def get_pipeline(pipeline_id: str):
p = _pipeline_or_404(pipeline_id)
for stage in (Stage.TTS, Stage.ALIGN, Stage.VIDEO):
await _poll_backend_stage(p, stage)
return _pipeline_view(p)
@app.post("/pipeline/{pipeline_id}/rerun/tts")
async def rerun_tts(pipeline_id: str, req: RerunTTSRequest):
p = _pipeline_or_404(pipeline_id)
if p["stages"][Stage.TTS]["status"] == StageStatus.RUNNING:
raise HTTPException(400, {
"error": "tts_already_running",
"detail": "TTS is already running. Wait for it to complete or fail first.",
})
if req.text is not None: p["config"]["text"] = req.text
if req.voice is not None: p["config"]["voice"] = req.voice
if req.rate is not None: p["config"]["rate"] = req.rate
p["stages"][Stage.ALIGN] = _blank_stage()
p["stages"][Stage.VIDEO] = _blank_stage()
p["assets"]["timestamps_url"] = None
p["assets"]["video_url"] = None
p["assets"]["video_download_url"] = None
p["assets"]["video_stream_url"] = None
err = await _submit_tts(p, p["config"]["text"], p["config"]["voice"], p["config"]["rate"])
if err:
return err
return JSONResponse({
"pipeline_id": pipeline_id,
"status": "tts_running",
"message": "TTS re-submitted. Poll /pipeline/{id} every 2s.",
})
@app.post("/pipeline/{pipeline_id}/align", response_model=None)
async def submit_align(pipeline_id: str, req: AlignSubmitRequest):
p = _pipeline_or_404(pipeline_id)
if p["stages"][Stage.TTS]["status"] != StageStatus.DONE:
raise HTTPException(400, {
"error": "tts_not_done",
"detail": "TTS must complete successfully before alignment.",
})
if p["stages"][Stage.ALIGN]["status"] == StageStatus.RUNNING:
raise HTTPException(400, {
"error": "align_already_running",
"detail": "Alignment is already running.",
})
language = req.language or p["config"]["language"]
pass_number = req.pass_number or p["config"]["pass_number"]
aligner_type = req.aligner_type or p["config"].get("aligner_type", "mfa")
p["config"]["aligner_type"] = aligner_type
backend_type = await _submit_align(p, language, pass_number, aligner_type)
return JSONResponse({
"pipeline_id": pipeline_id,
"status": "align_running",
"aligner_used": backend_type,
"message": f"{backend_type.upper()} alignment submitted. Poll /pipeline/{{id}} every 2s.",
})
@app.post("/pipeline/{pipeline_id}/rerun/align", response_model=None)
async def rerun_align(pipeline_id: str, req: AlignSubmitRequest):
p = _pipeline_or_404(pipeline_id)
if p["stages"][Stage.TTS]["status"] != StageStatus.DONE:
raise HTTPException(400, {"error": "tts_not_done", "detail": "TTS must be done first."})
if p["stages"][Stage.ALIGN]["status"] == StageStatus.RUNNING:
raise HTTPException(400, {"error": "align_already_running", "detail": "Alignment is already running."})
if req.language is not None: p["config"]["language"] = req.language
if req.pass_number is not None: p["config"]["pass_number"] = req.pass_number
if req.aligner_type is not None: p["config"]["aligner_type"] = req.aligner_type
p["stages"][Stage.VIDEO] = _blank_stage()
p["assets"]["video_url"] = None
p["assets"]["video_download_url"] = None
p["assets"]["video_stream_url"] = None
aligner_type = p["config"].get("aligner_type", "mfa")
backend_type = await _submit_align(p, p["config"]["language"], p["config"]["pass_number"], aligner_type)
return JSONResponse({
"pipeline_id": pipeline_id,
"status": "align_running",
"aligner_used": backend_type,
"message": f"{backend_type.upper()} alignment re-submitted. Poll /pipeline/{{id}} every 2s.",
})
@app.post("/pipeline/{pipeline_id}/video")
async def submit_video(pipeline_id: str, req: VideoSubmitRequest):
p = _pipeline_or_404(pipeline_id)
if p["stages"][Stage.TTS]["status"] != StageStatus.DONE:
raise HTTPException(400, {"error": "tts_not_done", "detail": "TTS must be done first."})
if p["stages"][Stage.VIDEO]["status"] == StageStatus.RUNNING:
raise HTTPException(400, {"error": "video_already_running", "detail": "Video is already running."})
background = req.background or p["config"]["background"]
duration = req.duration or p["config"]["duration"]
err = await _submit_video(p, req.subtitles_ass, background, duration)
if err:
return err
return JSONResponse({
"pipeline_id": pipeline_id,
"status": "video_running",
"message": "Video job submitted. Poll /pipeline/{id} every 5s.",
})
@app.post("/pipeline/{pipeline_id}/rerun/video")
async def rerun_video(pipeline_id: str, req: VideoSubmitRequest):
p = _pipeline_or_404(pipeline_id)
if p["stages"][Stage.TTS]["status"] != StageStatus.DONE:
raise HTTPException(400, {"error": "tts_not_done", "detail": "TTS must be done first."})
if p["stages"][Stage.VIDEO]["status"] == StageStatus.RUNNING:
raise HTTPException(400, {"error": "video_already_running", "detail": "Video is already running."})
if req.background is not None: p["config"]["background"] = req.background
if req.duration is not None: p["config"]["duration"] = req.duration
p["assets"]["video_url"] = None
p["assets"]["video_download_url"] = None
p["assets"]["video_stream_url"] = None
err = await _submit_video(p, req.subtitles_ass, p["config"]["background"], p["config"]["duration"])
if err:
return err
return JSONResponse({
"pipeline_id": pipeline_id,
"status": "video_running",
"message": "Video re-submitted. Poll /pipeline/{id} every 5s.",
})
@app.post("/pipeline/{pipeline_id}/finalize")
async def finalize_pipeline(pipeline_id: str):
p = pipelines.get(pipeline_id)
if not p:
return {"ok": True, "pipeline_id": pipeline_id, "note": "pipeline_not_in_memory"}
if p.get("finalized"):
return {"ok": True, "pipeline_id": pipeline_id, "note": "already_finalized"}
if p["stages"][Stage.VIDEO]["status"] != StageStatus.DONE:
raise HTTPException(400, {
"error": "video_not_done",
"detail": "Cannot finalize a pipeline whose video stage has not completed.",
})
p["finalized"] = True
pipeline_heartbeats.pop(pipeline_id, None)
asyncio.create_task(_run_delete_intermediates(pipeline_id))
logger.info(f"Pipeline {pipeline_id[:8]} finalized (video kept in dataset).")
return {
"ok": True,
"pipeline_id": pipeline_id,
"video_url": p["assets"].get("video_url"),
"video_download_url": p["assets"].get("video_download_url"),
"video_stream_url": p["assets"].get("video_stream_url"),
}
async def _run_delete_intermediates(pipeline_id: str):
try:
await store().delete_intermediates(pipeline_id)
except Exception as e:
logger.error(f"delete_intermediates failed for {pipeline_id[:8]}: {e}")
@app.get("/status")
async def get_status():
summary = _status_summary()
return {
"tts": {
**summary["tts"],
"description": "Text-to-Speech spaces (2 slots each = 8 total)",
},
"mfa": {
**summary["mfa"],
"description": "Montreal Forced Aligner (fine-tune, precise English)",
},
"qwen": {
**summary["qwen"],
"description": "Qwen Neural Aligner (fast, 2-pass refinement)",
},
"aligners": {
**summary["aligners"],
"description": "Combined aligners (MFA + Qwen)",
},
"ffmpeg": {
**summary["ffmpeg"],
"description": "Video encoding spaces (2 slots each = 4 total)",
},
}
@app.post("/pipeline/{pipeline_id}/heartbeat")
async def pipeline_heartbeat(pipeline_id: str):
p = _touch(pipeline_id)
if not p:
raise HTTPException(404, {"error": "pipeline_not_found"})
pipeline_heartbeats[pipeline_id] = datetime.utcnow()
stages = {name: s["status"] for name, s in p["stages"].items()}
return {"pipeline_id": pipeline_id, "acknowledged": True, "stages": stages}
@app.get("/debug/dataset-routing/{pipeline_id}")
async def debug_dataset_routing(pipeline_id: str):
"""Test which dataset a pipeline ID would route to"""
if not _store:
return {"error": "DatasetStore not initialized"}
first_hex = pipeline_id[0]
hex_value = int(first_hex, 16)
is_odd = hex_value % 2 == 1
repo_1 = _store.repo_1
repo_2 = _store.repo_2
is_dual = _store._dual
if is_dual:
chosen_repo = repo_2 if is_odd else repo_1
mode = "DUAL-DATASET"
else:
chosen_repo = repo_1
mode = "SINGLE-DATASET"
return {
"pipeline_id": pipeline_id,
"mode": mode,
"first_char": first_hex,
"hex_value": hex_value,
"is_odd": is_odd,
"repo_1": repo_1,
"repo_2": repo_2 if repo_2 else "NOT CONFIGURED",
"chosen_repo": chosen_repo,
"routing": "SECONDARY (repo_2)" if (is_dual and is_odd) else "PRIMARY (repo_1)"
}
@app.get("/capacity")
async def get_capacity():
active_pipelines = [
{
"pipeline_id": p["pipeline_id"],
"stage": next(
(s for s in (Stage.TTS, Stage.ALIGN, Stage.VIDEO)
if p["stages"][s]["status"] == StageStatus.RUNNING),
"idle"
),
"created_at": p["created_at"],
}
for p in pipelines.values()
if any(
p["stages"][s]["status"] == StageStatus.RUNNING
for s in (Stage.TTS, Stage.ALIGN, Stage.VIDEO)
)
]
waiting = [
p for p in pipelines.values()
if all(
p["stages"][s]["status"] != StageStatus.RUNNING
for s in (Stage.TTS, Stage.ALIGN, Stage.VIDEO)
)
and any(
p["stages"][s]["status"] == StageStatus.IDLE
for s in (Stage.ALIGN, Stage.VIDEO)
)
and p["stages"][Stage.TTS]["status"] == StageStatus.DONE
]
return {
"active": len(active_pipelines),
"cap": 8,
"slots_free": max(0, 8 - len(active_pipelines)),
"at_capacity": len(active_pipelines) >= 8,
"pipelines": active_pipelines,
"waiting_count": len(waiting),
"total_in_memory": len(pipelines),
}
@app.get("/debug/rate-limit-status")
async def debug_rate_limit_status(request: Request):
"""Debug endpoint to check rate limit status for requesting IP"""
client_ip = _get_client_ip(request)
is_admin = _is_admin_request(request)
allowed, current_count, retry_after = _check_rate_limit(client_ip)
timestamps = rate_limit_storage.get(client_ip, [])
return {
"ip": client_ip if not is_admin else "admin",
"is_admin": is_admin,
"allowed": allowed,
"current_usage": current_count,
"limit": RATE_LIMIT_MAX_PER_HOUR,
"window_hours": RATE_LIMIT_WINDOW_HOURS,
"retry_after_seconds": retry_after if not allowed else 0,
"recent_requests": [ts.isoformat() for ts in sorted(timestamps, reverse=True)],
"total_ips_tracked": len(rate_limit_storage),
}
@app.post("/pipeline/{pipeline_id}/cancel/{stage}")
async def cancel_stage(pipeline_id: str, stage: str, request: Request):
if stage not in (Stage.TTS, Stage.ALIGN, Stage.VIDEO):
raise HTTPException(400, {
"error": "invalid_stage",
"detail": f"Stage must be one of: tts, align, video",
})
p = _pipeline_or_404(pipeline_id)
s = p["stages"][stage]
analytics = analytics_storage.get(pipeline_id)
if s["status"] != StageStatus.RUNNING:
raise HTTPException(400, {
"error": "stage_not_running",
"detail": f"Stage '{stage}' is not currently running (status: {s['status']}). Nothing to cancel.",
})
url = s.get("backend_url")
jid = s.get("backend_job_id")
btype = s.get("backend_type")
if url and jid:
try:
if btype == "ffmpeg":
await http().delete(
f"{url}/job/{jid}",
headers={"X-APP-KEY": APP_KEY},
timeout=10.0,
)
else:
await http().post(
f"{url}/cancel/{jid}",
json={"client_id": _client_id(pipeline_id)},
timeout=10.0,
)
logger.info(f"Pipeline {pipeline_id[:8]}: user cancelled {stage} job {jid} on {url}")
except Exception as e:
logger.warning(f"Pipeline {pipeline_id[:8]}: cancel request to backend failed ({e}) β marking failed anyway")
s["status"] = StageStatus.FAILED
s["error"] = "Cancelled by user"
if analytics:
_record_stage_failure(
analytics, stage, url or "N/A", btype or "unknown", jid or "N/A",
"Cancelled by user", "user_cancelled"
)
return {
"ok": True,
"pipeline_id": pipeline_id,
"stage": stage,
"job_id": jid,
"backend_url": url,
}
# =============================================================================
# ENHANCED ADMIN ANALYTICS ENDPOINTS
# =============================================================================
@app.get("/admin/analytics")
async def admin_analytics(request: Request):
"""Get comprehensive analytics summary with backend stats"""
if not _is_admin_request(request):
raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
return _get_analytics_summary()
@app.get("/admin/active-jobs")
async def admin_active_jobs(request: Request):
"""Get all currently running jobs with details"""
if not _is_admin_request(request):
raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
active_jobs = _get_active_jobs()
return {
"active_jobs": active_jobs,
"total_active": len(active_jobs),
"capacity": 8,
"slots_available": max(0, 8 - len(active_jobs)),
}
@app.get("/admin/pipeline/{pipeline_id}/analytics")
async def admin_pipeline_analytics(pipeline_id: str, request: Request):
"""Get detailed analytics for a specific pipeline with failure details"""
if not _is_admin_request(request):
raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
analytics = analytics_storage.get(pipeline_id)
if not analytics:
raise HTTPException(404, {"error": "pipeline_not_found", "detail": "Pipeline not found in analytics"})
return analytics.to_dict()
@app.get("/admin/failures")
async def admin_failures(request: Request):
"""Get detailed failure breakdown with exact backend URLs"""
if not _is_admin_request(request):
raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
failures = []
for pid, analytics in analytics_storage.items():
if analytics.final_status == "failed":
# Determine which stage failed and get its failure detail
failed_stage = None
failure_detail = None
if analytics.tts_status == "failed":
failed_stage = "tts"
failure_detail = analytics.tts_failure_detail
elif analytics.align_status == "failed":
failed_stage = "align"
failure_detail = analytics.align_failure_detail
elif analytics.video_status == "failed":
failed_stage = "video"
failure_detail = analytics.video_failure_detail
failures.append({
"pipeline_id": pid,
"created_at": analytics.created_at.isoformat(),
"user_ip": analytics.user_ip,
"is_admin": analytics.is_admin,
"failed_stage": failed_stage,
"failure": {
"backend_url": failure_detail.backend_url if failure_detail else None,
"backend_type": failure_detail.backend_type if failure_detail else None,
"job_id": failure_detail.job_id if failure_detail else None,
"error_message": failure_detail.error_message if failure_detail else None,
"error_type": failure_detail.error_type if failure_detail else None,
"failed_at": failure_detail.failed_at.isoformat() if failure_detail else None,
"http_status": failure_detail.http_status if failure_detail else None,
},
"stage_errors": {
"tts_error": analytics.tts_error,
"align_error": analytics.align_error,
"video_error": analytics.video_error,
}
})
return {
"total_failures": len(failures),
"failures": failures,
"failure_stats_by_stage": dict(stage_failure_stats),
"error_type_breakdown": {
stage: dict(errors) for stage, errors in stage_failure_stats.items()
}
}
@app.get("/admin/rate-limit-status")
async def admin_rate_limit_status(request: Request):
"""Get rate limit status for all IPs"""
if not _is_admin_request(request):
raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
ip_status = []
for ip, timestamps in rate_limit_storage.items():
allowed, current_count, retry_after = _check_rate_limit(ip)
ip_status.append({
"ip": _anonymize_ip(ip),
"current_usage": current_count,
"limit": RATE_LIMIT_MAX_PER_HOUR,
"allowed": allowed,
"retry_after_seconds": retry_after if not allowed else 0,
"recent_requests": len(timestamps),
})
return {
"total_ips_tracked": len(rate_limit_storage),
"ips": ip_status,
"global_limit": RATE_LIMIT_MAX_PER_HOUR,
"window_hours": RATE_LIMIT_WINDOW_HOURS,
}
@app.get("/admin/clear-analytics")
async def admin_clear_analytics(request: Request):
"""Clear all analytics data"""
if not _is_admin_request(request):
raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
global analytics_storage, stage_failure_stats
count = len(analytics_storage)
analytics_storage.clear()
stage_failure_stats.clear()
return {
"cleared": count,
"message": f"Cleared {count} analytics records"
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860, timeout_keep_alive=180)
"""
ArchNemix Controller Space v1.8
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ADDED: Enhanced error tracking with exact backend URL for each failed stage
ADDED: Detailed debugging information for pipeline failures
ADDED: Failure context including stage, backend URL, job ID, and error message
"""
import os
import uuid
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, Tuple, List
from enum import Enum
from dataclasses import dataclass, asdict, field
from collections import defaultdict
import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, Response, RedirectResponse, StreamingResponse
from pydantic import BaseModel
from dataset import DatasetStore
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s",
)
logger = logging.getLogger(__name__)
# =============================================================================
# CONFIGURATION
# =============================================================================
APP_KEY = os.getenv("APP_KEY", "")
HF_TOKEN = os.getenv("HF_TOKEN", "")
HF_DATASET = os.getenv("HF_DATASET", "")
HF_DATASET_2 = os.getenv("HF_DATASET_2", "")
ADMIN_KEY = os.getenv("ADMIN_KEY", "") # Secret key that bypasses rate limiting
pipeline_heartbeats: Dict[str, datetime] = {}
FRONTEND_HEARTBEAT_GRACE = 45
FFMPEG_QUEUE_DEPTH = 2
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ENHANCED ADMIN ANALYTICS STORAGE - v1.8
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class StageFailureDetail:
"""Detailed information about a stage failure"""
stage: str
backend_url: str
backend_type: str
job_id: str
error_message: str
error_type: str # e.g., "timeout", "backend_error", "save_failed", "user_cancelled"
submitted_at: Optional[datetime] = None
failed_at: datetime = field(default_factory=datetime.utcnow)
http_status: Optional[int] = None
response_body: Optional[str] = None
class JobAnalytics:
"""Track detailed analytics for a single job/pipeline"""
pipeline_id: str
created_at: datetime
user_ip: str # anonymized in logs
is_admin: bool
rate_limited: bool = False
# Stage tracking with backend details
tts_submitted_at: Optional[datetime] = None
tts_completed_at: Optional[datetime] = None
tts_status: str = "idle"
tts_error: Optional[str] = None
tts_backend: Optional[str] = None # Exact URL of backend space
tts_backend_type: Optional[str] = None
tts_job_id: Optional[str] = None
tts_failure_detail: Optional[StageFailureDetail] = None
align_submitted_at: Optional[datetime] = None
align_completed_at: Optional[datetime] = None
align_status: str = "idle"
align_error: Optional[str] = None
align_backend: Optional[str] = None # Exact URL of backend space
align_backend_type: Optional[str] = None
align_job_id: Optional[str] = None
align_failure_detail: Optional[StageFailureDetail] = None
video_submitted_at: Optional[datetime] = None
video_completed_at: Optional[datetime] = None
video_status: str = "idle"
video_error: Optional[str] = None
video_backend: Optional[str] = None # Exact URL of backend space
video_backend_type: Optional[str] = None
video_job_id: Optional[str] = None
video_storage_method: Optional[str] = None # "dataset" or "ffmpeg_fallback"
video_failure_detail: Optional[StageFailureDetail] = None