fix: propagate recognized person names across local DOCX segments

The local DOCX flow analyzes each paragraph separately, so the backend's
per-text person propagation never crosses paragraph boundaries. A name
recognized once ("Frau Jorinde Quastenberg") stayed in clear text wherever
the model missed it in context ("bei Quastenberg nachfragen").

After all segment batches of a file, add the remaining occurrences of
confidently recognized full names, their parts (3+ characters) and names
after a salutation (including a genitive s) as reviewable PERSON hits.
Whitelist, placeholder filtering and the hit review still apply.

Synthetic reproduction with de_core_news_lg: 59 unmasked name occurrences
before, 0 after; comments, insertions, deletions and anchors verified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 15:48:09 +00:00
parent d2ed7130f0
commit dd0ac92518
4 changed files with 218 additions and 7 deletions

View File

@@ -8,6 +8,7 @@ import { analyzeDocxSegments } from "../velum";
import type { EntityType, PlaceholderMapping } from "../types";
import { checkedImageReport } from "./image-policy";
import type { ImagePolicy } from "./image-policy";
import { propagateDocxPersons } from "./person-propagation";
import { MAX_BATCH_CODEPOINTS } from "./project-review";
import { projectTextAnalyzer } from "./project-text-mapping";
import type { Hit } from "./project-work";
@@ -108,7 +109,9 @@ export async function inspectDocx(
size += segment.text.length + 2;
}
await flush();
return { hits, mapping: current, segmentCount: segments.length };
const propagated = types.includes("PERSON") ? propagateDocxPersons(segments, hits, current, relative)
: { hits, mapping: current };
return { ...propagated, segmentCount: segments.length };
}
export async function writeDocx(

View File

@@ -0,0 +1,107 @@
import type { PlaceholderMapping } from "../types";
import type { Hit } from "./project-work";
// Seeds follow the backend's per-text person propagation: only confident
// PERSON hits that look like capitalized names. Unlike the backend, the parts of
// a detected full name are propagated even if the model never recognized them
// alone, because lone surnames are what it misses most in running text.
// Common words stay out of reach unless the model put them into a name.
const NAME = /^[A-ZÄÖÜ][A-Za-zÄÖÜäöüß’'-]+(?:[ \t]+[A-ZÄÖÜ][A-Za-zÄÖÜäöüß’'-]+)*$/u;
const MIN_SEED_SCORE = 0.85;
// The backend's salutation recognizer ("Frau Müller", "Dr. Schmidt") scores
// 0.7, but its structure reliably marks the following words as a name.
const SALUTATION = /^(?:Frau|Herr|Dr\.|Prof\.|Mag\.|Ing\.|DI)\s+/u;
const MIN_SALUTATION_SCORE = 0.7;
function escape(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Velum analyzes every DOCX segment separately, so a name recognized in one
* paragraph is not propagated to paragraphs where the model misses it (for
* example "bei Quastenberg nachfragen"). Add those occurrences as reviewable
* hits for the whole file.
*/
export function propagateDocxPersons(
segments: Array<{ text: string; source: string; kind: string }>, hits: Hit[], mapping: PlaceholderMapping,
relative: string,
): { hits: Hit[]; mapping: PlaceholderMapping } {
const candidates = new Map<string, number>();
const add = (name: string, score: number) => candidates.set(name, Math.max(candidates.get(name) ?? 0, score));
for (const hit of hits) {
if (hit.kind !== "content" || hit.type !== "PERSON") continue;
const salutation = hit.original.trim().match(SALUTATION);
const name = hit.original.trim().slice(salutation?.[0].length ?? 0);
if (hit.score < (salutation ? MIN_SALUTATION_SCORE : MIN_SEED_SCORE) || !NAME.test(name)) continue;
const parts = name.split(/[ \t]+/);
if (parts.length < 2 && !salutation) continue;
add(name, hit.score);
for (const part of parts) if (parts.length > 1 && Array.from(part).length >= 3) add(part, hit.score);
}
if (!candidates.size) return { hits, mapping };
const next: PlaceholderMapping = { ...mapping };
const identities = new Map<string, string>();
let counter = 0;
for (const [key, entry] of Object.entries(next)) {
if (entry.type !== "PERSON") continue;
identities.set(entry.original.trim().toLowerCase(), key);
counter = Math.max(counter, Number(key.match(/_(\d+)$/)?.[1] ?? 0));
}
const canonical = (key: string): string => {
const seen = new Set<string>();
while (next[key]?.merged_into && !seen.has(key)) {
seen.add(key);
key = next[key].merged_into!;
}
return key;
};
const placeholderFor = (name: string): string => {
let key = identities.get(name.toLowerCase());
if (!key) {
key = `PERSON_${String(++counter).padStart(2, "0")}`;
if (next[key]) throw new Error("Doppelte Platzhalternummer in der Projektzuordnung.");
next[key] = { original: name, type: "PERSON" };
identities.set(name.toLowerCase(), key);
}
return canonical(key);
};
const occupied = new Map<number, Array<[number, number]>>();
for (const hit of hits) {
if (hit.segment === undefined) continue;
const ranges = occupied.get(hit.segment) ?? [];
ranges.push([hit.start, hit.end]);
occupied.set(hit.segment, ranges);
}
// Longest names first, so a full name is masked as a unit before its parts.
// A German genitive "s" stays outside the masked span.
const patterns = [...candidates.keys()].sort((a, b) => b.length - a.length || a.localeCompare(b))
.map((name) => [name, new RegExp(`(?<![\\p{L}\\p{N}_])${escape(name)}(?=s?(?![\\p{L}\\p{N}_]))`, "gu")] as const);
const added: Hit[] = [];
for (const [index, segment] of segments.entries()) {
if (segment.kind !== "text") continue;
const ranges = occupied.get(index) ?? [];
for (const [name, pattern] of patterns) {
for (const match of segment.text.matchAll(pattern)) {
// Hit offsets count code points, matching the Python codec.
const start = Array.from(segment.text.slice(0, match.index)).length;
const end = start + Array.from(name).length;
if (ranges.some(([s, e]) => start < e && s < end)) continue;
ranges.push([start, end]);
const characters = Array.from(segment.text);
added.push({
id: `${relative}:local-docx:${index}:${start}:${end}`, file: relative, source: segment.source,
original: name, placeholder: placeholderFor(name), type: "PERSON", score: candidates.get(name)!,
context: characters.slice(Math.max(0, start - 60), end + 60).join(""),
start, end, kind: "content", segment: index,
});
}
}
occupied.set(index, ranges);
}
if (!added.length) return { hits, mapping };
const merged = [...hits, ...added].sort((a, b) => (a.segment ?? 0) - (b.segment ?? 0) || a.start - b.start);
return { hits: merged, mapping: next };
}