import { useState, useRef, useCallback, useEffect } from "react"; import { motion, AnimatePresence } from "framer-motion"; import { Activity, Video, Cpu, Info, CheckCircle2, XCircle, AlertTriangle, RotateCcw, ScanSearch, Eye, BarChart2, Mic2, Layers, Thermometer } from "lucide-react"; import TimelineChart from "./TimelineChart"; import AudioVisualSync from "./AudioVisualSync"; import VLMReasoningPanel from "./VLMReasoningPanel"; import { useAuth } from '../../hooks/useAuth.tsx'; import { API_BASE_URL } from '../../config'; const API = `${API_BASE_URL}`; const SIGNAL_META: Record = { spatial: { label: 'Spatial Neural', icon: Cpu, desc: 'Detects facial textures & diffusion artifacts', color: '#a78bfa' }, temporal: { label: 'Temporal Flow', icon: Layers, desc: 'RAFT-based pixel-motion logic & morphing', color: '#60a5fa' }, audio: { label: 'Audio-Lip Sync', icon: Mic2, desc: 'Phoneme-to-Viseme alignment audit', color: '#34d399' }, forensic: { label: 'Forensic Noise', icon: Thermometer, desc: 'PRNU sensor noise & spectral FFT signatures', color: '#f97316' }, reasoning: { label: 'VLM Reasoning', icon: ScanSearch, desc: 'Autonomous physics & geometry consistency', color: '#ef4444' }, }; const VERDICT_CONFIG = { 'DEEPFAKE': { color: '#ef4444', bg: 'rgba(239,68,68,0.1)', border: 'rgba(239,68,68,0.3)', icon: XCircle, label: 'AI DEEPFAKE', badge: 'CRITICAL' }, 'LIKELY FAKE': { color: '#f97316', bg: 'rgba(249,115,22,0.1)', border: 'rgba(249,115,22,0.3)', icon: AlertTriangle, label: 'LIKELY AI', badge: 'HIGH' }, 'UNCERTAIN': { color: '#eab308', bg: 'rgba(234,179,8,0.1)', border: 'rgba(234,179,8,0.3)', icon: Info, label: 'UNCERTAIN', badge: 'MEDIUM' }, 'LIKELY REAL': { color: '#22c55e', bg: 'rgba(34,197,94,0.1)', border: 'rgba(34,197,94,0.3)', icon: CheckCircle2, label: 'AUTHENTIC', badge: 'LOW' }, }; import DashboardLayout from '../../components/layout/DashboardLayout'; const VideoLabPage = () => { const { token } = useAuth(); const [phase, setPhase] = useState<"idle" | "uploading" | "polling" | "done" | "error">("idle"); const [result, setResult] = useState(null); const [error, setError] = useState(""); const [progress, setProgress] = useState(""); const fileRef = useRef(null); const pollRef = useRef | null>(null); const fileNameRef = useRef(''); const pollJob = useCallback(async (jobId: string) => { try { const res = await fetch(`${API}/video/status/${jobId}`, { headers: { ...(token ? { "Authorization": `Bearer ${token}` } : {}) } }); if (!res.ok) throw new Error("Poll failed"); const data = await res.json(); if (data.status === "complete" || data.status === "success") { if (pollRef.current) clearInterval(pollRef.current); setResult(data); setPhase("done"); } else if (data.status === "error") { if (pollRef.current) clearInterval(pollRef.current); setError(data.detail || "Analysis failed"); setPhase("error"); } } catch (e) { console.warn("Polling hiccup:", e); } }, []); const handleFile = useCallback(async (file: File) => { setPhase("uploading"); setProgress("Injecting payload..."); fileNameRef.current = file.name; const form = new FormData(); form.append("file", file); try { const res = await fetch(`${API}/video/analyze/async`, { method: "POST", headers: { ...(token ? { "Authorization": `Bearer ${token}` } : {}) }, body: form, }); if (!res.ok) throw new Error(`Upload failed: ${res.status}`); const { job_id } = await res.json(); setPhase("polling"); setProgress("Analyzing temporal flux..."); pollRef.current = setInterval(() => pollJob(job_id), 2500); } catch (e: any) { setError(e.message || "Upload failed"); setPhase("error"); } }, [pollJob]); const reset = () => { if (pollRef.current) clearInterval(pollRef.current); setPhase("idle"); setResult(null); setError(""); setProgress(""); if (fileRef.current) fileRef.current.value = ""; }; useEffect(() => { return () => { if (pollRef.current) clearInterval(pollRef.current); }; }, []); const vCfg = result?.data ? (VERDICT_CONFIG[result.data.verdict as keyof typeof VERDICT_CONFIG] || VERDICT_CONFIG['UNCERTAIN']) : null; return (

Video lab

Deepfake motion temporal audit

{phase === "idle" && (

Video analysis lab

Slight pixel-motion variations and frequency anomalies distinguish natural photon noise from diffusion dreaming.

fileRef.current?.click()} onDragOver={(e) => { e.preventDefault(); }} className="relative group cursor-pointer max-w-2xl mx-auto" >

Initialize Forensic Audit

MP4, MOV, WEBM ยท Sora, Gemini & Runway v10.0 Consistency Engine

{ const f = e.target.files?.[0]; if (f) handleFile(f); }} />
)} {(phase === "uploading" || phase === "polling") && (

{progress}

EXTRACTING OPTICAL FLOW VECTORS...
CALCULATING SENSOR NOISE PRINT...

)} {phase === "done" && result?.data && ( {/* Result Hero */}
{/* Verdict Card */}
{Math.round(result.data.ai_probability * 100)}% AI PROBABILITY

{vCfg?.label}

{vCfg?.badge} THREAT

Our forensic ensemble has detected consistent patterns of synthetic generation. The analysis of {result.data.metadata?.total_frames || '8'} frames confirms a {result.data.verdict.toLowerCase()} status with {result.data.agreement_count} module agreement.

Process: {result.data.processing_time}
Resolution: {result.data.metadata?.dimensions}
{/* Signals Panel */}

Forensic Signals

{Object.entries(result.data.signals).map(([key, val]: any) => { const meta = SIGNAL_META[key]; if (!meta) return null; const pct = Math.round(val * 100); const Icon = meta.icon; return (
{meta.label}
{pct}%
); })}
{/* Evidence Spotlight & RAFT Heatmap */} {result.data.evidence_heatmap && (
Optical Flow Heatmap
RAFT FLOW ANALYSIS

Evidence Spotlight

The RAFT-Optical Flow engine has isolated a mass-discontinuity in the temporal flux. Natural motion is rigid, while AI-generated pixels exhibit "morphing" residuals captured in this forensic heatmap.

"Physical reality breaks detected near frame {Math.round(result.data.metadata?.total_frames / 2)}"

CONSISTENCY SCORE

Physics Validation 0.6 ? '#ef4444' : '#22c55e' }}> {result.data.signals?.reasoning > 0.6 ? 'POOR' : 'EXCELLENT'}
0.6 ? '#ef4444' : '#22c55e' }} />

Measures adherence to mass-conservation and lighting-physics constraints. High scores indicate physical reality.

)} {/* New Analysis Visualizations */}
{/* Timeline Chart */}

Audit Timeline

ENGINE_CONSISTENCY_v10.0
{/* VLM Reasoning */}
{/* Sub Panels */}
{/* Evidence List */}

Forensic Brief

{result.data.reasons.map((reason: string, i: number) => (

{reason}

))}
{/* Physics Info */}

Temporal Evidence

Motion Stability
0.7 ? '#ef4444' : '#22c55e' }}> {result.data.signals.temporal_flow > 0.7 ? 'UNSTABLE' : 'STABLE'}
PAVR Ratio
{(result.data.signals.temporal_flow * 15).toFixed(2)}x
0.7 ? '#ef4444' : '#22c55e' }} />

Video sequences generated by diffusion models (Sora/Gen-3) exhibit significant peaks in pixel-mass variance where objects undergo non-physical morphing.

Total Frames
{result.data.metadata?.total_frames}
Frame Rate
{result.data.metadata?.fps} fps
)} {phase === "error" && (

Analysis Failed

{error}

)}
); }; export default VideoLabPage;