Spaces:
Running
Running
first commit
Browse filesFiles changed (9)
- DockerfileAdded+26
- README.md+31-4
- app/__init__.pyAdded
- app/main.pyAdded+78
- app/model.pyAdded+76
- app/requirements.txtAdded+9
- app/static/index.htmlAdded+477
- app/video.pyAdded+32
- model.safetensorsAdded+3
1234567891011121314151617181920212223242526FROM python:3.11-slim
RUN apt-get update && apt-get install -y --no-install-recommends \ libgl1 \ libglib2.0-0 \ && rm -rf /var/lib/apt/lists/*
WORKDIR /code
COPY app/requirements.txt /code/requirements.txtRUN pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu \ -r /code/requirements.txt
ENV HF_HOME=/code/.hf-cacheENV PYTHONUNBUFFERED=1
RUN python -c "from transformers import AutoImageProcessor, AutoModelForImageClassification; \AutoImageProcessor.from_pretrained('microsoft/swinv2-base-patch4-window16-256', cache_dir='/code/.hf-cache'); \AutoModelForImageClassification.from_pretrained('microsoft/swinv2-base-patch4-window16-256', cache_dir='/code/.hf-cache')"
COPY model.safetensors /code/model.safetensorsCOPY app /code/app
EXPOSE 7860
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]1234567891011---title: OpenFakeDemoemoji: ⚡colorFrom: greencolorTo: bluesdk: dockerpinned: falselicense: cc-by-nc-4.0---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314151617181920212223242526272829303132333435363738---title: OpenFakeDemoemoji: 🔍colorFrom: bluecolorTo: indigosdk: dockerapp_port: 7860pinned: falselicense: cc-by-nc-4.0---# Deepfake DetectorUpload an image or short video to check if it's AI-generated. Powered by a Swin Transformer V2 model fine-tuned on real vs synthetic images.## How it works- **Images**: a single forward pass through `microsoft/swinv2-base-patch4-window16-256` with a 2-class fine-tuned head (label 0 = real, label 1 = fake). The reliability score is `1 - P(fake)`.- **Videos**: 5 frames are sampled uniformly across the duration; the per-frame `P(fake)` values are averaged.## Endpoints- `GET /` — the web UI (English / French toggle)- `POST /api/predict` — multipart upload, field `file`. Returns `{ media_type, p_fake, reliability, n_frames, frame_probs? }`.## Local development```bashdocker build -t openfake-demo .docker run --rm -p 7860:7860 openfake-demo```Then open http://localhost:7860.## Notes- Free Hugging Face Spaces sleep after 48 hours of inactivity. The first request after sleep takes 30–60 seconds while the container boots.- Uploaded files are processed in memory and not persisted.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import ioimport tempfilefrom pathlib import Path
from fastapi import FastAPI, File, HTTPException, UploadFilefrom fastapi.staticfiles import StaticFilesfrom PIL import Image
from .model import load_detector, predict_imagefrom .video import sample_frames
MAX_IMAGE_SIZE_MB = 20MAX_VIDEO_SIZE_MB = 100N_VIDEO_FRAMES = 5
IMAGE_TYPES = {"image/jpeg", "image/jpg", "image/png", "image/webp"}VIDEO_TYPES = {"video/mp4", "video/quicktime", "video/webm", "video/x-matroska"}
app = FastAPI(title="Deepfake Detector")
@app.on_event("startup")def warmup(): load_detector()
@app.post("/api/predict")async def predict(file: UploadFile = File(...)): content_type = (file.content_type or "").lower() raw = await file.read() size_mb = len(raw) / (1024 * 1024)
if content_type in IMAGE_TYPES: if size_mb > MAX_IMAGE_SIZE_MB: raise HTTPException(413, f"Image exceeds {MAX_IMAGE_SIZE_MB} MB") try: image = Image.open(io.BytesIO(raw)) except Exception: raise HTTPException(400, "Invalid image") p_fake = predict_image(image) return { "media_type": "image", "p_fake": p_fake, "reliability": 1.0 - p_fake, "n_frames": 1, }
if content_type in VIDEO_TYPES: if size_mb > MAX_VIDEO_SIZE_MB: raise HTTPException(413, f"Video exceeds {MAX_VIDEO_SIZE_MB} MB") suffix = Path(file.filename or "video.mp4").suffix or ".mp4" with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp: tmp.write(raw) tmp_path = tmp.name try: frames = sample_frames(tmp_path, N_VIDEO_FRAMES) except ValueError as e: raise HTTPException(400, str(e)) finally: try: Path(tmp_path).unlink(missing_ok=True) except Exception: pass probs = [predict_image(f) for f in frames] p_fake = sum(probs) / len(probs) return { "media_type": "video", "p_fake": p_fake, "reliability": 1.0 - p_fake, "n_frames": len(frames), "frame_probs": probs, }
raise HTTPException(415, f"Unsupported media type: {content_type}")
static_dir = Path(__file__).parent / "static"app.mount("/", StaticFiles(directory=str(static_dir), html=True), name="static")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import osfrom pathlib import Path
import torchimport torch.nn as nnfrom PIL import Imagefrom safetensors.torch import load_filefrom transformers import AutoImageProcessor, AutoModelForImageClassification
HF_NAME = "microsoft/swinv2-base-patch4-window16-256"WEIGHTS_PATH = Path(__file__).parent.parent / "model.safetensors"NUM_LABELS = 2
_device = torch.device("cpu")_processor = None_model = None
def _strip_prefixes(state_dict: dict) -> dict: """Strip common wrapper prefixes (DDP, Lightning) from state dict keys.""" prefixes = ("module.", "model.") cleaned = {} for k, v in state_dict.items(): new_k = k for p in prefixes: if new_k.startswith(p): new_k = new_k[len(p):] break cleaned[new_k] = v return cleaned
def load_detector(): global _processor, _model if _model is not None: return _processor, _model
cache_dir = os.environ.get("HF_HOME", "/tmp/hf-cache")
processor = AutoImageProcessor.from_pretrained( HF_NAME, cache_dir=cache_dir ) model = AutoModelForImageClassification.from_pretrained( HF_NAME, cache_dir=cache_dir )
model.num_labels = NUM_LABELS model.config.num_labels = NUM_LABELS model.config.id2label = {0: "real", 1: "fake"} model.config.label2id = {"real": 0, "fake": 1} model.classifier = nn.Linear(model.swinv2.num_features, NUM_LABELS)
state_dict = load_file(str(WEIGHTS_PATH)) state_dict = _strip_prefixes(state_dict) missing, unexpected = model.load_state_dict(state_dict, strict=False) if missing: print(f"[load_detector] missing keys ({len(missing)}): {missing[:10]}") if unexpected: print(f"[load_detector] unexpected keys ({len(unexpected)}): {unexpected[:10]}")
model.eval().to(_device) _processor = processor _model = model return _processor, _model
@torch.no_grad()def predict_image(image: Image.Image) -> float: """Returns P(fake) in [0, 1].""" processor, model = load_detector() if image.mode != "RGB": image = image.convert("RGB") inputs = processor(images=image, return_tensors="pt").to(_device) logits = model(**inputs).logits probs = torch.softmax(logits, dim=-1) return float(probs[0, 1].item())123456789fastapi==0.115.0uvicorn[standard]==0.30.6torch==2.4.1transformers==4.45.2safetensors==0.4.5Pillow==10.4.0opencv-python-headless==4.10.0.84python-multipart==0.0.12numpy==1.26.4123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Deepfake detector</title> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet" /> <script src="https://cdn.tailwindcss.com"></script> <style> html, body { font-family: 'Inter', system-ui, -apple-system, sans-serif; } body { background: #f8fafc; color: #0f172a; } .arc-fg { transition: stroke-dashoffset 900ms cubic-bezier(0.22, 1, 0.36, 1); } .drop-active { border-color: #1d4ed8; background-color: #eff6ff; } .fade-in { animation: fadeIn 350ms ease-out both; } @keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } } </style></head><body class="min-h-screen"> <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6"> <header class="flex items-center justify-between"> <div class="flex items-center gap-2"> <div class="w-9 h-9 rounded-lg bg-blue-600 flex items-center justify-center text-white font-bold">OF</div> <span class="font-bold text-lg" data-i18n="title">Deepfake detector</span> </div> <div class="inline-flex items-center rounded-full border border-gray-200 bg-white p-1 text-sm"> <button id="lang-en" class="px-3 py-1 rounded-full font-semibold">EN</button> <button id="lang-fr" class="px-3 py-1 rounded-full font-semibold">FR</button> </div> </header>
<main class="mt-10 sm:mt-16"> <section class="text-center max-w-2xl mx-auto"> <h1 class="text-4xl sm:text-5xl font-extrabold tracking-tight" data-i18n="title">Deepfake detector</h1> <p class="mt-4 text-gray-600 text-lg" data-i18n="subtitle">Upload an image or short video to check if it's AI-generated.</p> </section>
<section id="card-root" class="mt-10"> <!-- Upload zone --> <div id="upload-card" class="bg-white rounded-2xl border border-gray-200 p-6 sm:p-10 shadow-sm"> <label id="dropzone" for="file-input" class="block border-2 border-dashed border-gray-300 rounded-xl p-10 text-center cursor-pointer hover:border-blue-400 transition-colors"> <input id="file-input" type="file" class="hidden" accept="image/jpeg,image/png,image/webp,video/mp4,video/quicktime,video/webm" /> <div id="upload-prompt"> <div class="mx-auto w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center mb-4"> <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"> <path stroke-linecap="round" stroke-linejoin="round" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M12 12V4m0 0l-4 4m4-4l4 4"/> </svg> </div> <div class="text-base font-semibold text-gray-900" data-i18n="upload_cta">Choose a file or drag and drop</div> <div class="text-sm text-gray-500 mt-1" data-i18n="upload_hint">JPG, PNG, MP4 up to 100 MB</div> </div> <div id="preview" class="hidden"> <div id="preview-media" class="mx-auto mb-4 max-h-64 flex justify-center"></div> <div id="preview-filename" class="text-sm font-medium text-gray-900 truncate"></div> <div id="preview-size" class="text-xs text-gray-500 mt-1"></div> </div> </label>
<div id="error-banner" class="hidden mt-4 rounded-lg bg-red-50 border border-red-200 text-red-700 px-4 py-3 text-sm"></div>
<div class="mt-6 flex flex-col sm:flex-row gap-3 justify-center"> <button id="analyze-btn" disabled class="px-6 py-3 rounded-xl bg-blue-600 text-white font-semibold disabled:bg-gray-300 disabled:cursor-not-allowed hover:bg-blue-700 transition-colors"> <span data-i18n="analyze">Analyze</span> </button> <button id="reset-btn" class="hidden px-6 py-3 rounded-xl border border-gray-300 text-gray-700 font-semibold hover:bg-gray-50"> <span data-i18n="clear">Clear</span> </button> </div> </div>
<!-- Loading --> <div id="loading-card" class="hidden bg-white rounded-2xl border border-gray-200 p-10 shadow-sm text-center"> <div class="mx-auto w-12 h-12 border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin"></div> <div id="loading-text" class="mt-5 text-gray-700 font-medium" data-i18n="analyzing">Analyzing...</div> </div>
<!-- Result --> <div id="result-card" class="hidden bg-white rounded-2xl border border-gray-200 p-6 sm:p-10 shadow-sm fade-in"> <div class="flex items-start justify-between flex-wrap gap-2"> <div> <div class="text-sm font-semibold text-gray-900 flex items-center gap-1.5"> <span data-i18n="reliability_score">Reliability score</span> <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"> <path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/> </svg> </div> <button id="how-link" class="mt-1 text-sm text-gray-500 underline decoration-gray-300 hover:text-gray-700"> <span data-i18n="how_calculated">How is this calculated?</span> </button> </div> </div>
<div class="mt-8 grid grid-cols-1 md:grid-cols-2 gap-8 items-center"> <div class="flex flex-col items-center"> <div class="relative w-48 h-48 sm:w-56 sm:h-56"> <svg viewBox="0 0 200 200" class="w-full h-full -rotate-90"> <circle cx="100" cy="100" r="80" fill="none" stroke="#e5e7eb" stroke-width="14" stroke-linecap="round"/> <circle id="arc-fg" cx="100" cy="100" r="80" fill="none" stroke="#1d4ed8" stroke-width="14" stroke-linecap="round" stroke-dasharray="502.65" stroke-dashoffset="502.65" class="arc-fg"/> </svg> <div class="absolute inset-0 flex flex-col items-center justify-center"> <div class="text-xs uppercase tracking-wider text-gray-500 font-semibold" data-i18n="reliability">Reliability</div> <div id="reliability-pct" class="text-4xl sm:text-5xl font-extrabold mt-1 text-gray-900">--%</div> </div> </div> </div>
<div> <div id="verdict-text" class="text-3xl sm:text-4xl font-extrabold leading-tight text-blue-600"></div> <div id="advice-text" class="mt-3 text-lg sm:text-xl font-semibold text-gray-900"></div> <div id="frames-info" class="mt-4 text-sm text-gray-500"></div> </div> </div>
<div class="mt-8 flex justify-center"> <button id="analyze-another-btn" class="px-6 py-3 rounded-xl border border-gray-300 text-gray-700 font-semibold hover:bg-gray-50"> <span data-i18n="analyze_another">Analyze another file</span> </button> </div> </div> </section>
<footer class="mt-16 text-center text-xs text-gray-400"> <span data-i18n="privacy_note">Files are processed in memory and not stored.</span> </footer> </main> </div>
<!-- Modal --> <div id="modal-backdrop" class="hidden fixed inset-0 bg-black/40 z-40"></div> <div id="modal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4"> <div class="bg-white rounded-2xl max-w-lg w-full p-6 shadow-xl"> <h2 id="modal-title" class="text-xl font-bold" data-i18n="how_calculated_title">How the score is computed</h2> <p id="modal-body" class="mt-3 text-gray-700 leading-relaxed" data-i18n="how_calculated_body"></p> <div class="mt-5 text-right"> <button id="modal-close" class="px-4 py-2 rounded-lg bg-blue-600 text-white font-semibold hover:bg-blue-700"> <span data-i18n="close">Close</span> </button> </div> </div> </div>
<script> const I18N = { en: { title: "Deepfake detector", subtitle: "Upload an image or short video to check if it's AI-generated.", upload_cta: "Choose a file or drag and drop", upload_hint: "JPG, PNG, MP4 up to 100 MB", analyze: "Analyze", clear: "Clear", analyzing: "Analyzing...", analyzing_video: "Sampling frames and running the model...", reliability_score: "Reliability score", how_calculated: "How is this calculated?", reliability: "Reliability", verdict_low_image: "This image is likely not reliable,", verdict_low_video: "This video is likely not reliable,", verdict_mid_image: "We're uncertain about this image,", verdict_mid_video: "We're uncertain about this video,", verdict_high_image: "This image is likely authentic,", verdict_high_video: "This video is likely authentic,", advice_low: "you should not share it with your network.", advice_mid: "verify it from trusted sources before sharing.", advice_high: "but always cross-check important content.", analyze_another: "Analyze another file", error_generic: "Something went wrong. Please try again.", error_size: "File is too large.", error_type: "Unsupported file type.", frames_info: "Averaged over {n} frames.", how_calculated_title: "How the score is computed", how_calculated_body: "We use a Swin Transformer V2 model fine-tuned to distinguish real photographs from AI-generated images. For videos, we sample 5 frames evenly across the duration and average the model's confidence. The reliability score is 1 minus the model's probability that the content is AI-generated.", close: "Close", privacy_note: "Files are processed in memory and not stored.", }, fr: { title: "Détecteur de deepfake", subtitle: "Téléversez une image ou une courte vidéo pour vérifier si elle est générée par IA.", upload_cta: "Choisissez un fichier ou glissez-déposez", upload_hint: "JPG, PNG, MP4 jusqu'à 100 Mo", analyze: "Analyser", clear: "Effacer", analyzing: "Analyse en cours...", analyzing_video: "Échantillonnage des images et exécution du modèle...", reliability_score: "Score de fiabilité", how_calculated: "Comment est-ce calculé ?", reliability: "Fiabilité", verdict_low_image: "Cette image n'est probablement pas fiable,", verdict_low_video: "Cette vidéo n'est probablement pas fiable,", verdict_mid_image: "Nous ne sommes pas certains pour cette image,", verdict_mid_video: "Nous ne sommes pas certains pour cette vidéo,", verdict_high_image: "Cette image est probablement authentique,", verdict_high_video: "Cette vidéo est probablement authentique,", advice_low: "vous ne devriez pas la partager avec votre réseau.", advice_mid: "vérifiez auprès de sources fiables avant de partager.", advice_high: "vérifiez tout de même les contenus importants.", analyze_another: "Analyser un autre fichier", error_generic: "Une erreur est survenue. Veuillez réessayer.", error_size: "Le fichier est trop volumineux.", error_type: "Type de fichier non pris en charge.", frames_info: "Moyenne sur {n} images.", how_calculated_title: "Comment le score est calculé", how_calculated_body: "Nous utilisons un modèle Swin Transformer V2 entraîné pour distinguer les vraies photographies des images générées par IA. Pour les vidéos, nous échantillonnons 5 images réparties uniformément sur la durée et faisons la moyenne de la confiance du modèle. Le score de fiabilité correspond à 1 moins la probabilité estimée que le contenu soit généré par IA.", close: "Fermer", privacy_note: "Les fichiers sont traités en mémoire et ne sont pas conservés.", }, };
const CIRCUMFERENCE = 2 * Math.PI * 80;
const state = { lang: localStorage.getItem("lang") || (navigator.language.startsWith("fr") ? "fr" : "en"), file: null, result: null, loading: false, error: null, };
const $ = (id) => document.getElementById(id);
function t() { return I18N[state.lang]; }
function applyI18n() { document.documentElement.lang = state.lang; document.querySelectorAll("[data-i18n]").forEach((el) => { const key = el.getAttribute("data-i18n"); if (t()[key] != null) el.textContent = t()[key]; }); $("lang-en").className = "px-3 py-1 rounded-full font-semibold " + (state.lang === "en" ? "bg-blue-600 text-white" : "text-gray-600"); $("lang-fr").className = "px-3 py-1 rounded-full font-semibold " + (state.lang === "fr" ? "bg-blue-600 text-white" : "text-gray-600"); if (state.result) renderResultText(); }
function setLang(lang) { state.lang = lang; localStorage.setItem("lang", lang); applyI18n(); }
function getVerdict(reliability, mediaType) { const T = t(); if (reliability >= 0.70) { return { verdict: mediaType === "video" ? T.verdict_high_video : T.verdict_high_image, advice: T.advice_high, tone: "high", }; } if (reliability >= 0.40) { return { verdict: mediaType === "video" ? T.verdict_mid_video : T.verdict_mid_image, advice: T.advice_mid, tone: "mid", }; } return { verdict: mediaType === "video" ? T.verdict_low_video : T.verdict_low_image, advice: T.advice_low, tone: "low", }; }
function showPreview(file) { const previewMedia = $("preview-media"); previewMedia.innerHTML = ""; if (file.type.startsWith("image/")) { const img = document.createElement("img"); img.src = URL.createObjectURL(file); img.className = "max-h-64 rounded-lg object-contain"; img.onload = () => URL.revokeObjectURL(img.src); previewMedia.appendChild(img); } else { const video = document.createElement("video"); video.src = URL.createObjectURL(file); video.className = "max-h-64 rounded-lg"; video.muted = true; video.playsInline = true; video.preload = "metadata"; previewMedia.appendChild(video); } $("upload-prompt").classList.add("hidden"); $("preview").classList.remove("hidden"); $("preview-filename").textContent = file.name; $("preview-size").textContent = `${(file.size / (1024 * 1024)).toFixed(2)} MB`; $("analyze-btn").disabled = false; $("reset-btn").classList.remove("hidden"); }
function resetUpload() { state.file = null; state.error = null; $("file-input").value = ""; $("upload-prompt").classList.remove("hidden"); $("preview").classList.add("hidden"); $("analyze-btn").disabled = true; $("reset-btn").classList.add("hidden"); $("error-banner").classList.add("hidden"); }
function showError(msg) { const banner = $("error-banner"); banner.textContent = msg; banner.classList.remove("hidden"); }
function setFile(file) { $("error-banner").classList.add("hidden"); if (!file) return; const isImage = file.type.startsWith("image/"); const isVideo = file.type.startsWith("video/"); if (!isImage && !isVideo) { showError(t().error_type); return; } const maxMB = isVideo ? 100 : 20; if (file.size / (1024 * 1024) > maxMB) { showError(t().error_size); return; } state.file = file; showPreview(file); }
function renderResultText() { if (!state.result) return; const r = state.result.reliability; const v = getVerdict(r, state.result.media_type); $("verdict-text").textContent = v.verdict; $("advice-text").textContent = v.advice; $("reliability-pct").textContent = `${Math.round(r * 100)}%`; const arc = $("arc-fg"); const tones = { high: "#16a34a", mid: "#d97706", low: "#1d4ed8", }; arc.setAttribute("stroke", tones[v.tone]); if (state.result.media_type === "video") { $("frames-info").textContent = t().frames_info.replace("{n}", state.result.n_frames); } else { $("frames-info").textContent = ""; } }
function animateArc(reliability) { const arc = $("arc-fg"); arc.style.transition = "none"; arc.setAttribute("stroke-dashoffset", CIRCUMFERENCE); requestAnimationFrame(() => { requestAnimationFrame(() => { arc.style.transition = ""; const target = CIRCUMFERENCE * (1 - Math.max(0, Math.min(1, reliability))); arc.setAttribute("stroke-dashoffset", target); }); }); }
function showCard(name) { ["upload-card", "loading-card", "result-card"].forEach((id) => { $(id).classList.toggle("hidden", id !== name); }); }
async function analyze() { if (!state.file) return; state.loading = true; state.error = null; const isVideo = state.file.type.startsWith("video/"); $("loading-text").textContent = isVideo ? t().analyzing_video : t().analyzing; showCard("loading-card");
const form = new FormData(); form.append("file", state.file);
try { const res = await fetch("/api/predict", { method: "POST", body: form }); if (!res.ok) { let detail = t().error_generic; if (res.status === 413) detail = t().error_size; else if (res.status === 415) detail = t().error_type; else { const body = await res.json().catch(() => ({})); if (body.detail) detail = body.detail; } throw new Error(detail); } state.result = await res.json(); renderResultText(); showCard("result-card"); animateArc(state.result.reliability); } catch (e) { showError(e.message); showCard("upload-card"); } finally { state.loading = false; } }
function openModal() { $("modal").classList.remove("hidden"); $("modal").classList.add("flex"); $("modal-backdrop").classList.remove("hidden"); } function closeModal() { $("modal").classList.add("hidden"); $("modal").classList.remove("flex"); $("modal-backdrop").classList.add("hidden"); }
function init() { applyI18n();
$("lang-en").addEventListener("click", () => setLang("en")); $("lang-fr").addEventListener("click", () => setLang("fr"));
const fileInput = $("file-input"); fileInput.addEventListener("change", (e) => { const f = e.target.files && e.target.files[0]; if (f) setFile(f); });
const dz = $("dropzone"); ["dragenter", "dragover"].forEach((evt) => { dz.addEventListener(evt, (e) => { e.preventDefault(); e.stopPropagation(); dz.classList.add("drop-active"); }); }); ["dragleave", "drop"].forEach((evt) => { dz.addEventListener(evt, (e) => { e.preventDefault(); e.stopPropagation(); dz.classList.remove("drop-active"); }); }); dz.addEventListener("drop", (e) => { const f = e.dataTransfer.files && e.dataTransfer.files[0]; if (f) setFile(f); });
$("analyze-btn").addEventListener("click", analyze); $("reset-btn").addEventListener("click", (e) => { e.preventDefault(); e.stopPropagation(); resetUpload(); }); $("analyze-another-btn").addEventListener("click", () => { state.result = null; resetUpload(); showCard("upload-card"); });
$("how-link").addEventListener("click", openModal); $("modal-close").addEventListener("click", closeModal); $("modal-backdrop").addEventListener("click", closeModal); document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeModal(); }); }
init(); </script></body></html>1234567891011121314151617181920212223242526272829303132import cv2import numpy as npfrom PIL import Image
def sample_frames(video_path: str, n_frames: int = 5) -> list[Image.Image]: """Sample n_frames uniformly across the video. Returns RGB PIL images.""" cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise ValueError("Could not open video file")
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) if total <= 0: cap.release() raise ValueError("Video has no readable frames")
n = min(n_frames, total) indices = np.linspace(0, total - 1, n, dtype=int)
frames = [] for idx in indices: cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx)) ok, frame = cap.read() if not ok: continue frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frames.append(Image.fromarray(frame))
cap.release() if not frames: raise ValueError("No frames could be decoded from video") return frames123version https://git-lfs.github.com/spec/v1oid sha256:69e90d17644cfd2599af271900168562cec8f102411b0dfa58e1451694ff7f8asize 347645480DockerfileAdded+26
README.md+31-4
app/__init__.pyAdded
app/main.pyAdded+78
app/model.pyAdded+76
app/requirements.txtAdded+9
app/static/index.htmlAdded+477
app/video.pyAdded+32
model.safetensorsAdded+3