Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
-
ArchNemix Controller Space v1.
|
| 3 |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
-
ADDED: Admin
|
| 5 |
ADDED: IP-based rate limiting (10 pipelines/hour per IP)
|
| 6 |
|
| 7 |
Orchestrates 12 backend HuggingFace Spaces in a staged pipeline:
|
|
@@ -23,7 +23,7 @@ HF Secrets required:
|
|
| 23 |
HF_TOKEN β write access to your pipeline dataset
|
| 24 |
HF_DATASET β e.g. "YourOrg/archnemix-pipelines"
|
| 25 |
HF_DATASET_2 β optional secondary dataset for dual-dataset mode
|
| 26 |
-
|
| 27 |
"""
|
| 28 |
|
| 29 |
|
|
@@ -56,7 +56,7 @@ APP_KEY = os.getenv("APP_KEY", "")
|
|
| 56 |
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 57 |
HF_DATASET = os.getenv("HF_DATASET", "")
|
| 58 |
HF_DATASET_2 = os.getenv("HF_DATASET_2", "")
|
| 59 |
-
|
| 60 |
|
| 61 |
pipeline_heartbeats: Dict[str, datetime] = {}
|
| 62 |
FRONTEND_HEARTBEAT_GRACE = 45
|
|
@@ -169,9 +169,18 @@ def _get_client_ip(request: Request) -> str:
|
|
| 169 |
return request.client.host if request.client else "unknown"
|
| 170 |
|
| 171 |
|
| 172 |
-
def
|
| 173 |
-
"""
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
|
| 177 |
def _cleanup_old_timestamps(ip: str) -> None:
|
|
@@ -196,7 +205,6 @@ def _cleanup_old_timestamps(ip: str) -> None:
|
|
| 196 |
def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
|
| 197 |
"""
|
| 198 |
Check if IP has exceeded rate limit.
|
| 199 |
-
Admin IP bypasses rate limiting entirely.
|
| 200 |
|
| 201 |
Returns:
|
| 202 |
(allowed, current_count, seconds_until_oldest_expires)
|
|
@@ -205,11 +213,6 @@ def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
|
|
| 205 |
(True, 5, 1200) β allowed, 5 requests in last hour, oldest expires in 20 min
|
| 206 |
(False, 10, 300) β blocked, 10 requests in last hour, retry in 5 min
|
| 207 |
"""
|
| 208 |
-
# π BYPASS: Admin IP has no limits
|
| 209 |
-
if _is_admin_ip(ip):
|
| 210 |
-
logger.info("Rate limit bypassed for admin")
|
| 211 |
-
return True, 0, 0
|
| 212 |
-
|
| 213 |
_cleanup_old_timestamps(ip)
|
| 214 |
|
| 215 |
if ip not in rate_limit_storage:
|
|
@@ -231,13 +234,8 @@ def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
|
|
| 231 |
def _record_request(ip: str) -> None:
|
| 232 |
"""
|
| 233 |
Record a new pipeline start request for this IP.
|
| 234 |
-
|
| 235 |
"""
|
| 236 |
-
# π BYPASS: Don't record admin IP requests
|
| 237 |
-
if _is_admin_ip(ip):
|
| 238 |
-
logger.info("Rate limit recording skipped for admin")
|
| 239 |
-
return
|
| 240 |
-
|
| 241 |
_cleanup_old_timestamps(ip)
|
| 242 |
|
| 243 |
if ip not in rate_limit_storage:
|
|
@@ -314,7 +312,7 @@ class VideoSubmitRequest(BaseModel):
|
|
| 314 |
|
| 315 |
app = FastAPI(
|
| 316 |
title="ArchNemix Controller v1",
|
| 317 |
-
version="1.
|
| 318 |
docs_url="/docs",
|
| 319 |
redoc_url=None,
|
| 320 |
)
|
|
@@ -1150,12 +1148,12 @@ async def startup():
|
|
| 1150 |
global _http, _store
|
| 1151 |
|
| 1152 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1153 |
-
# ADMIN
|
| 1154 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1155 |
-
if
|
| 1156 |
-
logger.info(f"β
|
| 1157 |
else:
|
| 1158 |
-
logger.info("βΉ
|
| 1159 |
|
| 1160 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1161 |
# DATASET REACHABILITY CHECK β FIRST THING AT STARTUP
|
|
@@ -1221,14 +1219,14 @@ async def startup():
|
|
| 1221 |
asyncio.create_task(_status_loop())
|
| 1222 |
asyncio.create_task(_cleanup_loop())
|
| 1223 |
asyncio.create_task(_frontend_heartbeat_watchdog())
|
| 1224 |
-
asyncio.create_task(_rate_limit_cleanup_loop())
|
| 1225 |
|
| 1226 |
logger.info("=" * 80)
|
| 1227 |
logger.info(f"RATE LIMITING: {RATE_LIMIT_MAX_PER_HOUR} pipelines per IP per {RATE_LIMIT_WINDOW_HOURS}h")
|
| 1228 |
-
if
|
| 1229 |
-
logger.info("ADMIN BYPASS: Active β admin
|
| 1230 |
logger.info("=" * 80)
|
| 1231 |
-
logger.info("ArchNemix Controller v1.
|
| 1232 |
|
| 1233 |
|
| 1234 |
async def _frontend_heartbeat_watchdog():
|
|
@@ -1299,9 +1297,9 @@ async def shutdown():
|
|
| 1299 |
async def root():
|
| 1300 |
return {
|
| 1301 |
"name": "ArchNemix Controller",
|
| 1302 |
-
"version": "1.
|
| 1303 |
"endpoints": {
|
| 1304 |
-
"POST /pipeline/start": "Start new pipeline (rate limited: 10/hour per IP, admin bypass available)",
|
| 1305 |
"GET /pipeline/{id}": "Poll pipeline state + per-stage status",
|
| 1306 |
"POST /pipeline/{id}/rerun/tts": "Re-run TTS only (new text/voice/rate optional)",
|
| 1307 |
"POST /pipeline/{id}/align": "Submit alignment (uses completed TTS audio)",
|
|
@@ -1312,7 +1310,7 @@ async def root():
|
|
| 1312 |
"GET /status": "Live slot availability for all spaces",
|
| 1313 |
},
|
| 1314 |
"rate_limit": f"{RATE_LIMIT_MAX_PER_HOUR} pipelines per {RATE_LIMIT_WINDOW_HOURS} hour(s) per IP",
|
| 1315 |
-
"admin_bypass": bool(
|
| 1316 |
"video_storage": "Dataset first (permanent), fallback to FFmpeg /tmp URLs (1-hour TTL) if upload fails",
|
| 1317 |
}
|
| 1318 |
|
|
@@ -1324,18 +1322,26 @@ async def start_pipeline(req: PipelineStartRequest, request: Request):
|
|
| 1324 |
# STEP 1: CHECK RATE LIMIT (BEFORE ANYTHING ELSE)
|
| 1325 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1326 |
client_ip = _get_client_ip(request)
|
| 1327 |
-
|
| 1328 |
|
| 1329 |
-
|
| 1330 |
-
|
| 1331 |
-
|
| 1332 |
-
|
| 1333 |
-
|
| 1334 |
-
"
|
| 1335 |
-
|
| 1336 |
-
|
| 1337 |
-
|
| 1338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1339 |
|
| 1340 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1341 |
# STEP 2: CHECK GLOBAL CAPACITY
|
|
@@ -1361,8 +1367,9 @@ async def start_pipeline(req: PipelineStartRequest, request: Request):
|
|
| 1361 |
pid = p["pipeline_id"]
|
| 1362 |
pipelines[pid] = p
|
| 1363 |
|
| 1364 |
-
# Record this request for rate limiting
|
| 1365 |
-
|
|
|
|
| 1366 |
|
| 1367 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1368 |
# STEP 4: SUBMIT TTS JOB
|
|
@@ -1385,7 +1392,7 @@ async def start_pipeline(req: PipelineStartRequest, request: Request):
|
|
| 1385 |
|
| 1386 |
logger.info(
|
| 1387 |
f"Pipeline {pid[:8]} started β TTS job {p['stages'][Stage.TTS]['backend_job_id']} "
|
| 1388 |
-
f"(usage: {current_count + 1}/{RATE_LIMIT_MAX_PER_HOUR})"
|
| 1389 |
)
|
| 1390 |
|
| 1391 |
return JSONResponse(
|
|
@@ -1686,15 +1693,13 @@ async def get_capacity():
|
|
| 1686 |
async def debug_rate_limit_status(request: Request):
|
| 1687 |
"""Debug endpoint to check rate limit status for requesting IP"""
|
| 1688 |
client_ip = _get_client_ip(request)
|
|
|
|
| 1689 |
allowed, current_count, retry_after = _check_rate_limit(client_ip)
|
| 1690 |
|
| 1691 |
-
# Hide admin IP in debug output
|
| 1692 |
-
is_admin = _is_admin_ip(client_ip)
|
| 1693 |
-
|
| 1694 |
timestamps = rate_limit_storage.get(client_ip, [])
|
| 1695 |
|
| 1696 |
return {
|
| 1697 |
-
"ip":
|
| 1698 |
"is_admin": is_admin,
|
| 1699 |
"allowed": allowed,
|
| 1700 |
"current_usage": current_count,
|
|
|
|
| 1 |
"""
|
| 2 |
+
ArchNemix Controller Space v1.6
|
| 3 |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
+
ADDED: Admin API Key bypass for rate limiting (ADMIN_KEY secret)
|
| 5 |
ADDED: IP-based rate limiting (10 pipelines/hour per IP)
|
| 6 |
|
| 7 |
Orchestrates 12 backend HuggingFace Spaces in a staged pipeline:
|
|
|
|
| 23 |
HF_TOKEN β write access to your pipeline dataset
|
| 24 |
HF_DATASET β e.g. "YourOrg/archnemix-pipelines"
|
| 25 |
HF_DATASET_2 β optional secondary dataset for dual-dataset mode
|
| 26 |
+
ADMIN_KEY β optional: secret key that bypasses rate limiting (send via X-Admin-Key header)
|
| 27 |
"""
|
| 28 |
|
| 29 |
|
|
|
|
| 56 |
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 57 |
HF_DATASET = os.getenv("HF_DATASET", "")
|
| 58 |
HF_DATASET_2 = os.getenv("HF_DATASET_2", "")
|
| 59 |
+
ADMIN_KEY = os.getenv("ADMIN_KEY", "") # Secret key that bypasses rate limiting
|
| 60 |
|
| 61 |
pipeline_heartbeats: Dict[str, datetime] = {}
|
| 62 |
FRONTEND_HEARTBEAT_GRACE = 45
|
|
|
|
| 169 |
return request.client.host if request.client else "unknown"
|
| 170 |
|
| 171 |
|
| 172 |
+
def _is_admin_request(request: Request) -> bool:
|
| 173 |
+
"""
|
| 174 |
+
Check if request has admin credentials via API key header.
|
| 175 |
+
Returns True if admin bypass should be applied.
|
| 176 |
+
"""
|
| 177 |
+
# Check for admin key in headers
|
| 178 |
+
admin_header = request.headers.get("X-Admin-Key")
|
| 179 |
+
if ADMIN_KEY and admin_header and admin_header == ADMIN_KEY:
|
| 180 |
+
logger.info("Rate limit bypassed for admin (API key)")
|
| 181 |
+
return True
|
| 182 |
+
|
| 183 |
+
return False
|
| 184 |
|
| 185 |
|
| 186 |
def _cleanup_old_timestamps(ip: str) -> None:
|
|
|
|
| 205 |
def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
|
| 206 |
"""
|
| 207 |
Check if IP has exceeded rate limit.
|
|
|
|
| 208 |
|
| 209 |
Returns:
|
| 210 |
(allowed, current_count, seconds_until_oldest_expires)
|
|
|
|
| 213 |
(True, 5, 1200) β allowed, 5 requests in last hour, oldest expires in 20 min
|
| 214 |
(False, 10, 300) β blocked, 10 requests in last hour, retry in 5 min
|
| 215 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
_cleanup_old_timestamps(ip)
|
| 217 |
|
| 218 |
if ip not in rate_limit_storage:
|
|
|
|
| 234 |
def _record_request(ip: str) -> None:
|
| 235 |
"""
|
| 236 |
Record a new pipeline start request for this IP.
|
| 237 |
+
Automatically cleans old timestamps first.
|
| 238 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
_cleanup_old_timestamps(ip)
|
| 240 |
|
| 241 |
if ip not in rate_limit_storage:
|
|
|
|
| 312 |
|
| 313 |
app = FastAPI(
|
| 314 |
title="ArchNemix Controller v1",
|
| 315 |
+
version="1.6.0",
|
| 316 |
docs_url="/docs",
|
| 317 |
redoc_url=None,
|
| 318 |
)
|
|
|
|
| 1148 |
global _http, _store
|
| 1149 |
|
| 1150 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1151 |
+
# ADMIN KEY CONFIGURATION
|
| 1152 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1153 |
+
if ADMIN_KEY:
|
| 1154 |
+
logger.info(f"β ADMIN_KEY configured (rate limit bypass active for key holders)")
|
| 1155 |
else:
|
| 1156 |
+
logger.info("βΉ ADMIN_KEY not configured (rate limiting active for all users)")
|
| 1157 |
|
| 1158 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1159 |
# DATASET REACHABILITY CHECK β FIRST THING AT STARTUP
|
|
|
|
| 1219 |
asyncio.create_task(_status_loop())
|
| 1220 |
asyncio.create_task(_cleanup_loop())
|
| 1221 |
asyncio.create_task(_frontend_heartbeat_watchdog())
|
| 1222 |
+
asyncio.create_task(_rate_limit_cleanup_loop())
|
| 1223 |
|
| 1224 |
logger.info("=" * 80)
|
| 1225 |
logger.info(f"RATE LIMITING: {RATE_LIMIT_MAX_PER_HOUR} pipelines per IP per {RATE_LIMIT_WINDOW_HOURS}h")
|
| 1226 |
+
if ADMIN_KEY:
|
| 1227 |
+
logger.info("ADMIN BYPASS: Active β admin key holders bypass rate limits")
|
| 1228 |
logger.info("=" * 80)
|
| 1229 |
+
logger.info("ArchNemix Controller v1.6 ready (admin key bypass + rate limiting + video dataset-first with FFmpeg fallback).")
|
| 1230 |
|
| 1231 |
|
| 1232 |
async def _frontend_heartbeat_watchdog():
|
|
|
|
| 1297 |
async def root():
|
| 1298 |
return {
|
| 1299 |
"name": "ArchNemix Controller",
|
| 1300 |
+
"version": "1.6.0",
|
| 1301 |
"endpoints": {
|
| 1302 |
+
"POST /pipeline/start": "Start new pipeline (rate limited: 10/hour per IP, admin key bypass available)",
|
| 1303 |
"GET /pipeline/{id}": "Poll pipeline state + per-stage status",
|
| 1304 |
"POST /pipeline/{id}/rerun/tts": "Re-run TTS only (new text/voice/rate optional)",
|
| 1305 |
"POST /pipeline/{id}/align": "Submit alignment (uses completed TTS audio)",
|
|
|
|
| 1310 |
"GET /status": "Live slot availability for all spaces",
|
| 1311 |
},
|
| 1312 |
"rate_limit": f"{RATE_LIMIT_MAX_PER_HOUR} pipelines per {RATE_LIMIT_WINDOW_HOURS} hour(s) per IP",
|
| 1313 |
+
"admin_bypass": bool(ADMIN_KEY),
|
| 1314 |
"video_storage": "Dataset first (permanent), fallback to FFmpeg /tmp URLs (1-hour TTL) if upload fails",
|
| 1315 |
}
|
| 1316 |
|
|
|
|
| 1322 |
# STEP 1: CHECK RATE LIMIT (BEFORE ANYTHING ELSE)
|
| 1323 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1324 |
client_ip = _get_client_ip(request)
|
| 1325 |
+
is_admin = _is_admin_request(request)
|
| 1326 |
|
| 1327 |
+
# Admin bypass - skip all rate limit checks
|
| 1328 |
+
if not is_admin:
|
| 1329 |
+
allowed, current_count, retry_after = _check_rate_limit(client_ip)
|
| 1330 |
+
|
| 1331 |
+
if not allowed:
|
| 1332 |
+
logger.warning(f"Rate limit exceeded for IP")
|
| 1333 |
+
return JSONResponse(status_code=429, content={
|
| 1334 |
+
"error": "rate_limit_exceeded",
|
| 1335 |
+
"detail": f"You have reached the limit of {RATE_LIMIT_MAX_PER_HOUR} videos per hour. Please wait before starting a new pipeline.",
|
| 1336 |
+
"retry_after": retry_after,
|
| 1337 |
+
"current_usage": current_count,
|
| 1338 |
+
"limit": RATE_LIMIT_MAX_PER_HOUR,
|
| 1339 |
+
"window_hours": RATE_LIMIT_WINDOW_HOURS,
|
| 1340 |
+
})
|
| 1341 |
+
else:
|
| 1342 |
+
# Admin bypass - use dummy values
|
| 1343 |
+
current_count = 0
|
| 1344 |
+
retry_after = 0
|
| 1345 |
|
| 1346 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1347 |
# STEP 2: CHECK GLOBAL CAPACITY
|
|
|
|
| 1367 |
pid = p["pipeline_id"]
|
| 1368 |
pipelines[pid] = p
|
| 1369 |
|
| 1370 |
+
# Record this request for rate limiting (skip for admin)
|
| 1371 |
+
if not is_admin:
|
| 1372 |
+
_record_request(client_ip)
|
| 1373 |
|
| 1374 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1375 |
# STEP 4: SUBMIT TTS JOB
|
|
|
|
| 1392 |
|
| 1393 |
logger.info(
|
| 1394 |
f"Pipeline {pid[:8]} started β TTS job {p['stages'][Stage.TTS]['backend_job_id']} "
|
| 1395 |
+
f"(usage: {current_count + (0 if is_admin else 1)}/{RATE_LIMIT_MAX_PER_HOUR})"
|
| 1396 |
)
|
| 1397 |
|
| 1398 |
return JSONResponse(
|
|
|
|
| 1693 |
async def debug_rate_limit_status(request: Request):
|
| 1694 |
"""Debug endpoint to check rate limit status for requesting IP"""
|
| 1695 |
client_ip = _get_client_ip(request)
|
| 1696 |
+
is_admin = _is_admin_request(request)
|
| 1697 |
allowed, current_count, retry_after = _check_rate_limit(client_ip)
|
| 1698 |
|
|
|
|
|
|
|
|
|
|
| 1699 |
timestamps = rate_limit_storage.get(client_ip, [])
|
| 1700 |
|
| 1701 |
return {
|
| 1702 |
+
"ip": client_ip if not is_admin else "admin",
|
| 1703 |
"is_admin": is_admin,
|
| 1704 |
"allowed": allowed,
|
| 1705 |
"current_usage": current_count,
|