feat(ocr): rewrite UI with quality tiers, enhance toggle, editable results, download

This commit is contained in:
Siddharth Kumar Sah
2026-04-12 18:37:09 +08:00
parent 864145f4b1
commit 2d9ec4e258
+129 -47
View File
@@ -1,13 +1,20 @@
import { Check, Copy } from "lucide-react"; import { Check, ChevronDown, ChevronRight, Copy, Download, Info } from "lucide-react";
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import { ProgressCard } from "@/components/common/progress-card"; import { ProgressCard } from "@/components/common/progress-card";
import { formatHeaders } from "@/lib/api"; import { formatHeaders } from "@/lib/api";
import { copyToClipboard, generateId } from "@/lib/utils"; import { copyToClipboard, generateId } from "@/lib/utils";
import { useFileStore } from "@/stores/file-store"; import { useFileStore } from "@/stores/file-store";
type OcrEngine = "tesseract" | "paddleocr"; type OcrQuality = "fast" | "balanced" | "best";
const QUALITY_OPTIONS: { value: OcrQuality; label: string }[] = [
{ value: "fast", label: "Fast" },
{ value: "balanced", label: "Balanced" },
{ value: "best", label: "Best" },
];
const LANGUAGES = [ const LANGUAGES = [
{ code: "auto", label: "Auto-detect" },
{ code: "en", label: "English" }, { code: "en", label: "English" },
{ code: "de", label: "German" }, { code: "de", label: "German" },
{ code: "fr", label: "French" }, { code: "fr", label: "French" },
@@ -17,13 +24,30 @@ const LANGUAGES = [
{ code: "ko", label: "Korean" }, { code: "ko", label: "Korean" },
]; ];
const ENHANCE_DEFAULTS: Record<OcrQuality, boolean> = {
fast: true,
balanced: true,
best: false,
};
function SectionLabel({ children }: { children: React.ReactNode }) {
return (
<p className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/70 pt-1">
{children}
</p>
);
}
export function OcrSettings() { export function OcrSettings() {
const { files, processing, error, setProcessing, setError } = useFileStore(); const { files, processing, error, setProcessing, setError } = useFileStore();
const [engine, setEngine] = useState<OcrEngine>("tesseract"); const [quality, setQuality] = useState<OcrQuality>("balanced");
const [language, setLanguage] = useState("en"); const [language, setLanguage] = useState("auto");
const [enhance, setEnhance] = useState(true);
const [enhanceManuallySet, setEnhanceManuallySet] = useState(false);
const [langOpen, setLangOpen] = useState(false);
const [text, setText] = useState<string | null>(null); const [text, setText] = useState<string | null>(null);
const [detectedEngine, setDetectedEngine] = useState<string>("");
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
const [progressPhase, setProgressPhase] = useState<"idle" | "uploading" | "processing">("idle"); const [progressPhase, setProgressPhase] = useState<"idle" | "uploading" | "processing">("idle");
const [progressPercent, setProgressPercent] = useState(0); const [progressPercent, setProgressPercent] = useState(0);
@@ -31,6 +55,19 @@ export function OcrSettings() {
const [elapsed, setElapsed] = useState(0); const [elapsed, setElapsed] = useState(0);
const elapsedRef = useRef<ReturnType<typeof setInterval> | null>(null); const elapsedRef = useRef<ReturnType<typeof setInterval> | null>(null);
const handleQualityChange = (q: OcrQuality) => {
setQuality(q);
// Update enhance default unless user has manually toggled it
if (!enhanceManuallySet) {
setEnhance(ENHANCE_DEFAULTS[q]);
}
};
const handleEnhanceToggle = (checked: boolean) => {
setEnhance(checked);
setEnhanceManuallySet(true);
};
const handleProcess = async () => { const handleProcess = async () => {
if (files.length === 0) return; if (files.length === 0) return;
@@ -49,7 +86,6 @@ export function OcrSettings() {
const clientJobId = generateId(); const clientJobId = generateId();
// Open SSE for server-side progress
const es = new EventSource(`/api/v1/jobs/${clientJobId}/progress`); const es = new EventSource(`/api/v1/jobs/${clientJobId}/progress`);
es.onmessage = (event) => { es.onmessage = (event) => {
try { try {
@@ -65,7 +101,7 @@ export function OcrSettings() {
const formData = new FormData(); const formData = new FormData();
formData.append("file", files[0]); formData.append("file", files[0]);
formData.append("settings", JSON.stringify({ engine, language })); formData.append("settings", JSON.stringify({ quality, language, enhance }));
formData.append("clientJobId", clientJobId); formData.append("clientJobId", clientJobId);
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
@@ -85,8 +121,7 @@ export function OcrSettings() {
if (xhr.status >= 200 && xhr.status < 300) { if (xhr.status >= 200 && xhr.status < 300) {
try { try {
const data = JSON.parse(xhr.responseText); const data = JSON.parse(xhr.responseText);
setText(data.text || ""); setText(data.text ?? "");
setDetectedEngine(data.engine || engine);
} catch { } catch {
setError("Invalid response"); setError("Invalid response");
} }
@@ -116,7 +151,7 @@ export function OcrSettings() {
}; };
const handleCopy = async () => { const handleCopy = async () => {
if (text) { if (text !== null) {
const ok = await copyToClipboard(text); const ok = await copyToClipboard(text);
if (ok) { if (ok) {
setCopied(true); setCopied(true);
@@ -125,49 +160,79 @@ export function OcrSettings() {
} }
}; };
const handleDownload = () => {
if (text === null) return;
const blob = new Blob([text], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
const baseName = files[0]?.name?.replace(/\.[^.]+$/, "") ?? "extracted";
a.href = url;
a.download = `${baseName}_ocr.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
const hasFile = files.length > 0; const hasFile = files.length > 0;
const langLabel = LANGUAGES.find((l) => l.code === language)?.label ?? "Auto-detect";
return ( return (
<div className="space-y-4"> <div className="space-y-3">
{/* Engine selector */} {/* Quality selector */}
<div> <SectionLabel>Quality</SectionLabel>
<p className="text-sm font-medium text-muted-foreground">OCR Engine</p> <div className="grid grid-cols-3 gap-1.5">
<div className="flex gap-1 mt-1"> {QUALITY_OPTIONS.map((opt) => (
<button <button
key={opt.value}
type="button" type="button"
onClick={() => setEngine("tesseract")} onClick={() => handleQualityChange(opt.value)}
className={`flex-1 text-xs py-1.5 rounded ${ className={`py-2 px-2 rounded-lg border text-xs font-medium transition-colors ${
engine === "tesseract" quality === opt.value
? "bg-primary text-primary-foreground" ? "border-primary bg-primary/10 text-primary"
: "bg-muted text-muted-foreground" : "border-border text-muted-foreground hover:border-primary/50"
}`} }`}
> >
Tesseract {opt.label}
</button> </button>
<button ))}
type="button"
onClick={() => setEngine("paddleocr")}
className={`flex-1 text-xs py-1.5 rounded ${
engine === "paddleocr"
? "bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground"
}`}
>
PaddleOCR
</button>
</div>
</div> </div>
{/* Language selector */} {/* Enhance toggle */}
<div> <label className="flex items-center gap-2 cursor-pointer">
<label htmlFor="ocr-language" className="text-xs text-muted-foreground"> <input
Language type="checkbox"
checked={enhance}
onChange={(e) => handleEnhanceToggle(e.target.checked)}
className="rounded border-border accent-primary"
/>
<span className="text-sm text-muted-foreground">Enhance before scanning</span>
<span
title="Automatically deskews, enhances contrast, removes noise, and upscales the image before scanning for better accuracy."
className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-muted-foreground/40 text-muted-foreground/60 text-[10px] cursor-help"
>
<Info className="h-2.5 w-2.5" />
</span>
</label> </label>
{/* Language (collapsible) */}
<div>
<button
type="button"
onClick={() => setLangOpen(!langOpen)}
className="flex items-center gap-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/70 hover:text-foreground w-full pt-1"
>
{langOpen ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
Language
<span className="ml-auto text-primary text-[10px] normal-case font-normal">
{langLabel}
</span>
</button>
{langOpen && (
<select <select
id="ocr-language"
value={language} value={language}
onChange={(e) => setLanguage(e.target.value)} onChange={(e) => setLanguage(e.target.value)}
className="w-full mt-0.5 px-2 py-1.5 rounded border border-border bg-background text-sm text-foreground" className="w-full mt-1.5 px-2 py-1.5 rounded border border-border bg-background text-sm text-foreground"
> >
{LANGUAGES.map((lang) => ( {LANGUAGES.map((lang) => (
<option key={lang.code} value={lang.code}> <option key={lang.code} value={lang.code}>
@@ -175,12 +240,13 @@ export function OcrSettings() {
</option> </option>
))} ))}
</select> </select>
)}
</div> </div>
{/* Error */} {/* Error */}
{error && <p className="text-xs text-red-500">{error}</p>} {error && <p className="text-xs text-red-500">{error}</p>}
{/* Process button */} {/* Process button / progress */}
{processing ? ( {processing ? (
<ProgressCard <ProgressCard
active={processing} active={processing}
@@ -206,9 +272,18 @@ export function OcrSettings() {
{text !== null && ( {text !== null && (
<div className="space-y-2"> <div className="space-y-2">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<label htmlFor="ocr-result-text" className="text-xs font-medium text-muted-foreground"> <span className="text-xs font-medium text-muted-foreground">Extracted Text</span>
Extracted Text ({detectedEngine}) <div className="flex items-center gap-3">
</label> {text.length > 0 && (
<button
type="button"
onClick={handleDownload}
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
>
<Download className="h-3 w-3" />
Download
</button>
)}
<button <button
type="button" type="button"
onClick={handleCopy} onClick={handleCopy}
@@ -218,15 +293,22 @@ export function OcrSettings() {
{copied ? "Copied" : "Copy"} {copied ? "Copied" : "Copy"}
</button> </button>
</div> </div>
</div>
{text.length > 0 ? (
<>
<textarea <textarea
id="ocr-result-text" data-testid="ocr-result-text"
readOnly
value={text} value={text}
onChange={(e) => setText(e.target.value)}
rows={8} rows={8}
className="w-full px-2 py-1.5 rounded border border-border bg-muted text-xs text-foreground font-mono resize-y" className="w-full px-2 py-1.5 rounded border border-border bg-muted text-xs text-foreground font-mono resize-y"
/> />
{text.length > 0 && ( <p className="text-[10px] text-muted-foreground">{text.length} characters</p>
<p className="text-[10px] text-muted-foreground">{text.length} characters extracted</p> </>
) : (
<p className="text-xs text-muted-foreground italic py-4 text-center">
No text detected in this image
</p>
)} )}
</div> </div>
)} )}