249 lines
7.4 KiB
TypeScript
249 lines
7.4 KiB
TypeScript
import type {
|
|
EntityType,
|
|
PlaceholderMapping,
|
|
PseudonymizeResponse,
|
|
} from "../types";
|
|
import { makeTextBatches, spansBySegment } from "./project-review";
|
|
import type { TextBatch } from "./project-review";
|
|
|
|
type Analyze = (
|
|
text: string,
|
|
mapping: PlaceholderMapping,
|
|
entityTypes: EntityType[],
|
|
forceMasks: Record<string, string[]>,
|
|
) => Promise<PseudonymizeResponse>;
|
|
|
|
/** Retry a failing server batch in smaller groups, without losing file boundaries. */
|
|
export async function analyzeProjectBatch(
|
|
batch: TextBatch,
|
|
mapping: PlaceholderMapping,
|
|
entityTypes: EntityType[],
|
|
forceMasks: Record<string, string[]>,
|
|
analyze: Analyze,
|
|
phase: string,
|
|
labelForKey: (key: string) => string = (key) => key,
|
|
): Promise<{
|
|
mapping: PlaceholderMapping;
|
|
results: Array<{ batch: TextBatch; result: PseudonymizeResponse }>;
|
|
}> {
|
|
try {
|
|
const result = await analyze(batch.text, mapping, entityTypes, forceMasks);
|
|
return { mapping: result.mapping, results: [{ batch, result }] };
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
if (!/request failed: 5\d\d\b/i.test(message)) throw error;
|
|
if (batch.segments.length < 2) {
|
|
throw new Error(
|
|
`${phase}: ${labelForKey(batch.segments[0]?.key ?? "unbekannte Datei")}: ${message}`,
|
|
{ cause: error },
|
|
);
|
|
}
|
|
const middle = Math.floor(batch.segments.length / 2);
|
|
const halves = [
|
|
batch.segments.slice(0, middle),
|
|
batch.segments.slice(middle),
|
|
];
|
|
let current = mapping;
|
|
const results: Array<{ batch: TextBatch; result: PseudonymizeResponse }> =
|
|
[];
|
|
for (const segments of halves) {
|
|
const [part] = makeTextBatches(
|
|
segments.map(({ key, text }) => ({ key, text })),
|
|
Number.POSITIVE_INFINITY,
|
|
);
|
|
const analyzed = await analyzeProjectBatch(
|
|
part,
|
|
current,
|
|
entityTypes,
|
|
forceMasks,
|
|
analyze,
|
|
phase,
|
|
labelForKey,
|
|
);
|
|
current = analyzed.mapping;
|
|
results.push(...analyzed.results);
|
|
}
|
|
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 };
|
|
}
|