feat: add batch processing for multiple file uploads
- Add BatchState management in taskStore with progress tracking - Implement batch processing service with concurrency control - Direct Track: max 5 parallel tasks - OCR Track: sequential processing (GPU VRAM limit) - Refactor ProcessingPage to support batch mode with BatchProcessingPanel - Update UploadPage to initialize batch state for multi-file uploads - Add i18n translations for batch processing (zh-TW, en-US) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
435
frontend/src/components/BatchProcessingPanel.tsx
Normal file
435
frontend/src/components/BatchProcessingPanel.tsx
Normal file
@@ -0,0 +1,435 @@
|
||||
/**
|
||||
* BatchProcessingPanel - Batch processing UI component
|
||||
*
|
||||
* Displays batch processing settings, task list, and progress for multi-file processing.
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { useToast } from '@/components/ui/toast'
|
||||
import {
|
||||
Play,
|
||||
Pause,
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
FileText,
|
||||
Loader2,
|
||||
Settings,
|
||||
ListChecks,
|
||||
Zap,
|
||||
Eye,
|
||||
RotateCcw,
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
useBatchState,
|
||||
useBatchProgress,
|
||||
useBatchOptions,
|
||||
useTaskStore,
|
||||
type BatchStrategy,
|
||||
} from '@/store/taskStore'
|
||||
import { analyzeBatchTasks, processBatch, cancelBatch } from '@/services/batchProcessing'
|
||||
import type { LayoutModel, PreprocessingMode } from '@/types/apiV2'
|
||||
|
||||
export default function BatchProcessingPanel() {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const { toast } = useToast()
|
||||
|
||||
const batchState = useBatchState()
|
||||
const progress = useBatchProgress()
|
||||
const batchOptions = useBatchOptions()
|
||||
const { setBatchOptions, clearBatch } = useTaskStore()
|
||||
|
||||
const [isAnalyzing, setIsAnalyzing] = useState(false)
|
||||
const [isProcessing, setIsProcessing] = useState(false)
|
||||
|
||||
// Calculate progress percentage
|
||||
const progressPercentage =
|
||||
progress.total > 0 ? Math.round(((progress.completed + progress.failed) / progress.total) * 100) : 0
|
||||
|
||||
// Analyze all tasks when component mounts
|
||||
useEffect(() => {
|
||||
const runAnalysis = async () => {
|
||||
if (batchState.taskIds.length > 0 && !isAnalyzing) {
|
||||
// Check if any task needs analysis
|
||||
const needsAnalysis = batchState.taskIds.some(
|
||||
(taskId) => !batchState.taskStates[taskId]?.recommendedTrack
|
||||
)
|
||||
if (needsAnalysis) {
|
||||
setIsAnalyzing(true)
|
||||
try {
|
||||
await analyzeBatchTasks(batchState.taskIds)
|
||||
} finally {
|
||||
setIsAnalyzing(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
runAnalysis()
|
||||
}, [batchState.taskIds.length]) // Only run once when tasks are loaded
|
||||
|
||||
// Handle start processing
|
||||
const handleStartProcessing = useCallback(async () => {
|
||||
setIsProcessing(true)
|
||||
try {
|
||||
await processBatch()
|
||||
toast({
|
||||
title: t('batch.processingComplete', { defaultValue: '批次處理完成' }),
|
||||
description: t('batch.processingCompleteDesc', {
|
||||
defaultValue: `已完成 ${progress.completed} 個任務`,
|
||||
completed: progress.completed,
|
||||
}),
|
||||
variant: 'success',
|
||||
})
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('batch.processingError', { defaultValue: '批次處理錯誤' }),
|
||||
description: error instanceof Error ? error.message : '未知錯誤',
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsProcessing(false)
|
||||
}
|
||||
}, [progress.completed, t, toast])
|
||||
|
||||
// Handle cancel processing
|
||||
const handleCancelProcessing = useCallback(async () => {
|
||||
try {
|
||||
await cancelBatch()
|
||||
toast({
|
||||
title: t('batch.processingCancelled', { defaultValue: '批次處理已取消' }),
|
||||
variant: 'default',
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Cancel error:', error)
|
||||
}
|
||||
}, [t, toast])
|
||||
|
||||
// Handle clear batch and go to upload
|
||||
const handleClearAndUpload = useCallback(() => {
|
||||
clearBatch()
|
||||
navigate('/upload')
|
||||
}, [clearBatch, navigate])
|
||||
|
||||
// Handle view results
|
||||
const handleViewResults = useCallback(() => {
|
||||
navigate('/tasks')
|
||||
}, [navigate])
|
||||
|
||||
// Get task status icon
|
||||
const getStatusIcon = (status: string) => {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return <CheckCircle className="w-4 h-4 text-success" />
|
||||
case 'processing':
|
||||
return <Loader2 className="w-4 h-4 text-primary animate-spin" />
|
||||
case 'failed':
|
||||
return <XCircle className="w-4 h-4 text-destructive" />
|
||||
default:
|
||||
return <FileText className="w-4 h-4 text-muted-foreground" />
|
||||
}
|
||||
}
|
||||
|
||||
// Get status badge
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return <Badge variant="success">{t('processing.completed', { defaultValue: '已完成' })}</Badge>
|
||||
case 'processing':
|
||||
return <Badge variant="default">{t('processing.processing', { defaultValue: '處理中' })}</Badge>
|
||||
case 'failed':
|
||||
return <Badge variant="destructive">{t('processing.failed', { defaultValue: '失敗' })}</Badge>
|
||||
default:
|
||||
return <Badge variant="secondary">{t('processing.pending', { defaultValue: '等待中' })}</Badge>
|
||||
}
|
||||
}
|
||||
|
||||
// Get track badge
|
||||
const getTrackBadge = (track: string | null) => {
|
||||
if (!track) return null
|
||||
const label = track === 'direct' ? 'Direct' : track === 'ocr' ? 'OCR' : track.toUpperCase()
|
||||
const variant = track === 'direct' ? 'outline' : 'secondary'
|
||||
return <Badge variant={variant}>{label}</Badge>
|
||||
}
|
||||
|
||||
const allCompleted = progress.completed + progress.failed === progress.total && progress.total > 0
|
||||
const canStart = !isAnalyzing && !isProcessing && !batchState.isProcessing && progress.pending > 0
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Page Header */}
|
||||
<div className="page-header">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="page-title">{t('batch.title', { defaultValue: '批次處理' })}</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{t('batch.subtitle', {
|
||||
defaultValue: '共 {{count}} 個檔案',
|
||||
count: progress.total,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
{allCompleted && (
|
||||
<div className="flex items-center gap-2 text-success">
|
||||
<CheckCircle className="w-6 h-6" />
|
||||
<span className="font-semibold">
|
||||
{t('batch.allComplete', { defaultValue: '全部完成' })}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Overall Progress */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<ListChecks className="w-5 h-5 text-primary" />
|
||||
</div>
|
||||
<CardTitle>{t('batch.progress', { defaultValue: '批次進度' })}</CardTitle>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{progress.completed > 0 && (
|
||||
<Badge variant="success">
|
||||
{t('batch.completed', { defaultValue: '已完成' })}: {progress.completed}
|
||||
</Badge>
|
||||
)}
|
||||
{progress.processing > 0 && (
|
||||
<Badge variant="default">
|
||||
{t('batch.processing', { defaultValue: '處理中' })}: {progress.processing}
|
||||
</Badge>
|
||||
)}
|
||||
{progress.failed > 0 && (
|
||||
<Badge variant="destructive">
|
||||
{t('batch.failed', { defaultValue: '失敗' })}: {progress.failed}
|
||||
</Badge>
|
||||
)}
|
||||
{progress.pending > 0 && (
|
||||
<Badge variant="secondary">
|
||||
{t('batch.pending', { defaultValue: '等待中' })}: {progress.pending}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Progress bar */}
|
||||
<div>
|
||||
<div className="flex justify-between text-sm mb-3">
|
||||
<span className="text-muted-foreground font-medium">
|
||||
{t('batch.overallProgress', { defaultValue: '整體進度' })}
|
||||
</span>
|
||||
<span className="font-bold text-xl text-primary">{progressPercentage}%</span>
|
||||
</div>
|
||||
<Progress value={progressPercentage} max={100} className="h-4" />
|
||||
</div>
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="flex gap-3 pt-4 border-t border-border">
|
||||
{!allCompleted && canStart && (
|
||||
<Button onClick={handleStartProcessing} className="gap-2" size="lg">
|
||||
<Play className="w-4 h-4" />
|
||||
{t('batch.startProcessing', { defaultValue: '開始批次處理' })}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{(isProcessing || batchState.isProcessing) && (
|
||||
<Button onClick={handleCancelProcessing} variant="destructive" className="gap-2" size="lg">
|
||||
<Pause className="w-4 h-4" />
|
||||
{t('batch.cancelProcessing', { defaultValue: '取消處理' })}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{allCompleted && (
|
||||
<>
|
||||
<Button onClick={handleViewResults} className="gap-2" size="lg">
|
||||
<Eye className="w-4 h-4" />
|
||||
{t('batch.viewResults', { defaultValue: '查看結果' })}
|
||||
</Button>
|
||||
<Button onClick={handleClearAndUpload} variant="outline" className="gap-2" size="lg">
|
||||
<RotateCcw className="w-4 h-4" />
|
||||
{t('batch.uploadMore', { defaultValue: '上傳更多' })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{isAnalyzing && (
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
<span>{t('batch.analyzing', { defaultValue: '分析文件中...' })}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Batch Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Settings className="w-5 h-5 text-primary" />
|
||||
</div>
|
||||
<CardTitle>{t('batch.settings', { defaultValue: '批次設定' })}</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Processing Strategy */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">
|
||||
{t('batch.strategy', { defaultValue: '處理策略' })}
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{[
|
||||
{ value: 'auto', label: t('batch.strategyAuto', { defaultValue: '自動判斷' }), desc: '系統自動選擇最佳處理方式' },
|
||||
{ value: 'force_ocr', label: t('batch.strategyOcr', { defaultValue: '全部 OCR' }), desc: '強制使用 OCR 處理' },
|
||||
{ value: 'force_direct', label: t('batch.strategyDirect', { defaultValue: '全部 Direct' }), desc: '強制使用 Direct 處理' },
|
||||
].map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
onClick={() => setBatchOptions({ strategy: option.value as BatchStrategy })}
|
||||
disabled={isProcessing || batchState.isProcessing}
|
||||
className={`p-3 rounded-lg border text-left transition-colors ${
|
||||
batchOptions.strategy === option.value
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:border-primary/50'
|
||||
} disabled:opacity-50 disabled:cursor-not-allowed`}
|
||||
>
|
||||
<div className="font-medium text-sm">{option.label}</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">{option.desc}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Layout Model (for OCR) */}
|
||||
{batchOptions.strategy !== 'force_direct' && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">
|
||||
{t('batch.layoutModel', { defaultValue: 'Layout Model (OCR)' })}
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{[
|
||||
{ value: 'chinese', label: 'Chinese', desc: '中文文件最佳' },
|
||||
{ value: 'default', label: 'Default', desc: '英文學術論文' },
|
||||
{ value: 'cdla', label: 'CDLA', desc: '中文版面分析' },
|
||||
].map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
onClick={() => setBatchOptions({ layoutModel: option.value as LayoutModel })}
|
||||
disabled={isProcessing || batchState.isProcessing}
|
||||
className={`p-3 rounded-lg border text-left transition-colors ${
|
||||
batchOptions.layoutModel === option.value
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:border-primary/50'
|
||||
} disabled:opacity-50 disabled:cursor-not-allowed`}
|
||||
>
|
||||
<div className="font-medium text-sm">{option.label}</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">{option.desc}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Preprocessing Mode (for OCR) */}
|
||||
{batchOptions.strategy !== 'force_direct' && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">
|
||||
{t('batch.preprocessingMode', { defaultValue: '預處理模式 (OCR)' })}
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{[
|
||||
{ value: 'auto', label: t('batch.preprocessAuto', { defaultValue: '自動' }), desc: '自動分析並套用' },
|
||||
{ value: 'manual', label: t('batch.preprocessManual', { defaultValue: '手動' }), desc: '使用預設配置' },
|
||||
{ value: 'disabled', label: t('batch.preprocessDisabled', { defaultValue: '停用' }), desc: '不進行預處理' },
|
||||
].map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
onClick={() => setBatchOptions({ preprocessingMode: option.value as PreprocessingMode })}
|
||||
disabled={isProcessing || batchState.isProcessing}
|
||||
className={`p-3 rounded-lg border text-left transition-colors ${
|
||||
batchOptions.preprocessingMode === option.value
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:border-primary/50'
|
||||
} disabled:opacity-50 disabled:cursor-not-allowed`}
|
||||
>
|
||||
<div className="font-medium text-sm">{option.label}</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">{option.desc}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Concurrency Info */}
|
||||
<div className="p-3 bg-muted/30 rounded-lg border border-border">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Zap className="w-4 h-4 text-primary" />
|
||||
<span className="text-muted-foreground">
|
||||
{t('batch.concurrencyInfo', {
|
||||
defaultValue: 'Direct Track 最多 5 並行處理,OCR Track 依序處理 (GPU 限制)',
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Task List */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<FileText className="w-5 h-5 text-primary" />
|
||||
</div>
|
||||
<CardTitle>{t('batch.taskList', { defaultValue: '任務列表' })}</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{batchState.taskIds.map((taskId) => {
|
||||
const taskState = batchState.taskStates[taskId]
|
||||
if (!taskState) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
key={taskId}
|
||||
className="flex items-center gap-4 p-3 rounded-lg border border-border hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
{/* Status icon */}
|
||||
<div className="flex-shrink-0">{getStatusIcon(taskState.status)}</div>
|
||||
|
||||
{/* File info */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-foreground truncate">
|
||||
{taskState.filename || taskId}
|
||||
</p>
|
||||
{taskState.error && (
|
||||
<p className="text-xs text-destructive truncate">{taskState.error}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Track badge */}
|
||||
<div className="flex-shrink-0">
|
||||
{getTrackBadge(taskState.track || taskState.recommendedTrack)}
|
||||
</div>
|
||||
|
||||
{/* Status badge */}
|
||||
<div className="flex-shrink-0">{getStatusBadge(taskState.status)}</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user