fix: stream large project texts and scope API capabilities
Analyze UTF-8 text files as bounded batches of complete lines and reassemble only approved spans without loading entire files. Preserve line endings, BOM, Unicode offsets and source-change checks. Scope capability checks to selected file types, report missing features and HTTP failures, and retain the required Office image-policy handling. Cover large files, chunk boundaries, mappings and failure cleanup with regression tests.
This commit is contained in:
57
src/lib/image-policy.ts
Normal file
57
src/lib/image-policy.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
export type ImagePolicy = "placeholder" | "remove" | "keep";
|
||||
export type DocumentImageReport = {
|
||||
image_policy: ImagePolicy;
|
||||
images_replaced: number;
|
||||
images_removed: number;
|
||||
media_parts_removed: number;
|
||||
warnings: string[];
|
||||
};
|
||||
export const DEFAULT_IMAGE_POLICY: ImagePolicy = "placeholder";
|
||||
export const IMAGE_POLICY_LABELS: Record<ImagePolicy, string> = {
|
||||
placeholder: "Datenschutz-Platzhalter (Standard)",
|
||||
remove: "Bilder vollständig entfernen",
|
||||
keep: "Bilder behalten — Datenschutzrisiko",
|
||||
};
|
||||
export const KEEP_IMAGE_WARNING = "Achtung: Bilder können sensible Informationen enthalten. Sie werden unverändert übernommen und nicht auf personenbezogene Daten geprüft.";
|
||||
|
||||
export function checkedImagePolicy(policy: string): ImagePolicy {
|
||||
if (policy !== "placeholder" && policy !== "remove" && policy !== "keep") {
|
||||
throw new Error("Ungültige Bildbehandlung.");
|
||||
}
|
||||
return policy;
|
||||
}
|
||||
|
||||
export function sameImagePolicyCoverage(previous: { imagePolicy?: ImagePolicy } | undefined, policy: ImagePolicy): boolean {
|
||||
return previous?.imagePolicy === policy;
|
||||
}
|
||||
|
||||
export function checkedImageReport(value: unknown, policy: ImagePolicy): DocumentImageReport {
|
||||
const report = value as Partial<DocumentImageReport> | null;
|
||||
if (!report || report.image_policy !== policy) {
|
||||
throw new Error("Die Velum-API bestätigt die gewählte Bildbehandlung nicht. Bitte das Backend aktualisieren.");
|
||||
}
|
||||
for (const count of [report.images_replaced, report.images_removed, report.media_parts_removed]) {
|
||||
if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) {
|
||||
throw new Error("Die Velum-API liefert keine gültigen Bildzähler.");
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(report.warnings) || report.warnings.some((warning) => typeof warning !== "string")) {
|
||||
throw new Error("Die Velum-API liefert keine gültigen Bildwarnungen.");
|
||||
}
|
||||
return {
|
||||
image_policy: policy,
|
||||
images_replaced: report.images_replaced!, images_removed: report.images_removed!,
|
||||
media_parts_removed: report.media_parts_removed!,
|
||||
warnings: policy === "keep" && !report.warnings.includes(KEEP_IMAGE_WARNING) ? [KEEP_IMAGE_WARNING, ...report.warnings] : [...report.warnings],
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeImages(files: readonly { imageReport?: DocumentImageReport }[]): {
|
||||
replaced: number; removed: number; warnings: string[];
|
||||
} {
|
||||
return {
|
||||
replaced: files.reduce((total, file) => total + (file.imageReport?.images_replaced ?? 0), 0),
|
||||
removed: files.reduce((total, file) => total + (file.imageReport?.images_removed ?? 0), 0),
|
||||
warnings: [...new Set(files.flatMap((file) => file.imageReport?.warnings ?? []))],
|
||||
};
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { fileTextParts } from "./project-text-stream";
|
||||
import type { TextAnalysisPart } from "./project-text-stream";
|
||||
import type {
|
||||
EntityType,
|
||||
PlaceholderMapping,
|
||||
PseudonymizeResponse,
|
||||
} from "../types";
|
||||
import { makeTextBatches, spansBySegment } from "./project-review";
|
||||
import { makeTextBatches, MAX_BATCH_CODEPOINTS, spansBySegment } from "./project-review";
|
||||
import type { TextBatch } from "./project-review";
|
||||
|
||||
type Analyze = (
|
||||
@@ -31,7 +33,9 @@ export async function analyzeProjectBatch(
|
||||
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 (!/request failed: (?:413|5\d\d)\b/i.test(message)) {
|
||||
throw new Error(`${phase}: ${labelForKey(batch.segments[0]?.key ?? "unbekannte Datei")}: ${message}`, { cause: error });
|
||||
}
|
||||
if (batch.segments.length < 2) {
|
||||
throw new Error(
|
||||
`${phase}: ${labelForKey(batch.segments[0]?.key ?? "unbekannte Datei")}: ${message}`,
|
||||
@@ -83,11 +87,11 @@ 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(
|
||||
function* iterateTextForAnalysis(
|
||||
text: string,
|
||||
coreLength = TEXT_CORE_LENGTH,
|
||||
overlap = TEXT_CONTEXT_OVERLAP,
|
||||
): Array<{
|
||||
): Generator<{
|
||||
text: string;
|
||||
scanStart: number;
|
||||
coreStart: number;
|
||||
@@ -95,7 +99,6 @@ export function splitTextForAnalysis(
|
||||
}> {
|
||||
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);
|
||||
@@ -123,15 +126,18 @@ export function splitTextForAnalysis(
|
||||
if (scanStart > 0 && /[\uDC00-\uDFFF]/u.test(text[scanStart])) scanStart--;
|
||||
if (scanEnd < text.length && /[\uD800-\uDBFF]/u.test(text[scanEnd - 1]))
|
||||
scanEnd++;
|
||||
parts.push({
|
||||
yield {
|
||||
text: text.slice(scanStart, scanEnd),
|
||||
scanStart,
|
||||
coreStart,
|
||||
coreEnd,
|
||||
});
|
||||
};
|
||||
coreStart = coreEnd;
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
export function splitTextForAnalysis(text: string, coreLength = TEXT_CORE_LENGTH, overlap = TEXT_CONTEXT_OVERLAP) {
|
||||
return [...iterateTextForAnalysis(text, coreLength, overlap)];
|
||||
}
|
||||
|
||||
function utf16Positions(text: string): number[] {
|
||||
@@ -144,9 +150,9 @@ function utf16Positions(text: string): number[] {
|
||||
return positions;
|
||||
}
|
||||
|
||||
function reconcileSpans(spans: TextSpan[], file: string): TextSpan[] {
|
||||
function reconcileSpans<T extends TextSpan>(spans: T[], file: string): T[] {
|
||||
const sorted = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
|
||||
const result: TextSpan[] = [];
|
||||
const result: T[] = [];
|
||||
for (const span of sorted) {
|
||||
const last = result.at(-1);
|
||||
if (!last || span.start >= last.end) {
|
||||
@@ -173,34 +179,39 @@ export async function analyzeProjectTexts(
|
||||
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,
|
||||
});
|
||||
// Only the current request and its offset metadata stay alive. Do not build
|
||||
// arrays of every chunk and every concatenated request for a large file.
|
||||
function* batches(): Generator<{ batch: TextBatch; byKey: Map<string, TextChunk> }> {
|
||||
let chunks: TextChunk[] = [];
|
||||
let length = 0;
|
||||
for (const file of files) {
|
||||
let total = 0;
|
||||
try {
|
||||
for (const part of iterateTextForAnalysis(file.text)) if (part.coreEnd > part.coreStart) total++;
|
||||
let index = 0;
|
||||
for (const part of iterateTextForAnalysis(file.text)) {
|
||||
if (chunks.length && length + 4 + part.text.length > MAX_BATCH_CODEPOINTS) {
|
||||
yield { batch: makeTextBatches(chunks)[0], byKey: new Map(chunks.map((chunk) => [chunk.key, chunk])) };
|
||||
chunks = [];
|
||||
length = 0;
|
||||
}
|
||||
length += (chunks.length ? 4 : 0) + part.text.length;
|
||||
chunks.push({ ...part, key: String(chunks.length), file: file.key, index: index++, total });
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`${file.key}: ${(error as Error).message}`, { cause: error });
|
||||
}
|
||||
}
|
||||
if (chunks.length) yield { batch: makeTextBatches(chunks)[0], byKey: new Map(chunks.map((chunk) => [chunk.key, chunk])) };
|
||||
}
|
||||
const byKey = new Map(chunks.map((chunk) => [chunk.key, chunk]));
|
||||
const batches = makeTextBatches(
|
||||
chunks.map(({ key, text }) => ({ key, text })),
|
||||
);
|
||||
let total = 0;
|
||||
for (const entry of batches()) if (entry.batch.segments.length) total++;
|
||||
let current = mapping;
|
||||
for (const [index, batch] of batches.entries()) {
|
||||
onProgress(index + 1, batches.length);
|
||||
let hitCount = 0;
|
||||
let index = 0;
|
||||
for (const { batch, byKey } of batches()) {
|
||||
onProgress(++index, total);
|
||||
const analyzed = await analyzeProjectBatch(
|
||||
batch,
|
||||
current,
|
||||
@@ -237,6 +248,7 @@ export async function analyzeProjectTexts(
|
||||
const end = chunk.scanStart + positions[span.end];
|
||||
if (start >= chunk.coreStart && start < chunk.coreEnd) {
|
||||
spansByFile.get(chunk.file)!.push({ ...span, start, end });
|
||||
if (++hitCount > 50_000) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -246,3 +258,62 @@ export async function analyzeProjectTexts(
|
||||
spansByFile.set(file, reconcileSpans(spans, file));
|
||||
return { mapping: current, spansByFile };
|
||||
}
|
||||
|
||||
export type StreamTextSpan = TextSpan & { context: string };
|
||||
|
||||
/** Analyze complete-line parts lazily, sharing small requests across file boundaries. */
|
||||
export async function analyzeProjectTextFiles(
|
||||
files: Array<{ key: string; path: string }>, mapping: PlaceholderMapping,
|
||||
entityTypes: EntityType[], forceMasks: Record<string, string[]>, analyze: Analyze,
|
||||
onProgress: (file: string, batch: number) => void,
|
||||
): Promise<{ mapping: PlaceholderMapping; spansByFile: Map<string, StreamTextSpan[]> }> {
|
||||
const spansByFile = new Map(files.map((file) => [file.key, [] as StreamTextSpan[]]));
|
||||
type Part = TextAnalysisPart & { key: string; file: string };
|
||||
let parts: Part[] = [];
|
||||
let size = 0;
|
||||
let current = mapping;
|
||||
let batchIndex = 0;
|
||||
let hits = 0;
|
||||
const flush = async () => {
|
||||
if (!parts.length) return;
|
||||
const batch = makeTextBatches(parts)[0];
|
||||
const byKey = new Map(parts.map((part) => [part.key, part]));
|
||||
onProgress(parts[0].file, ++batchIndex);
|
||||
const analyzed = await analyzeProjectBatch(batch, current, entityTypes, forceMasks, analyze,
|
||||
"Textdateien analysieren", (key) => byKey.get(key)?.file ?? key);
|
||||
current = analyzed.mapping;
|
||||
for (const { batch: subBatch, result } of analyzed.results) {
|
||||
for (const [key, spans] of spansBySegment(subBatch, result.spans)) {
|
||||
const part = byKey.get(key)!;
|
||||
const positions = utf16Positions(part.text);
|
||||
for (const span of spans) {
|
||||
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0
|
||||
|| span.start >= span.end || span.end >= positions.length) throw new Error(`Ungültige Trefferposition der Velum-API: ${part.file}`);
|
||||
const start = part.scanStart + positions[span.start];
|
||||
const end = part.scanStart + positions[span.end];
|
||||
if (start < part.coreStart || start >= part.coreEnd) continue;
|
||||
// Copy the short snippet, allowing the request's source string to be freed.
|
||||
const context = Buffer.from(part.text.slice(Math.max(0, positions[span.start] - 70), positions[span.end] + 70), "utf8").toString("utf8");
|
||||
spansByFile.get(part.file)!.push({ ...span, start, end, context });
|
||||
if (++hits > 50_000) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
|
||||
}
|
||||
}
|
||||
}
|
||||
parts = [];
|
||||
size = 0;
|
||||
};
|
||||
for (const file of files) {
|
||||
try {
|
||||
for await (const part of fileTextParts(file.path)) {
|
||||
if (parts.length && size + 4 + part.text.length > MAX_BATCH_CODEPOINTS) await flush();
|
||||
size += (parts.length ? 4 : 0) + part.text.length;
|
||||
parts.push({ ...part, file: file.key, key: String(parts.length) });
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`${file.key}: ${(error as Error).message}`, { cause: error });
|
||||
}
|
||||
}
|
||||
await flush();
|
||||
for (const [file, spans] of spansByFile) spansByFile.set(file, reconcileSpans(spans, file));
|
||||
return { mapping: current, spansByFile };
|
||||
}
|
||||
|
||||
38
src/lib/project-capabilities.ts
Normal file
38
src/lib/project-capabilities.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
/** Requirements follow the files that will actually use the API. */
|
||||
export function requiredProjectCapabilities(documents: boolean): string[] {
|
||||
return ["request_force_masks", ...(documents ? [
|
||||
"document_hit_review", "document_review_mapping", "document_restoration",
|
||||
"comment_author_review", "revision_author_review", "document_image_policy",
|
||||
] : [])];
|
||||
}
|
||||
|
||||
export async function checkProjectCapabilities(
|
||||
url: string, documents: boolean,
|
||||
fetcher: (url: string, init: RequestInit) => Promise<Response>,
|
||||
): Promise<void> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetcher(url, { signal: AbortSignal.timeout(15_000) });
|
||||
} catch (error) {
|
||||
const timeout = error instanceof Error && /timeout|abort/i.test(error.name);
|
||||
throw new Error(`Velum: ${timeout ? "Zeitlimit bei der Prüfung der Projektfähigkeiten" : "Projekt-API nicht erreichbar"}: ${url}.`, { cause: error });
|
||||
}
|
||||
if (response.status === 404 || response.status === 405) {
|
||||
throw new Error(`Velum: Projekt-API-Endpunkt fehlt (HTTP ${response.status}): ${url}. Backend aktualisieren oder Basis-URL prüfen.`);
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(`Velum: Projektfähigkeiten nicht abrufbar (HTTP ${response.status}): ${url}. Anmeldung, Proxy und Backend prüfen.`);
|
||||
}
|
||||
if (!(response.headers.get("content-type") ?? "").includes("application/json")) {
|
||||
throw new Error(`Velum: Keine JSON-Antwort für ${url}. Anmeldung oder API-Weiterleitung prüfen.`);
|
||||
}
|
||||
const capabilities: unknown = await response.json();
|
||||
if (!capabilities || typeof capabilities !== "object" || Array.isArray(capabilities)) {
|
||||
throw new Error(`Velum: Ungültige Projektfähigkeiten von ${url}.`);
|
||||
}
|
||||
const missing = requiredProjectCapabilities(documents)
|
||||
.filter((key) => (capabilities as Record<string, unknown>)[key] !== true);
|
||||
if (missing.length) {
|
||||
throw new Error(`Velum: Backend unterstützt die ausgewählten ${documents ? "Office-/PDF-Dateien" : "Textdateien"} noch nicht vollständig. Fehlende API-Fähigkeiten: ${missing.join(", ")}. API: ${url}. Backend aktualisieren.`);
|
||||
}
|
||||
}
|
||||
157
src/lib/project-text-stream.ts
Normal file
157
src/lib/project-text-stream.ts
Normal file
@@ -0,0 +1,157 @@
|
||||
import { createReadStream, promises as fs } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
export const TEXT_CORE_LENGTH = 10_000;
|
||||
export const MAX_TEXT_LINE_LENGTH = 20_000;
|
||||
const OVERLAP = 384;
|
||||
|
||||
export async function hashProjectFile(path: string): Promise<string> {
|
||||
const hash = createHash("sha256");
|
||||
for await (const data of createReadStream(path)) hash.update(data);
|
||||
return hash.digest("hex");
|
||||
}
|
||||
|
||||
/** Preserve BOM, CRLF and Unicode; incomplete UTF-8 sequences carry into the next read. */
|
||||
export async function* decodedText(path: string, hash?: ReturnType<typeof createHash>, highWaterMark = 64 * 1024): AsyncGenerator<string> {
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
||||
for await (const data of createReadStream(path, { highWaterMark })) {
|
||||
const buffer = data as Buffer;
|
||||
hash?.update(buffer);
|
||||
if (buffer.includes(0)) throw new Error("Binärdatei");
|
||||
let text: string;
|
||||
try { text = decoder.decode(buffer, { stream: true }); }
|
||||
catch { throw new Error("Keine gültige UTF-8-Textdatei"); }
|
||||
if (text) yield text;
|
||||
}
|
||||
try {
|
||||
const tail = decoder.decode();
|
||||
if (tail) yield tail;
|
||||
} catch { throw new Error("Keine gültige UTF-8-Textdatei"); }
|
||||
}
|
||||
|
||||
export async function inspectTextFile(path: string): Promise<string> {
|
||||
const hash = createHash("sha256");
|
||||
for await (const text of decodedText(path, hash)) { if (!text.length) continue; }
|
||||
return hash.digest("hex");
|
||||
}
|
||||
|
||||
/** Yield complete lines, retaining their exact delimiters and the final unterminated line. */
|
||||
export async function* textLines(chunks: AsyncIterable<string>, maxLineLength = MAX_TEXT_LINE_LENGTH): AsyncGenerator<string> {
|
||||
let pending = "";
|
||||
let line = 1;
|
||||
const check = (value: string) => {
|
||||
if (value.length > maxLineLength) throw new Error(`Zeile ${line} ist länger als ${maxLineLength} Zeichen. Bitte diese Zeile an Wortgrenzen aufteilen; Velum zerschneidet keine Wörter.`);
|
||||
};
|
||||
for await (const chunk of chunks) {
|
||||
pending += chunk;
|
||||
let start = 0;
|
||||
const endings = /\r\n|\r|\n/g;
|
||||
for (let match = endings.exec(pending); match; match = endings.exec(pending)) {
|
||||
if (match[0] === "\r" && match.index === pending.length - 1) break;
|
||||
const end = match.index + match[0].length;
|
||||
const value = pending.slice(start, end);
|
||||
check(value);
|
||||
yield value;
|
||||
line++;
|
||||
start = end;
|
||||
}
|
||||
pending = pending.slice(start);
|
||||
check(pending);
|
||||
}
|
||||
if (pending) { check(pending); yield pending; }
|
||||
}
|
||||
|
||||
async function* lineCores(path: string): AsyncGenerator<string> {
|
||||
let core = "";
|
||||
for await (const line of textLines(decodedText(path))) {
|
||||
if (core && core.length + line.length > TEXT_CORE_LENGTH) { yield core; core = ""; }
|
||||
core += line;
|
||||
if (core.length >= TEXT_CORE_LENGTH) { yield core; core = ""; }
|
||||
}
|
||||
if (core) yield core;
|
||||
}
|
||||
|
||||
function leftContext(text: string): string {
|
||||
if (text.length <= OVERLAP) return text;
|
||||
// Start at a complete token; the core itself always contains complete lines.
|
||||
const tail = text.slice(-OVERLAP);
|
||||
const boundary = tail.search(/\s/u);
|
||||
return boundary < 0 ? "" : tail.slice(boundary + 1);
|
||||
}
|
||||
function rightContext(text: string): string {
|
||||
if (text.length <= OVERLAP) return text;
|
||||
const head = text.slice(0, OVERLAP);
|
||||
for (let i = head.length - 1; i >= 0; i--) if (/\s/u.test(head[i])) return head.slice(0, i + 1);
|
||||
return "";
|
||||
}
|
||||
|
||||
export type TextAnalysisPart = { text: string; scanStart: number; coreStart: number; coreEnd: number };
|
||||
|
||||
/** One previous, current and next core at most; no array of the entire source. */
|
||||
export async function* fileTextParts(path: string): AsyncGenerator<TextAnalysisPart> {
|
||||
const cores = lineCores(path)[Symbol.asyncIterator]();
|
||||
let current = await cores.next();
|
||||
let previous = "";
|
||||
let offset = 0;
|
||||
try {
|
||||
while (!current.done) {
|
||||
const next = await cores.next();
|
||||
const left = leftContext(previous);
|
||||
const right = rightContext(next.done ? "" : next.value);
|
||||
yield { text: left + current.value + right, scanStart: offset - left.length,
|
||||
coreStart: offset, coreEnd: offset + current.value.length };
|
||||
offset += current.value.length;
|
||||
previous = current.value;
|
||||
current = next;
|
||||
}
|
||||
} finally { await cores.return?.(undefined); }
|
||||
}
|
||||
|
||||
type ReplacementSpan = { start: number; end: number; placeholder: string; id: string };
|
||||
|
||||
/** Reassemble the original stream, substituting only approved original-coordinate spans. */
|
||||
export async function writeReplacedTextFile(
|
||||
source: string, target: string, spans: ReplacementSpan[], accepted: Set<string>, expectedHash: string,
|
||||
): Promise<string> {
|
||||
const selected = spans.filter((span) => accepted.has(span.id)).sort((a, b) => a.start - b.start);
|
||||
for (let index = 0; index < selected.length; index++) {
|
||||
const span = selected[index];
|
||||
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.start >= span.end
|
||||
|| (index && span.start < selected[index - 1].end)) throw new Error("Ungültige oder überlappende Trefferposition.");
|
||||
}
|
||||
const inputHash = createHash("sha256");
|
||||
const outputHash = createHash("sha256");
|
||||
const output = await fs.open(target, "wx", 0o600);
|
||||
const write = async (text: string) => {
|
||||
const bytes = Buffer.from(text, "utf8");
|
||||
outputHash.update(bytes);
|
||||
await output.writeFile(bytes);
|
||||
};
|
||||
let offset = 0;
|
||||
let pending = "";
|
||||
let index = 0;
|
||||
let complete = false;
|
||||
try {
|
||||
for await (const chunk of decodedText(source, inputHash)) {
|
||||
pending += chunk;
|
||||
let consumed = 0;
|
||||
while (index < selected.length && selected[index].end <= offset + pending.length) {
|
||||
const span = selected[index++];
|
||||
await write(pending.slice(consumed, span.start - offset));
|
||||
await write(span.placeholder);
|
||||
consumed = span.end - offset;
|
||||
}
|
||||
const flush = index < selected.length ? Math.min(pending.length, selected[index].start - offset) : pending.length;
|
||||
await write(pending.slice(consumed, flush));
|
||||
pending = pending.slice(flush);
|
||||
offset += flush;
|
||||
}
|
||||
if (index !== selected.length || pending) throw new Error("Trefferposition liegt außerhalb der Quelldatei.");
|
||||
if (inputHash.digest("hex") !== expectedHash) throw new Error("Datei wurde seit der Vorschau geändert.");
|
||||
complete = true;
|
||||
return outputHash.digest("hex");
|
||||
} finally {
|
||||
await output.close();
|
||||
if (!complete) await fs.rm(target, { force: true });
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { hashProjectFile, inspectTextFile } from "./project-text-stream";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { constants as fsConstants, promises as fs } from "node:fs";
|
||||
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
||||
import { environment } from "@raycast/api";
|
||||
import type { EntityType, MappingEntry, PlaceholderMapping } from "../types";
|
||||
import { whitelistKey } from "./project-whitelist";
|
||||
import type { DocumentImageReport, ImagePolicy } from "./image-policy";
|
||||
import type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||
import { restoreOriginalCase } from "./restore-case";
|
||||
import { mappingForRestoration } from "./mapping-groups";
|
||||
@@ -14,7 +16,7 @@ export type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||
export type ProjectRule = { type: "BEGRIFF" | "PERSON" | "ORG" | "ORT" | "FIRMA" | "KUNDE"; value: string };
|
||||
export type ProjectFile = { relPath: string; absPath: string; kind: "text" | "document"; size: number };
|
||||
export type SkippedProjectFile = { path: string; reason: string };
|
||||
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"] };
|
||||
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"]; imageReport?: DocumentImageReport };
|
||||
export type ProjectRun = {
|
||||
version: 2;
|
||||
origin?: "direct" | "imported";
|
||||
@@ -25,6 +27,8 @@ export type ProjectRun = {
|
||||
mapping: PlaceholderMapping;
|
||||
/** Categories actually used to analyze the files in this snapshot. */
|
||||
entityTypes?: EntityType[];
|
||||
/** Explicit image handling applied to documents in this snapshot. Unknown means reprocess. */
|
||||
imagePolicy?: ImagePolicy;
|
||||
/** Hash of each live project file and its immutable output in this run. */
|
||||
sourceState?: Record<string, { hash: string; output: string }>;
|
||||
/** Generic replacement mode for placeholders embedded in code identifiers. */
|
||||
@@ -231,7 +235,7 @@ export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024,
|
||||
export async function scanProjectFiles(root: string, maxSize?: number,
|
||||
validateText = true): Promise<{
|
||||
files: ProjectFile[]; skipped: SkippedProjectFile[];
|
||||
}> {
|
||||
@@ -258,15 +262,16 @@ export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024,
|
||||
continue;
|
||||
}
|
||||
const stat = await fs.stat(path);
|
||||
if (stat.size > maxSize) { skip(relPath, "Datei zu groß"); continue; }
|
||||
const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text";
|
||||
const limit = maxSize ?? (kind === "document" ? 20 * 1024 * 1024 : Number.POSITIVE_INFINITY);
|
||||
if (stat.size > limit) { skip(relPath, `Datei zu groß (Grenze: ${limit / 1024 / 1024} MiB)`); continue; }
|
||||
if (kind === "document" && extname(path).toLowerCase() !== ".pdf" && !(await isOfficeArchive(path))) {
|
||||
skip(relPath, "Kein lesbares Office-ZIP-Archiv (beschädigt, verschlüsselt oder falsche Endung)");
|
||||
continue;
|
||||
}
|
||||
if (kind === "text" && validateText) {
|
||||
if (await isBinary(path)) { skip(relPath, "Binärdatei"); continue; }
|
||||
try { new TextDecoder("utf-8", { fatal: true }).decode(await fs.readFile(path)); }
|
||||
try { await inspectTextFile(path); }
|
||||
catch { skip(relPath, "Keine gültige UTF-8-Textdatei"); continue; }
|
||||
}
|
||||
files.push({ relPath, absPath: path, kind, size: stat.size });
|
||||
@@ -589,8 +594,7 @@ export async function listRuns(projectPath: string, support = environment.suppor
|
||||
/** An unchanged output from an in-place run can be carried into the next snapshot. */
|
||||
export async function matchesPreviousOutput(directory: string, relPath: string, currentHash: string): Promise<boolean> {
|
||||
try {
|
||||
const previous = await fs.readFile(resolveWithin(join(directory, "files"), relPath));
|
||||
return digest(previous) === currentHash;
|
||||
return await hashProjectFile(resolveWithin(join(directory, "files"), relPath)) === currentHash;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
||||
throw error;
|
||||
@@ -728,7 +732,7 @@ export async function replaceProjectFilesInPlace(projectPath: string, runDirecto
|
||||
try {
|
||||
for (const file of files) {
|
||||
const source = resolveWithin(root, file.source);
|
||||
if (expectedHashes && digest(await fs.readFile(source)) !== expectedHashes.get(file.source)) {
|
||||
if (expectedHashes && await hashProjectFile(source) !== expectedHashes.get(file.source)) {
|
||||
throw new Error(`Projektdatei wurde vor dem Ersetzen erneut geändert: ${file.source}`);
|
||||
}
|
||||
await fs.unlink(source);
|
||||
|
||||
@@ -17,7 +17,11 @@ import {
|
||||
canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, reconcileDocumentHitIds, spansBySegment,
|
||||
withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
|
||||
} from "./lib/project-review";
|
||||
import { analyzeProjectBatch, analyzeProjectTexts } from "./lib/project-analysis";
|
||||
import { analyzeProjectBatch, analyzeProjectTextFiles } from "./lib/project-analysis";
|
||||
import { hashProjectFile, inspectTextFile, writeReplacedTextFile } from "./lib/project-text-stream";
|
||||
|
||||
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY, IMAGE_POLICY_LABELS, KEEP_IMAGE_WARNING, sameImagePolicyCoverage, summarizeImages } from "./lib/image-policy";
|
||||
import type { ImagePolicy, DocumentImageReport } from "./lib/image-policy";
|
||||
|
||||
const run = promisify(execFile);
|
||||
const MAX_REVIEW_HITS = 50000;
|
||||
@@ -28,10 +32,10 @@ type Hit = {
|
||||
};
|
||||
type Draft = { file: ProjectFile; hash: string; hits: Hit[]; analysisMapping?: PlaceholderMapping };
|
||||
type PathDraft = { key: string; value: string; hits: Hit[] };
|
||||
type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string; output: string; directory: string }>;
|
||||
type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string; output: string; directory: string; imageReport?: DocumentImageReport }>;
|
||||
paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping;
|
||||
matchModes?: Record<string, "token" | "anywhere">; hits: Hit[]; entityTypes: EntityType[];
|
||||
skipped: SkippedProjectFile[]; sourceInPlace: boolean };
|
||||
skipped: SkippedProjectFile[]; sourceInPlace: boolean; imagePolicy: ImagePolicy };
|
||||
|
||||
const typeLabels: Record<string, string> = {
|
||||
PERSON: "Personen", ORT: "Orte", ORG: "Organisationen", FIRMA: "Firmen",
|
||||
@@ -63,26 +67,12 @@ async function finderFolder(): Promise<string | undefined> {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function textFromBytes(data: Buffer): string {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(data);
|
||||
}
|
||||
|
||||
function isUnreadableDocument(error: unknown): boolean {
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
return /request failed: 422\b/i.test(message)
|
||||
&& /konnte nicht gelesen werden|not a zip file|BadZipFile/i.test(message);
|
||||
}
|
||||
|
||||
function contentHits(file: ProjectFile, spans: Array<{
|
||||
start: number; end: number; type: string; score: number; placeholder: string; original: string;
|
||||
}>, text: string): Hit[] {
|
||||
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)),
|
||||
}));
|
||||
}
|
||||
|
||||
function documentHits(file: ProjectFile, hits: DocumentHit[]): Hit[] {
|
||||
return hits.map((hit) => ({ ...hit, id: `${file.relPath}:document:${hit.id}`,
|
||||
file: file.relPath, kind: "content" as const }));
|
||||
@@ -104,8 +94,8 @@ function pathSegments(files: ProjectFile[]): PathDraft[] {
|
||||
|
||||
async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[], whitelist: ProjectWhitelistEntry[], entityTypes: EntityType[],
|
||||
skipped: SkippedProjectFile[], reanalyzeUnchanged: boolean,
|
||||
onProgress: (message: string) => void): Promise<Preview> {
|
||||
await requireProjectCapabilities();
|
||||
onProgress: (message: string) => void, imagePolicy: ImagePolicy): Promise<Preview> {
|
||||
await requireProjectCapabilities(files.some((file) => file.kind === "document"));
|
||||
const masks = forceMasks(withoutWhitelistedRules(rules, whitelist));
|
||||
const latestEntry = (await listRuns(root))[0];
|
||||
const latest = latestEntry?.run;
|
||||
@@ -118,41 +108,57 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
||||
const retained: Preview["retained"] = [];
|
||||
const draftsByPath = new Map<string, Draft>();
|
||||
const hits: Hit[] = [];
|
||||
const texts = new Map<string, string>();
|
||||
const sourceInPlace = Boolean(latest?.inPlace || latest?.sourceInPlace);
|
||||
const previousDirectory = latestEntry?.directory;
|
||||
for (const file of files) {
|
||||
const data = await fs.readFile(file.absPath);
|
||||
const hash = digest(data);
|
||||
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && latest && previousDirectory
|
||||
? await reusableProjectOutput(latest, previousDirectory, file.relPath, hash) : undefined;
|
||||
if (previousOutput && previousDirectory) {
|
||||
retained.push({ file, hash, output: previousOutput, directory: previousDirectory });
|
||||
onProgress(`Datei prüfen: ${file.relPath}`);
|
||||
let hash: string;
|
||||
try { hash = file.kind === "text" ? await inspectTextFile(file.absPath) : await hashProjectFile(file.absPath); }
|
||||
catch (error) {
|
||||
const reason = (error as Error).message;
|
||||
if (!/^(Binärdatei|Keine gültige UTF-8-Textdatei)$/.test(reason)) throw error;
|
||||
skipped.push({ path: file.relPath, reason });
|
||||
continue;
|
||||
}
|
||||
let decoded: string | undefined;
|
||||
if (file.kind === "text") {
|
||||
if (data.includes(0)) { skipped.push({ path: file.relPath, reason: "Binärdatei" }); continue; }
|
||||
try { decoded = textFromBytes(data); }
|
||||
catch { skipped.push({ path: file.relPath, reason: "Keine gültige UTF-8-Textdatei" }); continue; }
|
||||
const imageCoverageMatches = file.kind !== "document" || sameImagePolicyCoverage(latest, imagePolicy);
|
||||
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && imageCoverageMatches && latest && previousDirectory
|
||||
? await reusableProjectOutput(latest, previousDirectory, file.relPath, hash) : undefined;
|
||||
if (previousOutput && previousDirectory) {
|
||||
retained.push({ file, hash, output: previousOutput, directory: previousDirectory,
|
||||
imageReport: latest?.files.find((saved) => saved.output === previousOutput)?.imageReport });
|
||||
continue;
|
||||
}
|
||||
const draft: Draft = { file, hash, hits: [] };
|
||||
drafts.push(draft);
|
||||
draftsByPath.set(file.relPath, draft);
|
||||
if (decoded !== undefined) texts.set(file.relPath, decoded);
|
||||
}
|
||||
const addHits = (draft: Draft, found: Hit[]) => {
|
||||
draft.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
||||
hits.push(...draft.hits);
|
||||
if (hits.length > MAX_REVIEW_HITS) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
|
||||
};
|
||||
const analyzedTexts = await analyzeProjectTexts([...texts].map(([key, text]) => ({ key, text })),
|
||||
mapping, entityTypes, masks, pseudonymize,
|
||||
(index, total) => onProgress(`Textdateien analysieren: Paket ${index}/${total}`));
|
||||
const textDrafts = drafts.filter((draft) => draft.file.kind === "text");
|
||||
const analyzeText: typeof pseudonymize = async (text, current, types, rules) => {
|
||||
try {
|
||||
return await pseudonymize(text, current, types, rules, AbortSignal.timeout(60_000));
|
||||
} catch (error) {
|
||||
if (error instanceof Error && /timeout|abort/i.test(error.name)) {
|
||||
throw new Error("Velum: Analyse-Zeitlimit nach 60 Sekunden erreicht. Backend-Auslastung und Proxy-Zeitlimit prüfen.", { cause: error });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
const analyzedTexts = await analyzeProjectTextFiles(textDrafts.map((draft) => ({
|
||||
key: draft.file.relPath, path: draft.file.absPath,
|
||||
})), mapping, entityTypes, masks, analyzeText,
|
||||
(file, index) => onProgress(`Textdateien analysieren: ${file} · Paket ${index}`));
|
||||
mapping = analyzedTexts.mapping;
|
||||
for (const [path, spans] of analyzedTexts.spansByFile) {
|
||||
const draft = draftsByPath.get(path)!;
|
||||
addHits(draft, contentHits(draft.file, spans, texts.get(path)!));
|
||||
for (const draft of textDrafts) {
|
||||
if (await hashProjectFile(draft.file.absPath) !== draft.hash) throw new Error(`Datei wurde während der Analyse geändert: ${draft.file.relPath}`);
|
||||
addHits(draft, (analyzedTexts.spansByFile.get(draft.file.relPath) ?? []).map((span, index) => ({
|
||||
...span, id: `${draft.file.relPath}:content:${index}`, file: draft.file.relPath,
|
||||
source: draft.file.relPath, kind: "content" as const,
|
||||
})));
|
||||
}
|
||||
const documents = drafts.filter((draft) => draft.file.kind === "document");
|
||||
for (const [index, draft] of documents.entries()) {
|
||||
@@ -160,7 +166,7 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
||||
const data = await fs.readFile(draft.file.absPath);
|
||||
try {
|
||||
draft.analysisMapping = mapping;
|
||||
const result = await pseudonymizeDocument(basename(draft.file.relPath), data, mapping, masks, undefined, entityTypes);
|
||||
const result = await pseudonymizeDocument(basename(draft.file.relPath), data, mapping, masks, undefined, entityTypes, undefined, imagePolicy);
|
||||
mapping = result.mapping;
|
||||
addHits(draft, documentHits(draft.file, result.hits));
|
||||
} catch (error) {
|
||||
@@ -187,7 +193,7 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
||||
const byPath = new Map(paths.map((path) => [path.key, path]));
|
||||
for (const [index, batch] of pathBatches.entries()) {
|
||||
onProgress(`Dateinamen analysieren: Paket ${index + 1}/${pathBatches.length}`);
|
||||
const analyzed = await analyzeProjectBatch(batch, mapping, entityTypes, masks, pseudonymize,
|
||||
const analyzed = await analyzeProjectBatch(batch, mapping, entityTypes, masks, analyzeText,
|
||||
"Dateinamen analysieren");
|
||||
mapping = analyzed.mapping;
|
||||
for (const { batch: part, result } of analyzed.results) {
|
||||
@@ -206,7 +212,7 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[],
|
||||
}
|
||||
}
|
||||
return { drafts, retained, paths, mapping, previousMapping,
|
||||
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace };
|
||||
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace, imagePolicy };
|
||||
}
|
||||
|
||||
function outputPath(relPath: string, paths: PathDraft[], accepted: Set<string>, document: boolean,
|
||||
@@ -246,7 +252,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [completed, setCompleted] = useState<{ directory: string; inPlace: boolean; files: number;
|
||||
replaced: number } | null>(null);
|
||||
replaced: number; images: ReturnType<typeof summarizeImages> } | null>(null);
|
||||
const accepted = useMemo(() => new Set(groups.filter((group) => selectedGroups.has(group.key))
|
||||
.flatMap((group) => group.hits.map((hit) => hit.id))), [groups, selectedGroups]);
|
||||
const selectedOccurrences = accepted.size;
|
||||
@@ -298,7 +304,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
}
|
||||
if (!(await confirmAlert({
|
||||
title: inPlace ? "Geprüfte Auswahl anwenden und Originaldateien ersetzen?" : "Geprüfte Auswahl als Kopien erstellen?",
|
||||
message: `${selectedGroups.size} von ${groups.length} Begriffen in ${props.preview.drafts.length} neuen oder geänderten Dateien werden maskiert. ${groups.length - selectedGroups.size} abgewählte Begriffe werden als Projektausnahmen gespeichert. ${inPlace
|
||||
message: `${props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING + " " : ""}${IMAGE_POLICY_LABELS[props.preview.imagePolicy]}. ${selectedGroups.size} von ${groups.length} Begriffen in ${props.preview.drafts.length} neuen oder geänderten Dateien werden maskiert. ${groups.length - selectedGroups.size} abgewählte Begriffe werden als Projektausnahmen gespeichert. ${inPlace
|
||||
? "Die Originale und gegebenenfalls ihre Namen werden im Projektordner ersetzt und vorher außerhalb gesichert. PDF-Dateien werden als DOCX ausgegeben."
|
||||
: "Die pseudonymisierten Kopien werden neben dem Projektordner gespeichert."}`,
|
||||
primaryAction: { title: inPlace ? "Originaldateien ersetzen" : "Kopien erstellen",
|
||||
@@ -323,6 +329,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
run.mapping = mappingForSelection(props.preview.mapping, props.preview.previousMapping,
|
||||
acceptedHits, activeMerges);
|
||||
run.entityTypes = [...props.preview.entityTypes];
|
||||
run.imagePolicy = props.preview.imagePolicy;
|
||||
run.sourceState = {};
|
||||
run.commentAuthorCoverage = props.preview.entityTypes.includes("PERSON");
|
||||
run.reviewAuthorCoverage = props.preview.entityTypes.includes("PERSON");
|
||||
@@ -331,8 +338,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
const usedPaths = new Set<string>();
|
||||
const replacements: RunFile[] = [];
|
||||
for (const retained of props.preview.retained) {
|
||||
const data = await fs.readFile(retained.file.absPath);
|
||||
if (digest(data) !== retained.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${retained.file.relPath}`);
|
||||
if (await hashProjectFile(retained.file.absPath) !== retained.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${retained.file.relPath}`);
|
||||
const relPath = retained.output;
|
||||
if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`);
|
||||
usedPaths.add(relPath);
|
||||
@@ -341,26 +347,27 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
await fs.copyFile(resolveWithin(join(retained.directory, "files"), retained.output), target,
|
||||
fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE);
|
||||
await fs.chmod(target, 0o600);
|
||||
const file: RunFile = { source: retained.file.relPath, output: relPath, kind: retained.file.kind };
|
||||
const file: RunFile = { source: retained.file.relPath, output: relPath, kind: retained.file.kind, imageReport: retained.imageReport };
|
||||
run.files.push(file);
|
||||
run.sourceState[inPlace ? relPath : file.source] = {
|
||||
hash: inPlace ? digest(await fs.readFile(target)) : retained.hash, output: relPath,
|
||||
hash: inPlace ? await hashProjectFile(target) : retained.hash, output: relPath,
|
||||
};
|
||||
// A prior copy-only run did not change the source files. Switching to in-place
|
||||
// must install its reviewed outputs even when their names are unchanged.
|
||||
if (file.source !== file.output || (inPlace && !props.preview.sourceInPlace)) replacements.push(file);
|
||||
}
|
||||
for (const draft of props.preview.drafts) {
|
||||
const data = await fs.readFile(draft.file.absPath);
|
||||
if (digest(data) !== draft.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${draft.file.relPath}`);
|
||||
if (await hashProjectFile(draft.file.absPath) !== draft.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${draft.file.relPath}`);
|
||||
const relPath = outputPath(draft.file.relPath, props.preview.paths, accepted,
|
||||
draft.file.kind === "document", activeMerges);
|
||||
if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`);
|
||||
usedPaths.add(relPath);
|
||||
const target = resolveWithin(join(directory, "files"), relPath);
|
||||
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||
let output: Buffer;
|
||||
let outputHash: string;
|
||||
let imageReport: DocumentImageReport | undefined;
|
||||
if (draft.file.kind === "document") {
|
||||
const data = await fs.readFile(draft.file.absPath);
|
||||
const idPrefix = `${draft.file.relPath}:document:`;
|
||||
const reviewed = draft.hits.map((hit) => ({ ...hit, id: hit.id.slice(idPrefix.length) }));
|
||||
let docIds = draft.hits.filter((hit) => accepted.has(hit.id)).map((hit) => hit.id.slice(idPrefix.length));
|
||||
@@ -368,18 +375,18 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
let result;
|
||||
try {
|
||||
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||
masks, docIds, props.preview.entityTypes, draft.analysisMapping);
|
||||
masks, docIds, props.preview.entityTypes, draft.analysisMapping, props.preview.imagePolicy);
|
||||
} catch (error) {
|
||||
if (!/\b409\b/.test((error as Error).message) || !/Treffer passen nicht mehr/.test((error as Error).message)) {
|
||||
throw error;
|
||||
}
|
||||
const refreshed = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||
masks, undefined, props.preview.entityTypes);
|
||||
masks, undefined, props.preview.entityTypes, undefined, props.preview.imagePolicy);
|
||||
const ids = reconcileDocumentHitIds(reviewed, docIds, refreshed.hits);
|
||||
if (!ids) throw new Error(`${draft.file.relPath}: Erkennungen haben sich seit der Prüfung geändert. Bitte Treffer erneut prüfen.`);
|
||||
docIds = ids;
|
||||
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||
masks, docIds, props.preview.entityTypes, run.mapping);
|
||||
masks, docIds, props.preview.entityTypes, run.mapping, props.preview.imagePolicy);
|
||||
}
|
||||
const selectedIds = new Set(docIds);
|
||||
const selectedHits = result.hits.filter((hit) => selectedIds.has(hit.id));
|
||||
@@ -389,15 +396,18 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
&& (entry.merged_into ?? placeholder) === hit.placeholder))) {
|
||||
throw new Error(`${draft.file.relPath}: Zuordnungen haben sich seit der Prüfung geändert. Bitte Treffer erneut prüfen.`);
|
||||
}
|
||||
output = Buffer.from(result.file_base64, "base64");
|
||||
imageReport = checkedImageReport(result, props.preview.imagePolicy);
|
||||
const output = Buffer.from(result.file_base64, "base64");
|
||||
await fs.writeFile(target, output, { mode: 0o600 });
|
||||
outputHash = digest(output);
|
||||
} else {
|
||||
output = Buffer.from(replaceSpans(textFromBytes(data), withPersonMerges(draft.hits, activeMerges), accepted), "utf8");
|
||||
outputHash = await writeReplacedTextFile(draft.file.absPath, target,
|
||||
withPersonMerges(draft.hits, activeMerges), accepted, draft.hash);
|
||||
}
|
||||
await fs.writeFile(target, output, { mode: 0o600 });
|
||||
const file: RunFile = { source: draft.file.relPath, output: relPath, kind: draft.file.kind };
|
||||
const file: RunFile = { source: draft.file.relPath, output: relPath, kind: draft.file.kind, imageReport };
|
||||
run.files.push(file);
|
||||
run.sourceState[inPlace ? relPath : file.source] = {
|
||||
hash: inPlace ? digest(output) : draft.hash, output: relPath,
|
||||
hash: inPlace ? outputHash : draft.hash, output: relPath,
|
||||
};
|
||||
replacements.push(file);
|
||||
}
|
||||
@@ -421,6 +431,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
await saveProjectWhitelist(props.root, nextWhitelist);
|
||||
props.onWhitelistChanged(await loadProjectWhitelist(props.root));
|
||||
}
|
||||
const images = summarizeImages(run.files);
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = inPlace ? (replacements.length ? `${replacements.length} Dateien ersetzt` : "Dateiauswahl aktualisiert")
|
||||
: `${run.files.length} Kopien erstellt`;
|
||||
@@ -428,7 +439,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
: inPlace ? "Ausgeschlossene Dateien wurden im neuen Projektstand weggelassen."
|
||||
: "Die Kopien liegen neben dem Projektordner.";
|
||||
setCompleted({ directory: inPlace && replacements.length ? join(directory, "backup")
|
||||
: inPlace ? props.root : publishedCopyPath!, inPlace, files: run.files.length, replaced: replacements.length });
|
||||
: inPlace ? props.root : publishedCopyPath!, inPlace, files: run.files.length, replaced: replacements.length, images });
|
||||
await showInFinder(inPlace ? props.root : publishedCopyPath!).catch(() => undefined);
|
||||
} catch (error) {
|
||||
if (directory && !persisted) await fs.rm(directory, { recursive: true, force: true });
|
||||
@@ -440,6 +451,10 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
}
|
||||
|
||||
if (completed) return <List navigationTitle="Pseudonymisierung abgeschlossen">
|
||||
<List.Item icon={completed.images.warnings.length ? Icon.Warning : Icon.Image}
|
||||
title={`${completed.images.replaced} Bilder ersetzt · ${completed.images.removed} Bilder entfernt`}
|
||||
subtitle={IMAGE_POLICY_LABELS[props.preview.imagePolicy]} />
|
||||
{completed.images.warnings.map((warning) => <List.Item key={warning} icon={Icon.Warning} title={warning} />)}
|
||||
<List.Item icon={Icon.CheckCircle}
|
||||
title={completed.inPlace ? (completed.replaced ? "Projektdateien ersetzt" : "Dateiauswahl aktualisiert")
|
||||
: `${completed.files} pseudonymisierte Kopien erstellt`}
|
||||
@@ -456,7 +471,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
|
||||
if (stage === "merge") return <List isLoading={busy} navigationTitle="Personen zusammenfassen"
|
||||
searchBarPlaceholder="Person oder Platzhalter suchen">
|
||||
<List.Section title="Abschluss">
|
||||
<List.Section title={props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING : IMAGE_POLICY_LABELS[props.preview.imagePolicy]}>
|
||||
<List.Item icon={Icon.Play} title="Pseudonymisierung starten"
|
||||
subtitle={`${selectedGroups.size} Zuordnungen · ${people.length} Personen · ${props.preview.retained.length} unveränderte Dateien übernommen`}
|
||||
actions={<ActionPanel>
|
||||
@@ -494,7 +509,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
|
||||
return <List isLoading={busy} navigationTitle="Zuordnungen prüfen"
|
||||
searchBarPlaceholder="Begriff oder Platzhalter suchen">
|
||||
<List.Section title="Abschluss">
|
||||
<List.Section title={props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING : IMAGE_POLICY_LABELS[props.preview.imagePolicy]}>
|
||||
<List.Item key="apply" icon={Icon.Play}
|
||||
title={`${selectedGroups.size} von ${groups.length} Zuordnungen ausgewählt`}
|
||||
subtitle={`${selectedOccurrences} Vorkommen · ${props.preview.drafts.length} neue/geänderte Dateien · ${props.preview.retained.length} unverändert · ${props.preview.skipped.length} übersprungen`}
|
||||
@@ -561,7 +576,7 @@ function SkippedFiles(props: { files: SkippedProjectFile[] }) {
|
||||
}
|
||||
|
||||
function FileSelection(props: { root: string; files: ProjectFile[]; skipped: SkippedProjectFile[];
|
||||
excluded: string[]; rules: ProjectRule[]; types: EntityType[]; reanalyzeUnchanged: boolean;
|
||||
excluded: string[]; rules: ProjectRule[]; types: EntityType[]; reanalyzeUnchanged: boolean; imagePolicy: ImagePolicy;
|
||||
onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
|
||||
const { push } = useNavigation();
|
||||
const [selected, setSelected] = useState<Set<string>>(() => new Set(
|
||||
@@ -604,7 +619,7 @@ function FileSelection(props: { root: string; files: ProjectFile[]; skipped: Ski
|
||||
.map((file) => ({ path: file.relPath, reason: "Für dieses Projekt abgewählt" }))];
|
||||
const whitelist = await loadProjectWhitelist(props.root);
|
||||
const preview = await prepare(props.root, files, props.rules, whitelist, props.types, skipped,
|
||||
props.reanalyzeUnchanged, (message) => { toast.title = message; });
|
||||
props.reanalyzeUnchanged, (message) => { toast.title = message; }, props.imagePolicy);
|
||||
if (!preview.drafts.length && !preview.hits.length && !fileSelectionChanged) {
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = "Alle ausgewählten Projektdateien unverändert";
|
||||
@@ -657,6 +672,7 @@ function FileSelection(props: { root: string; files: ProjectFile[]; skipped: Ski
|
||||
export default function Command() {
|
||||
const { push } = useNavigation();
|
||||
const [root, setRoot] = useState("");
|
||||
const [imagePolicy, setImagePolicy] = useState<ImagePolicy>(DEFAULT_IMAGE_POLICY);
|
||||
const [rules, setRules] = useState("");
|
||||
const [availableTypes, setAvailableTypes] = useState<EntityType[]>([]);
|
||||
const [selectedTypes, setSelectedTypes] = useState<EntityType[]>([]);
|
||||
@@ -745,7 +761,7 @@ export default function Command() {
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = `${scan.files.length} Dateien zur Auswahl`;
|
||||
push(<FileSelection root={root} files={scan.files} skipped={scan.skipped} excluded={excluded}
|
||||
rules={parsed} types={selectedTypes} reanalyzeUnchanged={reanalyzeUnchanged}
|
||||
rules={parsed} types={selectedTypes} reanalyzeUnchanged={reanalyzeUnchanged} imagePolicy={imagePolicy}
|
||||
onWhitelistChanged={setWhitelist} />);
|
||||
} catch (error) {
|
||||
toast.style = Toast.Style.Failure;
|
||||
@@ -778,6 +794,13 @@ export default function Command() {
|
||||
onChange={setSelectedTypes} info="Die Auswahl wird beim Prüfen für diesen Projektordner gespeichert. Word-Kommentatoren und Bearbeiter von Änderungen werden mit der Kategorie Personen maskiert. Bei neuen Projekten sind Orte zunächst abgewählt.">
|
||||
{availableTypes.map((type) => <Form.TagPicker.Item key={type} value={type} title={labelForType(type)} />)}
|
||||
</Form.TagPicker>
|
||||
<Form.Dropdown id="imagePolicy" title="Bilder in Office/PDF" value={imagePolicy}
|
||||
onChange={(value) => setImagePolicy(checkedImagePolicy(value))}>
|
||||
{Object.entries(IMAGE_POLICY_LABELS).map(([value, title]) => <Form.Dropdown.Item key={value} value={value} title={title} />)}
|
||||
</Form.Dropdown>
|
||||
<Form.Description title={imagePolicy === "keep" ? "Achtung" : "Bildbehandlung"}
|
||||
text={imagePolicy === "keep" ? KEEP_IMAGE_WARNING
|
||||
: "Keine Analyse von Bildinhalten. Position und Größe bleiben bei Office-Platzhaltern soweit möglich erhalten. PDF wird als Word-Dokument neu aufgebaut. Entfernte Bilder sind nicht wiederherstellbar."} />
|
||||
<Form.Checkbox id="reanalyzeUnchanged" title="Erneute Analyse"
|
||||
label="Auch unveränderte Dateien erneut analysieren" value={reanalyzeUnchanged}
|
||||
onChange={setReanalyzeUnchanged}
|
||||
|
||||
25
src/velum.ts
25
src/velum.ts
@@ -1,4 +1,7 @@
|
||||
import { fetchWithAuth } from "./auth";
|
||||
import { checkProjectCapabilities } from "./lib/project-capabilities";
|
||||
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY } from "./lib/image-policy";
|
||||
import type { ImagePolicy, DocumentImageReport } from "./lib/image-policy";
|
||||
import { getPreferences } from "./preferences";
|
||||
import type {
|
||||
DepseudonymizeResponse,
|
||||
@@ -112,8 +115,10 @@ export async function pseudonymize(
|
||||
mapping: PlaceholderMapping,
|
||||
entityTypes?: EntityType[],
|
||||
forceMasks?: Record<string, string[]>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<PseudonymizeResponse> {
|
||||
const response = await fetchWithAuth(apiUrl("/api/pseudonymize"), {
|
||||
signal,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
@@ -141,19 +146,11 @@ export type DocumentHit = {
|
||||
original: string;
|
||||
};
|
||||
|
||||
export async function requireProjectCapabilities(): Promise<void> {
|
||||
const response = await fetchWithAuth(apiUrl("/api/project-capabilities"));
|
||||
if (!response.ok) throw new Error("Die Velum-API muss für die Projektfunktionen aktualisiert werden.");
|
||||
const capabilities = await parseJsonResponse<Record<string, boolean>>(response);
|
||||
if (!capabilities.request_force_masks || !capabilities.document_hit_review
|
||||
|| !capabilities.document_review_mapping
|
||||
|| !capabilities.document_restoration || !capabilities.comment_author_review
|
||||
|| !capabilities.revision_author_review) {
|
||||
throw new Error("Die Velum-API unterstützt die Projektfunktionen noch nicht vollständig.");
|
||||
}
|
||||
export async function requireProjectCapabilities(documents = false): Promise<void> {
|
||||
await checkProjectCapabilities(apiUrl("/api/project-capabilities"), documents, fetchWithAuth);
|
||||
}
|
||||
|
||||
export type DocumentResult = {
|
||||
export type DocumentResult = DocumentImageReport & {
|
||||
filename: string;
|
||||
content_type: string;
|
||||
file_base64: string;
|
||||
@@ -170,18 +167,22 @@ export async function pseudonymizeDocument(
|
||||
acceptedHitIds?: string[],
|
||||
entityTypes?: EntityType[],
|
||||
analysisMapping?: PlaceholderMapping,
|
||||
imagePolicy: ImagePolicy = DEFAULT_IMAGE_POLICY,
|
||||
): Promise<DocumentResult> {
|
||||
checkedImagePolicy(imagePolicy);
|
||||
const form = new FormData();
|
||||
form.set("file", new Blob([new Uint8Array(data)]), filename);
|
||||
form.set("mapping", JSON.stringify(mapping));
|
||||
form.set("force_masks", JSON.stringify(forceMasks));
|
||||
form.set("image_policy", imagePolicy);
|
||||
if (entityTypes !== undefined) form.set("entity_types", JSON.stringify(entityTypes));
|
||||
if (acceptedHitIds) form.set("accepted_hit_ids", JSON.stringify(acceptedHitIds));
|
||||
if (analysisMapping) form.set("analysis_mapping", JSON.stringify(analysisMapping));
|
||||
const response = await fetchWithAuth(apiUrl("/api/pseudonymize-document"), {
|
||||
method: "POST", body: form,
|
||||
});
|
||||
return parseJsonResponse<DocumentResult>(response);
|
||||
const result = await parseJsonResponse<DocumentResult>(response);
|
||||
return { ...result, ...checkedImageReport(result, imagePolicy) };
|
||||
}
|
||||
|
||||
export async function depseudonymizeDocument(
|
||||
|
||||
Reference in New Issue
Block a user