Files
breakpilot-lehrer/admin-lehrer/components/ocr-overlay/usePixelWordPositions.ts
Benjamin Admin b5d5371f72
Some checks failed
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / test-go-school (push) Successful in 35s
CI / test-go-edu-search (push) Successful in 31s
CI / test-python-klausur (push) Failing after 2m24s
CI / test-python-agent-core (push) Successful in 25s
CI / test-nodejs-website (push) Successful in 25s
fix: einheitliche Schriftgroesse + Border-Cluster-Filter im Overlay
1. Schriftgroesse basiert jetzt auf Median-Zeilenhoehe statt
   individueller Zellhoehe — keine Groessensprunge in Box-Bereichen
2. Sehr schmale Pixel-Cluster (< 0.5% Zellbreite) werden gefiltert,
   damit Box-Rahmen nicht als Textposition erkannt werden

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 09:34:41 +01:00

191 lines
6.3 KiB
TypeScript

import { useEffect, useState } from 'react'
import type { GridCell } from '@/app/(admin)/ai/ocr-overlay/types'
export interface WordPosition {
xPct: number
wPct: number
text: string
fontRatio: number
}
/**
* Analyse dark-pixel clusters on an image to determine
* the exact horizontal position & auto-font-size of word groups in each cell.
*
* When rotation=180, the image is rotated 180° before pixel analysis.
* Cell coordinates are transformed to the rotated space for reading,
* and cluster positions are mirrored back to the original coordinate system.
*
* Returns a Map<cell_id, WordPosition[]>.
*/
export function usePixelWordPositions(
imageUrl: string,
cells: GridCell[],
active: boolean,
rotation: 0 | 180 = 0,
): Map<string, WordPosition[]> {
const [cellWordPositions, setCellWordPositions] = useState<Map<string, WordPosition[]>>(new Map())
useEffect(() => {
if (!active || cells.length === 0 || !imageUrl) return
const img = new Image()
img.crossOrigin = 'anonymous'
img.onload = () => {
const imgW = img.naturalWidth
const imgH = img.naturalHeight
const canvas = document.createElement('canvas')
canvas.width = imgW
canvas.height = imgH
const ctx = canvas.getContext('2d')
if (!ctx) return
if (rotation === 180) {
ctx.translate(imgW, imgH)
ctx.rotate(Math.PI)
ctx.drawImage(img, 0, 0)
ctx.setTransform(1, 0, 0, 1, 0, 0)
} else {
ctx.drawImage(img, 0, 0)
}
const refFontSize = 40
const fontFam = "'Liberation Sans', Arial, sans-serif"
ctx.font = `${refFontSize}px ${fontFam}`
const positions = new Map<string, WordPosition[]>()
for (const cell of cells) {
if (!cell.bbox_pct || !cell.text) continue
const groups = cell.text.split(/\s{3,}/).map(s => s.trim()).filter(Boolean)
let cx: number, cy: number
const cw = Math.round(cell.bbox_pct.w / 100 * imgW)
const ch = Math.round(cell.bbox_pct.h / 100 * imgH)
if (rotation === 180) {
cx = Math.round((100 - cell.bbox_pct.x - cell.bbox_pct.w) / 100 * imgW)
cy = Math.round((100 - cell.bbox_pct.y - cell.bbox_pct.h) / 100 * imgH)
} else {
cx = Math.round(cell.bbox_pct.x / 100 * imgW)
cy = Math.round(cell.bbox_pct.y / 100 * imgH)
}
if (cw <= 0 || ch <= 0) continue
if (cx < 0) cx = 0
if (cy < 0) cy = 0
if (cx + cw > imgW || cy + ch > imgH) continue
const imageData = ctx.getImageData(cx, cy, cw, ch)
const proj = new Float32Array(cw)
for (let y = 0; y < ch; y++) {
for (let x = 0; x < cw; x++) {
const idx = (y * cw + x) * 4
const lum = 0.299 * imageData.data[idx] + 0.587 * imageData.data[idx + 1] + 0.114 * imageData.data[idx + 2]
if (lum < 128) proj[x]++
}
}
const threshold = Math.max(1, ch * 0.03)
const minGap = Math.max(5, Math.round(cw * 0.02))
let clusters: { start: number; end: number }[] = []
let inCluster = false
let clStart = 0
let gap = 0
for (let x = 0; x < cw; x++) {
if (proj[x] >= threshold) {
if (!inCluster) { clStart = x; inCluster = true }
gap = 0
} else if (inCluster) {
gap++
if (gap > minGap) {
clusters.push({ start: clStart, end: x - gap })
inCluster = false
gap = 0
}
}
}
if (inCluster) clusters.push({ start: clStart, end: cw - 1 - gap })
if (clusters.length === 0) continue
// Filter out very narrow clusters (likely box borders / vertical lines)
const minClusterW = Math.max(3, Math.round(cw * 0.005))
clusters = clusters.filter(c => (c.end - c.start + 1) > minClusterW)
if (clusters.length === 0) continue
if (rotation === 180) {
clusters = clusters.map(c => ({
start: cw - 1 - c.end,
end: cw - 1 - c.start,
})).reverse()
}
const wordPos: WordPosition[] = []
if (groups.length <= 1) {
const firstCl = clusters[0]
const lastCl = clusters[clusters.length - 1]
const clusterW = lastCl.end - firstCl.start + 1
const measured = ctx.measureText(cell.text.trim())
const autoFontPx = refFontSize * (clusterW / measured.width)
const fontRatio = Math.min(autoFontPx / ch, 1.0)
wordPos.push({
xPct: cell.bbox_pct.x + (firstCl.start / cw) * cell.bbox_pct.w,
wPct: ((lastCl.end - firstCl.start + 1) / cw) * cell.bbox_pct.w,
text: cell.text.trim(),
fontRatio,
})
} else if (clusters.length >= groups.length) {
for (let i = 0; i < groups.length; i++) {
const cl = clusters[i]
const clusterW = cl.end - cl.start + 1
const measured = ctx.measureText(groups[i])
const autoFontPx = refFontSize * (clusterW / measured.width)
const fontRatio = Math.min(autoFontPx / ch, 1.0)
wordPos.push({
xPct: cell.bbox_pct.x + (cl.start / cw) * cell.bbox_pct.w,
wPct: ((cl.end - cl.start + 1) / cw) * cell.bbox_pct.w,
text: groups[i],
fontRatio,
})
}
} else {
continue
}
positions.set(cell.cell_id, wordPos)
}
// Normalise: find the most common fontRatio (mode) and apply it to all
const allRatios: number[] = []
for (const wps of positions.values()) {
for (const wp of wps) allRatios.push(wp.fontRatio)
}
if (allRatios.length > 0) {
const buckets = new Map<number, number>()
for (const r of allRatios) {
const key = Math.round(r * 50) / 50
buckets.set(key, (buckets.get(key) || 0) + 1)
}
let modeRatio = allRatios[0]
let modeCount = 0
for (const [ratio, count] of buckets) {
if (count > modeCount) { modeRatio = ratio; modeCount = count }
}
for (const wps of positions.values()) {
for (const wp of wps) wp.fontRatio = modeRatio
}
}
setCellWordPositions(positions)
}
img.src = imageUrl
}, [active, cells, imageUrl, rotation])
return cellWordPositions
}