YTShortMakerArchx commited on
Commit
bf7d85f
Β·
verified Β·
1 Parent(s): d3cd464

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +206 -12
app.py CHANGED
@@ -1,6 +1,8 @@
1
  """
2
- ArchNemix Controller Space v1.3
3
  ════════════════════════════════════════════════════════════════════════════════
 
 
4
  Orchestrates 12 backend HuggingFace Spaces in a staged pipeline:
5
 
6
  TTS (Γ—4) β†’ Aligner/Qwen (Γ—8) β†’ FFmpeg (Γ—1)
@@ -57,6 +59,16 @@ pipeline_heartbeats: Dict[str, datetime] = {}
57
  FRONTEND_HEARTBEAT_GRACE = 45
58
  FFMPEG_QUEUE_DEPTH = 2
59
 
 
 
 
 
 
 
 
 
 
 
60
  ALLOWED_ORIGINS = [
61
  "https://shortgen-archx.pages.dev",
62
  "http://localhost:3000",
@@ -91,7 +103,7 @@ FFMPEG_SPACES = [
91
  ]
92
 
93
  non_used_spaces = [
94
- "https://archnemix-ffmpeg-polyglot-ffmpeg-rust.hf.space",
95
  ]
96
 
97
  ALL_SPACES: Dict[str, list] = {
@@ -127,6 +139,128 @@ class StageStatus:
127
  pipelines: Dict[str, Dict[str, Any]] = {}
128
  status_cache: Dict[str, Dict[str, Any]] = {}
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  # =============================================================================
131
  # REQUEST / RESPONSE MODELS
132
  # =============================================================================
@@ -161,7 +295,7 @@ class VideoSubmitRequest(BaseModel):
161
 
162
  app = FastAPI(
163
  title="ArchNemix Controller v1",
164
- version="1.3.0",
165
  docs_url="/docs",
166
  redoc_url=None,
167
  )
@@ -1060,7 +1194,12 @@ async def startup():
1060
  asyncio.create_task(_status_loop())
1061
  asyncio.create_task(_cleanup_loop())
1062
  asyncio.create_task(_frontend_heartbeat_watchdog())
1063
- logger.info("ArchNemix Controller v1.3 ready (video: dataset-first with FFmpeg fallback).")
 
 
 
 
 
1064
 
1065
 
1066
  async def _frontend_heartbeat_watchdog():
@@ -1131,9 +1270,9 @@ async def shutdown():
1131
  async def root():
1132
  return {
1133
  "name": "ArchNemix Controller",
1134
- "version": "1.3.0",
1135
  "endpoints": {
1136
- "POST /pipeline/start": "Start new pipeline (submits TTS immediately)",
1137
  "GET /pipeline/{id}": "Poll pipeline state + per-stage status",
1138
  "POST /pipeline/{id}/rerun/tts": "Re-run TTS only (new text/voice/rate optional)",
1139
  "POST /pipeline/{id}/align": "Submit alignment (uses completed TTS audio)",
@@ -1143,14 +1282,37 @@ async def root():
1143
  "POST /pipeline/{id}/finalize": "Mark pipeline complete β€” deletes dataset intermediates",
1144
  "GET /status": "Live slot availability for all spaces",
1145
  },
 
1146
  "video_storage": "Dataset first (permanent), fallback to FFmpeg /tmp URLs (1-hour TTL) if upload fails",
1147
  }
1148
 
1149
 
1150
  @app.post("/pipeline/start")
1151
- async def start_pipeline(req: PipelineStartRequest):
1152
-
1153
- # ── Global capacity cap ───────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1154
  active_count = sum(
1155
  1 for p in pipelines.values()
1156
  if any(
@@ -1164,12 +1326,20 @@ async def start_pipeline(req: PipelineStartRequest):
1164
  "detail": "All slots are currently busy. Try again in ~2 minutes.",
1165
  "retry_after": 120,
1166
  })
1167
- # ─────────────────────────────────────────────────────────────────────
1168
 
 
 
 
1169
  p = _new_pipeline(req)
1170
  pid = p["pipeline_id"]
1171
  pipelines[pid] = p
1172
-
 
 
 
 
 
 
1173
  err = await _submit_tts(p, req.text, req.voice, req.rate)
1174
  if err:
1175
  p["stages"][Stage.TTS]["status"] = StageStatus.FAILED
@@ -1186,7 +1356,10 @@ async def start_pipeline(req: PipelineStartRequest):
1186
  headers={"X-Pipeline-ID": pid},
1187
  )
1188
 
1189
- logger.info(f"Pipeline {pid[:8]} started β€” TTS job {p['stages'][Stage.TTS]['backend_job_id']}")
 
 
 
1190
 
1191
  return JSONResponse(
1192
  {
@@ -1481,6 +1654,27 @@ async def get_capacity():
1481
  "total_in_memory": len(pipelines),
1482
  }
1483
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1484
  @app.post("/pipeline/{pipeline_id}/cancel/{stage}")
1485
  async def cancel_stage(pipeline_id: str, stage: str):
1486
  if stage not in (Stage.TTS, Stage.ALIGN, Stage.VIDEO):
 
1
  """
2
+ ArchNemix Controller Space v1.4
3
  ════════════════════════════════════════════════════════════════════════════════
4
+ ADDED: IP-based rate limiting (10 pipelines/hour per IP)
5
+
6
  Orchestrates 12 backend HuggingFace Spaces in a staged pipeline:
7
 
8
  TTS (Γ—4) β†’ Aligner/Qwen (Γ—8) β†’ FFmpeg (Γ—1)
 
59
  FRONTEND_HEARTBEAT_GRACE = 45
60
  FFMPEG_QUEUE_DEPTH = 2
61
 
62
+ # ═════════════════════════════════════════════════════════════════════════════
63
+ # RATE LIMITING β€” NEW IN v1.4
64
+ # ═════════════════════════════════════════════════════════════════════════════
65
+ # In-memory storage: { "ip_address": [timestamp1, timestamp2, ...] }
66
+ # Stores timestamps of when each IP started a pipeline
67
+ # Cleaned automatically (removes timestamps older than 1 hour)
68
+ rate_limit_storage: Dict[str, list[datetime]] = {}
69
+ RATE_LIMIT_MAX_PER_HOUR = 10
70
+ RATE_LIMIT_WINDOW_HOURS = 1
71
+
72
  ALLOWED_ORIGINS = [
73
  "https://shortgen-archx.pages.dev",
74
  "http://localhost:3000",
 
103
  ]
104
 
105
  non_used_spaces = [
106
+ "Currently None",
107
  ]
108
 
109
  ALL_SPACES: Dict[str, list] = {
 
139
  pipelines: Dict[str, Dict[str, Any]] = {}
140
  status_cache: Dict[str, Dict[str, Any]] = {}
141
 
142
+ # =============================================================================
143
+ # RATE LIMITING HELPERS
144
+ # =============================================================================
145
+
146
+ def _get_client_ip(request: Request) -> str:
147
+ """
148
+ Extract real client IP from request.
149
+ Checks headers in order:
150
+ 1. CF-Connecting-IP (Cloudflare)
151
+ 2. X-Forwarded-For (standard proxy header)
152
+ 3. request.client.host (direct connection)
153
+ """
154
+ # Cloudflare passes real IP in CF-Connecting-IP
155
+ cf_ip = request.headers.get("CF-Connecting-IP")
156
+ if cf_ip:
157
+ return cf_ip.strip()
158
+
159
+ # Standard X-Forwarded-For (might be comma-separated list)
160
+ forwarded = request.headers.get("X-Forwarded-For")
161
+ if forwarded:
162
+ # Take first IP in the chain (original client)
163
+ return forwarded.split(",")[0].strip()
164
+
165
+ # Fallback to direct connection IP
166
+ return request.client.host if request.client else "unknown"
167
+
168
+
169
+ def _cleanup_old_timestamps(ip: str) -> None:
170
+ """
171
+ Remove timestamps older than RATE_LIMIT_WINDOW_HOURS from storage.
172
+ Called before checking rate limit to keep storage clean.
173
+ """
174
+ if ip not in rate_limit_storage:
175
+ return
176
+
177
+ cutoff = datetime.utcnow() - timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
178
+ rate_limit_storage[ip] = [
179
+ ts for ts in rate_limit_storage[ip]
180
+ if ts > cutoff
181
+ ]
182
+
183
+ # Remove IP entirely if no recent requests
184
+ if not rate_limit_storage[ip]:
185
+ del rate_limit_storage[ip]
186
+
187
+
188
+ def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
189
+ """
190
+ Check if IP has exceeded rate limit.
191
+
192
+ Returns:
193
+ (allowed, current_count, seconds_until_oldest_expires)
194
+
195
+ Examples:
196
+ (True, 5, 1200) β€” allowed, 5 requests in last hour, oldest expires in 20 min
197
+ (False, 10, 300) β€” blocked, 10 requests in last hour, retry in 5 min
198
+ """
199
+ _cleanup_old_timestamps(ip)
200
+
201
+ if ip not in rate_limit_storage:
202
+ return True, 0, 0
203
+
204
+ current_count = len(rate_limit_storage[ip])
205
+
206
+ if current_count >= RATE_LIMIT_MAX_PER_HOUR:
207
+ # Calculate when oldest request expires
208
+ oldest_timestamp = min(rate_limit_storage[ip])
209
+ expires_at = oldest_timestamp + timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
210
+ seconds_until_expiry = int((expires_at - datetime.utcnow()).total_seconds())
211
+
212
+ return False, current_count, max(0, seconds_until_expiry)
213
+
214
+ return True, current_count, 0
215
+
216
+
217
+ def _record_request(ip: str) -> None:
218
+ """
219
+ Record a new pipeline start request for this IP.
220
+ Automatically cleans old timestamps first.
221
+ """
222
+ _cleanup_old_timestamps(ip)
223
+
224
+ if ip not in rate_limit_storage:
225
+ rate_limit_storage[ip] = []
226
+
227
+ rate_limit_storage[ip].append(datetime.utcnow())
228
+
229
+ logger.info(
230
+ f"Rate limit: IP {ip} now has {len(rate_limit_storage[ip])} "
231
+ f"request(s) in last {RATE_LIMIT_WINDOW_HOURS}h"
232
+ )
233
+
234
+
235
+ # =============================================================================
236
+ # RATE LIMIT CLEANUP LOOP
237
+ # =============================================================================
238
+
239
+ async def _rate_limit_cleanup_loop():
240
+ """
241
+ Background task that periodically cleans up old timestamps from all IPs.
242
+ Runs every 5 minutes to keep memory usage low.
243
+ """
244
+ while True:
245
+ await asyncio.sleep(300) # 5 minutes
246
+
247
+ cutoff = datetime.utcnow() - timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
248
+ cleaned_ips = 0
249
+
250
+ for ip in list(rate_limit_storage.keys()):
251
+ rate_limit_storage[ip] = [
252
+ ts for ts in rate_limit_storage[ip]
253
+ if ts > cutoff
254
+ ]
255
+
256
+ if not rate_limit_storage[ip]:
257
+ del rate_limit_storage[ip]
258
+ cleaned_ips += 1
259
+
260
+ if cleaned_ips > 0:
261
+ logger.info(f"Rate limit cleanup: removed {cleaned_ips} expired IP entries")
262
+
263
+
264
  # =============================================================================
265
  # REQUEST / RESPONSE MODELS
266
  # =============================================================================
 
295
 
296
  app = FastAPI(
297
  title="ArchNemix Controller v1",
298
+ version="1.4.0",
299
  docs_url="/docs",
300
  redoc_url=None,
301
  )
 
1194
  asyncio.create_task(_status_loop())
1195
  asyncio.create_task(_cleanup_loop())
1196
  asyncio.create_task(_frontend_heartbeat_watchdog())
1197
+ asyncio.create_task(_rate_limit_cleanup_loop()) # NEW: Start rate limit cleanup
1198
+
1199
+ logger.info("=" * 80)
1200
+ logger.info(f"RATE LIMITING: {RATE_LIMIT_MAX_PER_HOUR} pipelines per IP per {RATE_LIMIT_WINDOW_HOURS}h")
1201
+ logger.info("=" * 80)
1202
+ logger.info("ArchNemix Controller v1.4 ready (with rate limiting + video dataset-first with FFmpeg fallback).")
1203
 
1204
 
1205
  async def _frontend_heartbeat_watchdog():
 
1270
  async def root():
1271
  return {
1272
  "name": "ArchNemix Controller",
1273
+ "version": "1.4.0",
1274
  "endpoints": {
1275
+ "POST /pipeline/start": "Start new pipeline (rate limited: 10/hour per IP)",
1276
  "GET /pipeline/{id}": "Poll pipeline state + per-stage status",
1277
  "POST /pipeline/{id}/rerun/tts": "Re-run TTS only (new text/voice/rate optional)",
1278
  "POST /pipeline/{id}/align": "Submit alignment (uses completed TTS audio)",
 
1282
  "POST /pipeline/{id}/finalize": "Mark pipeline complete β€” deletes dataset intermediates",
1283
  "GET /status": "Live slot availability for all spaces",
1284
  },
1285
+ "rate_limit": f"{RATE_LIMIT_MAX_PER_HOUR} pipelines per {RATE_LIMIT_WINDOW_HOURS} hour(s) per IP",
1286
  "video_storage": "Dataset first (permanent), fallback to FFmpeg /tmp URLs (1-hour TTL) if upload fails",
1287
  }
1288
 
1289
 
1290
  @app.post("/pipeline/start")
1291
+ async def start_pipeline(req: PipelineStartRequest, request: Request):
1292
+
1293
+ # ══════════════════════════════════════════════════════════════════════════
1294
+ # STEP 1: CHECK RATE LIMIT (BEFORE ANYTHING ELSE)
1295
+ # ══════════════════════════════════════════════════════════════════════════
1296
+ client_ip = _get_client_ip(request)
1297
+ allowed, current_count, retry_after = _check_rate_limit(client_ip)
1298
+
1299
+ if not allowed:
1300
+ logger.warning(
1301
+ f"Rate limit exceeded for IP {client_ip} β€” "
1302
+ f"{current_count} requests in last {RATE_LIMIT_WINDOW_HOURS}h"
1303
+ )
1304
+ return JSONResponse(status_code=429, content={
1305
+ "error": "rate_limit_exceeded",
1306
+ "detail": f"You have reached the limit of {RATE_LIMIT_MAX_PER_HOUR} videos per hour. Please wait before starting a new pipeline.",
1307
+ "retry_after": retry_after,
1308
+ "current_usage": current_count,
1309
+ "limit": RATE_LIMIT_MAX_PER_HOUR,
1310
+ "window_hours": RATE_LIMIT_WINDOW_HOURS,
1311
+ })
1312
+
1313
+ # ══════════════════════════════════════════════════════════════════════════
1314
+ # STEP 2: CHECK GLOBAL CAPACITY
1315
+ # ════════════════════════════════════════════���═════════════════════════════
1316
  active_count = sum(
1317
  1 for p in pipelines.values()
1318
  if any(
 
1326
  "detail": "All slots are currently busy. Try again in ~2 minutes.",
1327
  "retry_after": 120,
1328
  })
 
1329
 
1330
+ # ══════════════════════════════════════════════════════════════════════════
1331
+ # STEP 3: CREATE PIPELINE AND RECORD REQUEST
1332
+ # ══════════════════════════════════════════════════════════════════════════
1333
  p = _new_pipeline(req)
1334
  pid = p["pipeline_id"]
1335
  pipelines[pid] = p
1336
+
1337
+ # Record this request for rate limiting
1338
+ _record_request(client_ip)
1339
+
1340
+ # ══════════════════════════════════════════════════════════════════════════
1341
+ # STEP 4: SUBMIT TTS JOB
1342
+ # ══════════════════════════════════════════════════════════════════════════
1343
  err = await _submit_tts(p, req.text, req.voice, req.rate)
1344
  if err:
1345
  p["stages"][Stage.TTS]["status"] = StageStatus.FAILED
 
1356
  headers={"X-Pipeline-ID": pid},
1357
  )
1358
 
1359
+ logger.info(
1360
+ f"Pipeline {pid[:8]} started β€” TTS job {p['stages'][Stage.TTS]['backend_job_id']} "
1361
+ f"(IP: {client_ip}, usage: {current_count + 1}/{RATE_LIMIT_MAX_PER_HOUR})"
1362
+ )
1363
 
1364
  return JSONResponse(
1365
  {
 
1654
  "total_in_memory": len(pipelines),
1655
  }
1656
 
1657
+
1658
+ @app.get("/debug/rate-limit-status")
1659
+ async def debug_rate_limit_status(request: Request):
1660
+ """Debug endpoint to check rate limit status for requesting IP"""
1661
+ client_ip = _get_client_ip(request)
1662
+ allowed, current_count, retry_after = _check_rate_limit(client_ip)
1663
+
1664
+ timestamps = rate_limit_storage.get(client_ip, [])
1665
+
1666
+ return {
1667
+ "ip": client_ip,
1668
+ "allowed": allowed,
1669
+ "current_usage": current_count,
1670
+ "limit": RATE_LIMIT_MAX_PER_HOUR,
1671
+ "window_hours": RATE_LIMIT_WINDOW_HOURS,
1672
+ "retry_after_seconds": retry_after if not allowed else 0,
1673
+ "recent_requests": [ts.isoformat() for ts in sorted(timestamps, reverse=True)],
1674
+ "total_ips_tracked": len(rate_limit_storage),
1675
+ }
1676
+
1677
+
1678
  @app.post("/pipeline/{pipeline_id}/cancel/{stage}")
1679
  async def cancel_stage(pipeline_id: str, stage: str):
1680
  if stage not in (Stage.TTS, Stage.ALIGN, Stage.VIDEO):