"""Hugging Face Gradio Space worker (free tier). A background poller claims `pending` scans from Supabase and processes them (Gemini + ffmpeg), then sends the notify email. Gradio only keeps the Space alive and serves a tiny status page; the Render backend pings the Space URL so it wakes and the poller runs promptly. """ from __future__ import annotations import datetime import logging import os import threading import time import gradio as gr from analyzer import run_scan logging.basicConfig(level=logging.INFO) log = logging.getLogger("worker") # ZeroGPU Spaces require at least one @spaces.GPU function to exist, even though # this worker is CPU-only (ffmpeg + Gemini API). This dummy satisfies that check; # it is never actually called, so no GPU time is ever used. try: import spaces @spaces.GPU(duration=15) def _gpu_noop(): # pragma: no cover return "ok" except Exception: # noqa: BLE001 — not on ZeroGPU (e.g. local run); ignore spaces = None def _gpu_noop(): # type: ignore return "ok" POLL_SECONDS = int(os.environ.get("POLL_SECONDS", "5")) def _notify(client, scan_id: str, refunded: float = 0) -> None: """Email the user if they asked to be notified, and send the desktop push.""" try: row = ( client.table("scans") .select("user_id,notify,notify_email,filename,status") .eq("id", scan_id).limit(1).execute() ) r = row.data[0] if row.data else None if r and r.get("status") == "done" and r.get("notify") and r.get("notify_email"): from notify import send_report_ready_email send_report_ready_email(r["notify_email"], r.get("filename") or "your video") if r: from push import notify_user name = r.get("filename") or "your video" if r.get("status") == "done": notify_user(client, r.get("user_id"), "scan_done", "Your report is ready ✅", f"The scan for {name} is complete. Tap to view it.", f"/scan/{scan_id}", f"scan-{scan_id}") elif r.get("status") == "error": back = f" Your {refunded:g} credits were refunded." if refunded else "" notify_user(client, r.get("user_id"), "scan_error", "Scan could not be completed", f"Something went wrong scanning {name}.{back} Tap for details.", f"/scan/{scan_id}", f"scan-{scan_id}") except Exception: # noqa: BLE001 log.warning("notify failed for %s", scan_id, exc_info=True) # Queue priority (same numbers as backend/main.py): the next scan is the highest # score = plan points + WAIT_BOOST per minute waited # so higher plans go first, and a free scan beats even a brand new Studio scan # after (50 - 10) / 4 = 10 minutes of waiting. Nobody waits forever. WAIT_BOOST = 4 FREE_POINTS = 10 def _score(row: dict, now: datetime.datetime) -> float: try: created = datetime.datetime.fromisoformat((row.get("created_at") or "").replace("Z", "+00:00")) except ValueError: created = now waited_min = max(0.0, (now - created).total_seconds() / 60) prio = row.get("priority") return (prio if prio is not None else FREE_POINTS) + WAIT_BOOST * waited_min def _waiting(client) -> list: """Pending scans, best score first (falls back to oldest first if the priority column isn't there yet).""" try: rows = client.table("scans").select("id,video_path,priority,created_at").eq("status", "pending").limit(200).execute().data or [] except Exception: # noqa: BLE001 rows = client.table("scans").select("id,video_path,created_at").eq("status", "pending").limit(200).execute().data or [] now = datetime.datetime.now(datetime.timezone.utc) rows.sort(key=lambda r: (-_score(r, now), r.get("created_at") or "")) return rows def poll_loop() -> None: """Forever: take the best waiting scan, run it, then look at the line again (so a paid scan that arrived meanwhile is picked next).""" from storage import get_client client = get_client() log.info("Poller started (every %ss)", POLL_SECONDS) while True: ran = False try: for row in _waiting(client): sid = row["id"] # claim atomically: only succeeds while the row is still pending claim = ( client.table("scans") .update({"status": "processing"}) .eq("id", sid).eq("status", "pending").execute() ) if not claim.data: continue # another worker took it ran = True try: run_scan(sid, row["video_path"]) _notify(client, sid) except Exception as exc: # noqa: BLE001 log.warning("scan %s failed: %s", sid, str(exc)[:300]) try: client.table("scans").update( {"status": "error", "error": str(exc)[:500]} ).eq("id", sid).execute() except Exception: # noqa: BLE001 pass # the user paid for a report they didn't get: give the credits back (once) from storage import refund_scan _notify(client, sid, refund_scan(client, sid)) break # re-rank the line before the next scan except Exception: # noqa: BLE001 log.exception("poll error") if not ran: time.sleep(POLL_SECONDS) # start the poller as soon as the Space boots threading.Thread(target=poll_loop, daemon=True).start() with gr.Blocks(title="Content Filter Worker") as demo: gr.Markdown( "## Content Filter AI worker\n" "This Space processes video scans in the background. Nothing to do here." ) # hidden control just so the @spaces.GPU function is registered at startup _btn = gr.Button("warmup", visible=False) _out = gr.Textbox(visible=False) _btn.click(_gpu_noop, inputs=None, outputs=_out) demo.queue().launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", "7860")))