Fast, accurate OCR with correctness assessment.
import type { ImageParseTextRange } from './imageParseBlocks';
import { comparableImageParseFormula } from './imageParseFormulaMarkdown';
import { groupImageParseHighlightNodes } from './imageParseHighlightGroups';
/** Sanitized preview syntax-tree node; positioning and grouping only add trusted attributes. */
export interface ImageParsePreviewNode {
type: string;
tagName?: string;
value?: string;
properties?: Record<string, unknown>;
children?: ImageParsePreviewNode[];
position?: { start: { offset?: number }; end: { offset?: number } };
}
/** Correspondence between a rendered semantic node and an original-image recognition block. */
export interface ImageParseLinkedRange {
id: string;
range: ImageParseTextRange;
}
const BLOCK_TAGS = new Set([
'p',
'li',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'table',
'pre',
'blockquote',
]);
/**
* Mark the matching semantic block on the Markdown syntax tree, without injecting HTML and without breaking tables or formulas apart.
* Highlighting keeps the whole block's Markdown structure, and source offsets must match the text passed to the renderer.
*/
export function imageParseHighlight(
range?: ImageParseTextRange,
linkedRanges: readonly ImageParseLinkedRange[] = [],
deduplicateFormulas = false,
) {
return (tree: ImageParsePreviewNode) => {
if (!range && !linkedRanges.length && !deduplicateFormulas) return;
const indexed = linkedRanges
.map((item, order) => ({ ...item, order }))
.sort((left, right) => left.range.start - right.range.start);
const maxEnds: number[] = [];
indexed.forEach((item, index) => {
maxEnds.push(Math.max(maxEnds[index - 1] ?? -Infinity, item.range.end));
});
const matches = (start: number, end: number) => {
// The prefix maximum end supports overlapping ranges; blocks in ordinary reading order only visit adjacent hits.
let low = 0;
let high = indexed.length;
while (low < high) {
const middle = (low + high) >>> 1;
if (indexed[middle].range.start < end) low = middle + 1;
else high = middle;
}
const found: typeof indexed = [];
for (let index = low - 1; index >= 0 && maxEnds[index] > start; index--) {
if (indexed[index].range.end > start) found.push(indexed[index]);
}
return found.sort((left, right) => left.order - right.order);
};
const matchingIds = new Map<ImageParsePreviewNode, string[]>();
const displayMath = new Map<ImageParsePreviewNode, string>();
const aliasedHighlights = new Set<ImageParsePreviewNode>();
function collect(node: ImageParsePreviewNode) {
const start = node.position?.start.offset;
const end = node.position?.end.offset;
if (
node.tagName &&
BLOCK_TAGS.has(node.tagName) &&
start !== undefined &&
end !== undefined
) {
const matching = matches(start, end);
if (matching.length)
matchingIds.set(
node,
matching.map(({ id }) => id),
);
}
if (isDisplayMathPre(node) && start !== undefined && end !== undefined) {
displayMath.set(node, comparableImageParseFormula(nodeText(node)));
}
node.children?.forEach(collect);
}
collect(tree);
// Compatible with old drafts already open: only merge an adjacent duplicate representation, and move the old range onto the display formula.
// Do not search across the body for the same formula, and do not merge two different original-image regions into one click target.
if (deduplicateFormulas) {
const children: ImageParsePreviewNode[] = [];
let previousMath: ImageParsePreviewNode | undefined;
for (const child of tree.children ?? []) {
const node = semanticNode(child);
if (node.type === 'text' && !node.value?.trim()) {
children.push(child);
continue;
}
const start = node.position?.start.offset;
const end = node.position?.end.offset;
const ids = matchingIds.get(node) ?? [];
const previousIds = previousMath ? (matchingIds.get(previousMath) ?? []) : [];
const distinctBlocks =
ids.length > 0 && previousIds.length > 0 && ids.some((id) => !previousIds.includes(id));
if (
previousMath &&
node.tagName === 'p' &&
displayMath.get(previousMath) === comparableImageParseFormula(nodeText(node)) &&
!distinctBlocks
) {
matchingIds.set(previousMath, [...new Set([...previousIds, ...ids])]);
if (
range &&
start !== undefined &&
end !== undefined &&
start < range.end &&
end > range.start
)
aliasedHighlights.add(previousMath);
continue;
}
children.push(child);
previousMath = displayMath.has(node) ? node : undefined;
}
tree.children = children;
}
groupImageParseHighlightNodes(tree, matchingIds);
function visit(node: ImageParsePreviewNode) {
const start = node.position?.start.offset;
const end = node.position?.end.offset;
if (
node.tagName &&
(BLOCK_TAGS.has(node.tagName) || node.properties?.dataOcrGroupId !== undefined) &&
start !== undefined &&
end !== undefined
) {
const highlighted =
aliasedHighlights.has(node) || Boolean(range && start < range.end && end > range.start);
const matching = matchingIds.get(node) ?? [];
// When one semantic node corresponds to several original-image blocks, do not guess, so the click does not land in the wrong place.
const linkedId = matching.length === 1 ? matching[0] : undefined;
if (highlighted || matching.length) {
const existingClass = node.properties?.className;
const classes = Array.isArray(existingClass) ? existingClass : [];
// Tables are stroked and rounded by a dedicated shell and must not be covered by the ordinary text selection style.
const highlightClasses =
highlighted && node.tagName !== 'table'
? ['ring-1', 'ring-inset', 'ring-primary/60', 'rounded-sm']
: [];
if (node.tagName === 'pre') {
// KaTeX replaces the pre node of display-math; a shell keeps the positioning marker.
const original = { ...node };
node.tagName = 'div';
node.children = [original];
node.properties = {};
}
node.properties = {
...node.properties,
...(matching.length ? { dataOcrLinkedIds: JSON.stringify(matching) } : {}),
...(highlighted
? {
dataOcrHighlight: 'true',
className: [...classes, ...highlightClasses],
}
: {}),
...(linkedId
? {
dataOcrBlockId: linkedId,
role: 'button',
tabIndex: 0,
className: [
...classes,
...highlightClasses,
'cursor-pointer',
'hover:bg-primary/5',
'focus-visible:outline-none',
'focus-visible:ring-2',
'focus-visible:ring-ring',
],
}
: {}),
};
// One semantic block has already been hit, so a list item and its inner paragraph do not each create a click target.
return;
}
}
node.children?.forEach(visit);
}
visit(tree);
};
}
function nodeText(node: ImageParsePreviewNode): string {
return node.value ?? node.children?.map(nodeText).join('') ?? '';
}
function isDisplayMathPre(node: ImageParsePreviewNode): boolean {
if (node.tagName !== 'pre') return false;
const code = node.children?.find((child) => child.tagName === 'code');
const className = code?.properties?.className;
const classes = Array.isArray(className) ? className : [className];
return classes.includes('math-display');
}
function semanticNode(node: ImageParsePreviewNode): ImageParsePreviewNode {
if (node.tagName !== 'div' || typeof node.properties?.dataEditStart !== 'number') return node;
const children = node.children?.filter(
(child) => child.type !== 'text' || Boolean(child.value?.trim()),
);
return children?.length === 1 ? children[0] : node;
}