feat: integrate Ground Truth review into Kombi Pipeline last step

- New StepGridReview component: split-view (scan image left, grid right),
  confidence stats, row-accept buttons, zoom controls
- Kombi Pipeline case 6 now uses StepGridReview instead of plain GridEditor
- Kombi step label changed to "Review & GT"
- Ground Truth queue page simplified to overview/navigation only
  (links to Kombi pipeline for actual review work)
- Deep-link support: /ai/ocr-overlay?session=xxx&mode=kombi

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Benjamin Admin
2026-03-23 15:04:23 +01:00
parent 4e809c3860
commit 7a6eadde8b
4 changed files with 717 additions and 459 deletions

View File

@@ -1,19 +1,15 @@
'use client'
/**
* Ground-Truth Review Workflow
* Ground-Truth Queue & Progress
*
* Efficient mass-review of OCR sessions:
* - Session queue with auto-advance
* - Split-view: original image left, grid right
* - Confidence highlighting on cells
* - Quick-accept per row
* - Inline cell editing
* - Batch mark as ground truth
* - Progress tracking
* Overview page showing all sessions with their GT status.
* Clicking a session opens it in the Kombi Pipeline (/ai/ocr-overlay)
* where the actual review (split-view, inline edit, GT marking) happens.
*/
import { useState, useEffect, useCallback, useRef } from 'react'
import { useState, useEffect, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { PagePurpose } from '@/components/common/PagePurpose'
const KLAUSUR_API = '/klausur-api'
@@ -32,27 +28,14 @@ interface Session {
has_ground_truth: boolean
}
interface GridZone {
zone_id: string
zone_type: string
columns: Array<{ col_index: number; col_type: string; header: string }>
rows: Array<{ row_index: number; is_header: boolean }>
cells: GridCell[]
}
interface GridCell {
cell_id: string
row_index: number
col_index: number
col_type: string
text: string
confidence?: number
is_bold?: boolean
}
interface GridResult {
zones: GridZone[]
summary?: {
interface GTSession {
session_id: string
name: string
filename: string
document_category: string | null
pipeline: string | null
saved_at: string | null
summary: {
total_zones: number
total_columns: number
total_rows: number
@@ -60,221 +43,125 @@ interface GridResult {
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function confidenceColor(conf: number | undefined): string {
if (conf === undefined) return ''
if (conf >= 80) return 'bg-emerald-50'
if (conf >= 50) return 'bg-amber-50'
return 'bg-red-50'
}
function confidenceBorder(conf: number | undefined): string {
if (conf === undefined) return 'border-slate-200'
if (conf >= 80) return 'border-emerald-200'
if (conf >= 50) return 'border-amber-300'
return 'border-red-300'
}
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
export default function GroundTruthReviewPage() {
// Session list & queue
export default function GroundTruthQueuePage() {
const router = useRouter()
const [allSessions, setAllSessions] = useState<Session[]>([])
const [filter, setFilter] = useState<'all' | 'unreviewed' | 'reviewed'>('unreviewed')
const [currentIdx, setCurrentIdx] = useState(0)
const [gtSessions, setGtSessions] = useState<GTSession[]>([])
const [filter, setFilter] = useState<'all' | 'unreviewed' | 'reviewed'>('all')
const [loading, setLoading] = useState(true)
// Current session data
const [grid, setGrid] = useState<GridResult | null>(null)
const [loadingGrid, setLoadingGrid] = useState(false)
const [editingCell, setEditingCell] = useState<string | null>(null)
const [editText, setEditText] = useState('')
const [acceptedRows, setAcceptedRows] = useState<Set<string>>(new Set())
const [zoom, setZoom] = useState(100)
// Batch operations
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(new Set())
const [marking, setMarking] = useState(false)
const [markResult, setMarkResult] = useState<string | null>(null)
// Stats
const [reviewedCount, setReviewedCount] = useState(0)
const [totalCount, setTotalCount] = useState(0)
const imageRef = useRef<HTMLDivElement>(null)
// Load all sessions
const loadSessions = useCallback(async () => {
// Load sessions + GT sessions
const loadData = useCallback(async () => {
setLoading(true)
try {
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions?limit=200`)
if (!res.ok) return
const data = await res.json()
const sessions: Session[] = (data.sessions || []).map((s: any) => ({
id: s.id,
name: s.name || '',
filename: s.filename || '',
status: s.status || 'active',
created_at: s.created_at || '',
document_category: s.document_category || null,
has_ground_truth: !!(s.ground_truth && s.ground_truth.build_grid_reference),
}))
setAllSessions(sessions)
setTotalCount(sessions.length)
setReviewedCount(sessions.filter(s => s.has_ground_truth).length)
const [sessRes, gtRes] = await Promise.all([
fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions?limit=200`),
fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/ground-truth-sessions`),
])
if (sessRes.ok) {
const data = await sessRes.json()
const gtSet = new Set<string>()
if (gtRes.ok) {
const gtData = await gtRes.json()
const gts: GTSession[] = gtData.sessions || []
setGtSessions(gts)
for (const g of gts) gtSet.add(g.session_id)
}
const sessions: Session[] = (data.sessions || [])
.filter((s: any) => !s.parent_session_id)
.map((s: any) => ({
id: s.id,
name: s.name || '',
filename: s.filename || '',
status: s.status || 'active',
created_at: s.created_at || '',
document_category: s.document_category || null,
has_ground_truth: gtSet.has(s.id),
}))
setAllSessions(sessions)
}
} catch (e) {
console.error('Failed to load sessions:', e)
console.error('Failed to load data:', e)
} finally {
setLoading(false)
}
}, [])
useEffect(() => { loadSessions() }, [loadSessions])
useEffect(() => {
loadData()
}, [loadData])
// Filtered sessions
const filteredSessions = allSessions.filter(s => {
if (filter === 'unreviewed') return !s.has_ground_truth && s.status === 'active'
const filteredSessions = allSessions.filter((s) => {
if (filter === 'unreviewed') return !s.has_ground_truth
if (filter === 'reviewed') return s.has_ground_truth
return true
})
const currentSession = filteredSessions[currentIdx] || null
const reviewedCount = allSessions.filter((s) => s.has_ground_truth).length
const totalCount = allSessions.length
const pct = totalCount > 0 ? Math.round((reviewedCount / totalCount) * 100) : 0
// Load grid for current session
const loadGrid = useCallback(async (sessionId: string) => {
setLoadingGrid(true)
setGrid(null)
setAcceptedRows(new Set())
setEditingCell(null)
try {
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/grid-editor`)
if (res.ok) {
const data = await res.json()
setGrid(data.grid || data)
}
} catch (e) {
console.error('Failed to load grid:', e)
} finally {
setLoadingGrid(false)
}
}, [])
useEffect(() => {
if (currentSession) loadGrid(currentSession.id)
}, [currentSession, loadGrid])
// Navigation
const goNext = () => {
if (currentIdx < filteredSessions.length - 1) setCurrentIdx(currentIdx + 1)
}
const goPrev = () => {
if (currentIdx > 0) setCurrentIdx(currentIdx - 1)
// Open session in Kombi pipeline
const openInPipeline = (sessionId: string) => {
router.push(`/ai/ocr-overlay?session=${sessionId}&mode=kombi`)
}
// Accept row
const acceptRow = (zoneId: string, rowIdx: number) => {
const key = `${zoneId}-${rowIdx}`
setAcceptedRows(prev => new Set([...prev, key]))
}
// Edit cell
const startEdit = (cell: GridCell) => {
setEditingCell(cell.cell_id)
setEditText(cell.text)
}
const saveEdit = async () => {
if (!editingCell || !currentSession) return
try {
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${currentSession.id}/update-cell`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cell_id: editingCell, text: editText }),
})
// Update local state
if (grid) {
const newGrid = { ...grid }
for (const zone of newGrid.zones) {
for (const cell of zone.cells) {
if (cell.cell_id === editingCell) {
cell.text = editText
}
}
}
setGrid(newGrid)
}
} catch (e) {
console.error('Failed to save cell:', e)
}
setEditingCell(null)
}
// Mark as ground truth
const markGroundTruth = async (sessionId: string) => {
setMarking(true)
setMarkResult(null)
try {
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/mark-ground-truth`, {
method: 'POST',
})
if (res.ok) {
setMarkResult('success')
// Update local session state
setAllSessions(prev => prev.map(s =>
s.id === sessionId ? { ...s, has_ground_truth: true } : s
))
setReviewedCount(prev => prev + 1)
} else {
setMarkResult('error')
}
} catch {
setMarkResult('error')
} finally {
setMarking(false)
}
}
// Batch mark
// Batch mark as GT
const batchMark = async () => {
setMarking(true)
let success = 0
for (const sid of selectedSessions) {
try {
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}/mark-ground-truth`, {
method: 'POST',
})
const res = await fetch(
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}/mark-ground-truth?pipeline=kombi`,
{ method: 'POST' },
)
if (res.ok) success++
} catch { /* skip */ }
} catch {
/* skip */
}
}
setAllSessions(prev => prev.map(s =>
selectedSessions.has(s.id) ? { ...s, has_ground_truth: true } : s
))
setReviewedCount(prev => prev + success)
setSelectedSessions(new Set())
setMarking(false)
setMarkResult(`${success} Sessions als Ground Truth markiert`)
setTimeout(() => setMarkResult(null), 3000)
loadData()
}
// All cells for current grid
const allCells = grid?.zones?.flatMap(z => z.cells) || []
const lowConfCells = allCells.filter(c => (c.confidence ?? 100) < 50)
const toggleSelect = (id: string) => {
setSelectedSessions((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
const imageUrl = currentSession
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${currentSession.id}/image/original`
: null
const selectAll = () => {
if (selectedSessions.size === filteredSessions.length) {
setSelectedSessions(new Set())
} else {
setSelectedSessions(new Set(filteredSessions.map((s) => s.id)))
}
}
return (
<div className="space-y-6">
<div className="max-w-[1600px] mx-auto p-4 space-y-4">
<div className="max-w-5xl mx-auto p-4 space-y-4">
<PagePurpose
title="Ground Truth Review"
purpose="Effiziente Massenpruefung von OCR-Sessions: Bild und Grid nebeneinander pruefen, Fehler inline korrigieren, Sessions als Ground Truth markieren."
title="Ground Truth Queue"
purpose="Uebersicht aller OCR-Sessions und deren Ground-Truth-Status. Zum Pruefen und Korrigieren eine Session oeffnen — sie wird im Kombi-Modus (OCR Overlay) bearbeitet."
audience={['Entwickler', 'QA']}
defaultCollapsed
architecture={{
@@ -282,310 +169,251 @@ export default function GroundTruthReviewPage() {
databases: ['PostgreSQL (ocr_pipeline_sessions)'],
}}
relatedPages={[
{ name: 'OCR Pipeline', href: '/ai/ocr-pipeline', description: 'OCR-Pipeline ausfuehren' },
{ name: 'OCR Regression', href: '/ai/ocr-regression', description: 'Regressions-Tests' },
{
name: 'Kombi Pipeline',
href: '/ai/ocr-overlay',
description: 'Sessions bearbeiten und GT markieren',
},
{
name: 'OCR Regression',
href: '/ai/ocr-regression',
description: 'Regressions-Tests',
},
]}
/>
{/* Progress Bar */}
<div className="bg-white rounded-lg border border-slate-200 p-4">
<div className="flex items-center justify-between mb-2">
<h2 className="text-lg font-bold text-slate-900">Ground Truth Review</h2>
<h2 className="text-lg font-bold text-slate-900">
Ground Truth Fortschritt
</h2>
<span className="text-sm text-slate-500">
{reviewedCount} von {totalCount} geprueft ({totalCount > 0 ? Math.round(reviewedCount / totalCount * 100) : 0}%)
{reviewedCount} von {totalCount} markiert ({pct}%)
</span>
</div>
<div className="w-full bg-slate-100 rounded-full h-2.5">
<div
className="bg-teal-500 h-2.5 rounded-full transition-all duration-500"
style={{ width: `${totalCount > 0 ? (reviewedCount / totalCount) * 100 : 0}%` }}
style={{ width: `${pct}%` }}
/>
</div>
<div className="flex items-center gap-4 mt-2 text-xs text-slate-500">
<span className="flex items-center gap-1">
<span className="w-2 h-2 rounded-full bg-teal-400" />
{reviewedCount} Ground Truth
</span>
<span className="flex items-center gap-1">
<span className="w-2 h-2 rounded-full bg-slate-300" />
{totalCount - reviewedCount} offen
</span>
<span>
{gtSessions.reduce((sum, g) => sum + g.summary.total_cells, 0)}{' '}
Referenz-Zellen gesamt
</span>
</div>
</div>
{/* Filter + Queue */}
<div className="flex items-center gap-4">
{/* Filter + Actions */}
<div className="flex items-center gap-4 flex-wrap">
<div className="flex gap-1 bg-slate-100 rounded-lg p-1">
{(['unreviewed', 'reviewed', 'all'] as const).map(f => (
{(['all', 'unreviewed', 'reviewed'] as const).map((f) => (
<button
key={f}
onClick={() => { setFilter(f); setCurrentIdx(0) }}
onClick={() => setFilter(f)}
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${
filter === f
? 'bg-white text-slate-900 shadow-sm font-medium'
: 'text-slate-500 hover:text-slate-700'
}`}
>
{f === 'unreviewed' ? 'Offen' : f === 'reviewed' ? 'Geprueft' : 'Alle'}
{f === 'all'
? 'Alle'
: f === 'unreviewed'
? 'Offen'
: 'Ground Truth'}
<span className="ml-1 text-xs text-slate-400">
({allSessions.filter(s =>
f === 'unreviewed' ? !s.has_ground_truth && s.status === 'active'
: f === 'reviewed' ? s.has_ground_truth
: true
).length})
(
{
allSessions.filter((s) =>
f === 'unreviewed'
? !s.has_ground_truth
: f === 'reviewed'
? s.has_ground_truth
: true,
).length
}
)
</span>
</button>
))}
</div>
{/* Navigation */}
<div className="flex items-center gap-2 ml-auto">
<button onClick={goPrev} disabled={currentIdx === 0}
className="p-2 rounded hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed">
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
</button>
<span className="text-sm text-slate-500 min-w-[80px] text-center">
{filteredSessions.length > 0 ? `${currentIdx + 1} / ${filteredSessions.length}` : '—'}
</span>
<button onClick={goNext} disabled={currentIdx >= filteredSessions.length - 1}
className="p-2 rounded hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed">
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
<div className="ml-auto flex items-center gap-2">
{selectedSessions.size > 0 && (
<button
onClick={batchMark}
disabled={marking}
className="px-3 py-1.5 bg-teal-600 text-white text-sm rounded-lg hover:bg-teal-700 disabled:opacity-50"
>
{marking
? 'Markiere...'
: `${selectedSessions.size} als GT markieren`}
</button>
)}
<button
onClick={selectAll}
className="px-3 py-1.5 text-sm text-slate-500 hover:text-slate-700 border border-slate-200 rounded-lg hover:bg-slate-50"
>
{selectedSessions.size === filteredSessions.length
? 'Keine auswaehlen'
: 'Alle auswaehlen'}
</button>
</div>
{/* Batch mark button */}
{selectedSessions.size > 0 && (
<button
onClick={batchMark}
disabled={marking}
className="px-3 py-1.5 bg-teal-600 text-white text-sm rounded-lg hover:bg-teal-700 disabled:opacity-50"
>
{selectedSessions.size} markieren
</button>
)}
</div>
{/* Toast */}
{markResult && (
<div className={`p-3 rounded-lg text-sm ${
markResult === 'error' ? 'bg-red-50 text-red-700 border border-red-200'
: markResult === 'success' ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
: 'bg-blue-50 text-blue-700 border border-blue-200'
}`}>
{markResult === 'success' ? 'Als Ground Truth markiert!' : markResult === 'error' ? 'Fehler beim Markieren' : markResult}
<div className="p-3 rounded-lg text-sm bg-emerald-50 text-emerald-700 border border-emerald-200">
{markResult}
</div>
)}
{/* Main Content: Split View */}
{/* Session List */}
{loading ? (
<div className="text-center py-12 text-slate-400">Lade Sessions...</div>
) : !currentSession ? (
<div className="text-center py-12 text-slate-400">
Lade Sessions...
</div>
) : filteredSessions.length === 0 ? (
<div className="text-center py-12 text-slate-400">
<p className="text-lg">Keine Sessions in dieser Ansicht</p>
</div>
) : (
<div className="grid grid-cols-2 gap-4" style={{ minHeight: '70vh' }}>
{/* Left: Original Image */}
<div className="bg-white rounded-lg border border-slate-200 overflow-hidden flex flex-col">
<div className="flex items-center justify-between px-3 py-2 border-b border-slate-100 bg-slate-50">
<span className="text-sm font-medium text-slate-700 truncate">
{currentSession.name || currentSession.filename}
</span>
<div className="flex items-center gap-2">
<button onClick={() => setZoom(z => Math.max(50, z - 25))}
className="px-2 py-0.5 text-xs bg-slate-200 rounded hover:bg-slate-300">-</button>
<span className="text-xs text-slate-500 w-10 text-center">{zoom}%</span>
<button onClick={() => setZoom(z => Math.min(300, z + 25))}
className="px-2 py-0.5 text-xs bg-slate-200 rounded hover:bg-slate-300">+</button>
</div>
</div>
<div ref={imageRef} className="flex-1 overflow-auto p-2">
{imageUrl && (
<img
src={imageUrl}
alt="Original scan"
style={{ width: `${zoom}%`, maxWidth: 'none' }}
className="block"
/>
)}
</div>
</div>
{/* Right: Grid Review */}
<div className="bg-white rounded-lg border border-slate-200 overflow-hidden flex flex-col">
<div className="flex items-center justify-between px-3 py-2 border-b border-slate-100 bg-slate-50">
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-slate-700">
{allCells.length} Zellen
</span>
{lowConfCells.length > 0 && (
<span className="text-xs bg-red-100 text-red-700 px-2 py-0.5 rounded-full">
{lowConfCells.length} niedrige Konfidenz
</span>
)}
</div>
<div className="flex items-center gap-2">
{!currentSession.has_ground_truth && (
<button
onClick={() => markGroundTruth(currentSession.id)}
disabled={marking}
className="px-3 py-1 bg-teal-600 text-white text-xs rounded hover:bg-teal-700 disabled:opacity-50"
<div className="bg-white rounded-lg border border-slate-200 overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-slate-200 bg-slate-50 text-left text-slate-500">
<th className="px-4 py-2 w-8">
<input
type="checkbox"
checked={
selectedSessions.size === filteredSessions.length &&
filteredSessions.length > 0
}
onChange={selectAll}
className="rounded border-slate-300"
/>
</th>
<th className="px-4 py-2 font-medium">Status</th>
<th className="px-4 py-2 font-medium">Session</th>
<th className="px-4 py-2 font-medium">Kategorie</th>
<th className="px-4 py-2 font-medium">Erstellt</th>
<th className="px-4 py-2 font-medium text-right">
Aktion
</th>
</tr>
</thead>
<tbody>
{filteredSessions.map((s) => {
const gt = gtSessions.find((g) => g.session_id === s.id)
return (
<tr
key={s.id}
className="border-b border-slate-50 hover:bg-slate-50 transition-colors"
>
{marking ? 'Markiere...' : 'Als Ground Truth markieren'}
</button>
)}
{currentSession.has_ground_truth && (
<span className="text-xs bg-emerald-100 text-emerald-700 px-2 py-0.5 rounded-full">
Ground Truth
</span>
)}
<button
onClick={() => { markGroundTruth(currentSession.id); setTimeout(goNext, 500) }}
disabled={marking}
className="px-3 py-1 bg-slate-600 text-white text-xs rounded hover:bg-slate-700 disabled:opacity-50"
>
Markieren & Weiter
</button>
</div>
</div>
{/* Grid Content */}
<div className="flex-1 overflow-auto">
{loadingGrid ? (
<div className="flex items-center justify-center h-full text-slate-400">
<svg className="animate-spin h-6 w-6 mr-2" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
Lade Grid...
</div>
) : !grid || !grid.zones ? (
<div className="text-center py-8 text-slate-400 text-sm">
Kein Grid vorhanden. Bitte zuerst die Pipeline ausfuehren.
</div>
) : (
<div className="p-3 space-y-4">
{grid.zones.map((zone, zi) => (
<div key={zone.zone_id || zi} className="space-y-1">
{/* Zone header */}
<div className="text-xs text-slate-400 uppercase tracking-wide">
Zone {zi + 1} ({zone.zone_type})
{zone.columns?.length > 0 && (
<span className="ml-2">
{zone.columns.map((c: any) => (c.label || c.col_type || '').replace('column_', '')).join(' | ')}
</span>
)}
</div>
{/* Group cells by row */}
{Array.from(new Set(zone.cells.map(c => c.row_index)))
.sort((a, b) => a - b)
.map(rowIdx => {
const rowCells = zone.cells
.filter(c => c.row_index === rowIdx)
.sort((a, b) => a.col_index - b.col_index)
const rowKey = `${zone.zone_id || zi}-${rowIdx}`
const isAccepted = acceptedRows.has(rowKey)
return (
<div
key={rowKey}
className={`flex items-start gap-1 group ${isAccepted ? 'opacity-60' : ''}`}
>
{/* Quick accept button */}
<button
onClick={() => acceptRow(zone.zone_id || String(zi), rowIdx)}
className={`flex-shrink-0 w-6 h-6 rounded flex items-center justify-center mt-0.5 transition-colors ${
isAccepted
? 'bg-emerald-100 text-emerald-600'
: 'bg-slate-100 text-slate-400 hover:bg-emerald-100 hover:text-emerald-600'
}`}
title="Zeile als korrekt markieren"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
</button>
{/* Cells */}
<div className="flex-1 flex gap-1 flex-wrap">
{rowCells.map(cell => (
<div
key={cell.cell_id}
className={`flex-1 min-w-[80px] px-2 py-1 rounded text-sm border cursor-pointer transition-colors
${confidenceColor(cell.confidence)}
${confidenceBorder(cell.confidence)}
${editingCell === cell.cell_id ? 'ring-2 ring-teal-400' : 'hover:border-teal-300'}
${cell.is_bold ? 'font-bold' : ''}
`}
onClick={() => !isAccepted && startEdit(cell)}
title={`Konfidenz: ${cell.confidence ?? '?'}% | ${cell.col_type}`}
>
{editingCell === cell.cell_id ? (
<input
autoFocus
value={editText}
onChange={e => setEditText(e.target.value)}
onBlur={saveEdit}
onKeyDown={e => {
if (e.key === 'Enter') saveEdit()
if (e.key === 'Escape') setEditingCell(null)
}}
className="w-full bg-transparent outline-none text-sm"
/>
) : (
<span className={cell.text ? '' : 'text-slate-300 italic'}>
{cell.text || '(leer)'}
</span>
)}
</div>
))}
</div>
<td className="px-4 py-2">
<input
type="checkbox"
checked={selectedSessions.has(s.id)}
onChange={() => toggleSelect(s.id)}
className="rounded border-slate-300"
/>
</td>
<td className="px-4 py-2">
{s.has_ground_truth ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-700 border border-emerald-200">
<svg
className="w-3 h-3"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M5 13l4 4L19 7"
/>
</svg>
GT
</span>
) : (
<span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-500 border border-slate-200">
Offen
</span>
)}
</td>
<td className="px-4 py-2">
<div className="flex items-center gap-3">
<div className="flex-shrink-0 w-8 h-8 rounded bg-slate-100 overflow-hidden">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${s.id}/thumbnail?size=64`}
alt=""
className="w-full h-full object-cover"
loading="lazy"
onError={(e) => {
;(e.target as HTMLImageElement).style.display =
'none'
}}
/>
</div>
<div className="min-w-0">
<div className="font-medium text-slate-900 truncate">
{s.name || s.filename || s.id.slice(0, 8)}
</div>
{gt && (
<div className="text-xs text-slate-400">
{gt.summary.total_cells} Zellen,{' '}
{gt.summary.total_zones} Zonen
</div>
)
})}
</div>
))}
</div>
)}
</div>
</div>
)}
</div>
</div>
</td>
<td className="px-4 py-2">
{s.document_category ? (
<span className="text-xs bg-slate-100 px-1.5 py-0.5 rounded text-slate-600">
{s.document_category}
</span>
) : (
<span className="text-xs text-slate-300"></span>
)}
</td>
<td className="px-4 py-2 text-slate-500">
{new Date(s.created_at).toLocaleDateString('de-DE', {
day: '2-digit',
month: '2-digit',
year: '2-digit',
})}
</td>
<td className="px-4 py-2 text-right">
<button
onClick={() => openInPipeline(s.id)}
className="px-3 py-1 text-xs bg-teal-600 text-white rounded hover:bg-teal-700 transition-colors"
>
{s.has_ground_truth
? 'Ueberpruefen'
: 'Im Kombi-Modus oeffnen'}
</button>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
{/* Session List (collapsed) */}
{filteredSessions.length > 1 && (
<details className="bg-white rounded-lg border border-slate-200">
<summary className="px-4 py-3 cursor-pointer text-sm font-medium text-slate-700 hover:bg-slate-50">
Session-Liste ({filteredSessions.length})
</summary>
<div className="border-t border-slate-100 max-h-60 overflow-y-auto">
{filteredSessions.map((s, idx) => (
<div
key={s.id}
className={`flex items-center gap-3 px-4 py-2 text-sm cursor-pointer hover:bg-slate-50 border-b border-slate-50 ${
idx === currentIdx ? 'bg-teal-50' : ''
}`}
onClick={() => setCurrentIdx(idx)}
>
<input
type="checkbox"
checked={selectedSessions.has(s.id)}
onChange={e => {
e.stopPropagation()
setSelectedSessions(prev => {
const next = new Set(prev)
if (next.has(s.id)) next.delete(s.id)
else next.add(s.id)
return next
})
}}
className="rounded border-slate-300"
/>
<span className={`w-2 h-2 rounded-full flex-shrink-0 ${s.has_ground_truth ? 'bg-emerald-400' : 'bg-slate-300'}`} />
<span className="truncate flex-1">{s.name || s.filename || s.id}</span>
{s.document_category && (
<span className="text-xs bg-slate-100 px-1.5 py-0.5 rounded text-slate-500">{s.document_category}</span>
)}
</div>
))}
</div>
</details>
)}
</div>
</div>
)

View File

@@ -1,6 +1,7 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useState, useRef } from 'react'
import { useSearchParams } from 'next/navigation'
import { PagePurpose } from '@/components/common/PagePurpose'
import { PipelineStepper } from '@/components/ocr-pipeline/PipelineStepper'
import { StepOrientation } from '@/components/ocr-pipeline/StepOrientation'
@@ -13,6 +14,7 @@ import { StepWordRecognition } from '@/components/ocr-pipeline/StepWordRecogniti
import { OverlayReconstruction } from '@/components/ocr-overlay/OverlayReconstruction'
import { PaddleDirectStep } from '@/components/ocr-overlay/PaddleDirectStep'
import { GridEditor } from '@/components/grid-editor/GridEditor'
import { StepGridReview } from '@/components/ocr-pipeline/StepGridReview'
import { OVERLAY_PIPELINE_STEPS, PADDLE_DIRECT_STEPS, KOMBI_STEPS, DOCUMENT_CATEGORIES, dbStepToOverlayUi, type PipelineStep, type SessionListItem, type DocumentCategory } from './types'
const KLAUSUR_API = '/klausur-api'
@@ -39,6 +41,9 @@ export default function OcrOverlayPage() {
})),
)
const searchParams = useSearchParams()
const deepLinkHandled = useRef(false)
useEffect(() => {
loadSessions()
}, [])
@@ -114,6 +119,22 @@ export default function OcrOverlayPage() {
}
}, [])
// Handle deep-link: ?session=xxx&mode=kombi (from GT Queue page)
useEffect(() => {
if (deepLinkHandled.current) return
const urlSession = searchParams.get('session')
const urlMode = searchParams.get('mode')
if (urlSession) {
deepLinkHandled.current = true
if (urlMode === 'kombi' || urlMode === 'paddle-direct') {
setMode(urlMode)
const baseSteps = urlMode === 'kombi' ? KOMBI_STEPS : PADDLE_DIRECT_STEPS
setSteps(baseSteps.map((s, i) => ({ ...s, status: i === 0 ? 'active' : 'pending' })))
}
openSession(urlSession)
}
}, [searchParams, openSession])
const deleteSession = useCallback(async (sid: string) => {
try {
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}`, { method: 'DELETE' })
@@ -306,7 +327,7 @@ export default function OcrOverlayPage() {
) : null
case 6:
return mode === 'kombi' ? (
<GridEditor sessionId={sessionId} onNext={handleNext} />
<StepGridReview sessionId={sessionId} onNext={handleNext} />
) : null
default:
return null

View File

@@ -71,7 +71,7 @@ export const KOMBI_STEPS: PipelineStep[] = [
{ id: 'crop', name: 'Zuschneiden', icon: '✂️', status: 'pending' },
{ id: 'kombi', name: 'PP-OCRv5 + Tesseract', icon: '🔀', status: 'pending' },
{ id: 'structure', name: 'Struktur', icon: '🔍', status: 'pending' },
{ id: 'grid-editor', name: 'Tabelle', icon: '📊', status: 'pending' },
{ id: 'grid-editor', name: 'Review & GT', icon: '📊', status: 'pending' },
]
/** Map from DB step to overlay UI step index */

View File

@@ -0,0 +1,409 @@
'use client'
/**
* StepGridReview — Last step of the Kombi Pipeline
*
* Split view: original scan on the left, GridEditor on the right.
* Adds confidence stats, row-accept buttons, and integrates with
* the GT marking flow in the parent page.
*/
import { useCallback, useEffect, useState } from 'react'
import { useGridEditor } from '@/components/grid-editor/useGridEditor'
import type { GridZone } from '@/components/grid-editor/types'
import { GridToolbar } from '@/components/grid-editor/GridToolbar'
import { GridTable } from '@/components/grid-editor/GridTable'
const KLAUSUR_API = '/klausur-api'
interface StepGridReviewProps {
sessionId: string | null
onNext?: () => void
}
export function StepGridReview({ sessionId, onNext }: StepGridReviewProps) {
const {
grid,
loading,
saving,
error,
dirty,
selectedCell,
setSelectedCell,
buildGrid,
loadGrid,
saveGrid,
updateCellText,
toggleColumnBold,
toggleRowHeader,
undo,
redo,
canUndo,
canRedo,
getAdjacentCell,
} = useGridEditor(sessionId)
const [showImage, setShowImage] = useState(true)
const [zoom, setZoom] = useState(100)
const [acceptedRows, setAcceptedRows] = useState<Set<string>>(new Set())
// Load grid on mount
useEffect(() => {
if (sessionId) loadGrid()
}, [sessionId, loadGrid])
// Reset accepted rows when session changes
useEffect(() => {
setAcceptedRows(new Set())
}, [sessionId])
// Keyboard shortcuts
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'z' && !e.shiftKey) {
e.preventDefault()
undo()
} else if ((e.metaKey || e.ctrlKey) && e.key === 'z' && e.shiftKey) {
e.preventDefault()
redo()
} else if ((e.metaKey || e.ctrlKey) && e.key === 's') {
e.preventDefault()
saveGrid()
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [undo, redo, saveGrid])
const handleNavigate = useCallback(
(cellId: string, direction: 'up' | 'down' | 'left' | 'right') => {
const target = getAdjacentCell(cellId, direction)
if (target) {
setSelectedCell(target)
setTimeout(() => {
const el = document.getElementById(`cell-${target}`)
if (el) {
el.focus()
if (el instanceof HTMLInputElement) el.select()
}
}, 0)
}
},
[getAdjacentCell, setSelectedCell],
)
const acceptRow = (zoneIdx: number, rowIdx: number) => {
setAcceptedRows((prev) => {
const next = new Set(prev)
const key = `${zoneIdx}-${rowIdx}`
if (next.has(key)) next.delete(key)
else next.add(key)
return next
})
}
const acceptAllRows = () => {
if (!grid) return
const all = new Set<string>()
for (const zone of grid.zones) {
for (const row of zone.rows) {
all.add(`${zone.zone_index}-${row.index}`)
}
}
setAcceptedRows(all)
}
// Confidence stats
const allCells = grid?.zones?.flatMap((z) => z.cells) || []
const lowConfCells = allCells.filter(
(c) => c.confidence > 0 && c.confidence < 60,
)
const totalRows = grid?.zones?.reduce((sum, z) => sum + z.rows.length, 0) ?? 0
if (!sessionId) {
return (
<div className="text-center py-12 text-gray-400">
Keine Session ausgewaehlt.
</div>
)
}
if (loading) {
return (
<div className="flex items-center justify-center py-16">
<div className="flex items-center gap-3 text-gray-500 dark:text-gray-400">
<svg className="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
/>
</svg>
Grid wird geladen...
</div>
</div>
)
}
if (error) {
return (
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<p className="text-sm text-red-700 dark:text-red-300">
Fehler: {error}
</p>
<button
onClick={buildGrid}
className="mt-2 text-xs px-3 py-1.5 bg-red-600 text-white rounded hover:bg-red-700"
>
Erneut versuchen
</button>
</div>
)
}
if (!grid || !grid.zones.length) {
return (
<div className="text-center py-12">
<p className="text-gray-400 mb-4">Kein Grid vorhanden.</p>
<button
onClick={buildGrid}
className="px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 text-sm"
>
Grid aus OCR-Ergebnissen erstellen
</button>
</div>
)
}
const imageUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
return (
<div className="space-y-3">
{/* Review Stats Bar */}
<div className="flex items-center gap-4 text-xs flex-wrap">
<span className="text-gray-500 dark:text-gray-400">
{grid.summary.total_zones} Zone(n), {grid.summary.total_columns} Spalten,{' '}
{grid.summary.total_rows} Zeilen, {grid.summary.total_cells} Zellen
</span>
{lowConfCells.length > 0 && (
<span className="px-2 py-0.5 rounded-full bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 border border-red-200 dark:border-red-800">
{lowConfCells.length} niedrige Konfidenz
</span>
)}
<span className="text-gray-400 dark:text-gray-500">
{acceptedRows.size}/{totalRows} Zeilen akzeptiert
</span>
{acceptedRows.size < totalRows && (
<button
onClick={acceptAllRows}
className="text-teal-600 dark:text-teal-400 hover:text-teal-700 dark:hover:text-teal-300"
>
Alle akzeptieren
</button>
)}
<div className="ml-auto flex items-center gap-2">
<button
onClick={() => setShowImage(!showImage)}
className={`px-2.5 py-1 rounded text-xs border transition-colors ${
showImage
? 'bg-teal-50 dark:bg-teal-900/30 border-teal-200 dark:border-teal-700 text-teal-700 dark:text-teal-300'
: 'bg-gray-50 dark:bg-gray-800 border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400'
}`}
>
{showImage ? 'Bild ausblenden' : 'Bild einblenden'}
</button>
<span className="text-gray-400 dark:text-gray-500">
{grid.duration_seconds.toFixed(1)}s
</span>
</div>
</div>
{/* Toolbar */}
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2">
<GridToolbar
dirty={dirty}
saving={saving}
canUndo={canUndo}
canRedo={canRedo}
showOverlay={false}
onSave={saveGrid}
onUndo={undo}
onRedo={redo}
onRebuild={buildGrid}
onToggleOverlay={() => setShowImage(!showImage)}
/>
</div>
{/* Split View: Image left + Grid right */}
<div
className={showImage ? 'grid grid-cols-2 gap-3' : ''}
style={{ minHeight: '55vh' }}
>
{/* Left: Original Image */}
{showImage && (
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden flex flex-col">
<div className="flex items-center justify-between px-3 py-2 border-b border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
<span className="text-xs font-medium text-gray-600 dark:text-gray-400">
Original Scan (zugeschnitten)
</span>
<div className="flex items-center gap-2">
<button
onClick={() => setZoom((z) => Math.max(50, z - 25))}
className="px-2 py-0.5 text-xs bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300"
>
-
</button>
<span className="text-xs text-gray-500 dark:text-gray-400 w-10 text-center">
{zoom}%
</span>
<button
onClick={() => setZoom((z) => Math.min(300, z + 25))}
className="px-2 py-0.5 text-xs bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300"
>
+
</button>
<button
onClick={() => setZoom(100)}
className="px-2 py-0.5 text-xs bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300"
>
Fit
</button>
</div>
</div>
<div className="flex-1 overflow-auto p-2">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={imageUrl}
alt="Original scan"
style={{ width: `${zoom}%`, maxWidth: 'none' }}
className="block"
/>
</div>
</div>
)}
{/* Right: Grid with row-accept buttons */}
<div
className="overflow-auto space-y-3"
style={{ maxHeight: showImage ? '70vh' : undefined }}
>
{/* Zone tables with row-accept buttons */}
{(() => {
// Group consecutive zones with same vsplit_group
const groups: GridZone[][] = []
for (const zone of grid.zones) {
const prev = groups[groups.length - 1]
if (
prev &&
zone.vsplit_group != null &&
prev[0].vsplit_group === zone.vsplit_group
) {
prev.push(zone)
} else {
groups.push([zone])
}
}
return groups.map((group) => (
<div key={group[0].vsplit_group ?? group[0].zone_index}>
{/* Row-accept sidebar wraps each zone group */}
<div className="flex gap-1">
{/* Accept buttons column */}
<div className="flex-shrink-0 pt-[52px]">
{group[0].rows.map((row) => {
const key = `${group[0].zone_index}-${row.index}`
const isAccepted = acceptedRows.has(key)
return (
<button
key={row.index}
onClick={() =>
acceptRow(group[0].zone_index, row.index)
}
className={`w-6 h-6 mb-px rounded flex items-center justify-center transition-colors ${
isAccepted
? 'bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400'
: 'bg-gray-100 dark:bg-gray-800 text-gray-300 dark:text-gray-600 hover:bg-emerald-100 dark:hover:bg-emerald-900/30 hover:text-emerald-500'
}`}
title={
isAccepted
? 'Klick zum Entfernen'
: 'Zeile als korrekt markieren'
}
>
<svg
className="w-3.5 h-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2.5}
d="M5 13l4 4L19 7"
/>
</svg>
</button>
)
})}
</div>
{/* Grid table(s) */}
<div
className={`flex-1 min-w-0 ${group.length > 1 ? 'flex gap-2' : ''}`}
>
{group.map((zone) => (
<div
key={zone.zone_index}
className={`${group.length > 1 ? 'flex-1 min-w-0' : ''} bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden`}
>
<GridTable
zone={zone}
layoutMetrics={grid.layout_metrics}
selectedCell={selectedCell}
onSelectCell={setSelectedCell}
onCellTextChange={updateCellText}
onToggleColumnBold={toggleColumnBold}
onToggleRowHeader={toggleRowHeader}
onNavigate={handleNavigate}
/>
</div>
))}
</div>
</div>
</div>
))
})()}
</div>
</div>
{/* Tips + Next */}
<div className="flex items-center justify-between">
<div className="text-[11px] text-gray-400 dark:text-gray-500 flex items-center gap-4">
<span>Tab: naechste Zelle</span>
<span>Enter: Zeile runter</span>
<span>Ctrl+Z/Y: Undo/Redo</span>
<span>Ctrl+S: Speichern</span>
</div>
{onNext && (
<button
onClick={async () => {
if (dirty) await saveGrid()
onNext()
}}
className="px-4 py-2 bg-teal-600 text-white text-sm rounded-lg hover:bg-teal-700 transition-colors"
>
Fertig
</button>
)}
</div>
</div>
)
}