// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * Alignment: turn a `CanonicalRow` (raw + components) into a `LabeledRow` * (raw + tokens + BIO labels) or a `QuarantinedRow` (raw + reason) per the Phase 1 plan. * * Pipeline: * * 1. For each `(tag, value)` in `components`, find the value's character span in `raw`. * First try a verbatim substring match (case-insensitive, whitespace-collapsed). * If that fails, fall back to fuzzy match via `fastest-levenshtein`, * with a tunable edit distance threshold. * 2. If any component cannot be located, reject the row with a human-readable reason and send it to the * quarantine pile (`reason: "component-not-found:"` or `"edit-distance-exceeded::"`). * 3. Tokenize `raw` with the supplied `Tokenizer` (defaults to the whitespace tokenizer). * 4. For each token: walk the list of component spans, pick the one whose span * contains the token's character range. * First token in a component span → `B-`; subsequent tokens → `I-`; no overlap → `O`. * 5. Emit the located char spans verbatim as `span_starts[]` / `span_ends[]` / * `span_tags[]` (the v0.5.0 char-offset format). * * Structural invariants the function preserves (the span ones loudly — a violation throws * rather than quarantines, because it indicates a bug here rather than bad source data): * * - `tokens.length === labels.length` always. * - Each component contributes at most one contiguous BIO run (no `B-tag … O … I-tag` gaps). * This is enforced by greedy first-match span assignment + ordered token iteration. * - The span triple is sorted ascending by start and non-overlapping. * - `raw` is NFC-normalized (asserted per row. a non-NFC raw makes char offsets ambiguous * downstream — NFD `é` occupies two code units where NFC `é` occupies one — and silently so). */ import type { BIOLabel, ComponentTag } from "@mailwoman/codex/component" import type { TextFragment } from "@mailwoman/core/tokenization/Span" import { distance as levenshteinDistance } from "fastest-levenshtein" import type { CanonicalRow, LabeledRow, QuarantinedRow } from "#types" import { whitespaceTokenizer, type Tokenizer } from "#utils/tokenize" /** * Options for `alignRow`. */ export interface AlignOptions { /** * Tokenizer to use. * * @defaultValue `whitespaceTokenizer()` */ tokenizer?: Tokenizer /** * Max Levenshtein edit distance to accept when a verbatim substring match fails. * * Set `0` to require verbatim matches only. * * Distance is computed against same-length windows in `raw`, so the threshold * scales naturally with the component value length. * * @defaultValue `2` */ maxEditDistance?: number /** * Case-insensitive comparison for substring search. * * The retained span in `raw` is the original case. * Only matching is case-insensitive. * * @defaultValue `true` */ caseInsensitive?: boolean } /** * Either a successful labeled row or a quarantined one. */ export type AlignmentResult = { kind: "labeled"; row: LabeledRow } | { kind: "quarantined"; row: QuarantinedRow } /** * One located char-offset label span over a row's `raw` ([start, end) in UTF-16 code units). The element type behind the parallel `span_starts[]`/`span_ends[]`/`span_tags[]` triple on `LabeledRow`. */ export interface ComponentSpan { tag: ComponentTag start: number end: number } /** * The char spans of a row's components in `raw`, sorted by start, or the quarantine * reason when a component cannot be placed. * * `raw` and the component values must already be NFC-normalized. * * {@linkcode alignRow} labels a row from these spans, and the WOF sampler keys a row's * structure cell by their order, so both read a component that occurs inside another * (a region whose name appears inside its locality's name) the same way. */ export function locateComponentSpans( raw: string, components: CanonicalRow["components"], opts: Pick = {} ): { spans: ComponentSpan[] } | { reason: string } { const maxEditDistance = opts.maxEditDistance ?? 2 const caseInsensitive = opts.caseInsensitive ?? true const spans: ComponentSpan[] = [] const claimed: Array<[number, number]> = [] const haystack = caseInsensitive ? raw.toLowerCase() : raw // Longest value first: a short component mustn't claim a word that a longer, // more specific component owns. // Emit order is unaffected, since spans are re-sorted by start below. const entries = (Object.entries(components) as Array<[ComponentTag, string | undefined]>).toSorted( (a, b) => (b[1]?.length ?? 0) - (a[1]?.length ?? 0) ) for (const [tag, value] of entries) { if (!value) continue const needle = caseInsensitive ? value.toLowerCase() : value // A raw rendered from its components writes each value in its own case at its own slot, // so a word-aligned occurrence in the value's own case is preferred over an earlier case-folded // one (`119 West UNION Street, WEST UNION, IL`: the locality is the second `WEST UNION`). const exact = caseInsensitive ? locateVerbatimBoundary(raw, value, claimed) : null const span = exact ?? locateSpan({ haystack, needle, raw, claimed, maxEditDistance }) if (!span) return { reason: `component-not-found:${tag}` } // An out-of-bounds offset can never be a valid char span, so quarantine the row // rather than crash assertSpanInvariants and take down a multi-hour build. if (span.start < 0 || span.end > raw.length || span.start >= span.end) { return { reason: `span-out-of-bounds:${tag}` } } spans.push({ tag, start: span.start, end: span.end }) claimed.push([span.start, span.end]) } spans.sort((a, b) => a.start - b.start) return { spans } } /** * Align a single row. */ /** * A copy of a row's components with each value in NFC, the form {@linkcode alignRow} writes to a labeled row. * * A caller that decides a row's split before aligning it reads these, * so the decision equals the one made on the aligned row. */ export function nfcComponents(components: CanonicalRow["components"]): CanonicalRow["components"] { const normalized = { ...components } for (const key of Object.keys(normalized)) { const value = normalized[key as keyof typeof normalized] if (typeof value === "string") { normalized[key as keyof typeof normalized] = value.normalize("NFC") } } return normalized } export function alignRow(row: CanonicalRow, opts: AlignOptions = {}): AlignmentResult { const tokenizer = opts.tokenizer ?? whitespaceTokenizer() const maxEditDistance = opts.maxEditDistance ?? 2 const caseInsensitive = opts.caseInsensitive ?? true if (!row.raw) { return { kind: "quarantined", row: { row, reason: "raw-empty" } } } const raw = row.raw.normalize("NFC") const components = nfcComponents(row.components) const located = locateComponentSpans(raw, components, { maxEditDistance, caseInsensitive }) if ("reason" in located) { return { kind: "quarantined", row: { row, reason: located.reason } } } const componentSpans = located.spans assertSpanInvariants(componentSpans, { ...row, raw }) const tokens = tokenizer.tokenize(raw) const labels = labelTokens(tokens, componentSpans) const labeled: LabeledRow = { ...row, raw, components, tokens: tokens.map((t) => t.text), labels, span_starts: componentSpans.map((s) => s.start), span_ends: componentSpans.map((s) => s.end), span_tags: componentSpans.map((s) => s.tag), } return { kind: "labeled", row: labeled } } /** * Enforce the span-triple invariants: in-bounds, sorted ascending by start, non-overlapping. * * For `alignRow`: `claimed`-span bookkeeping in `locateSpan` already makes overlap impossible * and the caller sorts, so a violation here is a bug in this file rather than bad source data. * Throw rather than quarantine, so the corruption cannot ride into a corpus. * * Any code that emits the triple without going through `alignRow` must pass its output through this. */ export function assertSpanInvariants( spans: readonly ComponentSpan[], row: Pick ): void { for (let i = 0; i < spans.length; i++) { const s = spans[i]! if (!(s.start >= 0 && s.start < s.end && s.end <= row.raw.length)) { throw new Error( `alignRow: span out of bounds (source=${row.source}, source_id=${row.source_id}): ` + `${s.tag}@[${s.start}, ${s.end}) over raw of length ${row.raw.length}` ) } if (i === 0) continue const prev = spans[i - 1]! if (s.start < prev.start) { throw new Error( `alignRow: spans not sorted (source=${row.source}, source_id=${row.source_id}): ` + `${prev.tag}@[${prev.start}, ${prev.end}) precedes ${s.tag}@[${s.start}, ${s.end})` ) } if (s.start < prev.end) { throw new Error( `alignRow: spans overlap (source=${row.source}, source_id=${row.source_id}): ` + `${prev.tag}@[${prev.start}, ${prev.end}) overlaps ${s.tag}@[${s.start}, ${s.end})` ) } } } /** * Locate `needle` in `haystack` (both already normalized for case if requested), * preferring verbatim substring match. * * Falls back to a fuzzy window scan when verbatim fails and `maxEditDistance > 0`. * Already-claimed spans are skipped so two components don't grab overlapping ranges. * * @returns The span in the original `raw` (not the lower-cased `haystack`). */ function locateSpan(args: { haystack: string needle: string raw: string claimed: Array<[number, number]> maxEditDistance: number }): { start: number; end: number } | null { const { haystack, needle, claimed, maxEditDistance } = args if (!needle) return null // Pass 1: verbatim substring. // Word-boundary-aligned matches are preferred over intra-word ones, so a short // value cannot claim the inside of an earlier word. // Intra-word matches stay allowed as the fallback because they're essential for affix // supervision (street_suffix "straße" inside "Hauptstraße" has no boundary-aligned occurrence). let intraWord: { start: number; end: number } | null = null let from = 0 while (true) { const idx = haystack.indexOf(needle, from) if (idx === -1) break const end = idx + needle.length if (!overlapsClaimed(idx, end, claimed)) { if (isBoundaryAligned(haystack, idx, end)) return { start: idx, end } intraWord ??= { start: idx, end } } from = idx + 1 } if (intraWord) return intraWord if (maxEditDistance <= 0) return null // Pass 2: fuzzy sliding-window. const len = needle.length for (let i = 0; i + len <= haystack.length; i++) { if (overlapsClaimed(i, i + len, claimed)) continue const window = haystack.slice(i, i + len) if (window === needle) return { start: i, end: i + len } const d = levenshteinDistance(window, needle) if (d <= maxEditDistance) return { start: i, end: i + len } } return null } /** * The first unclaimed, word-aligned occurrence of `needle` in `raw`, in `needle`'s own case. */ function locateVerbatimBoundary( raw: string, needle: string, claimed: Array<[number, number]> ): { start: number; end: number } | null { if (!needle) return null for (let idx = raw.indexOf(needle); idx !== -1; idx = raw.indexOf(needle, idx + 1)) { const end = idx + needle.length if (!overlapsClaimed(idx, end, claimed) && isBoundaryAligned(raw, idx, end)) return { start: idx, end } } return null } const WORD_CHAR = /[\p{L}\p{N}]/u /** * Both needle edges sit on word boundaries of the haystack (string edges count as boundaries). */ function isBoundaryAligned(haystack: string, start: number, end: number): boolean { const before = start === 0 || !WORD_CHAR.test(haystack[start - 1]!) const after = end === haystack.length || !WORD_CHAR.test(haystack[end]!) return before && after } function overlapsClaimed(start: number, end: number, claimed: Array<[number, number]>): boolean { for (const [a, b] of claimed) { if (start < b && a < end) return true } return false } /** * Assign BIO labels to tokens from component spans sorted by start offset. */ function labelTokens(tokens: readonly TextFragment[], spans: readonly ComponentSpan[]): readonly BIOLabel[] { const out: BIOLabel[] = [] const seenSpan = new Set() for (const token of tokens) { // A token inside one span takes that span's tag. // A token that overlaps exactly one span without lying inside it holds that component // plus text a layout glued to it, such as `HR-10000` around the postcode `10000`, // so it takes that span's tag too and the token labels agree with the span triple. // A token across two spans stays `O`. let index = spans.findIndex((s) => token.start >= s.start && token.end <= s.end) if (index < 0) { const overlapping = spans.flatMap((s, i) => (token.start < s.end && token.end > s.start ? [i] : [])) if (overlapping.length === 1) { index = overlapping[0]! } } if (index < 0) { out.push("O") continue } const tag = spans[index]!.tag out.push((seenSpan.has(index) ? `I-${tag}` : `B-${tag}`) as BIOLabel) seenSpan.add(index) } return out }