fix: analyze large project text files in bounded chunks

This commit is contained in:
muena
2026-10-19 09:43:36 +02:00
parent e783c67af0
commit 1442ed4740
3 changed files with 255 additions and 18 deletions

View File

@@ -3,7 +3,7 @@ import type {
PlaceholderMapping,
PseudonymizeResponse,
} from "../types";
import { makeTextBatches } from "./project-review";
import { makeTextBatches, spansBySegment } from "./project-review";
import type { TextBatch } from "./project-review";
type Analyze = (
@@ -21,6 +21,7 @@ export async function analyzeProjectBatch(
forceMasks: Record<string, string[]>,
analyze: Analyze,
phase: string,
labelForKey: (key: string) => string = (key) => key,
): Promise<{
mapping: PlaceholderMapping;
results: Array<{ batch: TextBatch; result: PseudonymizeResponse }>;
@@ -33,7 +34,7 @@ export async function analyzeProjectBatch(
if (!/request failed: 5\d\d\b/i.test(message)) throw error;
if (batch.segments.length < 2) {
throw new Error(
`${phase}: ${batch.segments[0]?.key ?? "unbekannte Datei"}: ${message}`,
`${phase}: ${labelForKey(batch.segments[0]?.key ?? "unbekannte Datei")}: ${message}`,
{ cause: error },
);
}
@@ -57,6 +58,7 @@ export async function analyzeProjectBatch(
forceMasks,
analyze,
phase,
labelForKey,
);
current = analyzed.mapping;
results.push(...analyzed.results);
@@ -64,3 +66,183 @@ export async function analyzeProjectBatch(
return { mapping: current, results };
}
}
type TextSpan = PseudonymizeResponse["spans"][number];
type TextChunk = {
key: string;
file: string;
index: number;
total: number;
text: string;
scanStart: number;
coreStart: number;
coreEnd: number;
};
export const TEXT_CORE_LENGTH = 10_000;
const TEXT_CONTEXT_OVERLAP = 384;
/** Split only at whitespace, retaining context on both sides of every boundary. */
export function splitTextForAnalysis(
text: string,
coreLength = TEXT_CORE_LENGTH,
overlap = TEXT_CONTEXT_OVERLAP,
): Array<{
text: string;
scanStart: number;
coreStart: number;
coreEnd: number;
}> {
if (coreLength < 2 || overlap < 0)
throw new Error("Ungültige Abschnittsgröße.");
const parts = [];
let coreStart = 0;
while (coreStart < text.length) {
let coreEnd = Math.min(text.length, coreStart + coreLength);
if (coreEnd < text.length) {
const minimum = coreStart + Math.floor(coreLength / 2);
let boundary = text.lastIndexOf("\n", coreEnd - 1);
if (boundary < minimum) {
boundary = -1;
for (let index = coreEnd - 1; index >= minimum; index--) {
if (/\s/u.test(text[index])) {
boundary = index;
break;
}
}
}
if (boundary < minimum) {
throw new Error(
"Textdatei enthält einen sehr langen Abschnitt ohne Trennstelle. Bitte die Datei aufteilen.",
);
}
coreEnd = boundary + 1;
}
let scanStart = Math.max(0, coreStart - overlap);
let scanEnd = Math.min(text.length, coreEnd + overlap);
if (scanStart > 0 && /[\uDC00-\uDFFF]/u.test(text[scanStart])) scanStart--;
if (scanEnd < text.length && /[\uD800-\uDBFF]/u.test(text[scanEnd - 1]))
scanEnd++;
parts.push({
text: text.slice(scanStart, scanEnd),
scanStart,
coreStart,
coreEnd,
});
coreStart = coreEnd;
}
return parts;
}
function utf16Positions(text: string): number[] {
const positions = [0];
let offset = 0;
for (const character of text) {
offset += character.length;
positions.push(offset);
}
return positions;
}
function reconcileSpans(spans: TextSpan[], file: string): TextSpan[] {
const sorted = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
const result: TextSpan[] = [];
for (const span of sorted) {
const last = result.at(-1);
if (!last || span.start >= last.end) {
result.push(span);
continue;
}
if (span.end <= last.end) continue;
throw new Error(
`Überlappende Treffer an einer Abschnittsgrenze: ${file}. Bitte Datei abschnittsweise prüfen.`,
);
}
return result;
}
/** Analyze arbitrarily large UTF-8 text files without sending a whole file to Velum. */
export async function analyzeProjectTexts(
files: Array<{ key: string; text: string }>,
mapping: PlaceholderMapping,
entityTypes: EntityType[],
forceMasks: Record<string, string[]>,
analyze: Analyze,
onProgress: (index: number, total: number) => void,
): Promise<{
mapping: PlaceholderMapping;
spansByFile: Map<string, TextSpan[]>;
}> {
const chunks: TextChunk[] = [];
const spansByFile = new Map(files.map(({ key }) => [key, [] as TextSpan[]]));
for (const file of files) {
let parts: ReturnType<typeof splitTextForAnalysis>;
try {
parts = splitTextForAnalysis(file.text);
} catch (error) {
throw new Error(`${file.key}: ${(error as Error).message}`, {
cause: error,
});
}
for (const [index, part] of parts.entries()) {
chunks.push({
...part,
key: String(chunks.length),
file: file.key,
index,
total: parts.length,
});
}
}
const byKey = new Map(chunks.map((chunk) => [chunk.key, chunk]));
const batches = makeTextBatches(
chunks.map(({ key, text }) => ({ key, text })),
);
let current = mapping;
for (const [index, batch] of batches.entries()) {
onProgress(index + 1, batches.length);
const analyzed = await analyzeProjectBatch(
batch,
current,
entityTypes,
forceMasks,
analyze,
"Textdateien analysieren",
(key) => {
const chunk = byKey.get(key);
return chunk
? `${chunk.file} (Abschnitt ${chunk.index + 1}/${chunk.total})`
: key;
},
);
current = analyzed.mapping;
for (const { batch: part, result } of analyzed.results) {
const bySegment = spansBySegment(part, result.spans);
for (const segment of part.segments) {
const chunk = byKey.get(segment.key)!;
const chunkSpans = bySegment.get(segment.key) ?? [];
if (!chunkSpans.length) continue;
const positions = utf16Positions(chunk.text);
for (const span of chunkSpans) {
if (
span.start < 0 ||
span.end >= positions.length ||
span.start >= span.end
) {
throw new Error(
`Ungültige Trefferposition der Velum-API: ${chunk.file}`,
);
}
const start = chunk.scanStart + positions[span.start];
const end = chunk.scanStart + positions[span.end];
if (start >= chunk.coreStart && start < chunk.coreEnd) {
spansByFile.get(chunk.file)!.push({ ...span, start, end });
}
}
}
}
}
for (const [file, spans] of spansByFile)
spansByFile.set(file, reconcileSpans(spans, file));
return { mapping: current, spansByFile };
}

View File

@@ -17,7 +17,7 @@ import {
canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, spansBySegment,
withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
} from "./lib/project-review";
import { analyzeProjectBatch } from "./lib/project-analysis";
import { analyzeProjectBatch, analyzeProjectTexts } from "./lib/project-analysis";
const run = promisify(execFile);
const MAX_REVIEW_HITS = 50000;
@@ -76,7 +76,7 @@ function isUnreadableDocument(error: unknown): boolean {
function contentHits(file: ProjectFile, spans: Array<{
start: number; end: number; type: string; score: number; placeholder: string; original: string;
}>, text: string): Hit[] {
return toUtf16Offsets(text, spans).map((span, index) => ({
return spans.map((span, index) => ({
...span, id: `${file.relPath}:content:${index}`, file: file.relPath,
source: file.relPath, kind: "content" as const,
context: text.slice(Math.max(0, span.start - 70), Math.min(text.length, span.end + 70)),
@@ -142,19 +142,13 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
hits.push(...draft.hits);
if (hits.length > MAX_REVIEW_HITS) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
};
const batches = makeTextBatches([...texts].map(([key, text]) => ({ key, text })));
for (const [index, batch] of batches.entries()) {
onProgress(`Textdateien analysieren: Paket ${index + 1}/${batches.length}`);
const analyzed = await analyzeProjectBatch(batch, mapping, entityTypes, masks, pseudonymize,
"Textdateien analysieren");
mapping = analyzed.mapping;
for (const { batch: part, result } of analyzed.results) {
const byFile = spansBySegment(part, result.spans);
for (const segment of part.segments) {
const draft = draftsByPath.get(segment.key)!;
addHits(draft, contentHits(draft.file, byFile.get(segment.key) ?? [], segment.text));
}
}
const analyzedTexts = await analyzeProjectTexts([...texts].map(([key, text]) => ({ key, text })),
mapping, entityTypes, masks, pseudonymize,
(index, total) => onProgress(`Textdateien analysieren: Paket ${index}/${total}`));
mapping = analyzedTexts.mapping;
for (const [path, spans] of analyzedTexts.spansByFile) {
const draft = draftsByPath.get(path)!;
addHits(draft, contentHits(draft.file, spans, texts.get(path)!));
}
const documents = drafts.filter((draft) => draft.file.kind === "document");
for (const [index, draft] of documents.entries()) {

View File

@@ -1,5 +1,9 @@
import { expect, it } from "bun:test";
import { analyzeProjectBatch } from "../src/lib/project-analysis";
import {
analyzeProjectBatch,
analyzeProjectTexts,
splitTextForAnalysis,
} from "../src/lib/project-analysis";
import { makeTextBatches, spansBySegment } from "../src/lib/project-review";
import type { PlaceholderMapping, PseudonymizeResponse } from "../src/types";
@@ -79,3 +83,60 @@ it("nennt nach der Eingrenzung die fehlerhafte Datei", async () => {
"Textdateien analysieren: b.md: Velum API request failed: 500",
);
});
it("analysiert eine große Textdatei abschnittsweise und ordnet Grenztreffer an der Originalposition zu", async () => {
const prefix = `😀${"x ".repeat(4999)}Max `;
const source = `${prefix}Mustermann ${"text ".repeat(3000)}`;
const requests: number[] = [];
const analyzed = await analyzeProjectTexts(
[{ key: "groß.txt", text: source }],
{},
["PERSON"],
{},
async (text, mapping) => {
requests.push(text.length);
const matches = [...text.matchAll(/Max Mustermann/g)].map((match) => {
const start = [...text.slice(0, match.index)].length;
return {
start,
end: start + 14,
type: "PERSON",
original: "Max Mustermann",
placeholder: "PERSON_01",
score: 1,
};
});
return {
pseudonymized_text: text,
selected_entity_types: ["PERSON"],
mapping: matches.length
? {
...mapping,
PERSON_01: { original: "Max Mustermann", type: "PERSON" },
}
: mapping,
entity_count: matches.length ? 1 : 0,
spans: matches,
};
},
() => undefined,
);
expect(requests.length).toBeGreaterThan(1);
expect(Math.max(...requests)).toBeLessThan(24_000);
expect(analyzed.spansByFile.get("groß.txt")).toEqual([
{
start: prefix.length - 4,
end: prefix.length + 10,
type: "PERSON",
original: "Max Mustermann",
placeholder: "PERSON_01",
score: 1,
},
]);
});
it("verweigert das stumme Zerschneiden eines überlangen Worts", () => {
expect(() => splitTextForAnalysis("x".repeat(100), 20, 5)).toThrow(
"ohne Trennstelle",
);
});