This commit is contained in:
beabigegg
2025-11-12 22:53:17 +08:00
commit da700721fa
130 changed files with 23393 additions and 0 deletions

View File

@@ -0,0 +1,321 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useMutation, useQuery } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/toast'
import { useUploadStore } from '@/store/uploadStore'
import { apiClient } from '@/services/api'
import type { ExportRequest, ExportOptions } from '@/types/api'
type ExportFormat = 'txt' | 'json' | 'excel' | 'markdown' | 'pdf'
export default function ExportPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const { toast } = useToast()
const { batchId } = useUploadStore()
const [format, setFormat] = useState<ExportFormat>('txt')
const [selectedRuleId, setSelectedRuleId] = useState<number | undefined>()
const [options, setOptions] = useState<ExportOptions>({
confidence_threshold: 0.5,
include_metadata: true,
filename_pattern: '{filename}_ocr',
css_template: 'default',
})
// Fetch export rules
const { data: exportRules } = useQuery({
queryKey: ['exportRules'],
queryFn: () => apiClient.getExportRules(),
enabled: true,
})
// Fetch CSS templates
const { data: cssTemplates } = useQuery({
queryKey: ['cssTemplates'],
queryFn: () => apiClient.getCSSTemplates(),
enabled: format === 'pdf',
})
// Export mutation
const exportMutation = useMutation({
mutationFn: async (data: ExportRequest) => {
const blob = await apiClient.exportResults(data)
return { blob, format: data.format }
},
onSuccess: ({ blob, format: exportFormat }) => {
// Create download link
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
// Determine file extension
const extensions: Record<ExportFormat, string> = {
txt: 'txt',
json: 'json',
excel: 'xlsx',
markdown: 'md',
pdf: 'pdf',
}
a.download = `batch_${batchId}_export.${extensions[exportFormat]}`
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
document.body.removeChild(a)
toast({
title: t('export.exportSuccess'),
description: `已成功匯出為 ${exportFormat.toUpperCase()} 格式`,
variant: 'success',
})
},
onError: (error: any) => {
toast({
title: t('export.exportError'),
description: error.response?.data?.detail || t('errors.networkError'),
variant: 'destructive',
})
},
})
const handleExport = () => {
if (!batchId) {
toast({
title: t('errors.validationError'),
description: '請先上傳並處理檔案',
variant: 'destructive',
})
return
}
const exportRequest: ExportRequest = {
batch_id: batchId,
format,
rule_id: selectedRuleId,
options,
}
exportMutation.mutate(exportRequest)
}
const handleFormatChange = (newFormat: ExportFormat) => {
setFormat(newFormat)
// Reset CSS template if switching away from PDF
if (newFormat !== 'pdf') {
setOptions((prev) => ({ ...prev, css_template: undefined }))
} else {
setOptions((prev) => ({ ...prev, css_template: 'default' }))
}
}
const handleRuleChange = (ruleId: number | undefined) => {
setSelectedRuleId(ruleId)
if (ruleId && exportRules) {
const rule = exportRules.find((r) => r.id === ruleId)
if (rule && rule.config_json) {
// Apply rule configuration
setOptions((prev) => ({
...prev,
...rule.config_json,
css_template: rule.css_template || prev.css_template,
}))
}
}
}
// Show helpful message when no batch is selected
if (!batchId) {
return (
<div className="max-w-2xl mx-auto mt-12">
<Card>
<CardHeader>
<CardTitle>{t('export.title')}</CardTitle>
</CardHeader>
<CardContent className="text-center space-y-4">
<p className="text-muted-foreground">
{t('export.noBatchMessage', { defaultValue: '尚未選擇任何批次。請先上傳並完成處理檔案。' })}
</p>
<Button onClick={() => navigate('/upload')}>
{t('export.goToUpload', { defaultValue: '前往上傳頁面' })}
</Button>
</CardContent>
</Card>
</div>
)
}
return (
<div className="max-w-4xl mx-auto space-y-6">
<div>
<h1 className="text-3xl font-bold text-foreground mb-2">{t('export.title')}</h1>
<p className="text-muted-foreground"> ID: {batchId}</p>
</div>
{/* Format Selection */}
<Card>
<CardHeader>
<CardTitle>{t('export.format')}</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 md:grid-cols-5 gap-3">
{(['txt', 'json', 'excel', 'markdown', 'pdf'] as ExportFormat[]).map((fmt) => (
<button
key={fmt}
onClick={() => handleFormatChange(fmt)}
className={`p-4 border rounded-lg text-center transition-colors ${
format === fmt
? 'border-primary bg-primary/10 text-primary font-semibold'
: 'border-gray-200 hover:border-primary/50'
}`}
>
<div className="text-sm">{t(`export.formats.${fmt}`)}</div>
</button>
))}
</div>
</CardContent>
</Card>
{/* Export Rules */}
{exportRules && exportRules.length > 0 && (
<Card>
<CardHeader>
<CardTitle>{t('export.rules.title')}</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
<label className="block text-sm font-medium text-foreground">
{t('export.rules.selectRule')}
</label>
<select
value={selectedRuleId || ''}
onChange={(e) => handleRuleChange(e.target.value ? Number(e.target.value) : undefined)}
className="w-full px-3 py-2 border border-gray-200 rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value=""> (使)</option>
{exportRules.map((rule) => (
<option key={rule.id} value={rule.id}>
{rule.rule_name}
</option>
))}
</select>
</div>
</CardContent>
</Card>
)}
{/* Export Options */}
<Card>
<CardHeader>
<CardTitle>{t('export.options.title')}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Confidence Threshold */}
<div>
<label className="block text-sm font-medium text-foreground mb-2">
{t('export.options.confidenceThreshold')}: {options.confidence_threshold}
</label>
<input
type="range"
min="0"
max="1"
step="0.05"
value={options.confidence_threshold}
onChange={(e) =>
setOptions((prev) => ({
...prev,
confidence_threshold: Number(e.target.value),
}))
}
className="w-full"
/>
<div className="flex justify-between text-xs text-muted-foreground mt-1">
<span>0</span>
<span>0.5</span>
<span>1.0</span>
</div>
</div>
{/* Include Metadata */}
<div className="flex items-center space-x-2">
<input
type="checkbox"
id="include-metadata"
checked={options.include_metadata}
onChange={(e) =>
setOptions((prev) => ({
...prev,
include_metadata: e.target.checked,
}))
}
className="w-4 h-4 border border-gray-200 rounded"
/>
<label htmlFor="include-metadata" className="text-sm font-medium text-foreground">
{t('export.options.includeMetadata')}
</label>
</div>
{/* Filename Pattern */}
<div>
<label className="block text-sm font-medium text-foreground mb-2">
{t('export.options.filenamePattern')}
</label>
<input
type="text"
value={options.filename_pattern}
onChange={(e) =>
setOptions((prev) => ({
...prev,
filename_pattern: e.target.value,
}))
}
className="w-full px-3 py-2 border border-gray-200 rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="{filename}_ocr"
/>
<p className="text-xs text-muted-foreground mt-1">
: {'{filename}'}, {'{batch_id}'}, {'{date}'}
</p>
</div>
{/* CSS Template (PDF only) */}
{format === 'pdf' && cssTemplates && cssTemplates.length > 0 && (
<div>
<label className="block text-sm font-medium text-foreground mb-2">
{t('export.options.cssTemplate')}
</label>
<select
value={options.css_template || 'default'}
onChange={(e) =>
setOptions((prev) => ({
...prev,
css_template: e.target.value,
}))
}
className="w-full px-3 py-2 border border-gray-200 rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
>
{cssTemplates.map((template) => (
<option key={template.filename} value={template.filename}>
{template.name} - {template.description}
</option>
))}
</select>
</div>
)}
</CardContent>
</Card>
{/* Export Button */}
<div className="flex justify-end gap-3">
<Button variant="outline" onClick={() => navigate('/results')}>
{t('common.back')}
</Button>
<Button onClick={handleExport} disabled={exportMutation.isPending}>
{exportMutation.isPending ? t('export.exporting') : t('export.exportButton')}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,97 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useAuthStore } from '@/store/authStore'
import { apiClient } from '@/services/api'
export default function LoginPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const setUser = useAuthStore((state) => state.setUser)
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
await apiClient.login({ username, password })
// For now, just set a basic user object (backend doesn't return user info)
setUser({ id: 1, username })
navigate('/upload')
} catch (err: any) {
const errorDetail = err.response?.data?.detail
if (Array.isArray(errorDetail)) {
// Handle validation error array from backend
setError(errorDetail.map((e: any) => e.msg || e.message || String(e)).join(', '))
} else if (typeof errorDetail === 'string') {
setError(errorDetail)
} else {
setError(t('auth.loginError'))
}
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen bg-background flex items-center justify-center">
<div className="w-full max-w-md">
<div className="bg-card rounded-lg shadow-lg p-8 border">
<div className="text-center mb-8">
<h1 className="text-3xl font-bold text-foreground mb-2">{t('app.title')}</h1>
<p className="text-muted-foreground">{t('app.subtitle')}</p>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label htmlFor="username" className="block text-sm font-medium text-foreground mb-2">
{t('auth.username')}
</label>
<input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full px-3 py-2 border border-input bg-background rounded-md focus:outline-none focus:ring-2 focus:ring-ring"
required
/>
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium text-foreground mb-2">
{t('auth.password')}
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-3 py-2 border border-input bg-background rounded-md focus:outline-none focus:ring-2 focus:ring-ring"
required
/>
</div>
{error && (
<div className="p-3 bg-destructive/10 border border-destructive rounded-md text-sm text-destructive">
{error}
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full py-2 px-4 bg-primary text-primary-foreground rounded-md font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? t('common.loading') : t('auth.loginButton')}
</button>
</form>
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,200 @@
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useQuery, useMutation } from '@tanstack/react-query'
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 { useUploadStore } from '@/store/uploadStore'
import { apiClient } from '@/services/api'
export default function ProcessingPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const { toast } = useToast()
const { batchId, files } = useUploadStore()
// Start OCR processing
const processOCRMutation = useMutation({
mutationFn: () => apiClient.processOCR({ batch_id: batchId! }),
onSuccess: () => {
toast({
title: '開始處理',
description: 'OCR 處理已開始',
variant: 'success',
})
},
onError: (error: any) => {
toast({
title: t('errors.processingFailed'),
description: error.response?.data?.detail || t('errors.networkError'),
variant: 'destructive',
})
},
})
// Poll batch status
const { data: batchStatus } = useQuery({
queryKey: ['batchStatus', batchId],
queryFn: () => apiClient.getBatchStatus(batchId!),
enabled: !!batchId,
refetchInterval: (query) => {
const data = query.state.data
if (!data) return 2000
// Stop polling if completed or failed
if (data.batch.status === 'completed' || data.batch.status === 'failed') {
return false
}
return 2000 // Poll every 2 seconds
},
})
// Auto-redirect when completed
useEffect(() => {
if (batchStatus?.batch.status === 'completed') {
setTimeout(() => {
navigate('/results')
}, 1000)
}
}, [batchStatus?.batch.status, navigate])
const handleStartProcessing = () => {
processOCRMutation.mutate()
}
const handleViewResults = () => {
navigate('/results')
}
const getStatusBadge = (status: string) => {
switch (status) {
case 'completed':
return <Badge variant="success">{t('processing.completed')}</Badge>
case 'processing':
return <Badge variant="default">{t('processing.processing')}</Badge>
case 'failed':
return <Badge variant="destructive">{t('processing.failed')}</Badge>
default:
return <Badge variant="secondary">{t('processing.pending')}</Badge>
}
}
// Show helpful message when no batch is selected
if (!batchId) {
return (
<div className="max-w-2xl mx-auto mt-12">
<Card>
<CardHeader>
<CardTitle>{t('processing.title')}</CardTitle>
</CardHeader>
<CardContent className="text-center space-y-4">
<p className="text-muted-foreground">
{t('processing.noBatchMessage', { defaultValue: '尚未選擇任何批次。請先上傳檔案以建立批次。' })}
</p>
<Button onClick={() => navigate('/upload')}>
{t('processing.goToUpload', { defaultValue: '前往上傳頁面' })}
</Button>
</CardContent>
</Card>
</div>
)
}
const isProcessing = batchStatus?.batch.status === 'processing'
const isCompleted = batchStatus?.batch.status === 'completed'
const isPending = !batchStatus || batchStatus.batch.status === 'pending'
return (
<div className="max-w-4xl mx-auto space-y-6">
<div>
<h1 className="text-3xl font-bold text-foreground mb-2">{t('processing.title')}</h1>
<p className="text-muted-foreground">
ID: {batchId} - {files.length}
</p>
</div>
{/* Overall Progress */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>{t('processing.progress')}</CardTitle>
{batchStatus && getStatusBadge(batchStatus.batch.status)}
</div>
</CardHeader>
<CardContent className="space-y-4">
<div>
<div className="flex justify-between text-sm mb-2">
<span className="text-muted-foreground">{t('processing.status')}</span>
<span className="font-medium">
{batchStatus?.batch.progress_percentage || 0}%
</span>
</div>
<Progress value={batchStatus?.batch.progress_percentage || 0} max={100} />
</div>
{batchStatus && (
<div className="text-sm text-muted-foreground">
{t('processing.filesProcessed', {
processed: batchStatus.files.filter((f) => f.status === 'completed').length,
total: batchStatus.files.length,
})}
</div>
)}
<div className="flex gap-3">
{isPending && (
<Button
onClick={handleStartProcessing}
disabled={processOCRMutation.isPending}
>
{processOCRMutation.isPending
? t('processing.processing')
: t('processing.startProcessing')}
</Button>
)}
{isCompleted && (
<Button onClick={handleViewResults}>{t('common.next')}</Button>
)}
</div>
</CardContent>
</Card>
{/* File List */}
{batchStatus && (
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
{batchStatus.files.map((file) => (
<div
key={file.id}
className="flex items-center justify-between p-3 bg-muted rounded-md"
>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-foreground truncate">
{file.filename}
</p>
{file.processing_time && (
<p className="text-xs text-muted-foreground">
: {file.processing_time.toFixed(2)}s
</p>
)}
{file.error && (
<p className="text-xs text-destructive">{file.error}</p>
)}
</div>
{getStatusBadge(file.status)}
</div>
))}
</div>
</CardContent>
</Card>
)}
</div>
)
}

View File

@@ -0,0 +1,157 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useQuery } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import ResultsTable from '@/components/ResultsTable'
import MarkdownPreview from '@/components/MarkdownPreview'
import { useToast } from '@/components/ui/toast'
import { useUploadStore } from '@/store/uploadStore'
import { apiClient } from '@/services/api'
export default function ResultsPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const { toast } = useToast()
const { batchId } = useUploadStore()
const [selectedFileId, setSelectedFileId] = useState<number | null>(null)
// Get batch status to show results
const { data: batchStatus, isLoading } = useQuery({
queryKey: ['batchStatus', batchId],
queryFn: () => apiClient.getBatchStatus(batchId!),
enabled: !!batchId,
})
// Get OCR result for selected file
const { data: ocrResult, isLoading: isLoadingResult } = useQuery({
queryKey: ['ocrResult', selectedFileId],
queryFn: () => apiClient.getOCRResult(selectedFileId!.toString()),
enabled: !!selectedFileId,
})
const handleViewResult = (fileId: number) => {
setSelectedFileId(fileId)
}
const handleDownloadPDF = async (fileId: number) => {
try {
const blob = await apiClient.exportPDF(fileId)
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `ocr-result-${fileId}.pdf`
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
document.body.removeChild(a)
toast({
title: t('export.exportSuccess'),
description: 'PDF 已下載',
variant: 'success',
})
} catch (error: any) {
toast({
title: t('export.exportError'),
description: error.response?.data?.detail || t('errors.networkError'),
variant: 'destructive',
})
}
}
const handleExport = () => {
navigate('/export')
}
// Show helpful message when no batch is selected
if (!batchId) {
return (
<div className="max-w-2xl mx-auto mt-12">
<Card>
<CardHeader>
<CardTitle>{t('results.title')}</CardTitle>
</CardHeader>
<CardContent className="text-center space-y-4">
<p className="text-muted-foreground">
{t('results.noBatchMessage', { defaultValue: '尚未選擇任何批次。請先上傳並處理檔案。' })}
</p>
<Button onClick={() => navigate('/upload')}>
{t('results.goToUpload', { defaultValue: '前往上傳頁面' })}
</Button>
</CardContent>
</Card>
</div>
)
}
const completedFiles = batchStatus?.files.filter((f) => f.status === 'completed') || []
return (
<div className="max-w-6xl mx-auto space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-foreground mb-2">{t('results.title')}</h1>
<p className="text-muted-foreground">
ID: {batchId} - {completedFiles.length}
</p>
</div>
<div className="flex gap-2">
<Button onClick={handleExport}>{t('nav.export')}</Button>
<Button
variant="outline"
disabled
title={t('translation.comingSoon')}
className="relative"
>
{t('translation.title')}
<span className="ml-2 text-xs bg-yellow-100 text-yellow-800 px-2 py-0.5 rounded">
{t('translation.comingSoon')}
</span>
</Button>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Results Table */}
<div>
<ResultsTable
files={batchStatus?.files || []}
onViewResult={handleViewResult}
onDownloadPDF={handleDownloadPDF}
/>
</div>
{/* Preview Panel */}
<div>
{selectedFileId && ocrResult ? (
<div className="space-y-4">
<MarkdownPreview
title={`${t('results.viewMarkdown')} - ${ocrResult.filename}`}
content={ocrResult.markdown_content}
/>
<div className="text-sm text-muted-foreground space-y-1">
<p>
{t('results.confidence')}: {((ocrResult.confidence || 0) * 100).toFixed(2)}%
</p>
<p>
{t('results.processingTime')}: {(ocrResult.processing_time || 0).toFixed(2)}s
</p>
<p>
{t('results.textBlocks')}: {ocrResult.json_data?.total_text_regions || 0}
</p>
</div>
</div>
) : (
<div className="h-full flex items-center justify-center border rounded-lg bg-muted/50">
<p className="text-muted-foreground">
{isLoadingResult ? t('common.loading') : '選擇檔案以查看結果'}
</p>
</div>
)}
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,325 @@
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/toast'
import { apiClient } from '@/services/api'
import type { ExportRule } from '@/types/api'
export default function SettingsPage() {
const { t } = useTranslation()
const { toast } = useToast()
const queryClient = useQueryClient()
const [isCreating, setIsCreating] = useState(false)
const [editingRule, setEditingRule] = useState<ExportRule | null>(null)
const [formData, setFormData] = useState({
rule_name: '',
confidence_threshold: 0.5,
include_metadata: true,
filename_pattern: '{filename}_ocr',
css_template: 'default',
})
// Fetch export rules
const { data: exportRules, isLoading } = useQuery({
queryKey: ['exportRules'],
queryFn: () => apiClient.getExportRules(),
})
// Create rule mutation
const createRuleMutation = useMutation({
mutationFn: (rule: any) => apiClient.createExportRule(rule),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['exportRules'] })
setIsCreating(false)
resetForm()
toast({
title: t('common.success'),
description: '規則已建立',
variant: 'success',
})
},
onError: (error: any) => {
toast({
title: t('common.error'),
description: error.response?.data?.detail || t('errors.networkError'),
variant: 'destructive',
})
},
})
// Update rule mutation
const updateRuleMutation = useMutation({
mutationFn: ({ ruleId, rule }: { ruleId: number; rule: any }) =>
apiClient.updateExportRule(ruleId, rule),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['exportRules'] })
setEditingRule(null)
resetForm()
toast({
title: t('common.success'),
description: '規則已更新',
variant: 'success',
})
},
onError: (error: any) => {
toast({
title: t('common.error'),
description: error.response?.data?.detail || t('errors.networkError'),
variant: 'destructive',
})
},
})
// Delete rule mutation
const deleteRuleMutation = useMutation({
mutationFn: (ruleId: number) => apiClient.deleteExportRule(ruleId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['exportRules'] })
toast({
title: t('common.success'),
description: '規則已刪除',
variant: 'success',
})
},
onError: (error: any) => {
toast({
title: t('common.error'),
description: error.response?.data?.detail || t('errors.networkError'),
variant: 'destructive',
})
},
})
const resetForm = () => {
setFormData({
rule_name: '',
confidence_threshold: 0.5,
include_metadata: true,
filename_pattern: '{filename}_ocr',
css_template: 'default',
})
}
const handleCreate = () => {
setIsCreating(true)
setEditingRule(null)
resetForm()
}
const handleEdit = (rule: ExportRule) => {
setEditingRule(rule)
setIsCreating(false)
setFormData({
rule_name: rule.rule_name,
confidence_threshold: rule.config_json.confidence_threshold || 0.5,
include_metadata: rule.config_json.include_metadata || true,
filename_pattern: rule.config_json.filename_pattern || '{filename}_ocr',
css_template: rule.css_template || 'default',
})
}
const handleSave = () => {
const ruleData = {
rule_name: formData.rule_name,
config_json: {
confidence_threshold: formData.confidence_threshold,
include_metadata: formData.include_metadata,
filename_pattern: formData.filename_pattern,
},
css_template: formData.css_template,
}
if (editingRule) {
updateRuleMutation.mutate({ ruleId: editingRule.id, rule: ruleData })
} else {
createRuleMutation.mutate(ruleData)
}
}
const handleCancel = () => {
setIsCreating(false)
setEditingRule(null)
resetForm()
}
const handleDelete = (ruleId: number) => {
if (window.confirm('確定要刪除此規則嗎?')) {
deleteRuleMutation.mutate(ruleId)
}
}
return (
<div className="max-w-4xl mx-auto space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold text-foreground">{t('settings.title')}</h1>
{!isCreating && !editingRule && (
<Button onClick={handleCreate}>{t('export.rules.newRule')}</Button>
)}
</div>
{/* Create/Edit Form */}
{(isCreating || editingRule) && (
<Card>
<CardHeader>
<CardTitle>
{editingRule ? t('common.edit') + ' ' + t('export.rules.title') : t('export.rules.newRule')}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Rule Name */}
<div>
<label className="block text-sm font-medium text-foreground mb-2">
{t('export.rules.ruleName')}
</label>
<input
type="text"
value={formData.rule_name}
onChange={(e) => setFormData((prev) => ({ ...prev, rule_name: e.target.value }))}
className="w-full px-3 py-2 border border-gray-200 rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="例如:高信心度匯出"
/>
</div>
{/* Confidence Threshold */}
<div>
<label className="block text-sm font-medium text-foreground mb-2">
{t('export.options.confidenceThreshold')}: {formData.confidence_threshold}
</label>
<input
type="range"
min="0"
max="1"
step="0.05"
value={formData.confidence_threshold}
onChange={(e) =>
setFormData((prev) => ({
...prev,
confidence_threshold: Number(e.target.value),
}))
}
className="w-full"
/>
</div>
{/* Include Metadata */}
<div className="flex items-center space-x-2">
<input
type="checkbox"
id="include-metadata-form"
checked={formData.include_metadata}
onChange={(e) =>
setFormData((prev) => ({
...prev,
include_metadata: e.target.checked,
}))
}
className="w-4 h-4 border border-gray-200 rounded"
/>
<label htmlFor="include-metadata-form" className="text-sm font-medium text-foreground">
{t('export.options.includeMetadata')}
</label>
</div>
{/* Filename Pattern */}
<div>
<label className="block text-sm font-medium text-foreground mb-2">
{t('export.options.filenamePattern')}
</label>
<input
type="text"
value={formData.filename_pattern}
onChange={(e) =>
setFormData((prev) => ({
...prev,
filename_pattern: e.target.value,
}))
}
className="w-full px-3 py-2 border border-gray-200 rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="{filename}_ocr"
/>
</div>
{/* CSS Template */}
<div>
<label className="block text-sm font-medium text-foreground mb-2">
{t('export.options.cssTemplate')}
</label>
<select
value={formData.css_template}
onChange={(e) => setFormData((prev) => ({ ...prev, css_template: e.target.value }))}
className="w-full px-3 py-2 border border-gray-200 rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="default"></option>
<option value="academic"></option>
<option value="business"></option>
<option value="report"></option>
</select>
</div>
{/* Actions */}
<div className="flex justify-end gap-3 pt-4">
<Button variant="outline" onClick={handleCancel}>
{t('common.cancel')}
</Button>
<Button
onClick={handleSave}
disabled={!formData.rule_name || createRuleMutation.isPending || updateRuleMutation.isPending}
>
{createRuleMutation.isPending || updateRuleMutation.isPending
? t('common.loading')
: t('common.save')}
</Button>
</div>
</CardContent>
</Card>
)}
{/* Rules List */}
<Card>
<CardHeader>
<CardTitle>{t('export.rules.title')}</CardTitle>
</CardHeader>
<CardContent>
{isLoading ? (
<p className="text-center text-muted-foreground py-8">{t('common.loading')}</p>
) : exportRules && exportRules.length > 0 ? (
<div className="space-y-3">
{exportRules.map((rule) => (
<div
key={rule.id}
className="flex items-center justify-between p-4 border border-gray-200 rounded-lg"
>
<div>
<h3 className="font-medium text-foreground">{rule.rule_name}</h3>
<p className="text-sm text-muted-foreground">
: {rule.config_json.confidence_threshold || 0.5} | CSS :{' '}
{rule.css_template || 'default'}
</p>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => handleEdit(rule)}>
{t('common.edit')}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleDelete(rule.id)}
disabled={deleteRuleMutation.isPending}
>
{t('common.delete')}
</Button>
</div>
</div>
))}
</div>
) : (
<p className="text-center text-muted-foreground py-8"></p>
)}
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,140 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useMutation } from '@tanstack/react-query'
import FileUpload from '@/components/FileUpload'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { useToast } from '@/components/ui/toast'
import { useUploadStore } from '@/store/uploadStore'
import { apiClient } from '@/services/api'
export default function UploadPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const { toast } = useToast()
const [selectedFiles, setSelectedFiles] = useState<File[]>([])
const { setBatchId, setFiles, setUploadProgress } = useUploadStore()
const uploadMutation = useMutation({
mutationFn: (files: File[]) => apiClient.uploadFiles(files),
onSuccess: (data) => {
setBatchId(data.batch_id)
setFiles(data.files)
toast({
title: t('upload.uploadSuccess'),
description: t('upload.fileCount', { count: data.files.length }),
variant: 'success',
})
navigate('/processing')
},
onError: (error: any) => {
toast({
title: t('upload.uploadError'),
description: error.response?.data?.detail || t('errors.networkError'),
variant: 'destructive',
})
},
})
const handleFilesSelected = (files: File[]) => {
setSelectedFiles((prev) => [...prev, ...files])
}
const handleRemoveFile = (index: number) => {
setSelectedFiles((prev) => prev.filter((_, i) => i !== index))
}
const handleClearAll = () => {
setSelectedFiles([])
setUploadProgress(0)
}
const handleUpload = () => {
if (selectedFiles.length === 0) {
toast({
title: t('errors.validationError'),
description: '請選擇至少一個檔案',
variant: 'destructive',
})
return
}
uploadMutation.mutate(selectedFiles)
}
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}
return (
<div className="max-w-4xl mx-auto space-y-6">
<div>
<h1 className="text-3xl font-bold text-foreground mb-2">{t('upload.title')}</h1>
<p className="text-muted-foreground">
OCR PDF Office
</p>
</div>
<FileUpload
onFilesSelected={handleFilesSelected}
disabled={uploadMutation.isPending}
/>
{selectedFiles.length > 0 && (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="text-lg">
{t('upload.selectedFiles')} ({selectedFiles.length})
</CardTitle>
<Button variant="outline" size="sm" onClick={handleClearAll}>
{t('upload.clearAll')}
</Button>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
{selectedFiles.map((file, index) => (
<div
key={index}
className="flex items-center justify-between p-3 bg-muted rounded-md"
>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-foreground truncate">{file.name}</p>
<p className="text-xs text-muted-foreground">{formatFileSize(file.size)}</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => handleRemoveFile(index)}
disabled={uploadMutation.isPending}
>
{t('upload.removeFile')}
</Button>
</div>
))}
</div>
<div className="mt-6 flex justify-end gap-3">
<Button
variant="outline"
onClick={handleClearAll}
disabled={uploadMutation.isPending}
>
{t('common.cancel')}
</Button>
<Button onClick={handleUpload} disabled={uploadMutation.isPending}>
{uploadMutation.isPending ? t('upload.uploading') : t('upload.uploadButton')}
</Button>
</div>
</CardContent>
</Card>
)}
</div>
)
}