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

42
frontend/src/App.css Normal file
View File

@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

53
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,53 @@
import { Routes, Route, Navigate } from 'react-router-dom'
import { useAuthStore } from '@/store/authStore'
import LoginPage from '@/pages/LoginPage'
import UploadPage from '@/pages/UploadPage'
import ProcessingPage from '@/pages/ProcessingPage'
import ResultsPage from '@/pages/ResultsPage'
import ExportPage from '@/pages/ExportPage'
import SettingsPage from '@/pages/SettingsPage'
import Layout from '@/components/Layout'
/**
* Protected Route Component
*/
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const isAuthenticated = useAuthStore((state) => state.isAuthenticated)
if (!isAuthenticated) {
return <Navigate to="/login" replace />
}
return <>{children}</>
}
function App() {
return (
<Routes>
{/* Public routes */}
<Route path="/login" element={<LoginPage />} />
{/* Protected routes with layout */}
<Route
path="/"
element={
<ProtectedRoute>
<Layout />
</ProtectedRoute>
}
>
<Route index element={<Navigate to="/upload" replace />} />
<Route path="upload" element={<UploadPage />} />
<Route path="processing" element={<ProcessingPage />} />
<Route path="results" element={<ResultsPage />} />
<Route path="export" element={<ExportPage />} />
<Route path="settings" element={<SettingsPage />} />
</Route>
{/* Catch all */}
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
)
}
export default App

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,120 @@
import { useCallback } from 'react'
import { useDropzone } from 'react-dropzone'
import { useTranslation } from 'react-i18next'
import { cn } from '@/lib/utils'
import { Card } from '@/components/ui/card'
interface FileUploadProps {
onFilesSelected: (files: File[]) => void
accept?: Record<string, string[]>
maxSize?: number
maxFiles?: number
disabled?: boolean
}
export default function FileUpload({
onFilesSelected,
accept = {
'image/*': ['.png', '.jpg', '.jpeg'],
'application/pdf': ['.pdf'],
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'],
'application/msword': ['.doc'],
'application/vnd.openxmlformats-officedocument.presentationml.presentation': ['.pptx'],
'application/vnd.ms-powerpoint': ['.ppt'],
},
maxSize = 50 * 1024 * 1024, // 50MB
maxFiles = 100,
disabled = false,
}: FileUploadProps) {
const { t } = useTranslation()
const onDrop = useCallback(
(acceptedFiles: File[]) => {
if (acceptedFiles.length > 0) {
onFilesSelected(acceptedFiles)
}
},
[onFilesSelected]
)
const { getRootProps, getInputProps, isDragActive, isDragReject, fileRejections } = useDropzone({
onDrop,
accept,
maxSize,
maxFiles,
disabled,
})
return (
<div>
<Card
{...getRootProps()}
className={cn(
'border-2 border-dashed transition-colors cursor-pointer hover:border-primary/50',
{
'border-primary bg-primary/5': isDragActive && !isDragReject,
'border-destructive bg-destructive/5': isDragReject,
'opacity-50 cursor-not-allowed': disabled,
}
)}
>
<div className="p-12 text-center">
<input {...getInputProps()} />
<div className="mb-4">
<svg
className="mx-auto h-12 w-12 text-muted-foreground"
stroke="currentColor"
fill="none"
viewBox="0 0 48 48"
aria-hidden="true"
>
<path
d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</div>
<div className="space-y-2">
{isDragActive ? (
<p className="text-lg font-medium text-primary">
{isDragReject ? t('upload.invalidFiles') : t('upload.dropFilesHere')}
</p>
) : (
<>
<p className="text-lg font-medium text-foreground">
{t('upload.dragAndDrop')}
</p>
<p className="text-sm text-muted-foreground">{t('upload.supportedFormats')}</p>
<p className="text-sm text-muted-foreground">{t('upload.maxFileSize')}</p>
</>
)}
</div>
</div>
</Card>
{fileRejections.length > 0 && (
<div className="mt-4 p-4 bg-destructive/10 border border-destructive rounded-md">
<p className="text-sm font-medium text-destructive mb-2">
{t('errors.uploadFailed')}
</p>
<ul className="text-sm text-destructive space-y-1">
{fileRejections.map(({ file, errors }) => (
<li key={file.name}>
{file.name}:{' '}
{errors.map((e) => {
if (e.code === 'file-too-large') return t('errors.fileTooBig')
if (e.code === 'file-invalid-type') return t('errors.unsupportedFormat')
return e.message
})}
</li>
))}
</ul>
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,71 @@
import { Outlet, NavLink } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useAuthStore } from '@/store/authStore'
import { apiClient } from '@/services/api'
export default function Layout() {
const { t } = useTranslation()
const logout = useAuthStore((state) => state.logout)
const handleLogout = () => {
apiClient.logout()
logout()
}
const navLinks = [
{ to: '/upload', label: t('nav.upload') },
{ to: '/processing', label: t('nav.processing') },
{ to: '/results', label: t('nav.results') },
{ to: '/export', label: t('nav.export') },
{ to: '/settings', label: t('nav.settings') },
]
return (
<div className="min-h-screen bg-background">
{/* Header */}
<header className="border-b bg-card">
<div className="container mx-auto px-4 py-4 flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-foreground">{t('app.title')}</h1>
<p className="text-sm text-muted-foreground">{t('app.subtitle')}</p>
</div>
<button
onClick={handleLogout}
className="px-4 py-2 text-sm font-medium text-foreground hover:text-primary transition-colors"
>
{t('nav.logout')}
</button>
</div>
</header>
{/* Navigation */}
<nav className="border-b bg-card">
<div className="container mx-auto px-4">
<ul className="flex space-x-1">
{navLinks.map((link) => (
<li key={link.to}>
<NavLink
to={link.to}
className={({ isActive }) =>
`block px-4 py-3 text-sm font-medium transition-colors ${
isActive
? 'text-primary border-b-2 border-primary'
: 'text-muted-foreground hover:text-foreground'
}`
}
>
{link.label}
</NavLink>
</li>
))}
</ul>
</div>
</nav>
{/* Main Content */}
<main className="container mx-auto px-4 py-8">
<Outlet />
</main>
</div>
)
}

View File

@@ -0,0 +1,26 @@
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
interface MarkdownPreviewProps {
title?: string
content: string
className?: string
}
export default function MarkdownPreview({ title, content, className }: MarkdownPreviewProps) {
return (
<Card className={className}>
{title && (
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
)}
<CardContent>
<div className="prose prose-sm max-w-none dark:prose-invert">
<pre className="whitespace-pre-wrap break-words bg-muted p-4 rounded-md overflow-auto max-h-[600px]">
{content}
</pre>
</div>
</CardContent>
</Card>
)
}

View File

@@ -0,0 +1,90 @@
import { useTranslation } from 'react-i18next'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import type { FileResult } from '@/types/api'
interface ResultsTableProps {
files: FileResult[]
onViewResult?: (fileId: number) => void
onDownloadPDF?: (fileId: number) => void
}
export default function ResultsTable({ files, onViewResult, onDownloadPDF }: ResultsTableProps) {
const { t } = useTranslation()
const getStatusBadge = (status: FileResult['status']) => {
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>
}
}
const formatTime = (seconds?: number) => {
if (!seconds) return 'N/A'
return `${seconds.toFixed(2)}s`
}
return (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>{t('results.filename')}</TableHead>
<TableHead>{t('results.status')}</TableHead>
<TableHead>{t('results.processingTime')}</TableHead>
<TableHead className="text-right">{t('results.actions')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{files.length === 0 ? (
<TableRow>
<TableCell colSpan={4} className="text-center text-muted-foreground">
{t('results.noResults')}
</TableCell>
</TableRow>
) : (
files.map((file) => (
<TableRow key={file.id}>
<TableCell className="font-medium">{file.filename}</TableCell>
<TableCell>{getStatusBadge(file.status)}</TableCell>
<TableCell>{formatTime(file.processing_time)}</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
{file.status === 'completed' && (
<>
<Button
variant="outline"
size="sm"
onClick={() => onViewResult?.(file.id)}
>
{t('results.viewMarkdown')}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => onDownloadPDF?.(file.id)}
>
{t('results.downloadPDF')}
</Button>
</>
)}
{file.status === 'failed' && file.error && (
<span className="text-sm text-destructive">{file.error}</span>
)}
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
)
}

View File

@@ -0,0 +1,30 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement> {
variant?: 'default' | 'secondary' | 'destructive' | 'outline' | 'success'
}
function Badge({ className, variant = 'default', ...props }: BadgeProps) {
return (
<div
className={cn(
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
{
'border-transparent bg-primary text-primary-foreground hover:bg-primary/80':
variant === 'default',
'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80':
variant === 'secondary',
'border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80':
variant === 'destructive',
'border-transparent bg-green-500 text-white hover:bg-green-600': variant === 'success',
'text-foreground': variant === 'outline',
},
className
)}
{...props}
/>
)
}
export { Badge }

View File

@@ -0,0 +1,42 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'default' | 'destructive' | 'outline' | 'secondary' | 'ghost' | 'link'
size?: 'default' | 'sm' | 'lg' | 'icon'
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant = 'default', size = 'default', ...props }, ref) => {
return (
<button
className={cn(
'inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background',
{
'bg-primary text-primary-foreground hover:bg-primary/90': variant === 'default',
'bg-destructive text-destructive-foreground hover:bg-destructive/90':
variant === 'destructive',
'border border-input hover:bg-accent hover:text-accent-foreground':
variant === 'outline',
'bg-secondary text-secondary-foreground hover:bg-secondary/80':
variant === 'secondary',
'hover:bg-accent hover:text-accent-foreground': variant === 'ghost',
'underline-offset-4 hover:underline text-primary': variant === 'link',
},
{
'h-10 py-2 px-4': size === 'default',
'h-9 px-3 rounded-md': size === 'sm',
'h-11 px-8 rounded-md': size === 'lg',
'h-10 w-10': size === 'icon',
},
className
)}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = 'Button'
export { Button }

View File

@@ -0,0 +1,55 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('rounded-lg border bg-card text-card-foreground shadow-sm', className)}
{...props}
/>
)
)
Card.displayName = 'Card'
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />
)
)
CardHeader.displayName = 'CardHeader'
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn('text-2xl font-semibold leading-none tracking-tight', className)}
{...props}
/>
)
)
CardTitle.displayName = 'CardTitle'
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
))
CardDescription.displayName = 'CardDescription'
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
)
)
CardContent.displayName = 'CardContent'
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex items-center p-6 pt-0', className)} {...props} />
)
)
CardFooter.displayName = 'CardFooter'
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

View File

@@ -0,0 +1,29 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
export interface ProgressProps extends React.HTMLAttributes<HTMLDivElement> {
value?: number
max?: number
}
const Progress = React.forwardRef<HTMLDivElement, ProgressProps>(
({ className, value = 0, max = 100, ...props }, ref) => {
const percentage = Math.min(Math.max((value / max) * 100, 0), 100)
return (
<div
ref={ref}
className={cn('relative h-4 w-full overflow-hidden rounded-full bg-secondary', className)}
{...props}
>
<div
className="h-full w-full flex-1 bg-primary transition-all duration-300 ease-in-out"
style={{ transform: `translateX(-${100 - percentage}%)` }}
/>
</div>
)
}
)
Progress.displayName = 'Progress'
export { Progress }

View File

@@ -0,0 +1,70 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="w-full overflow-auto">
<table ref={ref} className={cn('w-full caption-bottom text-sm', className)} {...props} />
</div>
)
)
Table.displayName = 'Table'
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />
))
TableHeader.displayName = 'TableHeader'
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody ref={ref} className={cn('[&_tr:last-child]:border-0', className)} {...props} />
))
TableBody.displayName = 'TableBody'
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted',
className
)}
{...props}
/>
)
)
TableRow.displayName = 'TableRow'
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
'h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0',
className
)}
{...props}
/>
))
TableHead.displayName = 'TableHead'
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', className)}
{...props}
/>
))
TableCell.displayName = 'TableCell'
export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell }

View File

@@ -0,0 +1,116 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
export type ToastProps = {
id: string
title?: string
description?: string
variant?: 'default' | 'destructive' | 'success'
duration?: number
}
type ToastContextType = {
toasts: ToastProps[]
toast: (props: Omit<ToastProps, 'id'>) => void
dismiss: (id: string) => void
}
const ToastContext = React.createContext<ToastContextType | undefined>(undefined)
export function ToastProvider({ children }: { children: React.ReactNode }) {
const [toasts, setToasts] = React.useState<ToastProps[]>([])
const toast = React.useCallback((props: Omit<ToastProps, 'id'>) => {
const id = Math.random().toString(36).substr(2, 9)
const duration = props.duration ?? 3000
setToasts((prev) => [...prev, { ...props, id }])
if (duration > 0) {
setTimeout(() => {
setToasts((prev) => prev.filter((t) => t.id !== id))
}, duration)
}
}, [])
const dismiss = React.useCallback((id: string) => {
setToasts((prev) => prev.filter((t) => t.id !== id))
}, [])
return (
<ToastContext.Provider value={{ toasts, toast, dismiss }}>
{children}
<ToastViewport toasts={toasts} dismiss={dismiss} />
</ToastContext.Provider>
)
}
export function useToast() {
const context = React.useContext(ToastContext)
if (!context) {
throw new Error('useToast must be used within ToastProvider')
}
return context
}
function ToastViewport({
toasts,
dismiss,
}: {
toasts: ToastProps[]
dismiss: (id: string) => void
}) {
return (
<div className="fixed top-0 right-0 z-50 w-full max-w-md p-4 space-y-4 pointer-events-none">
{toasts.map((toast) => (
<Toast key={toast.id} {...toast} onDismiss={() => dismiss(toast.id)} />
))}
</div>
)
}
function Toast({
title,
description,
variant = 'default',
onDismiss,
}: ToastProps & { onDismiss: () => void }) {
return (
<div
className={cn(
'pointer-events-auto w-full rounded-lg border p-4 shadow-lg transition-all',
'bg-background text-foreground',
{
'border-destructive': variant === 'destructive',
'border-green-500': variant === 'success',
}
)}
>
<div className="flex items-start gap-3">
<div className="flex-1 space-y-1">
{title && <div className="text-sm font-semibold">{title}</div>}
{description && <div className="text-sm text-muted-foreground">{description}</div>}
</div>
<button
onClick={onDismiss}
className="text-foreground/50 hover:text-foreground transition-colors"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</div>
</div>
)
}

View File

@@ -0,0 +1,22 @@
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import zhTW from './locales/zh-TW.json'
/**
* i18n Configuration
* Default language: Traditional Chinese (zh-TW)
*/
i18n.use(initReactI18next).init({
resources: {
'zh-TW': {
translation: zhTW,
},
},
lng: 'zh-TW',
fallbackLng: 'zh-TW',
interpolation: {
escapeValue: false,
},
})
export default i18n

View File

@@ -0,0 +1,153 @@
{
"app": {
"title": "OCR 批次處理系統",
"subtitle": "智能文字識別與轉換平台"
},
"nav": {
"upload": "上傳檔案",
"processing": "處理中",
"results": "結果檢視",
"export": "匯出",
"settings": "設定",
"logout": "登出"
},
"auth": {
"login": "登入",
"username": "使用者名稱",
"password": "密碼",
"loginButton": "登入",
"loginError": "登入失敗,請檢查帳號密碼",
"welcomeBack": "歡迎回來"
},
"upload": {
"title": "上傳檔案",
"dragAndDrop": "拖曳檔案至此,或點擊選擇檔案",
"dropFilesHere": "放開以上傳檔案",
"invalidFiles": "部分檔案格式不支援",
"supportedFormats": "支援格式PNG, JPG, JPEG, PDF, DOC, DOCX, PPT, PPTX",
"maxFileSize": "單檔最大 50MB",
"uploadButton": "開始上傳",
"uploading": "上傳中...",
"uploadSuccess": "上傳成功",
"uploadError": "上傳失敗",
"fileCount": "已選擇 {{count}} 個檔案",
"clearAll": "清除全部",
"removeFile": "移除",
"selectedFiles": "已選擇的檔案"
},
"processing": {
"title": "OCR 處理中",
"status": "狀態",
"progress": "進度",
"currentFile": "目前處理",
"filesProcessed": "已處理 {{processed}} / {{total}} 個檔案",
"startProcessing": "開始處理",
"processing": "處理中...",
"completed": "處理完成",
"failed": "處理失敗",
"pending": "等待中",
"estimatedTime": "預計剩餘時間",
"settings": {
"title": "處理設定",
"language": "識別語言",
"threshold": "信心度閾值",
"layoutDetection": "版面偵測"
}
},
"results": {
"title": "OCR 結果",
"filename": "檔案名稱",
"status": "狀態",
"confidence": "信心度",
"processingTime": "處理時間",
"actions": "操作",
"viewMarkdown": "檢視 Markdown",
"viewJSON": "檢視 JSON",
"downloadPDF": "下載 PDF",
"preview": "預覽",
"noResults": "尚無處理結果",
"textBlocks": "文字區塊",
"layoutInfo": "版面資訊"
},
"export": {
"title": "匯出結果",
"format": "匯出格式",
"formats": {
"txt": "純文字 (.txt)",
"json": "JSON (.json)",
"excel": "Excel (.xlsx)",
"markdown": "Markdown (.md)",
"pdf": "PDF (.pdf)"
},
"options": {
"title": "匯出選項",
"confidenceThreshold": "信心度閾值",
"includeMetadata": "包含元資料",
"filenamePattern": "檔案名稱模式",
"cssTemplate": "CSS 樣板"
},
"rules": {
"title": "匯出規則",
"selectRule": "選擇規則",
"saveRule": "儲存規則",
"newRule": "新增規則",
"ruleName": "規則名稱",
"deleteRule": "刪除規則"
},
"cssTemplates": {
"default": "預設",
"academic": "學術",
"business": "商務",
"report": "報告"
},
"exportButton": "匯出",
"exporting": "匯出中...",
"exportSuccess": "匯出成功",
"exportError": "匯出失敗"
},
"settings": {
"title": "設定",
"exportRules": "匯出規則管理",
"language": "語言",
"theme": "主題",
"about": "關於"
},
"common": {
"confirm": "確認",
"cancel": "取消",
"save": "儲存",
"delete": "刪除",
"edit": "編輯",
"close": "關閉",
"loading": "載入中...",
"error": "錯誤",
"success": "成功",
"warning": "警告",
"info": "資訊",
"search": "搜尋",
"filter": "篩選",
"sort": "排序",
"refresh": "重新整理",
"back": "返回",
"next": "下一步",
"previous": "上一步",
"submit": "提交"
},
"errors": {
"networkError": "網路錯誤,請稍後再試",
"unauthorized": "未授權,請重新登入",
"notFound": "找不到資源",
"serverError": "伺服器錯誤",
"validationError": "驗證錯誤",
"fileTooBig": "檔案過大",
"unsupportedFormat": "不支援的格式",
"uploadFailed": "上傳失敗",
"processingFailed": "處理失敗",
"exportFailed": "匯出失敗"
},
"translation": {
"title": "翻譯功能",
"comingSoon": "即將推出",
"description": "文件翻譯功能正在開發中,敬請期待"
}
}

57
frontend/src/index.css Normal file
View File

@@ -0,0 +1,57 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 221.2 83.2% 53.3%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 217.2 91.2% 59.8%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 224.3 76.3% 48%;
}
}
@layer base {
body {
background-color: hsl(var(--background));
color: hsl(var(--foreground));
}
}

34
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,34 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { I18nextProvider } from 'react-i18next'
import { ToastProvider } from './components/ui/toast'
import i18n from './i18n'
import './index.css'
import App from './App.tsx'
// Create React Query client
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
staleTime: 1000 * 60 * 5, // 5 minutes
},
},
})
createRoot(document.getElementById('root')!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<I18nextProvider i18n={i18n}>
<ToastProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ToastProvider>
</I18nextProvider>
</QueryClientProvider>
</StrictMode>,
)

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>
)
}

View File

@@ -0,0 +1,279 @@
import axios, { AxiosError } from 'axios'
import type { AxiosInstance } from 'axios'
import type {
LoginRequest,
LoginResponse,
UploadResponse,
ProcessRequest,
ProcessResponse,
TaskStatus,
BatchStatus,
OCRResult,
ExportRequest,
ExportRule,
CSSTemplate,
TranslateRequest,
TranslateResponse,
TranslationConfig,
ApiError,
} from '@/types/api'
/**
* API Client Configuration
*/
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:12010'
const API_VERSION = 'v1'
class ApiClient {
private client: AxiosInstance
private token: string | null = null
constructor() {
this.client = axios.create({
baseURL: `${API_BASE_URL}/api/${API_VERSION}`,
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
})
// Request interceptor to add auth token
this.client.interceptors.request.use(
(config) => {
if (this.token) {
config.headers.Authorization = `Bearer ${this.token}`
}
return config
},
(error) => Promise.reject(error)
)
// Response interceptor for error handling
this.client.interceptors.response.use(
(response) => response,
(error: AxiosError<ApiError>) => {
if (error.response?.status === 401) {
// Token expired or invalid
this.clearToken()
window.location.href = '/login'
}
return Promise.reject(error)
}
)
// Load token from localStorage
this.loadToken()
}
/**
* Set authentication token
*/
setToken(token: string) {
this.token = token
localStorage.setItem('auth_token', token)
}
/**
* Clear authentication token
*/
clearToken() {
this.token = null
localStorage.removeItem('auth_token')
}
/**
* Load token from localStorage
*/
private loadToken() {
const token = localStorage.getItem('auth_token')
if (token) {
this.token = token
}
}
/**
* Check if user is authenticated
*/
isAuthenticated(): boolean {
return this.token !== null
}
// ==================== Authentication ====================
/**
* Login
*/
async login(data: LoginRequest): Promise<LoginResponse> {
const response = await this.client.post<LoginResponse>('/auth/login', {
username: data.username,
password: data.password,
})
this.setToken(response.data.access_token)
return response.data
}
/**
* Logout
*/
logout() {
this.clearToken()
}
// ==================== File Upload ====================
/**
* Upload files
*/
async uploadFiles(files: File[]): Promise<UploadResponse> {
const formData = new FormData()
files.forEach((file) => {
formData.append('files', file)
})
const response = await this.client.post<UploadResponse>('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
return response.data
}
// ==================== OCR Processing ====================
/**
* Process OCR
*/
async processOCR(data: ProcessRequest): Promise<ProcessResponse> {
const response = await this.client.post<ProcessResponse>('/ocr/process', data)
return response.data
}
/**
* Get task status
*/
async getTaskStatus(taskId: string): Promise<TaskStatus> {
const response = await this.client.get<TaskStatus>(`/ocr/status/${taskId}`)
return response.data
}
/**
* Get OCR result
*/
async getOCRResult(taskId: string): Promise<OCRResult> {
const response = await this.client.get<OCRResult>(`/ocr/result/${taskId}`)
return response.data
}
/**
* Get batch status
*/
async getBatchStatus(batchId: number): Promise<BatchStatus> {
const response = await this.client.get<BatchStatus>(`/batch/${batchId}/status`)
return response.data
}
// ==================== Export ====================
/**
* Export results
*/
async exportResults(data: ExportRequest): Promise<Blob> {
const response = await this.client.post('/export', data, {
responseType: 'blob',
})
return response.data
}
/**
* Generate and download PDF
*/
async exportPDF(fileId: number, cssTemplate?: string): Promise<Blob> {
const params = cssTemplate ? { css_template: cssTemplate } : {}
const response = await this.client.get(`/export/pdf/${fileId}`, {
params,
responseType: 'blob',
})
return response.data
}
/**
* Get export rules
*/
async getExportRules(): Promise<ExportRule[]> {
const response = await this.client.get<ExportRule[]>('/export/rules')
return response.data
}
/**
* Create export rule
*/
async createExportRule(rule: Omit<ExportRule, 'id' | 'created_at'>): Promise<ExportRule> {
const response = await this.client.post<ExportRule>('/export/rules', rule)
return response.data
}
/**
* Update export rule
*/
async updateExportRule(ruleId: number, rule: Partial<ExportRule>): Promise<ExportRule> {
const response = await this.client.put<ExportRule>(`/export/rules/${ruleId}`, rule)
return response.data
}
/**
* Delete export rule
*/
async deleteExportRule(ruleId: number): Promise<void> {
await this.client.delete(`/export/rules/${ruleId}`)
}
/**
* Get CSS templates
*/
async getCSSTemplates(): Promise<CSSTemplate[]> {
const response = await this.client.get<CSSTemplate[]>('/export/css-templates')
return response.data
}
// ==================== Translation (FUTURE FEATURE - STUB) ====================
/**
* Translate document (STUB - Not yet implemented)
* This is a placeholder for future translation functionality
* @throws Will throw error with status 501 (Not Implemented)
*/
async translateDocument(data: TranslateRequest): Promise<TranslateResponse> {
// This endpoint is expected to return 501 Not Implemented until Phase 5
const response = await this.client.post<TranslateResponse>('/translate/document', data)
return response.data
}
/**
* Get translation configs (STUB - Not yet implemented)
* This is a placeholder for future translation functionality
* @throws Will throw error with status 501 (Not Implemented)
*/
async getTranslationConfigs(): Promise<TranslationConfig[]> {
// This endpoint is expected to return 501 Not Implemented until Phase 5
const response = await this.client.get<TranslationConfig[]>('/translate/configs')
return response.data
}
/**
* Create translation config (STUB - Not yet implemented)
* This is a placeholder for future translation functionality
* @throws Will throw error with status 501 (Not Implemented)
*/
async createTranslationConfig(
config: Omit<TranslationConfig, 'id' | 'created_at'>
): Promise<TranslationConfig> {
// This endpoint is expected to return 501 Not Implemented until Phase 5
const response = await this.client.post<TranslationConfig>('/translate/configs', config)
return response.data
}
}
// Export singleton instance
export const apiClient = new ApiClient()

View File

@@ -0,0 +1,36 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { User } from '@/types/api'
interface AuthState {
user: User | null
isAuthenticated: boolean
setUser: (user: User | null) => void
logout: () => void
}
/**
* Authentication Store
* Persisted to localStorage
*/
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
user: null,
isAuthenticated: false,
setUser: (user) =>
set({
user,
isAuthenticated: user !== null,
}),
logout: () =>
set({
user: null,
isAuthenticated: false,
}),
}),
{
name: 'auth-storage',
}
)
)

View File

@@ -0,0 +1,53 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { FileInfo } from '@/types/api'
interface UploadState {
batchId: number | null
files: FileInfo[]
uploadProgress: number
setBatchId: (id: number) => void
setFiles: (files: FileInfo[]) => void
setUploadProgress: (progress: number) => void
updateFileStatus: (fileId: number, status: FileInfo['status']) => void
clearUpload: () => void
}
/**
* Upload Store
* Manages file upload state with localStorage persistence
*/
export const useUploadStore = create<UploadState>()(
persist(
(set) => ({
batchId: null,
files: [],
uploadProgress: 0,
setBatchId: (id) => {
set({ batchId: id })
},
setFiles: (files) => set({ files }),
setUploadProgress: (progress) => set({ uploadProgress: progress }),
updateFileStatus: (fileId, status) =>
set((state) => ({
files: state.files.map((file) =>
file.id === fileId ? { ...file, status } : file
),
})),
clearUpload: () =>
set({
batchId: null,
files: [],
uploadProgress: 0,
}),
}),
{
name: 'tool-ocr-upload-store',
// Only persist batchId and files, not upload progress
partialize: (state) => ({
batchId: state.batchId,
files: state.files,
}),
}
)
)

174
frontend/src/types/api.ts Normal file
View File

@@ -0,0 +1,174 @@
/**
* API Type Definitions
* Based on backend OpenAPI specification
*/
// Authentication
export interface LoginRequest {
username: string
password: string
}
export interface LoginResponse {
access_token: string
token_type: string
}
export interface User {
id: number
username: string
}
// File Upload
export interface UploadResponse {
batch_id: number
files: FileInfo[]
}
export interface FileInfo {
id: number
filename: string
file_size: number
format: string
status: 'pending' | 'processing' | 'completed' | 'failed'
}
// OCR Processing
export interface ProcessRequest {
batch_id: number
lang?: string
confidence_threshold?: number
}
export interface ProcessResponse {
task_id: string
batch_id: number
status: string
}
export interface TaskStatus {
task_id: string
status: 'pending' | 'processing' | 'completed' | 'failed'
progress_percentage: number
current_file?: string
files_processed: number
total_files: number
error?: string
}
export interface BatchStatus {
batch: {
id: number
status: 'pending' | 'processing' | 'completed' | 'failed'
progress_percentage: number
created_at: string
completed_at?: string
}
files: FileResult[]
}
export interface FileResult {
id: number
filename: string
status: 'pending' | 'processing' | 'completed' | 'failed'
processing_time?: number
error?: string
}
// OCR Results
export interface OCRResult {
file_id: number
filename: string
status: string
markdown_content: string
json_data: OCRJsonData
confidence: number
processing_time: number
}
export interface OCRJsonData {
total_text_regions: number
average_confidence: number
text_blocks: TextBlock[]
layout_info?: LayoutInfo
}
export interface TextBlock {
text: string
confidence: number
bbox: [number, number, number, number]
position: number
}
export interface LayoutInfo {
tables_detected: number
images_detected: number
structure: string
}
// Export
export interface ExportRequest {
batch_id: number
format: 'txt' | 'json' | 'excel' | 'markdown' | 'pdf'
rule_id?: number
options?: ExportOptions
}
export interface ExportOptions {
confidence_threshold?: number
include_metadata?: boolean
filename_pattern?: string
css_template?: string
}
export interface ExportRule {
id: number
rule_name: string
config_json: Record<string, any>
css_template?: string
created_at: string
}
export interface CSSTemplate {
name: string
description: string
filename: string
}
// Translation (FUTURE FEATURE)
export interface TranslateRequest {
file_id: number
source_lang: string
target_lang: string
engine_type?: 'argos' | 'ernie' | 'google'
}
export interface TranslateResponse {
task_id: string
file_id: number
status: 'pending' | 'processing' | 'completed' | 'failed'
translated_content?: string
}
export interface TranslationConfig {
id: number
source_lang: string
target_lang: string
engine_type: 'argos' | 'ernie' | 'google'
engine_config: Record<string, any>
created_at: string
}
// API Response
export interface ApiResponse<T = any> {
success: boolean
data?: T
error?: string
message?: string
}
// Error Response
export interface ApiError {
detail: string
status_code: number
}