Spaces:
Running on Zero
Running on Zero
Download analyzer.py from Pabot/Content-filter-ai: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/spaces/Pabot/Content-filter-ai/resolve/main/analyzer.py
- Command line
-
hf download hf://spaces/Pabot/Content-filter-ai/analyzer.py
-
curl -L -o analyzer.py https://huggingface.co/spaces/Pabot/Content-filter-ai/resolve/main/analyzer.py
11.5 kB
| """Turns a video into a ScanResult. | |
| `analyze_local` does the heavy lifting with no Supabase dependency (Gemini + | |
| ffmpeg screenshots) so it can be run from the CLI on a local file. `run_scan` | |
| wraps it with the Supabase download / upload / save orchestration used by the | |
| HF Space worker (and by the API when the worker is down). | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| import math | |
| import os | |
| import tempfile | |
| from typing import Callable, Optional | |
| from frames import extract_frame, mmss, needs_prepare, prepare_for_gemini, probe_duration | |
| from progress import ScanProgress, estimates_for | |
| from gemini_client import DEFAULT_MODEL, PROMPT_VERSION, analyze_video_ex | |
| from schemas import ( | |
| CATEGORY_LABEL, | |
| GeminiAnalysis, | |
| Category, | |
| FlaggedClip, | |
| ScanResult, | |
| verdict_from_risk, | |
| ) | |
| log = logging.getLogger("analyzer") | |
| # on_screenshot(index, clip, local_jpg_path) -> public/usable url | |
| ScreenshotHook = Callable[[int, FlaggedClip, str], str] | |
| def _clip_time(start: float, end: float) -> float: | |
| """A representative moment for the thumbnail: midpoint, clamped sanely.""" | |
| return start + (end - start) / 2 if end > start else start | |
| def analyze_local( | |
| local_video: str, | |
| model: str | None = None, | |
| workdir: str | None = None, | |
| on_screenshot: Optional[ScreenshotHook] = None, | |
| progress: Optional[ScanProgress] = None, | |
| duration_override: float | None = None, | |
| cached: tuple[dict, str] | None = None, | |
| on_analysis=None, | |
| ) -> ScanResult: | |
| """Analyze a local video file and return the enriched ScanResult. | |
| Screenshots are written into `workdir`. `on_screenshot` maps a local JPEG to | |
| a URL (e.g. upload to Supabase); if omitted, the local path is used as-is. | |
| """ | |
| model = model or DEFAULT_MODEL | |
| workdir = workdir or tempfile.mkdtemp(prefix="scan_") | |
| duration = duration_override if duration_override is not None else probe_duration(local_video) | |
| if cached: # this exact file was analyzed before: identical report, no AI call | |
| analysis, model = GeminiAnalysis.model_validate(cached[0]), cached[1] | |
| else: | |
| analysis, model = analyze_video_ex( # model = the one actually used | |
| local_video, model=model, on_stage=progress.ramp if progress else None, | |
| ) | |
| if on_analysis: | |
| on_analysis(analysis, model) | |
| if progress: | |
| progress.stop_ramp() | |
| progress.update("finish", 0.0, force=True) | |
| by_key = { | |
| c.key: Category( | |
| key=c.key, | |
| label=CATEGORY_LABEL.get(c.key, c.key), | |
| risk=c.risk, | |
| summary=c.summary, | |
| signals=c.signals, | |
| ) | |
| for c in analysis.categories | |
| } | |
| # always return the three categories in a stable order (fill any missing) | |
| categories = [ | |
| by_key.get(key, Category(key=key, label=CATEGORY_LABEL[key], risk=0, summary="", signals=[])) | |
| for key in ("reuse", "copyright", "advertiser") | |
| ] | |
| clips: list[FlaggedClip] = [] | |
| for i, gc in enumerate(analysis.flagged_clips): | |
| cid = f"clip_{i:02d}" | |
| clip = FlaggedClip( | |
| id=cid, | |
| category=gc.category, | |
| start_seconds=gc.start_seconds, | |
| end_seconds=gc.end_seconds, | |
| start_mmss=mmss(gc.start_seconds), | |
| end_mmss=mmss(gc.end_seconds), | |
| reason=gc.reason, | |
| confidence=gc.confidence, | |
| ) | |
| try: | |
| shot_local = os.path.join(workdir, f"{cid}.jpg") | |
| extract_frame(local_video, _clip_time(gc.start_seconds, gc.end_seconds), shot_local) | |
| clip.screenshot_path = f"{cid}.jpg" | |
| clip.screenshot_url = on_screenshot(i, clip, shot_local) if on_screenshot else shot_local | |
| except Exception: # noqa: BLE001 | |
| log.exception("Screenshot failed for %s; continuing", cid) | |
| clips.append(clip) | |
| if progress: | |
| progress.update("finish", (i + 1) / max(1, len(analysis.flagged_clips))) | |
| # Overall risk should never read lower than the worst single category. | |
| overall = analysis.overall_risk | |
| if categories: | |
| overall = max(overall, max(c.risk for c in categories)) | |
| return ScanResult( | |
| overall_risk=overall, | |
| verdict=verdict_from_risk(overall), | |
| summary=analysis.summary, | |
| categories=categories, | |
| clips=clips, | |
| model=model, | |
| duration_seconds=duration, | |
| duration_mmss=mmss(duration) if duration is not None else None, | |
| ) | |
| def _mmss_to_seconds(value: str | None) -> float | None: | |
| """"10:32" or "1:02:03" -> seconds.""" | |
| try: | |
| parts = [int(p) for p in (value or "").split(":")] | |
| except ValueError: | |
| return None | |
| if not parts or len(parts) > 3: | |
| return None | |
| secs = 0 | |
| for p in parts: | |
| secs = secs * 60 + p | |
| return float(secs) or None | |
| # ---- check the real length ----------------------------------------------------- | |
| # The price and the plan's length cap were based on the length the browser | |
| # reported. Once the file is here we measure it ourselves: past the cap the scan | |
| # is stopped (and refunded), and if it's longer than billed the difference is | |
| # charged, or the scan is stopped when there aren't enough credits. | |
| CREDITS_PER_MINUTE = 0.4 # same as backend/main.py | |
| LENGTH_SLACK = 3 # seconds; browsers and ffprobe can disagree a little | |
| class ScanRejected(Exception): | |
| """A scan we refuse to run; the message is shown to the user.""" | |
| def credits_for(seconds: float) -> float: | |
| """0.4 credit per minute, rounded to the nearest minute (min 1).""" | |
| return round(max(1, math.floor(seconds / 60 + 0.5)) * CREDITS_PER_MINUTE, 1) | |
| def _m_ss(seconds: float) -> str: | |
| total = int(round(seconds)) | |
| return f"{total // 60}:{total % 60:02d}" | |
| def _length_label(seconds: float) -> str: | |
| total = int(round(seconds)) | |
| h, rem = divmod(total, 3600) | |
| return f"{h}h {rem // 60}min" if h else f"{rem // 60}:{rem % 60:02d} min" | |
| def check_length(client, scan_id: str, row: dict, real: float) -> None: | |
| from storage import charge_scan_extra | |
| cap = row.get("max_minutes") | |
| if cap and real > cap * 60 + LENGTH_SLACK: | |
| limit = f"{cap // 60} hour" if cap % 60 == 0 and cap >= 60 else f"{cap} minute" | |
| raise ScanRejected(f"This video is {_length_label(real)} long, over the {limit} limit of your plan.") | |
| paid = row.get("cost") | |
| if paid is not None: | |
| extra = round(credits_for(max(1.0, real - LENGTH_SLACK)) - float(paid), 1) | |
| if extra > 0 and not charge_scan_extra(client, scan_id, extra): | |
| raise ScanRejected( | |
| f"This video is {_length_label(real)} long, longer than it looked when it was uploaded, " | |
| "and there aren't enough credits for the full length." | |
| ) | |
| if extra > 0: | |
| log.info("Scan %s: charged %.1f more credits for the real length", scan_id, extra) | |
| client.table("scans").update({"duration_mmss": _m_ss(real)}).eq("id", scan_id).execute() | |
| def _scan_row(client, scan_id: str) -> dict: | |
| try: | |
| rows = client.table("scans").select("duration_mmss,cost,max_minutes").eq("id", scan_id).limit(1).execute().data | |
| except Exception: # noqa: BLE001 (new columns not added yet) | |
| rows = client.table("scans").select("duration_mmss").eq("id", scan_id).limit(1).execute().data | |
| return rows[0] if rows else {} | |
| def run_scan( | |
| scan_id: str, video_path: str, model: str | None = None, duration_seconds: float | None = None, | |
| ) -> ScanResult: | |
| """Process a single scan: download → check length → analyze → save.""" | |
| # Imported here so the CLI (analyze_local) doesn't require Supabase env vars. | |
| from storage import ( | |
| cache_get, cache_put, delete_video, download_video, file_fingerprint, get_client, save_result, set_status, | |
| upload_screenshot, | |
| ) | |
| client = get_client() | |
| workdir = tempfile.mkdtemp(prefix=f"scan_{scan_id}_") | |
| # keep the real extension so prepare_for_gemini can spot .mov and friends | |
| local_video = os.path.join(workdir, "input" + (os.path.splitext(video_path)[1].lower() or ".mp4")) | |
| progress = None | |
| try: | |
| set_status(client, scan_id, "processing") | |
| # length for the estimates: stored on the scan row when it was created | |
| row = _scan_row(client, scan_id) | |
| duration_seconds = _mmss_to_seconds(row.get("duration_mmss")) or duration_seconds | |
| # live progress (% + step + time left) for the report page | |
| from r2 import is_r2, size as r2_size # backend/r2.py or worker/r2.py | |
| from_r2 = is_r2(video_path) | |
| size = (r2_size(video_path) if from_r2 else None) or 50e6 | |
| minutes = (duration_seconds or 0) / 60 or size / 20e6 | |
| progress = ScanProgress(client, scan_id, estimates_for(size, minutes, needs_prepare(local_video, int(size)), from_r2)) | |
| progress.update("download", 0.0, force=True) | |
| download_video(client, video_path, local_video, on_progress=lambda f: progress.update("download", f)) | |
| progress.update("download", 1.0) | |
| real_seconds = probe_duration(local_video) | |
| if real_seconds: | |
| check_length(client, scan_id, row, real_seconds) | |
| duration_seconds = real_seconds | |
| # same file scanned before (by anyone)? reuse its analysis for an identical report | |
| cache_key = f"{PROMPT_VERSION}:{file_fingerprint(local_video)}" | |
| cached = cache_get(client, cache_key) | |
| if cached: | |
| for step in ("prepare", "upload", "analyze"): | |
| progress.set_estimate(step, 0) | |
| elif needs_prepare(local_video): | |
| progress.update("prepare", 0.0, force=True) | |
| local_video = prepare_for_gemini( | |
| local_video, workdir, duration=duration_seconds, | |
| on_progress=lambda f: progress.update("prepare", f), | |
| ) | |
| else: | |
| progress.set_estimate("prepare", 0) | |
| if not cached: | |
| progress.set_estimate("upload", os.path.getsize(local_video) / 15e6 + 8) | |
| def remember(analysis, used_model) -> None: | |
| cache_put(client, cache_key, analysis.model_dump(), used_model) | |
| def upload_cb(_i: int, clip: FlaggedClip, shot_local: str) -> str: | |
| path = f"{scan_id}/{clip.id}.jpg" | |
| clip.screenshot_path = path | |
| return upload_screenshot(client, shot_local, path) | |
| result = analyze_local( | |
| local_video, model=model, workdir=workdir, on_screenshot=upload_cb, progress=progress, | |
| duration_override=real_seconds, cached=cached, on_analysis=remember, | |
| ) | |
| save_result(client, scan_id, result.model_dump()) | |
| log.info("Scan %s done: %d%% (%s)", scan_id, result.overall_risk, result.verdict) | |
| return result | |
| except Exception as exc: # noqa: BLE001 | |
| if isinstance(exc, ScanRejected): | |
| log.info("Scan %s rejected: %s", scan_id, exc) | |
| else: | |
| log.exception("Scan %s failed", scan_id) | |
| try: | |
| set_status(client, scan_id, "error", error=str(exc)[:500]) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| raise | |
| finally: | |
| if progress: | |
| progress.stop_ramp() | |
| # the video is only needed while scanning: remove it once the work is done | |
| delete_video(client, video_path) | |
| try: | |
| for name in os.listdir(workdir): | |
| os.remove(os.path.join(workdir, name)) | |
| os.rmdir(workdir) | |
| except OSError: | |
| pass | |