import { useState, useEffect, useRef } from 'react' import { useLiveData } from '../context/LiveDataContext' import { Card, MetricCard, EmptyState, DataSourceTag, StatusBadge } from '../components/ui' import { Eye, Activity, AlertTriangle, Video, Upload, FileVideo, Play, CheckCircle2, AlertOctagon, Download, Loader2, BarChart3, Layers, Car, Siren, ShieldAlert, } from 'lucide-react' import { fetchComparison, fetchPerception, fetchVideoSamples, fetchLatestVideoAnalysis, analyzeSampleVideo, uploadAndAnalyzeVideo, } from '../services/api' export default function Perception() { const { safety } = useLiveData() const [comparison, setComparison] = useState([]) const [samples, setSamples] = useState([]) const [selectedSample, setSelectedSample] = useState('') const [analysisResult, setAnalysisResult] = useState(null) const [isProcessing, setIsProcessing] = useState(false) const [processError, setProcessError] = useState(null) const [activeTab, setActiveTab] = useState('samples') // 'samples' | 'upload' const [selectedFile, setSelectedFile] = useState(null) // Frame inspector state const [selectedFrame, setSelectedFrame] = useState(null) const [frameDetections, setFrameDetections] = useState([]) const [loadingFrame, setLoadingFrame] = useState(false) const fileInputRef = useRef(null) useEffect(() => { fetchComparison().then(setComparison).catch(() => {}) fetchVideoSamples().then((list) => { setSamples(list) if (list.length > 0) { // Default to accident_002.mp4 or first sample const defaultSample = list.find((s) => s.filename.includes('accident_002')) || list[0] setSelectedSample(defaultSample.relative_path) } }).catch(() => {}) fetchLatestVideoAnalysis().then((data) => { if (data && data.analysis) { setAnalysisResult(data) initFrameFromAnalysis(data.analysis) } }).catch(() => {}) }, []) const initFrameFromAnalysis = (analysis) => { if (!analysis) return const activeFrames = analysis.active_frame_numbers || [] const firstActive = activeFrames.length > 0 ? activeFrames[0] : 1 setSelectedFrame(firstActive) loadFrameData(firstActive) } const loadFrameData = async (frameNum) => { setLoadingFrame(true) try { const res = await fetchPerception(frameNum) if (res && res.detections) { setFrameDetections(res.detections) } else { setFrameDetections([]) } } catch (_) { setFrameDetections([]) } setLoadingFrame(false) } const handleFrameChange = (frameNum) => { setSelectedFrame(frameNum) loadFrameData(frameNum) } const handleAnalyzeSample = async () => { if (!selectedSample) return setIsProcessing(true) setProcessError(null) try { const res = await analyzeSampleVideo(selectedSample) setAnalysisResult(res) initFrameFromAnalysis(res.analysis) } catch (err) { setProcessError(err.message || 'Failed to process sample video') } setIsProcessing(false) } const handleFileUpload = async () => { if (!selectedFile) return setIsProcessing(true) setProcessError(null) try { const res = await uploadAndAnalyzeVideo(selectedFile) setAnalysisResult(res) initFrameFromAnalysis(res.analysis) } catch (err) { setProcessError(err.message || 'Failed to process uploaded video') } setIsProcessing(false) } const handleDownloadJSON = () => { if (!analysisResult) return const jsonStr = JSON.stringify(analysisResult, null, 2) const blob = new Blob([jsonStr], { type: 'application/json' }) const url = URL.createObjectURL(blob) const a = document.createElement('a') a.href = url a.download = `perception_analysis_${Date.now()}.json` document.body.appendChild(a) a.click() document.body.removeChild(a) URL.revokeObjectURL(url) } const riskScore = safety?.risk_score ?? 0 const nearMissRisk = safety?.near_miss_risk ?? 0 const confidence = safety?.safety_confidence ?? 0 const pairRisks = safety?.pair_risks ?? [] const accidentStatus = safety?.accident_status ?? 'unavailable_no_camera_frame_or_model' const isAccidentUnavailable = accidentStatus.includes('unavailable') const analysis = analysisResult?.analysis const summary = analysis?.summary const vehicleTypes = analysis?.vehicle_types || {} const emergencyAnalysis = analysis?.emergency_analysis const frameStats = analysis?.frame_statistics const confStats = analysis?.confidence_statistics const trackingCheck = analysis?.tracking_check return (

Perception & Video Evidence Analysis

Upload and process real traffic footage using the unified YOLO11n + ByteTrack + Emergency perception pipeline.

{/* ============================================================== */} {/* VIDEO PIPELINE WORKBENCH (UPLOAD OR SAMPLE) */} {/* ============================================================== */}
{/* Tabs */}
{/* Tab 1: Samples */} {activeTab === 'samples' && (
{/* Sample badges */}
Quick Test Presets:
)} {/* Tab 2: Upload */} {activeTab === 'upload' && (
fileInputRef.current?.click()} className="border-2 border-dashed border-slate-700 hover:border-blue-500 bg-slate-900/40 rounded-xl p-6 text-center cursor-pointer transition" >

{selectedFile ? selectedFile.name : 'Click or Drag & Drop Video File to Upload'}

Supports MP4, AVI, MOV, MKV. Pipeline runs detection + tracking + emergency classification on GPU.

setSelectedFile(e.target.files?.[0] || null)} className="hidden" />
{selectedFile && (
{selectedFile.name} ({(selectedFile.size / (1024 * 1024)).toFixed(2)} MB)
)}
)} {/* Status / Errors */} {isProcessing && (

Processing video through Unified Phase 6 Pipeline...

Running YOLO11n object tracker, ByteTrack association, and emergency classifier on GPU.

)} {processError && (
{processError}
)}
{/* ============================================================== */} {/* COMPREHENSIVE VIDEO EVIDENCE & PERCEPTION REPORT */} {/* ============================================================== */} {summary && (
{/* Header info & export */}
Analysis Completed: {analysisResult?.filename || 'Evidence Run'} {analysisResult?.elapsed_seconds ? `Execution time: ${analysisResult.elapsed_seconds}s • Output saved to outputs/perception_output.json` : 'Loaded from perception telemetry cache'}
{/* PART 1: DETECTION SUMMARY */}

Part 1 — Perception Detection Summary

Total Frames

{summary.total_frames}

Total Detections

{summary.total_detections}

Active Frames

{summary.active_frames}

Unique Vehicles

{summary.unique_vehicles}

Emergency Events

0 ? 'text-red-400' : 'text-slate-400'}`}> {summary.emergency_detections}

{/* Vehicle / Object Types Counter */}
Object & Vehicle Class Distribution:
{Object.entries(vehicleTypes).length === 0 ? ( No objects classified ) : ( Object.entries(vehicleTypes).map(([type, count]) => (
{type}: {count}
)) )}
{/* PART 2: EMERGENCY ANALYSIS */} {emergencyAnalysis && (

Part 2 — Emergency Vehicle Analysis

{emergencyAnalysis.emergency_detections > 0 ? (
ACTIVE EMERGENCY IDENTIFIED IN FOOTAGE {emergencyAnalysis.emergency_detections} Emergency Detections

Tracked Emergency Vehicle IDs:{' '} {emergencyAnalysis.emergency_vehicle_ids.length > 0 ? emergencyAnalysis.emergency_vehicle_ids.map((id) => `#${id}`).join(', ') : 'Unassigned Track ID'}

{emergencyAnalysis.sample_emergency_records?.length > 0 && (
{emergencyAnalysis.sample_emergency_records.slice(0, 5).map((rec, i) => ( ))}
Vehicle ID Confidence Velocity Heading
#{rec.vehicle_id} {(rec.confidence * 100).toFixed(0)}% {rec.speed != null ? `${rec.speed} km/h` : '—'} {rec.direction || 'unknown'}
)}
) : (
✓ No emergency preemption triggers detected in this video segment.
)}
)} {/* PART 3: FRAME & CONFIDENCE STATISTICS */}
{/* Frame Stats */}
Part 3 — Frame Statistics
Average/Frame {frameStats?.average_detections ?? 0}
Maximum/Frame {frameStats?.max_detections ?? 0}
Minimum/Frame {frameStats?.min_detections ?? 0}
{/* Confidence Stats */}
Part 4 — Model Confidence Statistics
Average Conf {confStats?.average_confidence != null ? `${(confStats.average_confidence * 100).toFixed(1)}%` : '—'}
Maximum Conf {confStats?.max_confidence != null ? `${(confStats.max_confidence * 100).toFixed(1)}%` : '—'}
Minimum Conf {confStats?.min_confidence != null ? `${(confStats.min_confidence * 100).toFixed(1)}%` : '—'}
{/* PART 4: INTERACTIVE FRAME INSPECTOR */}

Viewing Frame: #{selectedFrame ?? '—'} ({frameDetections.length} objects detected) {loadingFrame && Fetching frame detections...}
handleFrameChange(Number(e.target.value))} className="w-full accent-blue-500 cursor-pointer h-2 bg-slate-700 rounded-lg" /> handleFrameChange(Number(e.target.value))} className="w-20 bg-slate-800 border border-slate-700 text-xs text-white rounded px-2 py-1 text-center font-mono" />
{/* Detections table */} {!frameDetections.length ? (
No vehicles detected in frame #{selectedFrame}. Slide to an active frame.
) : (
{frameDetections.map((d, idx) => ( ))}
Track ID Classification Confidence Velocity Heading Bounding Box [x1, y1, x2, y2]
#{d.vehicle_id} {d.emergency ? '🚨 EMERGENCY' : d.type} {(d.confidence * 100).toFixed(0)}% {d.speed != null ? `${d.speed.toFixed(1)} km/h` : '—'} {d.direction || 'unknown'} {d.bounding_box ? `[${d.bounding_box.x1}, ${d.bounding_box.y1}, ${d.bounding_box.x2}, ${d.bounding_box.y2}]` : '—'}
)}
)} {/* ============================================================== */} {/* SUMO SAFETY RISK INTELLIGENCE */} {/* ============================================================== */}
{/* Accident detection card */}

Vision-Based Accident Detector

{isAccidentUnavailable ? ( <>

Unavailable in Simulation Mode

Reason: SUMO does not generate camera frames. Real video footage uploaded above is parsed by the YOLO pipeline.

) : (

{accidentStatus}

)}
{/* Vehicle pair risks */}
{!pairRisks.length ? ( ) : (
{pairRisks.map((p, i) => ( ))}
Vehicles TTC (s) Near-Miss P Risk Score
{Array.isArray(p.vehicles) ? p.vehicles.join(' ↔ ') : `Pair ${i + 1}`} {p.ttc_seconds != null ? Number(p.ttc_seconds).toFixed(2) : '—'} {p.near_miss_probability != null ? Number(p.near_miss_probability).toFixed(4) : '—'} {p.risk_score != null ? Number(p.risk_score).toFixed(4) : '—'}
)}
{/* Comparison results */} {comparison.length > 0 && (
{comparison.map((row, i) => ( ))}
Controller Avg Wait (s) Avg Queue Throughput Runs
{row.controller} {row.average_waiting_time_mean != null ? Number(row.average_waiting_time_mean).toFixed(2) : '—'} {row.average_queue_length_mean != null ? Number(row.average_queue_length_mean).toFixed(2) : '—'} {row.throughput_mean != null ? Number(row.throughput_mean).toFixed(0) : '—'} {row.successful_runs ?? '—'}
)}
) }