refactor: modify upload section

This commit is contained in:
2026-03-19 12:32:55 +05:30
parent 37d7a664e0
commit 8510bd9f32
11 changed files with 531 additions and 436 deletions

View File

@@ -1,55 +0,0 @@
'use client';
import { useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import { sessionService } from '@/services/api';
import { SessionContext } from '@/types';
import { PowerCircle, TrendingUp } from 'lucide-react';
import { PageHeader } from '@/components/page-header';
import { PoweredBy } from '@/components/powered-by';
import { ROUTES } from '@/utils/routes';
import { Reveal } from '@/components/ui/reveal';
const ProjectSelectionSection = dynamic(
() => import('@/components/project-selection-section').then((mod) => mod.ProjectSelectionSection),
{ ssr: false },
);
export default function NewAnalysisPage() {
const router = useRouter();
const handleSelectionComplete = (session: SessionContext) => {
// Save session to storage and navigate to upload page
sessionService.saveSession(session);
router.push(ROUTES.UPLOAD);
};
return (
<>
{/* Main Content */}
<main>
<div>
{/* Refined Left-Aligned Header */}
<div className="mb-8">
<PageHeader
title="VisionRoad Detection System"
description="Select project details to begin your AI-powered road infrastructure analysis"
icon={TrendingUp}
/>
</div>
{/* Project Selection Section */}
<Reveal delay={0.2} direction="up">
<div>
<ProjectSelectionSection onSelectionComplete={handleSelectionComplete} />
</div>
</Reveal>
<Reveal delay={0.4}>
<PoweredBy />
</Reveal>
</div>
</main>
</>
);
}

View File

@@ -77,7 +77,7 @@ export default function VideoResultsPage() {
}
}
sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS);
router.push(ROUTES.UPLOAD);
};
const getTitle = () => {

View File

@@ -29,7 +29,7 @@ export default function ResultsPage() {
const videoData = sessionService.loadVideoData();
if (!sessionService.isSessionValid(storedSession) || !videoData) {
router.replace(ROUTES.NEW_ANALYSIS);
router.replace(ROUTES.UPLOAD);
return;
}
@@ -52,7 +52,7 @@ export default function ResultsPage() {
}
}
sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS);
router.push(ROUTES.UPLOAD);
};
const getTitle = () => {

View File

@@ -1,6 +1,6 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, TrendingUp, ArrowUp, ArrowDown } from 'lucide-react';
@@ -25,9 +25,14 @@ export default function VideoProcessingPage() {
const [statusMessage, setStatusMessage] = useState('Initializing...');
const [error, setError] = useState<string | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const connectWebSocket = useCallback(
(vid: string) => {
if (wsRef.current) return wsRef.current;
const ws = new WebSocket(`${WS_URL}/ws/${vid}`);
wsRef.current = ws;
ws.onmessage = async (event) => {
const data = JSON.parse(event.data);
@@ -60,9 +65,14 @@ export default function VideoProcessingPage() {
ws.onerror = () => {
setStatusMessage('Connection lost. Reconnecting...');
wsRef.current = null;
setTimeout(() => connectWebSocket(vid), 3000);
};
ws.onclose = () => {
wsRef.current = null;
};
return ws;
},
[router],
@@ -72,10 +82,14 @@ export default function VideoProcessingPage() {
const storedSession = sessionService.loadSession();
setSession(storedSession);
let isMounted = true;
const checkStatus = async () => {
try {
const statusData = await videoService.getVideoStatus(videoId);
if (!isMounted) return;
if (statusData.status === 'completed') {
router.replace(`/results/${videoId}`);
return;
@@ -94,14 +108,24 @@ export default function VideoProcessingPage() {
setIsLoading(false);
} catch (err) {
console.error('Status check failed:', err);
setError('Failed to connect to server.');
setIsLoading(false);
if (isMounted) {
setError('Failed to connect to server.');
setIsLoading(false);
}
}
};
if (videoId) {
checkStatus();
}
return () => {
isMounted = false;
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
};
}, [videoId, router, connectWebSocket]);
if (isLoading) {

View File

@@ -1,6 +1,6 @@
'use client';
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
@@ -13,17 +13,16 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Loader2, TrendingUp, ArrowUp, ArrowDown } from 'lucide-react';
import { Loader2, TrendingUp, ChevronRight } from 'lucide-react';
import { PageHeader } from '@/components/page-header';
import { PoweredBy } from '@/components/powered-by';
import { sessionService, videoService } from '@/services/api';
import { SessionContext } from '@/types';
import { ROUTES } from '@/utils/routes';
import { storeVideoFile } from '@/lib/video-storage';
import { ProjectSelectionSection } from '@/components/project-selection-section';
import { Reveal } from '@/components/ui/reveal';
import { cn } from '@/lib/utils';
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const DETECTION_METHODS = [
{ value: 'yolo', label: 'YOLO Detection Model' },
{ value: 'yolo_vl', label: 'YOLO with Vision-Language Model' },
@@ -45,20 +44,21 @@ export default function UploadPage() {
// Upload states
const [uploading, setUploading] = useState(false);
const [progress, setProgress] = useState(0);
const [statusMessage, setStatusMessage] = useState('');
const [error, setError] = useState<string | null>(null);
// Load session on mount
useEffect(() => {
const storedSession = sessionService.loadSession();
if (!sessionService.isSessionValid(storedSession)) {
router.replace(ROUTES.NEW_ANALYSIS);
return;
}
setSession(storedSession);
// We don't load session on mount for the upload page to ensure
// project details are filled manually as requested.
setIsLoading(false);
}, [router]);
}, []);
const handleSelectionChange = useCallback((selectedSession: SessionContext | null) => {
setSession(selectedSession);
if (selectedSession) {
sessionService.saveSession(selectedSession);
}
}, []);
const handleUpload = async () => {
if (!file) {
@@ -66,27 +66,27 @@ export default function UploadPage() {
return;
}
if (!session) {
setError('Please complete the project selection first');
return;
}
const formData = new FormData();
formData.append('file', file);
formData.append('detection_mode', selectMethod);
if (session?.chainageId) {
formData.append('chainage_id', session.chainageId);
}
formData.append('chainage_id', session.chainageId as string);
if (jsonFile) {
formData.append('json_file', jsonFile);
}
setUploading(true);
setProgress(0);
setStatusMessage('Uploading...');
setError(null);
try {
const result = await videoService.uploadVideo(formData);
// Store file locally for potential recovery/results display
// Store file locally
if (file) {
try {
await storeVideoFile(result.video_id, file);
@@ -96,8 +96,6 @@ export default function UploadPage() {
}
sessionService.saveVideoData({ videoId: result.video_id });
// Redirect to the dynamic processing page
router.push(`/upload/${result.video_id}`);
} catch (err) {
let errorMessage = 'Upload failed';
@@ -107,200 +105,166 @@ export default function UploadPage() {
errorMessage = err.message;
}
setError(errorMessage);
setStatusMessage('');
setUploading(false);
setProgress(0);
}
};
const handleBackToSelection = () => {
sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS);
};
const getTitle = () => 'Road Analysis';
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="p-8">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</Card>
<Loader2 className="h-10 w-10 animate-spin text-primary" />
</div>
);
}
return (
<div className="min-h-screen">
{/* Main Content */}
<main className="min-h-screen flex flex-col">
<div className="flex-1 container mx-auto px-6 py-6 max-w-340 flex flex-col">
{/* Header */}
<div className="mb-6">
<PageHeader
title={getTitle()}
description="Upload video file and fill in required details to start the road analysis"
icon={TrendingUp}
/>
</div>
const isSessionComplete = !!(session && sessionService.isSessionValid(session));
const isFormValid = isSessionComplete && file;
{/* Compact Session Info Bar */}
{session && (
<div className="mb-6">
<Card className="p-0 border shadow-sm overflow-hidden">
<div className="flex flex-col md:flex-row md:items-center justify-between py-4 px-6 gap-6 bg-card">
<div className="flex flex-wrap items-center gap-x-12 gap-y-4">
{[
{ label: 'Project', value: session.projectName, primary: true },
{ label: 'Package', value: session.packageName },
{ label: 'Chainage', value: session.chainageName },
].map((item, idx) => (
<div
key={item.label}
className={cn(
'flex flex-col',
idx !== 0 && 'border-l pl-12 border-border/60',
)}
>
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
{item.label}
</span>
<span
className={cn(
'leading-tight flex items-center gap-1.5',
item.primary
? 'text-base font-bold'
: 'text-sm font-semibold text-muted-foreground',
)}
>
{item.value}
{item.label === 'Chainage' && session.chainageDirection && (
<span className="flex items-center gap-1 px-1 py-0.5 rounded bg-muted text-[10px] font-bold uppercase border ml-1">
{session.chainageDirection === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{session.chainageDirection}
</span>
)}
</span>
</div>
))}
return (
<div className="min-h-screen pb-12">
<main>
{/* Header */}
<div className="mb-10">
<PageHeader
title="Intelligent Road Asset AI Analysis"
description="High-precision detection for potholes, signboards, and culverts from video data"
icon={TrendingUp}
/>
</div>
<div className="space-y-8 mt-8">
{/* Module 1: Project Selection */}
<Reveal direction="up" delay={0.1}>
<Card className="border">
<CardHeader>
<CardTitle className="text-xl font-bold">1. Project Details</CardTitle>
<CardDescription>
Select the target project, package, and chainage segment.
</CardDescription>
</CardHeader>
<CardContent>
<ProjectSelectionSection
onSelectionChange={handleSelectionChange}
asStep={true}
hideButton={true}
/>
</CardContent>
</Card>
</Reveal>
{/* Module 2: Upload Data */}
<Reveal direction="up" delay={0.2}>
<Card className={cn("border transition-all duration-300", !isSessionComplete && "opacity-60 pointer-events-none grayscale-[0.5]")}>
<CardHeader>
<CardTitle className="text-xl font-bold flex items-center gap-2">
2. Upload Video Data
</CardTitle>
<CardDescription>
Provide the video file and optional GPS telemetry for processing.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid grid-cols-1 gap-6 text-sm">
{/* Video File Input */}
<div className="space-y-2">
<Label htmlFor="video-file" className="text-sm font-semibold">
Video File <span className="text-destructive">*</span>
</Label>
<div className="relative group">
<Input
id="video-file"
type="file"
accept="video/*"
onChange={(e) => {
setFile(e.target.files?.[0] || null);
setError(null);
}}
disabled={uploading || !isSessionComplete}
className="h-12 bg-muted/30 border-dashed border-2 group-hover:border-primary/50 transition-colors cursor-pointer file:mr-4 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary file:text-primary-foreground file:font-semibold file:text-xs"
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* JSON File Input */}
<div className="space-y-2">
<Label htmlFor="json-file" className="text-sm font-semibold">
GPS JSON File (Optional)
</Label>
<Input
id="json-file"
type="file"
accept=".json,application/json"
onChange={(e) => {
setJsonFile(e.target.files?.[0] || null);
setError(null);
}}
disabled={uploading || !isSessionComplete}
className="h-11 bg-muted/20 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary/10 file:text-primary file:font-medium file:text-xs"
/>
</div>
{/* Select Method */}
<div className="space-y-2">
<Label htmlFor="select-method" className="text-sm font-semibold">
Analysis Method
</Label>
<Select
value={selectMethod}
onValueChange={setSelectMethod}
disabled={uploading || !isSessionComplete}
>
<SelectTrigger id="select-method" className="h-11 bg-muted/20">
<SelectValue placeholder="Select method" />
</SelectTrigger>
<SelectContent>
{DETECTION_METHODS.map((method) => (
<SelectItem key={method.value} value={method.value}>
{method.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Error Display */}
{error && (
<div className="p-4 rounded-md bg-destructive/5 border border-destructive/20 text-destructive text-sm font-medium animate-in fade-in slide-in-from-top-1">
{error}
</div>
)}
{/* Primary Action Button */}
<div className="pt-2">
<Button
variant="outline"
size="sm"
onClick={handleBackToSelection}
className="font-semibold px-6 shrink-0 h-9"
onClick={handleUpload}
disabled={!isFormValid || uploading}
className="w-full h-14 font-extrabold uppercase tracking-wider"
>
Change Selection
{uploading ? (
<div className="flex items-center gap-3">
<Loader2 className="h-5 w-5 animate-spin" />
<span>Processing Upload...</span>
</div>
) : (
<div className="flex items-center gap-2">
<span>Upload & Process Analysis</span>
<ChevronRight className="h-5 w-5" />
</div>
)}
</Button>
</div>
</Card>
</div>
)}
</CardContent>
</Card>
</Reveal>
</div>
{/* Upload Card */}
<Card className="flex-1">
<CardHeader className="pb-4">
<CardTitle className="text-xl font-bold">Upload Video</CardTitle>
<CardDescription className="text-sm">
Select video file, GPS JSON file, and method for analysis
</CardDescription>
</CardHeader>
<CardContent className="pt-4 space-y-6">
<div className="space-y-6">
{/* Video File Input - Full Width */}
<div className="space-y-2">
<Label htmlFor="video-file" className="text-sm font-semibold">
Video File
</Label>
<Input
id="video-file"
type="file"
accept="video/*"
onChange={(e) => {
setFile(e.target.files?.[0] || null);
setError(null);
}}
disabled={uploading}
className="h-11 bg-muted/20 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary/10 file:text-primary file:font-medium file:text-xs hover:file:bg-primary/20"
/>
</div>
{/* JSON File and Method - Both in one line */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* JSON File Input */}
<div className="space-y-2">
<Label htmlFor="json-file" className="text-sm font-semibold">
GPS JSON File
</Label>
<Input
id="json-file"
type="file"
accept=".json,application/json"
onChange={(e) => {
setJsonFile(e.target.files?.[0] || null);
setError(null);
}}
disabled={uploading}
className="h-11 bg-muted/20 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary/10 file:text-primary file:font-medium file:text-xs hover:file:bg-primary/20"
/>
</div>
{/* Select Method */}
<div className="space-y-2">
<Label htmlFor="select-method" className="text-sm font-semibold">
Select Method
</Label>
<Select
value={selectMethod}
onValueChange={setSelectMethod}
disabled={uploading}
>
<SelectTrigger id="select-method" className="h-11">
<SelectValue placeholder="Select method" />
</SelectTrigger>
<SelectContent>
{DETECTION_METHODS.map((method) => (
<SelectItem key={method.value} value={method.value}>
{method.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Error Display */}
{error && (
<div className="p-4 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm leading-relaxed whitespace-pre-line">
{error}
</div>
)}
{/* Upload Button */}
<Button
onClick={handleUpload}
disabled={!file || uploading}
className="w-full h-14 text-base font-bold uppercase tracking-wide"
size="lg"
>
{uploading ? (
<div className="flex items-center gap-2">
<Loader2 className="h-5 w-5 animate-spin" />
<span>Processing...</span>
</div>
) : (
'Upload and Process'
)}
</Button>
</CardContent>
</Card>
<PoweredBy />
<div className="mt-12">
<Reveal delay={0.4}>
<PoweredBy />
</Reveal>
</div>
</main>
</div>