1 Commits

Author SHA1 Message Date
dd0ac92518 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>
2026-11-30 15:48:09 +00:00
4 changed files with 218 additions and 7 deletions

View File

@@ -14,18 +14,31 @@ nachverfolgten Änderungen, einschließlich gelöschter Texte und Feldcodes.
Kommentarverweise und Änderungsmarkierungen bleiben erhalten. Optionale
Microsoft-Kontoverknüpfungen in `word/people.xml` werden entfernt.
Die Erkennung bewertet jeden Absatz einzeln. Ein Name wird daher je nach Satz
erkannt oder nicht („Quastenberg prüft …“, aber nicht „bei Quastenberg
nachfragen“). Velum überträgt deshalb sicher erkannte Personennamen auf alle
weiteren Vorkommen in derselben Datei: vollständige Namen, deren Bestandteile
ab drei Zeichen und Namen nach einer Anrede wie `Frau` oder `Dr.`, auch mit
Genitiv-s. Diese Vorkommen erscheinen wie alle anderen in der Trefferprüfung und
lassen sich dort gemeinsam abwählen. Bleiben trotzdem Namen stehen, trage sie
als Projektbegriff ein, zum Beispiel `PERSON: Max Mustermann`.
Bei der Analyse und nach dem Bestätigen der Ausgabe kannst du Raycast
schließen. Öffne anschließend im selben Befehl denselben Projektordner, um
den Status oder die Trefferprüfung zu öffnen. Vor dem Anwenden prüft der
Hintergrundprozess den Datei-Hash.
Für die lokale DOCX-Verarbeitung muss `uv` installiert sein (zum Beispiel
`brew install uv`). Beim ersten Lauf verwendet es Python 3.11 und richtet
`lxml` aus seinem Paketcache ein. Das Velum-Backend muss den Segment-Endpunkt
bereitstellen. Beim Bauen der Erweiterung werden der Python-Codec und der
Hintergrundprozess mitgeliefert. Ist der Backend-Checkout an einem anderen
Ort, setze `VELUM_BACKEND_DIR` vor `npm run build` oder `npm run dev` auf
seinen `backend`-Ordner.
`brew install uv`). Beim ersten Lauf lädt es Python 3.11 und `lxml` 6.2.1 in
seinen Paketcache; dafür ist einmalig Internetzugang nötig. Dokumentinhalte
werden dabei nicht übertragen. Das Velum-Backend muss den Segment-Endpunkt
bereitstellen, also mindestens Stand `2517637` („support local DOCX segment
analysis“). Beim Bauen der Erweiterung werden der Python-Codec und der
Hintergrundprozess aus dem Backend-Checkout mitgeliefert. Der Checkout sollte
deshalb denselben Stand haben wie das produktive Backend. Ohne Angabe sucht
der Build unter `../../velum/backend`, relativ zu diesem Repository. Liegt der
Backend-Checkout an einem anderen Ort, setze `VELUM_BACKEND_DIR` vor
`npm run build` oder `npm run dev` auf seinen `backend`-Ordner.
`Projektdateien pseudonymisieren` übernimmt zuerst den geöffneten Finder-Ordner; bei Bedarf kann er im Formular erneut übernommen oder manuell gewählt werden. Im Formular werden die zu erkennenden Kategorien ausgewählt (Orte sind wegen häufiger Fehlalarme zunächst abgewählt). Danach analysiert Velum alle geeigneten Text-, DOCX-, XLSX-, PPTX- und PDF-Dateien sowie ihre Namen. Unterstriche zwischen Namensbestandteilen werden bei der Erkennung als Worttrenner behandelt; bekannte Platzhalter und wörtliche Codebegriffe bleiben erhalten. Auch Namen unveränderter Dateien werden in einem Folgelauf erneut geprüft. Ältere Word-Projektstände werden einmalig auf Kommentatoren geprüft, sofern `PERSON` ausgewählt ist. Kleine Textdateien und Namen werden in Paketen analysiert, um die Anzahl der API-Aufrufe zu verringern. Die Prüfung zeigt jede eindeutige Zuordnung einmal, nach Kategorie gruppiert, mit der Anzahl ihrer Vorkommen. Eine Zuordnung an- oder abzuwählen gilt für alle betroffenen Dateien; einzelne Vorkommen lassen sich bei Bedarf ansehen. Nach der Auswahl lassen sich erkannte Personen optional zusammenfassen, sodass ihre Erwähnungen denselben Platzhalter erhalten. `Pseudonymisierte Kopien erstellen` schreibt Dateien in den Raycast-Support-Bereich außerhalb des Projektordners. Alternativ ersetzt `Originaldateien ersetzen` die Dateien und gegebenenfalls ihre Namen vor Ort; zuvor legt Velum eine private Sicherung der Originale im Raycast-Support-Bereich an. PDF wird dabei als DOCX ausgegeben.

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 };
}

View File

@@ -0,0 +1,88 @@
import { expect, it } from "bun:test";
import { propagateDocxPersons } from "../src/lib/person-propagation";
import type { Hit } from "../src/lib/project-work";
import type { PlaceholderMapping } from "../src/types";
// Synthetic names only. The model recognizes them in the introduction, but
// not in the later paragraphs (observed with de_core_news_lg).
const segments = [
{ text: "Projektleitung: Frau Jorinde Quastenberg, Fachbereich Planung.", source: "Absatz", kind: "text" },
{ text: "Grüße Talvin", source: "Absatz", kind: "text" },
...Array.from({ length: 26 }, () => [
{ text: "bei Quastenberg nachfragen", source: "Absatz", kind: "text" },
{ text: "Feedback Jorinde Quastenberg: passt. 😀 Quastenberg", source: "Absatz", kind: "text" },
]).flat(),
{ text: "Quastenbergstraße und Talvin bleiben", source: "Absatz", kind: "text" },
{ text: "Jorinde Quastenberg", source: "Kommentar-Link", kind: "link" },
];
function hit(segment: number, start: number, original: string, placeholder: string, score = 0.85): Hit {
return { id: `a.docx:local-docx:${segment}:${start}:${start + original.length}`, file: "a.docx", source: "Absatz",
original, placeholder, type: "PERSON", score, context: "", start, end: start + original.length,
kind: "content", segment };
}
it("masks every occurrence of a recognized person name across DOCX segments", () => {
const mapping: PlaceholderMapping = {
PERSON_01: { original: "Jorinde Quastenberg", type: "PERSON" },
PERSON_02: { original: "Talvin", type: "PERSON" },
};
const detected = [hit(0, 21, "Jorinde Quastenberg", "PERSON_01"), hit(1, 6, "Talvin", "PERSON_02", 0.99)];
const result = propagateDocxPersons(segments, detected, mapping, "a.docx");
const masked = segments.map((segment, index) => {
const characters = Array.from(segment.text);
for (const found of result.hits.filter((entry) => entry.segment === index)) {
expect(characters.slice(found.start, found.end).join("")).toBe(found.original);
for (let position = found.start; position < found.end; position++) characters[position] = "#";
}
return characters.join("");
});
const remaining = masked.slice(0, -1).join("\n").match(/(?<![\p{L}])Quastenberg(?![\p{L}])/gu) ?? [];
expect(remaining).toHaveLength(0);
expect(result.hits).toHaveLength(2 + 26 * 3);
const surname = result.hits.find((entry) => entry.original === "Quastenberg")!;
expect(surname.placeholder).toBe("PERSON_03");
expect(result.mapping.PERSON_03).toEqual({ original: "Quastenberg", type: "PERSON" });
expect(result.hits.filter((entry) => entry.original === "Jorinde Quastenberg").every(
(entry) => entry.placeholder === "PERSON_01")).toBe(true);
// Unicode offsets count code points, like the Python codec.
expect(result.hits.find((entry) => entry.segment === 3 && entry.start > 30)!.start).toBe(39);
// No partial words, no lone first name without a full name, no link fields.
expect(masked[54]).toBe("Quastenbergstraße und Talvin bleiben");
expect(result.hits.some((entry) => entry.segment === 55)).toBe(false);
expect(mapping.PERSON_03).toBeUndefined();
});
it("does not seed propagation from weak or merged-away hits", () => {
const mapping: PlaceholderMapping = {
PERSON_04: { original: "Jorinde Quastenberg", type: "PERSON" },
PERSON_07: { original: "Quastenberg", type: "PERSON", merged_into: "PERSON_04" },
};
const weak = propagateDocxPersons(segments, [hit(0, 21, "Jorinde Quastenberg", "PERSON_04", 0.6)], mapping, "a.docx");
expect(weak.hits).toHaveLength(1);
const merged = propagateDocxPersons(segments, [hit(0, 21, "Jorinde Quastenberg", "PERSON_04")], mapping, "a.docx");
expect(merged.hits.find((entry) => entry.original === "Quastenberg")!.placeholder).toBe("PERSON_04");
expect(Object.keys(merged.mapping)).toEqual(["PERSON_04", "PERSON_07"]);
});
it("seeds from salutation hits without the salutation and keeps the genitive s", () => {
const texts = ["Projektleitung: Frau Jorinde Quastenberg, Planung.", "Dr. Ostermeier ist informiert.",
"Quastenbergs Bericht und Ostermeiers Notiz liegen vor.", "Frau und Herr bleiben Wörter.", "Ostermeierhof"];
const result = propagateDocxPersons(texts.map((text) => ({ text, source: "Absatz", kind: "text" })), [
hit(0, 16, "Frau Jorinde Quastenberg", "PERSON_01", 0.7),
hit(1, 0, "Dr. Ostermeier", "PERSON_02", 0.7),
], {
PERSON_01: { original: "Frau Jorinde Quastenberg", type: "PERSON" },
PERSON_02: { original: "Dr. Ostermeier", type: "PERSON" },
}, "a.docx");
const added = result.hits.filter((entry) => !["PERSON_01", "PERSON_02"].includes(entry.placeholder));
expect(added.map((entry) => [entry.segment, entry.original, texts[entry.segment!].slice(entry.start, entry.end)]))
.toEqual([[2, "Quastenberg", "Quastenberg"], [2, "Ostermeier", "Ostermeier"]]);
expect(result.hits.filter((entry) => entry.segment === 3 || entry.segment === 4)).toHaveLength(0);
expect(Object.values(result.mapping).map((entry) => entry.original)).toEqual([
"Frau Jorinde Quastenberg", "Dr. Ostermeier", "Quastenberg", "Ostermeier",
]);
});