feat: run Velum project jobs in the background and process DOCX locally
This commit is contained in:
135
src/lib/local-docx.ts
Normal file
135
src/lib/local-docx.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { constants, promises as fs } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { delimiter, dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { analyzeDocxSegments } from "../velum";
|
||||
import type { EntityType, PlaceholderMapping } from "../types";
|
||||
import { checkedImageReport } from "./image-policy";
|
||||
import type { ImagePolicy } from "./image-policy";
|
||||
import { MAX_BATCH_CODEPOINTS } from "./project-review";
|
||||
import { projectTextAnalyzer } from "./project-text-mapping";
|
||||
import type { Hit } from "./project-work";
|
||||
|
||||
type Segment = { text: string; source: string; kind: "text" | "author" | "link" | "email" };
|
||||
const exec = promisify(execFile);
|
||||
|
||||
async function docxCodec(assets: string, args: string[]): Promise<unknown> {
|
||||
const paths = [
|
||||
...(process.env.PATH ?? "").split(delimiter).filter(Boolean),
|
||||
"/opt/homebrew/bin", "/usr/local/bin", join(homedir(), ".local/bin"),
|
||||
];
|
||||
let uv: string | undefined;
|
||||
for (const directory of new Set(paths)) {
|
||||
const candidate = join(directory, "uv");
|
||||
try {
|
||||
await fs.access(candidate, constants.X_OK);
|
||||
uv = candidate;
|
||||
break;
|
||||
} catch { /* check the next executable directory */ }
|
||||
}
|
||||
if (!uv) throw new Error("Für lokale DOCX-Aufträge wird uv benötigt. Bitte uv installieren und Raycast erneut öffnen.");
|
||||
try {
|
||||
const { stdout } = await exec(uv, [
|
||||
"run", "--no-project", "--isolated", "--with", "lxml==6.2.1",
|
||||
"--python", "3.11", "python", "-m", "velum.docx_local", ...args,
|
||||
], { cwd: join(assets, "velum-docx"), maxBuffer: 192 * 1024 * 1024, env: { ...process.env, PYTHONUTF8: "1" } });
|
||||
return JSON.parse(stdout);
|
||||
} catch (error) {
|
||||
const stderr = (error as { stderr?: string }).stderr?.trim();
|
||||
throw new Error(stderr || "Lokaler DOCX-Schritt fehlgeschlagen.", { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
export async function inspectDocx(
|
||||
assets: string, path: string, relative: string, hash: string, policy: ImagePolicy,
|
||||
mapping: PlaceholderMapping, types: EntityType[], masks: Record<string, string[]>,
|
||||
progress: (message: string) => void,
|
||||
): Promise<{ hits: Hit[]; mapping: PlaceholderMapping; segmentCount: number }> {
|
||||
const segments = await docxCodec(assets, ["extract", path, policy, hash]) as Segment[];
|
||||
const hits: Hit[] = [];
|
||||
let batch: Segment[] = [];
|
||||
let offset = 0;
|
||||
let size = 0;
|
||||
let part = 0;
|
||||
let current = mapping;
|
||||
const analyze = projectTextAnalyzer(mapping, async (_text, window) => {
|
||||
const response = await analyzeDocxSegments(batch.map(({ text, kind }) => ({ text, kind })), window, types, masks);
|
||||
if (response.spans.length !== batch.length) throw new Error("Velum liefert eine ungültige Zahl von DOCX-Segmenten.");
|
||||
let start = 0;
|
||||
const spans = response.spans.flatMap((matches, index) => {
|
||||
const segment = Array.from(batch[index].text);
|
||||
const result = matches.map((span) => {
|
||||
if (!Number.isInteger(span.start) || !Number.isInteger(span.end)
|
||||
|| span.start < 0 || span.start >= span.end || span.end > segment.length) {
|
||||
throw new Error("Ungültige Trefferposition der Velum-DOCX-API.");
|
||||
}
|
||||
return { ...span, start: start + span.start, end: start + span.end };
|
||||
});
|
||||
start += segment.length + 2;
|
||||
return result;
|
||||
});
|
||||
return { spans, mapping: response.mapping, selected_entity_types: types, pseudonymized_text: "", entity_count: 0 };
|
||||
});
|
||||
async function flush() {
|
||||
if (batch.length === 0) return;
|
||||
progress(`DOCX analysieren: ${relative} · Paket ${++part}`);
|
||||
const text = batch.map((segment) => segment.text).join("\n\n");
|
||||
const analyzed = await analyze(text, current, types, masks);
|
||||
current = analyzed.mapping;
|
||||
let start = 0;
|
||||
let hit = 0;
|
||||
const ordered = [...analyzed.spans].sort((a, b) => a.start - b.start);
|
||||
for (const [index, segment] of batch.entries()) {
|
||||
const characters = Array.from(segment.text);
|
||||
const segmentIndex = offset + index;
|
||||
while (hit < ordered.length && ordered[hit].start < start + characters.length) {
|
||||
const span = ordered[hit++];
|
||||
const begin = span.start - start;
|
||||
const end = span.end - start;
|
||||
if (begin < 0 || end > characters.length) throw new Error("DOCX-Treffer überschreitet sein Segment.");
|
||||
hits.push({ ...span, start: begin, end, segment: segmentIndex,
|
||||
id: `${relative}:local-docx:${segmentIndex}:${begin}:${end}`, file: relative, source: segment.source,
|
||||
context: characters.slice(Math.max(0, begin - 60), end + 60).join(""), kind: "content" });
|
||||
}
|
||||
start += characters.length + 2;
|
||||
}
|
||||
if (hit !== ordered.length) throw new Error("DOCX-Treffer konnte keinem Segment zugeordnet werden.");
|
||||
offset += batch.length;
|
||||
batch = [];
|
||||
size = 0;
|
||||
}
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.text.length > 250_000) throw new Error("Ein einzelnes DOCX-Textfeld überschreitet 250.000 Zeichen.");
|
||||
if (batch.length && (size + segment.text.length + 2 > MAX_BATCH_CODEPOINTS || batch.length === 256)) await flush();
|
||||
batch.push(segment);
|
||||
size += segment.text.length + 2;
|
||||
}
|
||||
await flush();
|
||||
return { hits, mapping: current, segmentCount: segments.length };
|
||||
}
|
||||
|
||||
export async function writeDocx(
|
||||
assets: string, path: string, target: string, hash: string, policy: ImagePolicy, segmentCount: number,
|
||||
hits: Hit[], accepted: Set<string>,
|
||||
) {
|
||||
const replacements: Record<string, { start: number; end: number; original: string; placeholder: string }[]> = {};
|
||||
for (const hit of hits) {
|
||||
if (!accepted.has(hit.id)) continue;
|
||||
if (!Number.isSafeInteger(hit.segment) || hit.segment! < 0 || hit.segment! >= segmentCount) {
|
||||
throw new Error("DOCX-Treffer hat kein gültiges Segment.");
|
||||
}
|
||||
const { start, end, original, placeholder } = hit;
|
||||
(replacements[hit.segment!] ??= []).push({ start, end, original, placeholder });
|
||||
}
|
||||
for (const spans of Object.values(replacements)) spans.sort((a, b) => a.start - b.start);
|
||||
const instructions = join(dirname(target), ".velum-replacements-" + randomUUID());
|
||||
await fs.writeFile(instructions, JSON.stringify({ replacements, segmentCount }), { flag: "wx", mode: 0o600 });
|
||||
try {
|
||||
return checkedImageReport(await docxCodec(assets, ["apply", path, policy, hash, instructions, target]), policy);
|
||||
} finally {
|
||||
await fs.rm(instructions, { force: true });
|
||||
}
|
||||
}
|
||||
60
src/lib/mapping-export.ts
Normal file
60
src/lib/mapping-export.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { PlaceholderMapping } from "../types";
|
||||
import { mappingRoot } from "./mapping-groups";
|
||||
|
||||
export type MappingExportKind = "terms" | "replacements";
|
||||
|
||||
/** One record per line; literal backslashes and line breaks remain distinguishable. */
|
||||
function singleLine(value: string): string {
|
||||
return value.replace(/\\/g, "\\\\").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
|
||||
}
|
||||
|
||||
export function mappingExport(mapping: PlaceholderMapping, kind: MappingExportKind): { text: string; count: number } {
|
||||
const compare = (left: string, right: string) => left.localeCompare(right, "de", { numeric: true });
|
||||
if (kind === "terms") {
|
||||
const terms = [...new Set(Object.values(mapping).map((entry) => entry.original))].sort(compare);
|
||||
return { text: terms.map(singleLine).join("\n") + (terms.length ? "\n" : ""), count: terms.length };
|
||||
}
|
||||
if (kind !== "replacements") throw new Error("Unbekanntes Exportformat.");
|
||||
const pairs = new Map<string, { original: string; replacement: string }>();
|
||||
for (const [key, entry] of Object.entries(mapping)) {
|
||||
const replacement = mappingRoot(key, mapping);
|
||||
pairs.set(JSON.stringify([entry.original, replacement]), { original: entry.original, replacement });
|
||||
}
|
||||
const rows = [...pairs.values()].sort((left, right) => compare(left.original, right.original)
|
||||
|| compare(left.replacement, right.replacement));
|
||||
return {
|
||||
text: rows.map(({ original, replacement }) => `${singleLine(original)} → ${singleLine(replacement)}`).join("\n") + (rows.length ? "\n" : ""),
|
||||
count: rows.length,
|
||||
};
|
||||
}
|
||||
|
||||
/** Save a private, complete UTF-8 copy, without replacing earlier exports. */
|
||||
export async function writeMappingExport(title: string, mapping: PlaceholderMapping, kind: MappingExportKind,
|
||||
directory = join(homedir(), "Downloads", "Velum")): Promise<{ path: string; count: number }> {
|
||||
const { text, count } = mappingExport(mapping, kind);
|
||||
if (!count) throw new Error("Diese Übersetzungstabelle enthält noch keine Begriffe.");
|
||||
const name = [...title.normalize("NFC").replace(/[^\p{L}\p{N}_. -]/gu, "-")].slice(0, 40).join("")
|
||||
.replace(/^[.\s-]+|[.\s-]+$/g, "") || "Velum";
|
||||
const suffix = kind === "terms" ? "begriffe" : "ersetzungen";
|
||||
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
||||
const temporary = await fs.mkdtemp(join(directory, ".velum-export-"));
|
||||
try {
|
||||
const file = join(temporary, "export.txt");
|
||||
await fs.writeFile(file, text, { encoding: "utf8", flag: "wx", mode: 0o600 });
|
||||
for (let index = 0; index < 1000; index++) {
|
||||
const path = join(directory, `${name}-${suffix}${index ? ` (${index + 1})` : ""}.txt`);
|
||||
try {
|
||||
await fs.link(file, path);
|
||||
return { path, count };
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
||||
}
|
||||
}
|
||||
throw new Error("Zu viele gleichnamige Exportdateien. Bitte ältere Exporte umbenennen.");
|
||||
} finally {
|
||||
await fs.rm(temporary, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
@@ -208,7 +208,6 @@ export async function analyzeProjectTexts(
|
||||
let total = 0;
|
||||
for (const entry of batches()) if (entry.batch.segments.length) total++;
|
||||
let current = mapping;
|
||||
let hitCount = 0;
|
||||
let index = 0;
|
||||
for (const { batch, byKey } of batches()) {
|
||||
onProgress(++index, total);
|
||||
@@ -248,7 +247,6 @@ 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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -273,7 +271,6 @@ export async function analyzeProjectTextFiles(
|
||||
let size = 0;
|
||||
let current = mapping;
|
||||
let batchIndex = 0;
|
||||
let hits = 0;
|
||||
const flush = async () => {
|
||||
if (!parts.length) return;
|
||||
const batch = makeTextBatches(parts)[0];
|
||||
@@ -295,7 +292,6 @@ export async function analyzeProjectTextFiles(
|
||||
// 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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
164
src/lib/project-jobs.ts
Normal file
164
src/lib/project-jobs.ts
Normal file
@@ -0,0 +1,164 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { environment } from "@raycast/api";
|
||||
import { getPreferences } from "../preferences";
|
||||
import { canonicalProjectPath, projectDataRoot } from "./velum-project";
|
||||
import type { applyProject, prepareProject, Preview, ProjectOutput } from "./project-work";
|
||||
|
||||
export type AnalysisInput = {
|
||||
root: string;
|
||||
files: Parameters<typeof prepareProject>[2];
|
||||
rules: Parameters<typeof prepareProject>[3];
|
||||
whitelist: Parameters<typeof prepareProject>[4];
|
||||
entityTypes: Parameters<typeof prepareProject>[5];
|
||||
skipped: Parameters<typeof prepareProject>[6];
|
||||
reanalyzeUnchanged: boolean;
|
||||
imagePolicy: Parameters<typeof prepareProject>[9];
|
||||
fileSelectionChanged: boolean;
|
||||
};
|
||||
export type Decision = Parameters<typeof applyProject>[5];
|
||||
export type JobPhase = "analysis" | "apply";
|
||||
export type ProjectJobState =
|
||||
| { phase: JobPhase; pid: number; message: string }
|
||||
| { phase: "review" }
|
||||
| { phase: "complete"; output?: ProjectOutput; reused?: number }
|
||||
| { phase: "error"; message: string };
|
||||
|
||||
export function projectJobDirectory(root: string, support = environment.supportPath): string {
|
||||
return join(projectDataRoot(root, support), "active-job");
|
||||
}
|
||||
|
||||
export async function writeJobJson(directory: string, file: string, value: unknown): Promise<void> {
|
||||
const target = join(directory, file);
|
||||
const temporary = target + "." + randomUUID();
|
||||
try {
|
||||
await fs.writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
|
||||
await fs.rename(temporary, target);
|
||||
} finally {
|
||||
await fs.rm(temporary, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export async function readJobJson<T>(directory: string, file: string): Promise<T> {
|
||||
return JSON.parse(await fs.readFile(join(directory, file), "utf8")) as T;
|
||||
}
|
||||
|
||||
export async function readProjectJob(root: string): Promise<ProjectJobState | undefined> {
|
||||
const directory = projectJobDirectory(root);
|
||||
let state: ProjectJobState;
|
||||
try {
|
||||
state = await readJobJson<ProjectJobState>(directory, "state.json");
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
const info = await fs.stat(directory).catch((statError: NodeJS.ErrnoException) => {
|
||||
if (statError.code !== "ENOENT") throw statError;
|
||||
});
|
||||
if (info && Date.now() - info.mtimeMs > 10_000) {
|
||||
return { phase: "error", message: "Der Projektauftrag wurde beim Start unterbrochen." };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (state.phase === "analysis" || state.phase === "apply") {
|
||||
try {
|
||||
process.kill(state.pid, 0);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
|
||||
// The worker writes its terminal state before exiting.
|
||||
const last = await readJobJson<ProjectJobState>(directory, "state.json");
|
||||
if (last.phase !== "analysis" && last.phase !== "apply") return last;
|
||||
return { phase: "error", message: "Der lokale Hintergrundprozess wurde beendet." };
|
||||
}
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
export async function loadProjectReview(root: string): Promise<{ input: AnalysisInput; preview: Preview }> {
|
||||
const directory = projectJobDirectory(root);
|
||||
const [input, preview] = await Promise.all([
|
||||
readJobJson<AnalysisInput>(directory, "input.json"),
|
||||
readJobJson<Preview>(directory, "preview.json"),
|
||||
]);
|
||||
return { input, preview };
|
||||
}
|
||||
|
||||
async function launch(directory: string, phase: JobPhase): Promise<void> {
|
||||
const config = JSON.stringify({
|
||||
assets: environment.assetsPath,
|
||||
support: environment.supportPath,
|
||||
preferences: getPreferences(),
|
||||
});
|
||||
const child = spawn(process.execPath, [join(environment.assetsPath, "velum-project-worker.cjs"), directory, phase], {
|
||||
detached: true,
|
||||
stdio: ["pipe", "ignore", "ignore"],
|
||||
cwd: directory,
|
||||
});
|
||||
// Register a handler immediately, before doing any asynchronous filesystem IO.
|
||||
const started = new Promise<void>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("spawn", resolve);
|
||||
});
|
||||
child.stdin.on("error", () => undefined);
|
||||
try {
|
||||
await started;
|
||||
await writeJobJson(directory, "state.json", { phase, pid: child.pid,
|
||||
message: phase === "analysis" ? "Analyse startet" : "Ausgabe wird vorbereitet" });
|
||||
// Only the pipe receives credentials. Job metadata, logs and arguments are
|
||||
// safe to retain even after the window or worker closes.
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.stdin.once("error", reject);
|
||||
child.stdin.end(config, resolve);
|
||||
});
|
||||
} catch (error) {
|
||||
child.stdin.destroy();
|
||||
child.kill();
|
||||
throw error;
|
||||
} finally {
|
||||
child.unref();
|
||||
}
|
||||
}
|
||||
|
||||
export async function startProjectAnalysis(input: AnalysisInput): Promise<void> {
|
||||
const root = canonicalProjectPath(input.root);
|
||||
const directory = projectJobDirectory(root);
|
||||
await fs.mkdir(projectDataRoot(root), { recursive: true, mode: 0o700 });
|
||||
await fs.mkdir(directory, { mode: 0o700 });
|
||||
try {
|
||||
await writeJobJson(directory, "input.json", { ...input, root });
|
||||
await launch(directory, "analysis");
|
||||
} catch (error) {
|
||||
await writeJobJson(directory, "state.json", { phase: "error",
|
||||
message: "Der lokale Hintergrundprozess konnte nicht gestartet werden." });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function startProjectApply(root: string, decision: Decision): Promise<void> {
|
||||
const directory = projectJobDirectory(root);
|
||||
if ((await readProjectJob(root))?.phase !== "review") {
|
||||
throw new Error("Dieser Projektauftrag steht nicht mehr zur Prüfung bereit.");
|
||||
}
|
||||
// Exclusive creation prevents two windows from publishing the same review.
|
||||
await fs.writeFile(join(directory, "decision.json"), JSON.stringify(decision), { flag: "wx", mode: 0o600 });
|
||||
try {
|
||||
await launch(directory, "apply");
|
||||
} catch (error) {
|
||||
await fs.rm(join(directory, "decision.json"), { force: true });
|
||||
await writeJobJson(directory, "state.json", { phase: "review" });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function discardProjectJob(root: string): Promise<void> {
|
||||
const state = await readProjectJob(root);
|
||||
if (!state || state.phase === "analysis" || state.phase === "apply") {
|
||||
throw new Error("Der Hintergrundauftrag läuft noch.");
|
||||
}
|
||||
const directory = projectJobDirectory(root);
|
||||
if (state.phase === "review") {
|
||||
// Mutual exclusion with the review's Apply action.
|
||||
await fs.writeFile(join(directory, "decision.json"), "", { flag: "wx", mode: 0o600 });
|
||||
}
|
||||
await fs.rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
99
src/lib/project-text-mapping.ts
Normal file
99
src/lib/project-text-mapping.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import type { PlaceholderMapping, PseudonymizeResponse } from "../types";
|
||||
|
||||
type Analyze = (text: string, mapping: PlaceholderMapping, types: string[],
|
||||
masks: Record<string, string[]>) => Promise<PseudonymizeResponse>;
|
||||
|
||||
/** Keep project identities locally; the API sees only rules needed by this text. */
|
||||
export function projectTextAnalyzer(initial: PlaceholderMapping, analyze: Analyze): Analyze {
|
||||
const mapping: PlaceholderMapping = { ...initial };
|
||||
const identities = new Map<string, string>();
|
||||
const counters = new Map<string, number>();
|
||||
const identity = (type: string, original: string) => JSON.stringify([type, original.trim().toLowerCase()]);
|
||||
const roots = new Set(Object.values(initial).flatMap((entry) => entry.merged_into ? [entry.merged_into] : []));
|
||||
// Ordinary historical NER mappings do not force recognition. Only custom
|
||||
// terms and user-confirmed person aliases have recognition semantics.
|
||||
const rules: PlaceholderMapping = {};
|
||||
for (const [key, entry] of Object.entries(initial)) {
|
||||
identities.set(identity(entry.type, entry.original), key);
|
||||
const number = Number(key.replace(/[<>]/g, "").match(/_(\d+)$/)?.[1] ?? 0);
|
||||
counters.set(entry.type, Math.max(counters.get(entry.type) ?? 0, number));
|
||||
if (entry.type === "BEGRIFF" || entry.merged_into || roots.has(key)) rules[key] = entry;
|
||||
}
|
||||
const canonical = (key: string): string => {
|
||||
const seen = new Set<string>();
|
||||
while (mapping[key]?.merged_into) {
|
||||
if (seen.has(key)) throw new Error("Zyklische Personen-Zusammenführung.");
|
||||
seen.add(key);
|
||||
key = mapping[key].merged_into!;
|
||||
if (!mapping[key]) throw new Error("Ziel einer Personen-Zusammenführung fehlt.");
|
||||
}
|
||||
return key;
|
||||
};
|
||||
return async (text, _previous, types, masks) => {
|
||||
// Other project phases (for example Office analysis) may have extended
|
||||
// the mapping since the previous text request. Keep those identities too.
|
||||
if (_previous !== mapping) {
|
||||
const addedRoots = new Set(Object.values(_previous).flatMap((entry) => entry.merged_into ? [entry.merged_into] : []));
|
||||
for (const [key, entry] of Object.entries(_previous)) {
|
||||
if (mapping[key] && identity(mapping[key].type, mapping[key].original) !== identity(entry.type, entry.original)) {
|
||||
throw new Error("Widersprüchliche Platzhalter in der Projektzuordnung.");
|
||||
}
|
||||
mapping[key] = entry;
|
||||
identities.set(identity(entry.type, entry.original), key);
|
||||
const number = Number(key.replace(/[<>]/g, "").match(/_(\d+)$/)?.[1] ?? 0);
|
||||
counters.set(entry.type, Math.max(counters.get(entry.type) ?? 0, number));
|
||||
if (entry.type === "BEGRIFF" || entry.merged_into || addedRoots.has(key)) rules[key] = entry;
|
||||
}
|
||||
}
|
||||
const lower = text.toLowerCase().replace(/\s+/gu, " ");
|
||||
const window: PlaceholderMapping = {};
|
||||
for (const [key, entry] of Object.entries(rules)) {
|
||||
if (!lower.includes(entry.original.trim().toLowerCase().replace(/\s+/gu, " "))) continue;
|
||||
let dependency: string | null | undefined = key;
|
||||
const seen = new Set<string>();
|
||||
while (dependency) {
|
||||
if (seen.has(dependency) || !mapping[dependency]) throw new Error("Ungültige Personen-Zusammenführung.");
|
||||
seen.add(dependency);
|
||||
window[dependency] = mapping[dependency];
|
||||
dependency = mapping[dependency].merged_into;
|
||||
}
|
||||
}
|
||||
const response = await analyze(text, window, types, masks);
|
||||
const translated = new Map<string, string>();
|
||||
for (const [remote, entry] of Object.entries(response.mapping)) {
|
||||
const id = identity(entry.type, entry.original);
|
||||
let local = identities.get(id);
|
||||
if (!local) {
|
||||
const number = (counters.get(entry.type) ?? 0) + 1;
|
||||
counters.set(entry.type, number);
|
||||
local = `${entry.type}_${String(number).padStart(2, "0")}`;
|
||||
if (mapping[local]) throw new Error("Doppelte Platzhalternummer in der Projektzuordnung.");
|
||||
mapping[local] = { original: entry.original, type: entry.type };
|
||||
identities.set(id, local);
|
||||
if (entry.type === "BEGRIFF") rules[local] = mapping[local];
|
||||
}
|
||||
translated.set(remote, canonical(local));
|
||||
}
|
||||
const spans = response.spans.map((span) => {
|
||||
const placeholder = translated.get(span.placeholder);
|
||||
if (!placeholder) throw new Error("Velum-Treffer ohne passende Zuordnung.");
|
||||
return { ...span, placeholder };
|
||||
});
|
||||
// Rebuild from original positions so existing literal placeholders are
|
||||
// never accidentally renumbered alongside newly detected entities.
|
||||
const characters = Array.from(text);
|
||||
const pieces: string[] = [];
|
||||
let offset = 0;
|
||||
for (const span of [...spans].sort((a, b) => a.start - b.start)) {
|
||||
if (!Number.isInteger(span.start) || !Number.isInteger(span.end)
|
||||
|| span.start < offset || span.start >= span.end || span.end > characters.length) {
|
||||
throw new Error("Ungültige Trefferposition der Velum-API.");
|
||||
}
|
||||
pieces.push(characters.slice(offset, span.start).join(""), span.placeholder);
|
||||
offset = span.end;
|
||||
}
|
||||
pieces.push(characters.slice(offset).join(""));
|
||||
return { ...response, pseudonymized_text: pieces.join(""), mapping, spans,
|
||||
entity_count: identities.size };
|
||||
};
|
||||
}
|
||||
@@ -122,11 +122,22 @@ export async function writeReplacedTextFile(
|
||||
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");
|
||||
let fragments: string[] = [];
|
||||
let bufferedLength = 0;
|
||||
const flushOutput = async () => {
|
||||
if (!bufferedLength) return;
|
||||
const bytes = Buffer.from(fragments.join(""), "utf8");
|
||||
fragments = [];
|
||||
bufferedLength = 0;
|
||||
outputHash.update(bytes);
|
||||
await output.writeFile(bytes);
|
||||
};
|
||||
const write = async (text: string) => {
|
||||
if (!text) return;
|
||||
fragments.push(text);
|
||||
bufferedLength += text.length;
|
||||
if (bufferedLength >= 64 * 1024) await flushOutput();
|
||||
};
|
||||
let offset = 0;
|
||||
let pending = "";
|
||||
let index = 0;
|
||||
@@ -147,6 +158,7 @@ export async function writeReplacedTextFile(
|
||||
offset += flush;
|
||||
}
|
||||
if (index !== selected.length || pending) throw new Error("Trefferposition liegt außerhalb der Quelldatei.");
|
||||
await flushOutput();
|
||||
if (inputHash.digest("hex") !== expectedHash) throw new Error("Datei wurde seit der Vorschau geändert.");
|
||||
complete = true;
|
||||
return outputHash.digest("hex");
|
||||
|
||||
362
src/lib/project-work.ts
Normal file
362
src/lib/project-work.ts
Normal file
@@ -0,0 +1,362 @@
|
||||
import { constants as fsConstants, promises as fs } from "node:fs";
|
||||
import { basename, dirname, extname, join } from "node:path";
|
||||
import { pseudonymize, pseudonymizeDocument, requireProjectCapabilities } from "../velum";
|
||||
import type { DocumentHit } from "../velum";
|
||||
import type { EntityType, PlaceholderMapping } from "../types";
|
||||
import {
|
||||
createRun, digest, forceMasks, listRuns, loadProjectWhitelist, publishProjectCopies, replaceSpans,
|
||||
reusableProjectOutput, replaceProjectFilesInPlace, resolveWithin, safeRelativePath,
|
||||
saveProjectWhitelist, saveRun, sameEntityTypeCoverage, toUtf16Offsets,
|
||||
} from "./velum-project";
|
||||
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, RunFile, SkippedProjectFile } from "./velum-project";
|
||||
import {
|
||||
canonicalPerson, filenameScanText, makeTextBatches, mappingForSelection, reconcileDocumentHitIds, spansBySegment,
|
||||
withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
|
||||
} from "./project-review";
|
||||
import { analyzeProjectBatch, analyzeProjectTextFiles } from "./project-analysis";
|
||||
import { projectTextAnalyzer } from "./project-text-mapping";
|
||||
import { hashProjectFile, inspectTextFile, writeReplacedTextFile } from "./project-text-stream";
|
||||
import { checkedImageReport, sameImagePolicyCoverage, summarizeImages } from "./image-policy";
|
||||
import type { ImagePolicy, DocumentImageReport } from "./image-policy";
|
||||
import { inspectDocx, writeDocx } from "./local-docx";
|
||||
|
||||
export type Hit = {
|
||||
id: string; file: string; source: string; original: string; placeholder: string;
|
||||
type: string; score: number; context: string; start: number; end: number;
|
||||
kind: "content" | "path"; segment?: number;
|
||||
};
|
||||
type Draft = { file: ProjectFile; hash: string; hits: Hit[]; analysisMapping?: PlaceholderMapping; docxSegmentCount?: number };
|
||||
type PathDraft = { key: string; value: string; hits: Hit[] };
|
||||
export type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string; output: string; directory: string; imageReport?: DocumentImageReport; localDocx?: true }>;
|
||||
baseRunId?: string; paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping;
|
||||
matchModes?: Record<string, "token" | "anywhere">; hits: Hit[]; entityTypes: EntityType[];
|
||||
skipped: SkippedProjectFile[]; sourceInPlace: boolean; imagePolicy: ImagePolicy };
|
||||
|
||||
function isLocalDocx(file: ProjectFile): boolean {
|
||||
return file.kind === "document" && extname(file.relPath).toLowerCase() === ".docx";
|
||||
}
|
||||
|
||||
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 documentHits(file: ProjectFile, hits: DocumentHit[]): Hit[] {
|
||||
return hits.map((hit) => ({ ...hit, id: `${file.relPath}:document:${hit.id}`,
|
||||
file: file.relPath, kind: "content" as const }));
|
||||
}
|
||||
|
||||
function pathSegments(files: ProjectFile[]): PathDraft[] {
|
||||
const map = new Map<string, PathDraft>();
|
||||
for (const file of files) {
|
||||
const parts = file.relPath.split("/");
|
||||
for (let index = 0; index < parts.length; index++) {
|
||||
const key = parts.slice(0, index + 1).join("/");
|
||||
const isFile = index === parts.length - 1;
|
||||
const value = isFile ? basename(parts[index], extname(parts[index])) : parts[index];
|
||||
if (value && !map.has(key)) map.set(key, { key, value, hits: [] });
|
||||
}
|
||||
}
|
||||
return [...map.values()];
|
||||
}
|
||||
|
||||
export async function prepareProject(assets: string, root: string, files: ProjectFile[], rules: ProjectRule[], whitelist: ProjectWhitelistEntry[], entityTypes: EntityType[],
|
||||
skipped: SkippedProjectFile[], reanalyzeUnchanged: boolean,
|
||||
onProgress: (message: string) => void, imagePolicy: ImagePolicy): Promise<Preview> {
|
||||
await requireProjectCapabilities(files.some((file) => file.kind === "document" && !isLocalDocx(file)));
|
||||
const masks = forceMasks(withoutWhitelistedRules(rules, whitelist));
|
||||
const latestEntry = (await listRuns(root))[0];
|
||||
const latest = latestEntry?.run;
|
||||
const categoryCoverageChanged = Boolean(latest && !sameEntityTypeCoverage(latest, entityTypes));
|
||||
if (categoryCoverageChanged) onProgress("Kategorien geändert oder alter Stand: Dateien erneut analysieren");
|
||||
const previousMapping: PlaceholderMapping = latest?.mapping ?? {};
|
||||
const previousPlaceholders = Object.keys(previousMapping);
|
||||
let mapping: PlaceholderMapping = previousMapping;
|
||||
const drafts: Draft[] = [];
|
||||
const retained: Preview["retained"] = [];
|
||||
const hits: Hit[] = [];
|
||||
const sourceInPlace = Boolean(latest?.inPlace || latest?.sourceInPlace);
|
||||
const previousDirectory = latestEntry?.directory;
|
||||
for (const file of files) {
|
||||
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;
|
||||
}
|
||||
const imageCoverageMatches = file.kind !== "document" || sameImagePolicyCoverage(latest, imagePolicy);
|
||||
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && imageCoverageMatches && latest && previousDirectory
|
||||
? await reusableProjectOutput(latest, previousDirectory, file.relPath, hash) : undefined;
|
||||
const previousFile = latest?.files.find((saved) => saved.output === previousOutput);
|
||||
if (previousOutput && previousDirectory && (!isLocalDocx(file) || previousFile?.localDocx)) {
|
||||
retained.push({ file, hash, output: previousOutput, directory: previousDirectory,
|
||||
imageReport: previousFile?.imageReport, localDocx: previousFile?.localDocx });
|
||||
continue;
|
||||
}
|
||||
const draft: Draft = { file, hash, hits: [] };
|
||||
drafts.push(draft);
|
||||
}
|
||||
const addHits = (draft: Draft, found: Hit[]) => {
|
||||
draft.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
||||
for (const hit of draft.hits) hits.push(hit);
|
||||
};
|
||||
const textDrafts = drafts.filter((draft) => draft.file.kind === "text");
|
||||
const analyzeText = projectTextAnalyzer(mapping, 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 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) => Object.assign(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()) {
|
||||
onProgress(`Dokumente analysieren: ${index + 1}/${documents.length}`);
|
||||
try {
|
||||
if (isLocalDocx(draft.file)) {
|
||||
const result = await inspectDocx(assets, draft.file.absPath, draft.file.relPath, draft.hash,
|
||||
imagePolicy, mapping, entityTypes, masks, onProgress);
|
||||
mapping = result.mapping;
|
||||
draft.docxSegmentCount = result.segmentCount;
|
||||
addHits(draft, result.hits);
|
||||
continue;
|
||||
}
|
||||
const data = await fs.readFile(draft.file.absPath);
|
||||
draft.analysisMapping = mapping;
|
||||
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) {
|
||||
if (isLocalDocx(draft.file) || !isUnreadableDocument(error)) {
|
||||
throw new Error(`${draft.file.relPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
skipped.push({ path: draft.file.relPath, reason: "Office-/PDF-Inhalt konnte nicht gelesen werden" });
|
||||
drafts.splice(drafts.indexOf(draft), 1);
|
||||
}
|
||||
}
|
||||
// Names of retained files already have a reviewed output in the saved stand.
|
||||
// Only new or changed files need another filename analysis.
|
||||
if (!drafts.length && !retained.length) {
|
||||
const first = skipped[0];
|
||||
throw new Error(`Keine lesbaren Dateien im Projektordner gefunden.${first ? ` Übersprungen: ${first.path} (${first.reason}).` : ""}`);
|
||||
}
|
||||
const paths = pathSegments(drafts.map((draft) => draft.file));
|
||||
const knownTerms = [...Object.keys(mapping), ...Object.values(mapping).map((entry) => entry.original),
|
||||
...withoutWhitelistedRules(rules, whitelist).map((rule) => rule.value)];
|
||||
const pathBatches = makeTextBatches(paths.map((path) => ({
|
||||
key: path.key, text: filenameScanText(path.value, knownTerms),
|
||||
})));
|
||||
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, analyzeText,
|
||||
"Dateinamen analysieren");
|
||||
mapping = analyzed.mapping;
|
||||
for (const { batch: part, result } of analyzed.results) {
|
||||
const spans = spansBySegment(part, result.spans);
|
||||
for (const segment of part.segments) {
|
||||
const path = byPath.get(segment.key)!;
|
||||
const found = toUtf16Offsets(segment.text, spans.get(path.key) ?? []).map((span, hitIndex) => ({
|
||||
...span, id: `${path.key}:path:${hitIndex}`, file: path.key,
|
||||
source: "Datei- oder Ordnername", kind: "path" as const,
|
||||
context: path.value,
|
||||
}));
|
||||
path.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
||||
for (const hit of path.hits) hits.push(hit);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { drafts, retained, paths, mapping, previousMapping, baseRunId: latest?.id,
|
||||
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace, imagePolicy };
|
||||
}
|
||||
|
||||
function outputPath(relPath: string, paths: PathDraft[], accepted: Set<string>, document: boolean,
|
||||
merges: Record<string, string>): string {
|
||||
const lookup = new Map(paths.map((item) => [item.key, item]));
|
||||
const parts = relPath.split("/");
|
||||
const output = parts.map((part, index) => {
|
||||
const key = parts.slice(0, index + 1).join("/");
|
||||
const path = lookup.get(key);
|
||||
if (!path) return part;
|
||||
const isFile = index === parts.length - 1;
|
||||
const extension = isFile ? (document && extname(part).toLowerCase() === ".pdf" ? ".docx" : extname(part)) : "";
|
||||
return replaceSpans(path.value, withPersonMerges(path.hits, merges), accepted) + extension;
|
||||
});
|
||||
return safeRelativePath(output.join("/"));
|
||||
}
|
||||
|
||||
function withPersonMerges(hits: Hit[], merges: Record<string, string>): Hit[] {
|
||||
return hits.map((hit) => hit.type === "PERSON"
|
||||
? { ...hit, placeholder: canonicalPerson(hit.placeholder, merges) } : hit);
|
||||
}
|
||||
|
||||
export type ProjectOutput = {
|
||||
directory: string; inPlace: boolean; files: number; replaced: number;
|
||||
images: ReturnType<typeof summarizeImages>;
|
||||
};
|
||||
|
||||
export async function applyProject(
|
||||
assets: string, root: string, preview: Preview, rules: ProjectRule[], whitelist: ProjectWhitelistEntry[],
|
||||
decision: { inPlace: boolean; acceptedIds: string[]; activeMerges: Record<string, string>; rejected: ProjectWhitelistEntry[] },
|
||||
progress: (message: string) => void,
|
||||
): Promise<ProjectOutput> {
|
||||
const { inPlace, acceptedIds, activeMerges, rejected } = decision;
|
||||
const accepted = new Set(acceptedIds);
|
||||
const acceptedHits = preview.hits.filter((hit) => accepted.has(hit.id));
|
||||
if (acceptedHits.length !== accepted.size) throw new Error("Die Auswahl passt nicht mehr zur gespeicherten Vorschau.");
|
||||
let directory: string | undefined;
|
||||
let publishedCopyPath: string | undefined;
|
||||
let persisted = false;
|
||||
let keepRecoveryDirectory = false;
|
||||
try {
|
||||
if ((await listRuns(root))[0]?.run.id !== preview.baseRunId) {
|
||||
throw new Error("Seit der Vorschau wurde ein neuer Projektstand gespeichert. Bitte erneut analysieren.");
|
||||
}
|
||||
const created = await createRun(root);
|
||||
directory = created.directory;
|
||||
const { run } = created;
|
||||
run.mapping = mappingForSelection(preview.mapping, preview.previousMapping,
|
||||
acceptedHits, activeMerges);
|
||||
run.entityTypes = [...preview.entityTypes];
|
||||
run.imagePolicy = preview.imagePolicy;
|
||||
run.sourceState = {};
|
||||
run.commentAuthorCoverage = preview.entityTypes.includes("PERSON");
|
||||
run.reviewAuthorCoverage = preview.entityTypes.includes("PERSON");
|
||||
run.matchModes = preview.matchModes;
|
||||
run.sourceInPlace = preview.sourceInPlace || inPlace;
|
||||
const usedPaths = new Set<string>();
|
||||
const replacements: RunFile[] = [];
|
||||
const sources = new Map<string, string>();
|
||||
const total = preview.retained.length + preview.drafts.length;
|
||||
let processed = 0;
|
||||
for (const retained of preview.retained) {
|
||||
progress(`Ausgaben vorbereiten: ${++processed}/${total}`);
|
||||
sources.set(retained.file.relPath, retained.hash);
|
||||
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);
|
||||
const target = resolveWithin(join(directory, "files"), relPath);
|
||||
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||
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, imageReport: retained.imageReport, localDocx: retained.localDocx };
|
||||
run.files.push(file);
|
||||
run.sourceState[inPlace ? relPath : file.source] = {
|
||||
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 && !preview.sourceInPlace)) replacements.push(file);
|
||||
}
|
||||
for (const draft of preview.drafts) {
|
||||
progress(`Ausgaben vorbereiten: ${++processed}/${total}`);
|
||||
sources.set(draft.file.relPath, draft.hash);
|
||||
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, 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 outputHash: string;
|
||||
let imageReport: DocumentImageReport | undefined;
|
||||
if (draft.docxSegmentCount !== undefined) {
|
||||
imageReport = await writeDocx(assets, draft.file.absPath, target, draft.hash, preview.imagePolicy,
|
||||
draft.docxSegmentCount, withPersonMerges(draft.hits, activeMerges), accepted);
|
||||
outputHash = await hashProjectFile(target);
|
||||
} else 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));
|
||||
const masks = forceMasks(withoutWhitelistedRules(rules, whitelist));
|
||||
let result;
|
||||
try {
|
||||
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||
masks, docIds, preview.entityTypes, draft.analysisMapping, 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, preview.entityTypes, undefined, 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, preview.entityTypes, run.mapping, preview.imagePolicy);
|
||||
}
|
||||
const selectedIds = new Set(docIds);
|
||||
const selectedHits = result.hits.filter((hit) => selectedIds.has(hit.id));
|
||||
if (selectedHits.length !== selectedIds.size || selectedHits.some((hit) => !Object.entries(run.mapping)
|
||||
.some(([placeholder, entry]) => entry.type === hit.type
|
||||
&& entry.original.toLocaleLowerCase() === hit.original.toLocaleLowerCase()
|
||||
&& (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.`);
|
||||
}
|
||||
imageReport = checkedImageReport(result, preview.imagePolicy);
|
||||
const output = Buffer.from(result.file_base64, "base64");
|
||||
await fs.writeFile(target, output, { mode: 0o600 });
|
||||
outputHash = digest(output);
|
||||
} else {
|
||||
outputHash = await writeReplacedTextFile(draft.file.absPath, target,
|
||||
withPersonMerges(draft.hits, activeMerges), accepted, draft.hash);
|
||||
}
|
||||
const file: RunFile = { source: draft.file.relPath, output: relPath, kind: draft.file.kind, imageReport,
|
||||
localDocx: draft.docxSegmentCount !== undefined ? true : undefined };
|
||||
run.files.push(file);
|
||||
run.sourceState[inPlace ? relPath : file.source] = {
|
||||
hash: inPlace ? outputHash : draft.hash, output: relPath,
|
||||
};
|
||||
replacements.push(file);
|
||||
}
|
||||
if ((await listRuns(root))[0]?.run.id !== preview.baseRunId) {
|
||||
throw new Error("Seit der Vorschau wurde ein neuer Projektstand gespeichert. Bitte erneut analysieren.");
|
||||
}
|
||||
if (!inPlace) {
|
||||
publishedCopyPath = await publishProjectCopies(run, directory);
|
||||
run.copyPath = publishedCopyPath;
|
||||
}
|
||||
if (inPlace) {
|
||||
if (replacements.length) {
|
||||
// Keep recoverable files if an interrupted replacement needs its backup.
|
||||
keepRecoveryDirectory = true;
|
||||
await replaceProjectFilesInPlace(root, directory, replacements, sources);
|
||||
}
|
||||
run.inPlace = true;
|
||||
}
|
||||
await saveRun(directory, run);
|
||||
persisted = true;
|
||||
if (rejected.length) {
|
||||
const nextWhitelist = [...await loadProjectWhitelist(root), ...rejected];
|
||||
await saveProjectWhitelist(root, nextWhitelist);
|
||||
}
|
||||
return { directory: inPlace && replacements.length ? join(directory, "backup")
|
||||
: inPlace ? root : publishedCopyPath!, inPlace, files: run.files.length,
|
||||
replaced: replacements.length, images: summarizeImages(run.files) };
|
||||
} catch (error) {
|
||||
if (directory && !persisted && !keepRecoveryDirectory) await fs.rm(directory, { recursive: true, force: true });
|
||||
if (publishedCopyPath && !persisted) await fs.rm(publishedCopyPath, { recursive: true, force: true });
|
||||
throw new Error(`${(error as Error).message}${(persisted || keepRecoveryDirectory) && directory ? ` Kopien/Sicherung: ${directory}` : ""}`, { cause: error });
|
||||
}
|
||||
}
|
||||
@@ -16,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"]; imageReport?: DocumentImageReport };
|
||||
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"]; imageReport?: DocumentImageReport; localDocx?: true };
|
||||
export type ProjectRun = {
|
||||
version: 2;
|
||||
origin?: "direct" | "imported";
|
||||
@@ -236,7 +236,7 @@ export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
|
||||
}
|
||||
|
||||
export async function scanProjectFiles(root: string, maxSize?: number,
|
||||
validateText = true): Promise<{
|
||||
validateText = true, documentLimits: Readonly<Record<string, number>> = {}): Promise<{
|
||||
files: ProjectFile[]; skipped: SkippedProjectFile[];
|
||||
}> {
|
||||
const files: ProjectFile[] = [];
|
||||
@@ -263,7 +263,8 @@ export async function scanProjectFiles(root: string, maxSize?: number,
|
||||
}
|
||||
const stat = await fs.stat(path);
|
||||
const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text";
|
||||
const limit = maxSize ?? (kind === "document" ? 20 * 1024 * 1024 : Number.POSITIVE_INFINITY);
|
||||
const limit = maxSize ?? (kind === "document"
|
||||
? documentLimits[extname(path).toLowerCase()] ?? 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)");
|
||||
@@ -533,7 +534,8 @@ export async function scanRestorableCopyFiles(run: ProjectRun, directory: string
|
||||
root = join(directory, "files");
|
||||
}
|
||||
}
|
||||
const scan = await scanProjectFiles(root);
|
||||
// XLSX restoration runs locally as a stream and does not upload the file.
|
||||
const scan = await scanProjectFiles(root, undefined, true, { ".xlsx": Number.POSITIVE_INFINITY });
|
||||
const files = scan.files.filter((file) => file.kind === "text" || isRestorableDocument(file.relPath));
|
||||
return { root, files, skipped: scan.skipped.length + scan.files.length - files.length };
|
||||
}
|
||||
|
||||
21
src/lib/worker-runtime.ts
Normal file
21
src/lib/worker-runtime.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { NormalizedPreferences } from "../preferences";
|
||||
|
||||
// Only these Raycast services are used by the shared Node project code.
|
||||
export const environment = { assetsPath: "", supportPath: "" };
|
||||
let preferences: NormalizedPreferences;
|
||||
export function getPreferenceValues<T>(): T {
|
||||
return preferences as T;
|
||||
}
|
||||
|
||||
const tokenStore = new Map<string, string>();
|
||||
export const LocalStorage = {
|
||||
async getItem<T>(key: string) { return tokenStore.get(key) as T | undefined; },
|
||||
async setItem(key: string, value: string) { tokenStore.set(key, value); },
|
||||
async removeItem(key: string) { tokenStore.delete(key); },
|
||||
};
|
||||
|
||||
export function configureWorker(config: { assets: string; support: string; preferences: NormalizedPreferences }) {
|
||||
environment.assetsPath = config.assets;
|
||||
environment.supportPath = config.support;
|
||||
preferences = config.preferences;
|
||||
}
|
||||
274
src/lib/xlsx-restoration.ts
Normal file
274
src/lib/xlsx-restoration.ts
Normal file
@@ -0,0 +1,274 @@
|
||||
import { createReadStream, closeSync, openSync, writeSync, promises as fs } from "node:fs";
|
||||
import { join, posix } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { TextDecoder } from "node:util";
|
||||
import { Unzip, UnzipInflate, Zip, ZipDeflate } from "fflate";
|
||||
import { SaxesParser, type SaxesTagNS } from "saxes";
|
||||
import type { PlaceholderMapping } from "../types";
|
||||
|
||||
const EMPTY = new Uint8Array(0);
|
||||
const SPREADSHEET = new Set([
|
||||
"http://schemas.openxmlformats.org/spreadsheetml/2006/main",
|
||||
"http://purl.oclc.org/ooxml/spreadsheetml/main",
|
||||
]);
|
||||
const DRAWING = new Set([
|
||||
"http://schemas.openxmlformats.org/drawingml/2006/main",
|
||||
"http://purl.oclc.org/ooxml/drawingml/main",
|
||||
]);
|
||||
const WORD = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
const isTextRun = (node: SaxesTagNS) => node.local === "t" && (SPREADSHEET.has(node.uri) || DRAWING.has(node.uri) || node.uri === WORD);
|
||||
const isTextUnit = (node: SaxesTagNS) => SPREADSHEET.has(node.uri) && ["si", "is"].includes(node.local)
|
||||
|| node.local === "p" && (DRAWING.has(node.uri) || node.uri === WORD);
|
||||
const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, index) => {
|
||||
let value = index;
|
||||
for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ (value & 1 ? 0xedb88320 : 0);
|
||||
return value >>> 0;
|
||||
});
|
||||
function crcUpdate(crc: number, data: Uint8Array): number {
|
||||
for (const value of data) crc = (crc >>> 8) ^ CRC_TABLE[(crc ^ value) & 255];
|
||||
return crc;
|
||||
}
|
||||
type ZipPart = { size: number; crc: number };
|
||||
|
||||
/** Inspect the small central directory; never load a worksheet or the whole ZIP. */
|
||||
async function zipIndex(path: string): Promise<Map<string, ZipPart>> {
|
||||
const file = await fs.open(path, "r");
|
||||
try {
|
||||
const { size } = await file.stat();
|
||||
const tail = Buffer.alloc(Math.min(size, 65_557));
|
||||
await file.read(tail, 0, tail.length, size - tail.length);
|
||||
let end = -1;
|
||||
for (let i = tail.length - 22; i >= 0; i--) {
|
||||
if (tail.readUInt32LE(i) === 0x06054b50 && i + 22 + tail.readUInt16LE(i + 20) === tail.length) { end = i; break; }
|
||||
}
|
||||
if (end < 0) throw new Error("Excel-Datei ist kein vollständiges ZIP-Archiv.");
|
||||
const entries = tail.readUInt16LE(end + 10);
|
||||
const length = tail.readUInt32LE(end + 12), offset = tail.readUInt32LE(end + 16);
|
||||
if (tail.readUInt16LE(end + 4) || tail.readUInt16LE(end + 6) || entries !== tail.readUInt16LE(end + 8)
|
||||
|| entries === 0xffff || offset === 0xffffffff || length > 16 * 1024 * 1024 || offset + length > size - tail.length + end) {
|
||||
throw new Error("Nicht unterstütztes Excel-ZIP-Archiv (mehrteilig, ZIP64 oder zu großes Inhaltsverzeichnis).");
|
||||
}
|
||||
const directory = Buffer.alloc(length);
|
||||
if ((await file.read(directory, 0, length, offset)).bytesRead !== length) throw new Error("Unvollständiges ZIP-Inhaltsverzeichnis.");
|
||||
const parts = new Map<string, ZipPart>();
|
||||
let cursor = 0, total = 0;
|
||||
for (let index = 0; index < entries; index++) {
|
||||
if (cursor + 46 > length || directory.readUInt32LE(cursor) !== 0x02014b50) throw new Error("Ungültiges ZIP-Inhaltsverzeichnis.");
|
||||
const flags = directory.readUInt16LE(cursor + 8), method = directory.readUInt16LE(cursor + 10);
|
||||
const nameLength = directory.readUInt16LE(cursor + 28);
|
||||
const next = cursor + 46 + nameLength + directory.readUInt16LE(cursor + 30) + directory.readUInt16LE(cursor + 32);
|
||||
if (next > length || flags & 1 || ![0, 8].includes(method)) throw new Error("Verschlüsselte oder nicht unterstützte Excel-Datei.");
|
||||
const rawName = directory.subarray(cursor + 46, cursor + 46 + nameLength);
|
||||
if (!(flags & 0x800) && rawName.some((value) => value > 127)) throw new Error("Nicht unterstützte ZIP-Dateinamencodierung.");
|
||||
const name = new TextDecoder("utf-8", { fatal: true }).decode(rawName);
|
||||
if (parts.has(name) || name.startsWith("/") || name.includes("\\")
|
||||
|| posix.normalize(name) !== name || name.split("/").includes("..")) throw new Error("Ungültiger oder doppelter Excel-Paketbestandteil.");
|
||||
const part = { size: directory.readUInt32LE(cursor + 24), crc: directory.readUInt32LE(cursor + 16) };
|
||||
total += part.size;
|
||||
if (part.size === 0xffffffff || total > 2 * 1024 * 1024 * 1024) throw new Error("Entpackte Excel-Datei überschreitet 2 GiB.");
|
||||
parts.set(name, part);
|
||||
cursor = next;
|
||||
}
|
||||
if (cursor !== length || !parts.has("xl/workbook.xml") || !parts.has("[Content_Types].xml")) throw new Error("Datei ist kein unterstütztes Excel-Workbook.");
|
||||
return parts;
|
||||
} finally { await file.close(); }
|
||||
}
|
||||
|
||||
function escapeXml(value: string, attribute = false): string {
|
||||
let result = value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\r/g, " ");
|
||||
if (attribute) result = result.replace(/"/g, """).replace(/\t/g, "	").replace(/\n/g, " ");
|
||||
return result;
|
||||
}
|
||||
function restorationPattern(mapping: PlaceholderMapping) {
|
||||
const originals = new Map<string, string>();
|
||||
for (const [key, entry] of Object.entries(mapping)) {
|
||||
for (const char of entry.original) {
|
||||
const code = char.codePointAt(0)!;
|
||||
if ((code < 32 && ![9, 10, 13].includes(code)) || (code >= 0xd800 && code <= 0xdfff) || code === 0xfffe || code === 0xffff) {
|
||||
throw new Error("Zuordnung enthält Zeichen, die in Excel-XML nicht erlaubt sind.");
|
||||
}
|
||||
}
|
||||
originals.set(key, entry.original);
|
||||
}
|
||||
const keys = [...originals.keys()].filter((key) => key && !/^[A-Z][A-Z0-9]*_\d+$/.test(key)).sort((a, b) => b.length - a.length);
|
||||
const alternatives = keys.map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
||||
alternatives.push("[A-Z][A-Z0-9]*_\\d+");
|
||||
const pattern = originals.size ? new RegExp(`(?<![\\p{L}\\p{N}_])(?:${alternatives.join("|")})(?![\\p{L}\\p{N}_])`, "gu") : undefined;
|
||||
return { originals, pattern };
|
||||
}
|
||||
type Token = { markup: string } | { text: string; run: boolean };
|
||||
|
||||
/** Buffer one rich-text cell or drawing paragraph, never a table or worksheet. */
|
||||
function xmlRestorer(mapping: ReturnType<typeof restorationPattern>, emit: (text: string) => void, workbook: boolean) {
|
||||
let replacements = 0;
|
||||
const restore = (text: string) => mapping.pattern ? text.replace(mapping.pattern, (match) => {
|
||||
const original = mapping.originals.get(match);
|
||||
if (original === undefined) return match;
|
||||
replacements++;
|
||||
return original;
|
||||
}) : text;
|
||||
const parser = new SaxesParser({ xmlns: true });
|
||||
const stack: SaxesTagNS[] = [];
|
||||
let cell: { depth: number; tokens: Token[]; length: number } | undefined;
|
||||
let pending = "";
|
||||
const append = (token: Token) => {
|
||||
if (!cell) { emit("markup" in token ? token.markup : escapeXml(restore(token.text))); return; }
|
||||
cell.length += "markup" in token ? token.markup.length : token.text.length;
|
||||
if (cell.length > 4 * 1024 * 1024) throw new Error("Eine einzelne Excel-Zelle überschreitet 4 MiB XML.");
|
||||
cell.tokens.push(token);
|
||||
};
|
||||
const flushText = () => {
|
||||
if (!pending) return;
|
||||
const node = stack.at(-1);
|
||||
append({ text: pending, run: Boolean(node && isTextRun(node)) });
|
||||
pending = "";
|
||||
};
|
||||
const flushCell = () => {
|
||||
const tokens = cell!.tokens;
|
||||
const runs = tokens.filter((token): token is Extract<Token, { text: string }> => "text" in token && token.run);
|
||||
const joined = runs.map((run) => run.text).join("");
|
||||
const matches = mapping.pattern ? [...joined.matchAll(mapping.pattern)].filter((match) => mapping.originals.has(match[0])) : [];
|
||||
replacements += matches.length;
|
||||
let offset = 0, next = 0;
|
||||
for (const run of runs) {
|
||||
const start = offset, end = start + run.text.length;
|
||||
let cursor = 0, output = "";
|
||||
while (next < matches.length && matches[next].index + matches[next][0].length <= start) next++;
|
||||
for (let i = next; i < matches.length && matches[i].index < end; i++) {
|
||||
const match = matches[i], stop = match.index + match[0].length;
|
||||
output += run.text.slice(cursor, Math.max(cursor, match.index - start));
|
||||
if (match.index >= start) output += mapping.originals.get(match[0])!;
|
||||
cursor = Math.min(run.text.length, stop - start);
|
||||
}
|
||||
run.text = output + run.text.slice(cursor);
|
||||
offset = end;
|
||||
}
|
||||
for (const token of tokens) emit("markup" in token ? token.markup : escapeXml(token.run ? token.text : restore(token.text)));
|
||||
cell = undefined;
|
||||
};
|
||||
parser.on("xmldecl", (declaration) => {
|
||||
if (declaration.version !== "1.0") throw new Error("Nur XML 1.0 wird in Excel-Dateien unterstützt.");
|
||||
});
|
||||
parser.on("doctype", () => { throw new Error("DTD/Entities werden in Excel-Dateien nicht unterstützt."); });
|
||||
parser.on("opentag", (node) => {
|
||||
flushText();
|
||||
if (!stack.length && workbook && (!SPREADSHEET.has(node.uri) || node.local !== "workbook")) throw new Error("Ungültiger Excel-Workbook-Bestandteil.");
|
||||
stack.push(node);
|
||||
if (!cell && isTextUnit(node)) cell = { depth: stack.length, tokens: [], length: 0 };
|
||||
const attributes = Object.values(node.attributes).map((attr) => ` ${attr.name}="${escapeXml(restore(attr.value), true)}"`).join("");
|
||||
const preserve = SPREADSHEET.has(node.uri) && node.local === "t" && !node.attributes["xml:space"] ? ' xml:space="preserve"' : "";
|
||||
append({ markup: `<${node.name}${attributes}${preserve}>` });
|
||||
});
|
||||
parser.on("closetag", (node) => {
|
||||
flushText();
|
||||
append({ markup: `</${node.name}>` });
|
||||
if (cell?.depth === stack.length) flushCell();
|
||||
stack.pop();
|
||||
});
|
||||
const text = (value: string) => {
|
||||
pending += value;
|
||||
if (pending.length > 4 * 1024 * 1024) throw new Error("Ein Excel-Textknoten überschreitet 4 MiB.");
|
||||
};
|
||||
parser.on("text", text);
|
||||
parser.on("cdata", text);
|
||||
parser.on("comment", (value) => { flushText(); append({ markup: `<!--${value}-->` }); });
|
||||
parser.on("processinginstruction", (value) => { flushText(); append({ markup: `<?${value.target}${value.body ? " " + value.body : ""}?>` }); });
|
||||
emit('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>');
|
||||
return { push: (text: string) => parser.write(text), end: () => { parser.close(); flushText(); return replacements; } };
|
||||
}
|
||||
|
||||
/** Restore an XLSX directly from disk to a new private file, with bounded XML memory. */
|
||||
export async function restoreXlsxFile(source: string, target: string, mapping: PlaceholderMapping,
|
||||
onProgress: (percent: number) => void = () => undefined): Promise<{ replacements: number }> {
|
||||
const before = await fs.stat(source);
|
||||
const index = await zipIndex(source);
|
||||
const matcher = restorationPattern(mapping);
|
||||
const descriptor = openSync(target, "wx", 0o600);
|
||||
let complete = false, zipComplete = false, replacements = 0, processed = 0, progress = -1;
|
||||
const seen = new Set<string>(), finished = new Set<string>();
|
||||
const total = [...index.values()].reduce((sum, part) => sum + part.size, 0);
|
||||
const zip = new Zip((error, data, final) => {
|
||||
if (error) throw error;
|
||||
let offset = 0;
|
||||
while (offset < data.length) offset += writeSync(descriptor, data, offset, data.length - offset);
|
||||
if (final) zipComplete = true;
|
||||
});
|
||||
try {
|
||||
const unzip = new Unzip((file) => {
|
||||
const expected = index.get(file.name);
|
||||
if (!expected || seen.has(file.name)) throw new Error("Excel-ZIP-Inhaltsverzeichnis stimmt nicht mit den Paketdaten überein.");
|
||||
seen.add(file.name);
|
||||
const output = new ZipDeflate(file.name, { level: 4 });
|
||||
zip.add(output);
|
||||
let crc = 0xffffffff, size = 0;
|
||||
let fragments: string[] = [], length = 0;
|
||||
const flush = () => {
|
||||
if (!length) return;
|
||||
output.push(Buffer.from(fragments.join(""), "utf8"));
|
||||
fragments = []; length = 0;
|
||||
};
|
||||
const xml = /\.(xml|rels)$/i.test(file.name) ? xmlRestorer(matcher, (value) => {
|
||||
fragments.push(value); length += value.length;
|
||||
if (length >= 64 * 1024) flush();
|
||||
}, file.name === "xl/workbook.xml") : undefined;
|
||||
let decoder: TextDecoder | undefined, header = Buffer.alloc(0);
|
||||
const decode = (data: Uint8Array, final: boolean) => {
|
||||
if (!decoder) {
|
||||
header = Buffer.concat([header, data]);
|
||||
if (header.length < 4 && !final) return;
|
||||
const encoding = header[0] === 0xff && header[1] === 0xfe || header[0] === 0x3c && header[1] === 0 ? "utf-16le"
|
||||
: header[0] === 0xfe && header[1] === 0xff || header[0] === 0 && header[1] === 0x3c ? "utf-16be" : "utf-8";
|
||||
decoder = new TextDecoder(encoding, { fatal: true });
|
||||
data = header; header = Buffer.alloc(0);
|
||||
}
|
||||
xml!.push(decoder.decode(data, { stream: !final }));
|
||||
};
|
||||
file.ondata = (error, data, final) => {
|
||||
if (error) throw error;
|
||||
size += data.length;
|
||||
if (size > expected.size) throw new Error("Excel-Paketbestandteil überschreitet seine angegebene Größe.");
|
||||
crc = crcUpdate(crc, data);
|
||||
for (let offset = 0; offset < data.length; offset += 64 * 1024) {
|
||||
const part = data.subarray(offset, offset + 64 * 1024);
|
||||
if (xml) decode(part, false); else output.push(part);
|
||||
}
|
||||
processed += data.length;
|
||||
const percent = Math.floor(processed * 100 / Math.max(total, 1));
|
||||
if (percent !== progress) { progress = percent; onProgress(percent); }
|
||||
if (final) {
|
||||
if (size !== expected.size || ((crc ^ 0xffffffff) >>> 0) !== expected.crc) throw new Error("Excel-Paketbestandteil ist beschädigt (Größe/CRC).");
|
||||
if (xml) { decode(EMPTY, true); replacements += xml.end(); flush(); }
|
||||
output.push(EMPTY, true);
|
||||
finished.add(file.name);
|
||||
}
|
||||
};
|
||||
file.start();
|
||||
});
|
||||
unzip.register(UnzipInflate);
|
||||
for await (const data of createReadStream(source, { highWaterMark: 16 * 1024 })) unzip.push(data, false);
|
||||
unzip.push(EMPTY, true);
|
||||
if (finished.size !== index.size) throw new Error("Excel-ZIP-Archiv ist unvollständig.");
|
||||
zip.end();
|
||||
if (!zipComplete) throw new Error("Excel-Ausgabedatei wurde nicht vollständig geschrieben.");
|
||||
const after = await fs.stat(source);
|
||||
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino) throw new Error("Excel-Datei wurde während der Wiederherstellung geändert.");
|
||||
complete = true;
|
||||
return { replacements };
|
||||
} finally {
|
||||
zip.terminate();
|
||||
closeSync(descriptor);
|
||||
if (!complete) await fs.rm(target, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Compatibility for callers already holding an Office document in memory. */
|
||||
export async function restoreXlsxBuffer(data: Buffer, mapping: PlaceholderMapping): Promise<Buffer> {
|
||||
const directory = await fs.mkdtemp(join(tmpdir(), "velum-xlsx-restore-"));
|
||||
try {
|
||||
const source = join(directory, "source.xlsx"), target = join(directory, "restored.xlsx");
|
||||
await fs.writeFile(source, data, { mode: 0o600 });
|
||||
await restoreXlsxFile(source, target, mapping);
|
||||
return await fs.readFile(target);
|
||||
} finally { await fs.rm(directory, { recursive: true, force: true }); }
|
||||
}
|
||||
45
src/project-relocation-form.tsx
Normal file
45
src/project-relocation-form.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Action, ActionPanel, confirmAlert, Form, Icon, showToast, Toast, useNavigation } from "@raycast/api";
|
||||
import { useState } from "react";
|
||||
import { relocateProject } from "./lib/project-relocation";
|
||||
|
||||
export function RelocateProjectForm(props: { projectName: string; oldPath: string; onMoved: () => Promise<void> }) {
|
||||
const { pop } = useNavigation();
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function save(values: { newPath: string[] }) {
|
||||
const newPath = values.newPath?.[0];
|
||||
if (!newPath) {
|
||||
await showToast({ style: Toast.Style.Failure, title: "Bitte den neuen Projektordner wählen" });
|
||||
return;
|
||||
}
|
||||
if (!(await confirmAlert({
|
||||
title: "Projektordner aktualisieren?",
|
||||
message: `Alle gespeicherten Projektstände und Regeln werden künftig ${newPath} zugeordnet. `
|
||||
+ `Bisheriger Pfad: ${props.oldPath}. Die Dateien im gewählten Ordner werden nicht verändert.`,
|
||||
primaryAction: { title: "Projektpfad aktualisieren" },
|
||||
}))) return;
|
||||
setBusy(true);
|
||||
const toast = await showToast({ style: Toast.Style.Animated, title: "Projektpfad wird aktualisiert" });
|
||||
try {
|
||||
const result = await relocateProject(props.oldPath, newPath);
|
||||
await props.onMoved();
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = "Projektordner aktualisiert";
|
||||
toast.message = `${result.runsMoved} Projektstände übernommen`
|
||||
+ (result.copiesRelinked ? ` · ${result.copiesRelinked} Kopienordner neu gefunden` : "")
|
||||
+ (result.copiesMissing ? ` · ${result.copiesMissing} Kopienordner nicht gefunden; gespeicherte Stände bleiben verfügbar` : "");
|
||||
pop();
|
||||
} catch (error) {
|
||||
toast.style = Toast.Style.Failure;
|
||||
toast.title = "Projektpfad nicht aktualisiert";
|
||||
toast.message = (error as Error).message;
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
return <Form isLoading={busy} navigationTitle={`${props.projectName}: Projektordner ändern`}
|
||||
actions={<ActionPanel><Action.SubmitForm title="Projektpfad aktualisieren" icon={Icon.Folder}
|
||||
onSubmit={save} /></ActionPanel>}>
|
||||
<Form.Description title="Bisheriger Projektordner" text={props.oldPath} />
|
||||
<Form.FilePicker id="newPath" title="Neuer Projektordner" allowMultipleSelection={false}
|
||||
canChooseDirectories canChooseFiles={false} />
|
||||
<Form.Description text="Gespeicherte Stände, Ausnahmen und Projektbegriffe bleiben erhalten. Dateien im neuen Ordner werden weder analysiert noch geändert." />
|
||||
</Form>;
|
||||
}
|
||||
64
src/project-worker.ts
Normal file
64
src/project-worker.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { promises as fs, renameSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { configureWorker } from "./lib/worker-runtime";
|
||||
import { readJobJson, writeJobJson } from "./lib/project-jobs";
|
||||
import type { AnalysisInput, Decision, JobPhase, ProjectJobState } from "./lib/project-jobs";
|
||||
import { applyProject, prepareProject } from "./lib/project-work";
|
||||
import type { Preview } from "./lib/project-work";
|
||||
|
||||
async function main() {
|
||||
const [, , directory, phaseArg] = process.argv;
|
||||
if (!directory || (phaseArg !== "analysis" && phaseArg !== "apply")) throw new Error("Ungültiger Projektauftrag.");
|
||||
const phase: JobPhase = phaseArg;
|
||||
try {
|
||||
let configuration = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
for await (const chunk of process.stdin) configuration += chunk;
|
||||
const config = JSON.parse(configuration) as Parameters<typeof configureWorker>[0];
|
||||
configureWorker(config);
|
||||
configuration = "";
|
||||
|
||||
// Progress is small and independent of the persisted review. Limit disk
|
||||
// writes when an unchanged project has many files.
|
||||
let lastUpdate = 0;
|
||||
const progress = (message: string) => {
|
||||
if (Date.now() - lastUpdate < 300) return;
|
||||
lastUpdate = Date.now();
|
||||
const partial = join(directory, "status.tmp");
|
||||
const status: ProjectJobState = { phase, pid: process.pid, message };
|
||||
writeFileSync(partial, JSON.stringify(status), { mode: 0o600 });
|
||||
renameSync(partial, join(directory, "state.json"));
|
||||
};
|
||||
const input = await readJobJson<AnalysisInput>(directory, "input.json");
|
||||
if (phase === "analysis") {
|
||||
const preview = await prepareProject(config.assets, input.root, input.files, input.rules,
|
||||
input.whitelist, input.entityTypes, input.skipped, input.reanalyzeUnchanged, progress, input.imagePolicy);
|
||||
if (!preview.drafts.length && !preview.hits.length && !input.fileSelectionChanged) {
|
||||
await finish(directory, { phase: "complete", reused: preview.retained.length });
|
||||
} else {
|
||||
await writeJobJson(directory, "preview.json", preview);
|
||||
await writeJobJson(directory, "state.json", { phase: "review" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const [preview, decision] = await Promise.all([
|
||||
readJobJson<Preview>(directory, "preview.json"), readJobJson<Decision>(directory, "decision.json"),
|
||||
]);
|
||||
const output = await applyProject(config.assets, input.root, preview, input.rules, input.whitelist, decision, progress);
|
||||
await finish(directory, { phase: "complete", output });
|
||||
} catch (error) {
|
||||
await writeJobJson(directory, "state.json", {
|
||||
phase: "error", message: error instanceof Error ? error.message : "Lokaler Projektauftrag fehlgeschlagen.",
|
||||
});
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
async function finish(directory: string, state: ProjectJobState) {
|
||||
await Promise.all(["input.json", "preview.json", "decision.json"].map((file) =>
|
||||
fs.rm(join(directory, file), { force: true }).catch(() => undefined)));
|
||||
await writeJobJson(directory, "state.json", state);
|
||||
}
|
||||
|
||||
void main().catch(() => { process.exitCode = 1; });
|
||||
@@ -1,42 +1,28 @@
|
||||
import { Action, ActionPanel, Alert, Color, confirmAlert, Form, getSelectedFinderItems, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
|
||||
import { constants as fsConstants, promises as fs } from "node:fs";
|
||||
import { basename, dirname, extname, join } from "node:path";
|
||||
import { Action, ActionPanel, Alert, Color, confirmAlert, Detail, Form, getSelectedFinderItems, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { basename, dirname } from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import type { EntityType, PlaceholderMapping } from "./types";
|
||||
import { getEntityTypes, pseudonymize, pseudonymizeDocument, requireProjectCapabilities } from "./velum";
|
||||
import type { DocumentHit } from "./velum";
|
||||
import type { EntityType } from "./types";
|
||||
import { getEntityTypes } from "./velum";
|
||||
import {
|
||||
createRun, digest, forceMasks, listRuns, loadProjectEntityTypes, loadProjectFileExclusions, loadProjectRules, parseProjectRules, publishProjectCopies, replaceSpans,
|
||||
loadProjectWhitelist, reusableProjectOutput, replaceProjectFilesInPlace, resolveWithin, safeRelativePath, saveProjectFileExclusions, saveProjectRules,
|
||||
saveProjectEntityTypes, saveProjectWhitelist, saveRun, sameEntityTypeCoverage, scanProjectFiles, toUtf16Offsets, whitelistKey, withoutExcludedProjectFiles,
|
||||
listRuns, loadProjectEntityTypes, loadProjectFileExclusions, loadProjectRules, parseProjectRules,
|
||||
loadProjectWhitelist, saveProjectFileExclusions, saveProjectRules, saveProjectEntityTypes,
|
||||
saveProjectWhitelist, scanProjectFiles, whitelistKey, withoutExcludedProjectFiles,
|
||||
} from "./lib/velum-project";
|
||||
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, RunFile, SkippedProjectFile } from "./lib/velum-project";
|
||||
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, SkippedProjectFile } from "./lib/velum-project";
|
||||
import { canonicalPerson, groupReviewHits, mergePeople } from "./lib/project-review";
|
||||
import { checkedImagePolicy, DEFAULT_IMAGE_POLICY, IMAGE_POLICY_LABELS, KEEP_IMAGE_WARNING } from "./lib/image-policy";
|
||||
import type { ImagePolicy } from "./lib/image-policy";
|
||||
import {
|
||||
canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, reconcileDocumentHitIds, spansBySegment,
|
||||
withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
|
||||
} from "./lib/project-review";
|
||||
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";
|
||||
discardProjectJob, loadProjectReview, readProjectJob, startProjectAnalysis, startProjectApply,
|
||||
} from "./lib/project-jobs";
|
||||
import type { ProjectJobState } from "./lib/project-jobs";
|
||||
import type { Hit, Preview } from "./lib/project-work";
|
||||
|
||||
const run = promisify(execFile);
|
||||
const MAX_REVIEW_HITS = 50000;
|
||||
type Hit = {
|
||||
id: string; file: string; source: string; original: string; placeholder: string;
|
||||
type: string; score: number; context: string; start: number; end: number;
|
||||
kind: "content" | "path";
|
||||
};
|
||||
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; imageReport?: DocumentImageReport }>;
|
||||
paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping;
|
||||
matchModes?: Record<string, "token" | "anywhere">; hits: Hit[]; entityTypes: EntityType[];
|
||||
skipped: SkippedProjectFile[]; sourceInPlace: boolean; imagePolicy: ImagePolicy };
|
||||
|
||||
const REVIEW_PAGE_SIZE = 200;
|
||||
const typeLabels: Record<string, string> = {
|
||||
PERSON: "Personen", ORT: "Orte", ORG: "Organisationen", FIRMA: "Firmen",
|
||||
KUNDE: "Kunden", ADRESSE: "Adressen", BEGRIFF: "Eigene Begriffe",
|
||||
@@ -67,200 +53,68 @@ async function finderFolder(): Promise<string | undefined> {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
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 documentHits(file: ProjectFile, hits: DocumentHit[]): Hit[] {
|
||||
return hits.map((hit) => ({ ...hit, id: `${file.relPath}:document:${hit.id}`,
|
||||
file: file.relPath, kind: "content" as const }));
|
||||
}
|
||||
|
||||
function pathSegments(files: ProjectFile[]): PathDraft[] {
|
||||
const map = new Map<string, PathDraft>();
|
||||
for (const file of files) {
|
||||
const parts = file.relPath.split("/");
|
||||
for (let index = 0; index < parts.length; index++) {
|
||||
const key = parts.slice(0, index + 1).join("/");
|
||||
const isFile = index === parts.length - 1;
|
||||
const value = isFile ? basename(parts[index], extname(parts[index])) : parts[index];
|
||||
if (value && !map.has(key)) map.set(key, { key, value, hits: [] });
|
||||
}
|
||||
}
|
||||
return [...map.values()];
|
||||
}
|
||||
|
||||
async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[], whitelist: ProjectWhitelistEntry[], entityTypes: EntityType[],
|
||||
skipped: SkippedProjectFile[], reanalyzeUnchanged: boolean,
|
||||
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;
|
||||
const categoryCoverageChanged = Boolean(latest && !sameEntityTypeCoverage(latest, entityTypes));
|
||||
if (categoryCoverageChanged) onProgress("Kategorien geändert oder alter Stand: Dateien erneut analysieren");
|
||||
const previousMapping: PlaceholderMapping = latest?.mapping ?? {};
|
||||
const previousPlaceholders = Object.keys(previousMapping);
|
||||
let mapping: PlaceholderMapping = previousMapping;
|
||||
const drafts: Draft[] = [];
|
||||
const retained: Preview["retained"] = [];
|
||||
const draftsByPath = new Map<string, Draft>();
|
||||
const hits: Hit[] = [];
|
||||
const sourceInPlace = Boolean(latest?.inPlace || latest?.sourceInPlace);
|
||||
const previousDirectory = latestEntry?.directory;
|
||||
for (const file of files) {
|
||||
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;
|
||||
}
|
||||
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);
|
||||
}
|
||||
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 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 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()) {
|
||||
onProgress(`Dokumente analysieren: ${index + 1}/${documents.length}`);
|
||||
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, undefined, imagePolicy);
|
||||
mapping = result.mapping;
|
||||
addHits(draft, documentHits(draft.file, result.hits));
|
||||
} catch (error) {
|
||||
if (!isUnreadableDocument(error)) {
|
||||
throw new Error(`${draft.file.relPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
skipped.push({ path: draft.file.relPath, reason: "Office-/PDF-Inhalt konnte nicht gelesen werden" });
|
||||
drafts.splice(drafts.indexOf(draft), 1);
|
||||
draftsByPath.delete(draft.file.relPath);
|
||||
}
|
||||
}
|
||||
// Names of retained files already have a reviewed output in the saved stand.
|
||||
// Only new or changed files need another filename analysis.
|
||||
if (!drafts.length && !retained.length) {
|
||||
const first = skipped[0];
|
||||
throw new Error(`Keine lesbaren Dateien im Projektordner gefunden.${first ? ` Übersprungen: ${first.path} (${first.reason}).` : ""}`);
|
||||
}
|
||||
const paths = pathSegments(drafts.map((draft) => draft.file));
|
||||
const knownTerms = [...Object.keys(mapping), ...Object.values(mapping).map((entry) => entry.original),
|
||||
...withoutWhitelistedRules(rules, whitelist).map((rule) => rule.value)];
|
||||
const pathBatches = makeTextBatches(paths.map((path) => ({
|
||||
key: path.key, text: filenameScanText(path.value, knownTerms),
|
||||
})));
|
||||
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, analyzeText,
|
||||
"Dateinamen analysieren");
|
||||
mapping = analyzed.mapping;
|
||||
for (const { batch: part, result } of analyzed.results) {
|
||||
const spans = spansBySegment(part, result.spans);
|
||||
for (const segment of part.segments) {
|
||||
const path = byPath.get(segment.key)!;
|
||||
const found = toUtf16Offsets(segment.text, spans.get(path.key) ?? []).map((span, hitIndex) => ({
|
||||
...span, id: `${path.key}:path:${hitIndex}`, file: path.key,
|
||||
source: "Datei- oder Ordnername", kind: "path" as const,
|
||||
context: path.value,
|
||||
}));
|
||||
path.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
||||
hits.push(...path.hits);
|
||||
if (hits.length > MAX_REVIEW_HITS) throw new Error("Zu viele Treffer. Bitte weniger Kategorien auswählen.");
|
||||
}
|
||||
}
|
||||
}
|
||||
return { drafts, retained, paths, mapping, previousMapping,
|
||||
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace, imagePolicy };
|
||||
}
|
||||
|
||||
function outputPath(relPath: string, paths: PathDraft[], accepted: Set<string>, document: boolean,
|
||||
merges: Record<string, string>): string {
|
||||
const lookup = new Map(paths.map((item) => [item.key, item]));
|
||||
const parts = relPath.split("/");
|
||||
const output = parts.map((part, index) => {
|
||||
const key = parts.slice(0, index + 1).join("/");
|
||||
const path = lookup.get(key);
|
||||
if (!path) return part;
|
||||
const isFile = index === parts.length - 1;
|
||||
const extension = isFile ? (document && extname(part).toLowerCase() === ".pdf" ? ".docx" : extname(part)) : "";
|
||||
return replaceSpans(path.value, withPersonMerges(path.hits, merges), accepted) + extension;
|
||||
});
|
||||
return safeRelativePath(output.join("/"));
|
||||
}
|
||||
|
||||
function withPersonMerges(hits: Hit[], merges: Record<string, string>): Hit[] {
|
||||
return hits.map((hit) => hit.type === "PERSON"
|
||||
? { ...hit, placeholder: canonicalPerson(hit.placeholder, merges) } : hit);
|
||||
}
|
||||
|
||||
function OccurrenceReview(props: { original: string; placeholder: string; hits: Hit[] }) {
|
||||
const [page, setPage] = useState(0);
|
||||
const pages = Math.ceil(props.hits.length / REVIEW_PAGE_SIZE);
|
||||
return <List isShowingDetail navigationTitle={`${props.original} → ${props.placeholder}`}>
|
||||
{props.hits.map((hit) => <List.Item key={hit.id} title={hit.source}
|
||||
{pages > 1 && <List.Item title={`Vorkommen · Seite ${page + 1}/${pages}`} actions={<ActionPanel>
|
||||
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
|
||||
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
|
||||
</ActionPanel>} />}
|
||||
{props.hits.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((hit) => <List.Item key={hit.id} title={hit.source}
|
||||
subtitle={hit.kind === "path" ? "Datei- oder Ordnername" : "Dateiinhalt"}
|
||||
detail={<List.Item.Detail markdown={hit.context.replace(/</g, "<")} />} />)}
|
||||
</List>;
|
||||
}
|
||||
|
||||
function PersonMergeTargets(props: { people: Array<{ placeholder: string; originals: string[] }>;
|
||||
onChoose: (placeholder: string) => void }) {
|
||||
const { pop } = useNavigation();
|
||||
const [query, setQuery] = useState("");
|
||||
const [page, setPage] = useState(0);
|
||||
const matching = props.people.filter((person) => `${person.originals.join(" ")} ${person.placeholder}`
|
||||
.toLowerCase().includes(query.trim().toLowerCase()));
|
||||
const pages = Math.max(1, Math.ceil(matching.length / REVIEW_PAGE_SIZE));
|
||||
return <List navigationTitle="Zusammenführen mit" filtering={false} searchText={query}
|
||||
onSearchTextChange={(value) => { setQuery(value); setPage(0); }}>
|
||||
{pages > 1 && <List.Item title={`Seite ${page + 1}/${pages}`} actions={<ActionPanel>
|
||||
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
|
||||
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
|
||||
</ActionPanel>} />}
|
||||
{matching.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((person) =>
|
||||
<List.Item key={person.placeholder} title={person.originals.join(" · ")} subtitle={person.placeholder}
|
||||
actions={<ActionPanel><Action title="Personen zusammenfassen" icon={Icon.Link}
|
||||
onAction={() => { props.onChoose(person.placeholder); pop(); }} /></ActionPanel>} />)}
|
||||
</List>;
|
||||
}
|
||||
|
||||
function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: ProjectWhitelistEntry[];
|
||||
preview: Preview; fileSelectionChanged: boolean;
|
||||
onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
|
||||
const { pop } = useNavigation();
|
||||
const groups = useMemo(() => groupReviewHits(props.preview.hits), [props.preview.hits]);
|
||||
const [selectedGroups, setSelectedGroups] = useState<Set<string>>(() => new Set(groups.map((group) => group.key)));
|
||||
const [stage, setStage] = useState<"selection" | "merge">("selection");
|
||||
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [completed, setCompleted] = useState<{ directory: string; inPlace: boolean; files: number;
|
||||
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;
|
||||
const [query, setQuery] = useState("");
|
||||
const [page, setPage] = useState(0);
|
||||
const matchingGroups = useMemo(() => {
|
||||
const words = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||
return groups.filter((group) => {
|
||||
const value = `${group.original} ${group.placeholder} ${group.type} ${labelForType(group.type)}`.toLowerCase();
|
||||
return words.every((word) => value.includes(word));
|
||||
});
|
||||
}, [groups, query]);
|
||||
const pages = Math.max(1, Math.ceil(matchingGroups.length / REVIEW_PAGE_SIZE));
|
||||
const byType = useMemo(() => {
|
||||
const result = new Map<string, typeof groups>();
|
||||
for (const group of groups) (result.get(group.type) ?? (result.set(group.type, []), result.get(group.type)!)).push(group);
|
||||
for (const group of matchingGroups.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE)) (result.get(group.type) ?? (result.set(group.type, []), result.get(group.type)!)).push(group);
|
||||
return result;
|
||||
}, [groups]);
|
||||
}, [matchingGroups, page]);
|
||||
const people = useMemo(() => {
|
||||
const result = new Map<string, string[]>();
|
||||
for (const group of groups) {
|
||||
@@ -276,6 +130,9 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
&& !people.some((person) => person.placeholder === placeholder))
|
||||
.map(([placeholder, entry]) => ({ placeholder, originals: [entry.original] })),
|
||||
[people, props.preview.previousMapping]);
|
||||
const matchingPeople = useMemo(() => people.filter((person) =>
|
||||
`${person.originals.join(" ")} ${person.placeholder}`.toLowerCase().includes(query.trim().toLowerCase())), [people, query]);
|
||||
const personPages = Math.max(1, Math.ceil(matchingPeople.length / REVIEW_PAGE_SIZE));
|
||||
function toggle(key: string) {
|
||||
setSelectedGroups((current) => {
|
||||
const next = new Set(current);
|
||||
@@ -311,165 +168,24 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
style: inPlace ? Alert.ActionStyle.Destructive : Alert.ActionStyle.Default },
|
||||
}))) return;
|
||||
setBusy(true);
|
||||
const toast = await showToast({ style: Toast.Style.Animated,
|
||||
title: inPlace ? "Originaldateien werden ersetzt" : "Pseudonymisierte Kopien werden erstellt" });
|
||||
let directory: string | undefined;
|
||||
let publishedCopyPath: string | undefined;
|
||||
let persisted = false;
|
||||
try {
|
||||
const created = await createRun(props.root);
|
||||
directory = created.directory;
|
||||
const { run } = created;
|
||||
const acceptedHits = groups.filter((group) => selectedGroups.has(group.key))
|
||||
.flatMap((group) => group.hits);
|
||||
const selectedPeople = new Set(people.map((person) => person.placeholder));
|
||||
const availableTargets = new Set([...selectedPeople, ...earlierPeople.map((person) => person.placeholder)]);
|
||||
const activeMerges = Object.fromEntries(Object.entries(personMerges).filter(([source, target]) =>
|
||||
selectedPeople.has(source) && availableTargets.has(canonicalPerson(target, personMerges))));
|
||||
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");
|
||||
run.matchModes = props.preview.matchModes;
|
||||
run.sourceInPlace = props.preview.sourceInPlace || inPlace;
|
||||
const usedPaths = new Set<string>();
|
||||
const replacements: RunFile[] = [];
|
||||
for (const retained of props.preview.retained) {
|
||||
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);
|
||||
const target = resolveWithin(join(directory, "files"), relPath);
|
||||
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||
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, imageReport: retained.imageReport };
|
||||
run.files.push(file);
|
||||
run.sourceState[inPlace ? relPath : file.source] = {
|
||||
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) {
|
||||
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 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));
|
||||
const masks = forceMasks(withoutWhitelistedRules(props.rules, props.whitelist));
|
||||
let result;
|
||||
try {
|
||||
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||
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, 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, props.preview.imagePolicy);
|
||||
}
|
||||
const selectedIds = new Set(docIds);
|
||||
const selectedHits = result.hits.filter((hit) => selectedIds.has(hit.id));
|
||||
if (selectedHits.length !== selectedIds.size || selectedHits.some((hit) => !Object.entries(run.mapping)
|
||||
.some(([placeholder, entry]) => entry.type === hit.type
|
||||
&& entry.original.toLocaleLowerCase() === hit.original.toLocaleLowerCase()
|
||||
&& (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.`);
|
||||
}
|
||||
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 {
|
||||
outputHash = await writeReplacedTextFile(draft.file.absPath, target,
|
||||
withPersonMerges(draft.hits, activeMerges), accepted, draft.hash);
|
||||
}
|
||||
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 ? outputHash : draft.hash, output: relPath,
|
||||
};
|
||||
replacements.push(file);
|
||||
}
|
||||
if (!inPlace) {
|
||||
publishedCopyPath = await publishProjectCopies(run, directory);
|
||||
run.copyPath = publishedCopyPath;
|
||||
}
|
||||
await saveRun(directory, run);
|
||||
persisted = true;
|
||||
if (inPlace) {
|
||||
if (replacements.length) await replaceProjectFilesInPlace(props.root, directory, replacements);
|
||||
run.inPlace = true;
|
||||
await saveRun(directory, run);
|
||||
}
|
||||
const selectedTerms = new Set(groups.filter((group) => selectedGroups.has(group.key)).map(whitelistKey));
|
||||
const rejected = groups.filter((group) => !selectedGroups.has(group.key)
|
||||
&& !selectedTerms.has(whitelistKey(group)))
|
||||
const rejected = groups.filter((group) => !selectedGroups.has(group.key) && !selectedTerms.has(whitelistKey(group)))
|
||||
.map((group) => ({ type: group.type, original: group.original }));
|
||||
if (rejected.length) {
|
||||
const nextWhitelist = [...await loadProjectWhitelist(props.root), ...rejected];
|
||||
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`;
|
||||
toast.message = inPlace && replacements.length ? "Die Sicherung ist im Raycast-Datenordner gespeichert."
|
||||
: 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, images });
|
||||
await showInFinder(inPlace ? props.root : publishedCopyPath!).catch(() => undefined);
|
||||
await startProjectApply(props.root, { inPlace, acceptedIds: [...accepted], activeMerges, rejected });
|
||||
pop();
|
||||
} catch (error) {
|
||||
if (directory && !persisted) await fs.rm(directory, { recursive: true, force: true });
|
||||
if (publishedCopyPath && !persisted) await fs.rm(publishedCopyPath, { recursive: true, force: true });
|
||||
toast.style = Toast.Style.Failure;
|
||||
toast.title = "Pseudonymisierung fehlgeschlagen";
|
||||
toast.message = `${(error as Error).message}${persisted && directory ? ` Kopien/Sicherung: ${directory}` : ""}`;
|
||||
await showToast({ style: Toast.Style.Failure, title: "Ausgabe konnte nicht gestartet werden",
|
||||
message: (error as Error).message });
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
|
||||
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`}
|
||||
subtitle={completed.inPlace ? (completed.replaced ? "Die Originale wurden gesichert."
|
||||
: "Der neue Projektstand enthält nur die ausgewählten Dateien.")
|
||||
: completed.directory}
|
||||
actions={<ActionPanel>
|
||||
<Action title={completed.inPlace ? (completed.replaced ? "Sicherung im Finder anzeigen" : "Projekt im Finder anzeigen")
|
||||
: "Kopien im Finder anzeigen"}
|
||||
icon={Icon.Folder} onAction={() => showInFinder(completed.directory)} />
|
||||
<Action.CopyToClipboard title="Speicherpfad kopieren" content={completed.directory} />
|
||||
</ActionPanel>} />
|
||||
</List>;
|
||||
|
||||
if (stage === "merge") return <List isLoading={busy} navigationTitle="Personen zusammenfassen"
|
||||
if (stage === "merge") return <List isLoading={busy} navigationTitle="Personen zusammenfassen" filtering={false} searchText={query}
|
||||
onSearchTextChange={(value) => { setQuery(value); setPage(0); }}
|
||||
searchBarPlaceholder="Person oder Platzhalter suchen">
|
||||
<List.Section title={props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING : IMAGE_POLICY_LABELS[props.preview.imagePolicy]}>
|
||||
<List.Item icon={Icon.Play} title="Pseudonymisierung starten"
|
||||
@@ -477,11 +193,15 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
actions={<ActionPanel>
|
||||
<Action title="Originaldateien ersetzen" icon={Icon.Pencil} onAction={() => apply()} />
|
||||
<Action title="Pseudonymisierte Kopien erstellen" icon={Icon.Document} onAction={() => apply(false)} />
|
||||
<Action title="Zur Trefferauswahl" icon={Icon.ArrowLeft} onAction={() => setStage("selection")} />
|
||||
<Action title="Zur Trefferauswahl" icon={Icon.ArrowLeft} onAction={() => { setQuery(""); setPage(0); setStage("selection"); }} />
|
||||
</ActionPanel>} />
|
||||
</List.Section>
|
||||
{personPages > 1 && <List.Item title={`Seite ${page + 1}/${personPages}`} actions={<ActionPanel>
|
||||
{page + 1 < personPages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
|
||||
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
|
||||
</ActionPanel>} />}
|
||||
<List.Section title="Ausgewählte Personen · optional zusammenfassen">
|
||||
{people.map((person) => {
|
||||
{matchingPeople.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((person) => {
|
||||
const canonical = canonicalPerson(person.placeholder, personMerges);
|
||||
const targets = [...people, ...earlierPeople]
|
||||
.filter((other) => canonicalPerson(other.placeholder, personMerges) !== canonical);
|
||||
@@ -490,12 +210,9 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
subtitle={`→ ${canonical}`}
|
||||
accessories={canonical !== person.placeholder ? [{ text: "Zusammengeführt" }] : []}
|
||||
actions={<ActionPanel>
|
||||
{targets.length > 0 && <ActionPanel.Submenu title="Mit Person zusammenfassen" icon={Icon.Link}>
|
||||
{targets.map((target) => <Action key={target.placeholder}
|
||||
title={`${target.originals.join(" · ")} → ${canonicalPerson(target.placeholder, personMerges)}`}
|
||||
onAction={() => setPersonMerges((current) => mergePeople(current,
|
||||
person.placeholder, target.placeholder))} />)}
|
||||
</ActionPanel.Submenu>}
|
||||
{targets.length > 0 && <Action.Push title="Mit Person zusammenfassen" icon={Icon.Link}
|
||||
target={<PersonMergeTargets people={targets} onChoose={(target) => setPersonMerges((current) =>
|
||||
mergePeople(current, person.placeholder, target))} />} />}
|
||||
{canonical !== person.placeholder && <Action title="Zusammenführung lösen"
|
||||
onAction={() => setPersonMerges((current) => {
|
||||
const next = { ...current }; delete next[person.placeholder]; return next;
|
||||
@@ -507,7 +224,8 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
</List.Section>
|
||||
</List>;
|
||||
|
||||
return <List isLoading={busy} navigationTitle="Zuordnungen prüfen"
|
||||
return <List isLoading={busy} navigationTitle="Zuordnungen prüfen" filtering={false} searchText={query}
|
||||
onSearchTextChange={(value) => { setQuery(value); setPage(0); }}
|
||||
searchBarPlaceholder="Begriff oder Platzhalter suchen">
|
||||
<List.Section title={props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING : IMAGE_POLICY_LABELS[props.preview.imagePolicy]}>
|
||||
<List.Item key="apply" icon={Icon.Play}
|
||||
@@ -515,7 +233,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
subtitle={`${selectedOccurrences} Vorkommen · ${props.preview.drafts.length} neue/geänderte Dateien · ${props.preview.retained.length} unverändert · ${props.preview.skipped.length} übersprungen`}
|
||||
actions={<ActionPanel>
|
||||
<Action title="Auswahl abschließen und Personen prüfen" icon={Icon.ArrowRight}
|
||||
onAction={() => setStage("merge")} />
|
||||
onAction={() => { setQuery(""); setPage(0); setStage("merge"); }} />
|
||||
</ActionPanel>} />
|
||||
</List.Section>
|
||||
{props.preview.skipped.length > 0 && <List.Section title="Nicht verarbeitet">
|
||||
@@ -525,8 +243,14 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
actions={<ActionPanel><Action.Push title="Übersprungene Dateien anzeigen"
|
||||
target={<SkippedFiles files={props.preview.skipped} />} /></ActionPanel>} />
|
||||
</List.Section>}
|
||||
{pages > 1 && <List.Section title={`${matchingGroups.length} passende Zuordnungen`}>
|
||||
<List.Item title={`Seite ${page + 1}/${pages}`} actions={<ActionPanel>
|
||||
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
|
||||
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
|
||||
</ActionPanel>} />
|
||||
</List.Section>}
|
||||
{[...byType].map(([type, entries]) => <List.Section key={type}
|
||||
title={`${labelForType(type)} · ${entries.filter((entry) => selectedGroups.has(entry.key)).length}/${entries.length}`}>
|
||||
title={`${labelForType(type)} · ${groups.filter((entry) => entry.type === type && selectedGroups.has(entry.key)).length}/${groups.filter((entry) => entry.type === type).length}`}>
|
||||
{entries.map((group) => <List.Item key={group.key}
|
||||
icon={{ source: selectedGroups.has(group.key) ? Icon.CheckCircle : Icon.Circle,
|
||||
tintColor: selectedGroups.has(group.key) ? Color.Green : Color.SecondaryText }}
|
||||
@@ -541,15 +265,15 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
<Action title={`${labelForType(type)} komplett abwählen`}
|
||||
onAction={() => setSelectedGroups((current) => {
|
||||
const next = new Set(current);
|
||||
for (const entry of entries) next.delete(entry.key);
|
||||
for (const entry of groups) if (entry.type === type) next.delete(entry.key);
|
||||
return next;
|
||||
})} />
|
||||
<Action title={`${labelForType(type)} komplett auswählen`}
|
||||
onAction={() => setSelectedGroups((current) => new Set([...current, ...entries.map((entry) => entry.key)]))} />
|
||||
onAction={() => setSelectedGroups((current) => new Set([...current, ...groups.filter((entry) => entry.type === type).map((entry) => entry.key)]))} />
|
||||
<Action.Push title="Vorkommen ansehen" icon={Icon.Eye}
|
||||
target={<OccurrenceReview original={group.original} placeholder={group.placeholder} hits={group.hits} />} />
|
||||
<Action title="Auswahl abschließen und Personen prüfen" icon={Icon.ArrowRight}
|
||||
onAction={() => setStage("merge")} />
|
||||
onAction={() => { setQuery(""); setPage(0); setStage("merge"); }} />
|
||||
</ActionPanel>} />)}
|
||||
</List.Section>)}
|
||||
</List>;
|
||||
@@ -575,10 +299,77 @@ function SkippedFiles(props: { files: SkippedProjectFile[] }) {
|
||||
</List>;
|
||||
}
|
||||
|
||||
function ProjectJobStatus(props: { root: string; onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
|
||||
const { push, pop } = useNavigation();
|
||||
const [status, setStatus] = useState<ProjectJobState>();
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
let timeout: ReturnType<typeof setTimeout>;
|
||||
async function refresh() {
|
||||
try {
|
||||
const state = await readProjectJob(props.root);
|
||||
if (active) setStatus(state ?? { phase: "error", message: "Der Projektauftrag wurde entfernt." });
|
||||
} catch (error) {
|
||||
if (active) setStatus({ phase: "error", message: (error as Error).message });
|
||||
}
|
||||
if (active) timeout = setTimeout(refresh, 1000);
|
||||
}
|
||||
void refresh();
|
||||
return () => { active = false; clearTimeout(timeout); };
|
||||
}, [props.root]);
|
||||
|
||||
async function review() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const { input, preview } = await loadProjectReview(props.root);
|
||||
push(<HitReview root={props.root} rules={input.rules} whitelist={input.whitelist} preview={preview}
|
||||
fileSelectionChanged={input.fileSelectionChanged} onWhitelistChanged={props.onWhitelistChanged} />);
|
||||
} catch (error) {
|
||||
await showToast({ style: Toast.Style.Failure, title: "Vorschau nicht lesbar", message: (error as Error).message });
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
|
||||
async function discard() {
|
||||
try {
|
||||
await discardProjectJob(props.root);
|
||||
pop();
|
||||
} catch (error) {
|
||||
await showToast({ style: Toast.Style.Failure, title: "Auftrag konnte nicht geschlossen werden",
|
||||
message: (error as Error).message });
|
||||
}
|
||||
}
|
||||
|
||||
const running = status?.phase === "analysis" || status?.phase === "apply";
|
||||
const output = status?.phase === "complete" ? status.output : undefined;
|
||||
const title = status?.phase === "review" ? "Treffer bereit zur Prüfung"
|
||||
: status?.phase === "complete" ? output ? output.inPlace ? "Projektstand gespeichert" : `${output.files} Kopien erstellt`
|
||||
: `${status.reused ?? 0} unveränderte Dateien übernommen`
|
||||
: status?.phase === "error" ? "Projektauftrag fehlgeschlagen"
|
||||
: status?.phase === "apply" ? "Ausgabe läuft im Hintergrund" : "Analyse läuft im Hintergrund";
|
||||
return <List isLoading={busy || !status || running} navigationTitle={`Velum · ${basename(props.root)}`}>
|
||||
<List.Item title={title} subtitle={status && "message" in status ? status.message : undefined}
|
||||
icon={status?.phase === "error" ? Icon.ExclamationMark : status?.phase === "complete" ? Icon.CheckCircle : Icon.Document}
|
||||
actions={<ActionPanel>
|
||||
{status?.phase === "review" && <Action title="Treffer Prüfen" icon={Icon.ArrowRight} onAction={review} />}
|
||||
{output && <Action title={output.inPlace && output.replaced ? "Sicherung im Finder Anzeigen" : "Ergebnis im Finder Anzeigen"}
|
||||
icon={Icon.Folder} onAction={() => showInFinder(output.directory)} />}
|
||||
{output && <Action.CopyToClipboard title="Speicherpfad Kopieren" content={output.directory} />}
|
||||
{status?.phase === "error" && <Action.CopyToClipboard title="Fehlerdetails Kopieren" content={status.message} />}
|
||||
{status && !running && <Action title={status.phase === "review" ? "Vorschau Verwerfen" : "Auftrag Schließen"}
|
||||
icon={Icon.XMarkCircle} onAction={discard} />}
|
||||
</ActionPanel>} />
|
||||
{running && <List.Item title="Du kannst Raycast schließen" subtitle="Öffne denselben Projektordner, um den Status wieder zu sehen." />}
|
||||
{output && <List.Item title={`${output.images.replaced} Bilder ersetzt · ${output.images.removed} Bilder entfernt`} />}
|
||||
{output?.images.warnings.map((warning) => <List.Item key={warning} icon={Icon.Warning} title={warning} />)}
|
||||
</List>;
|
||||
}
|
||||
|
||||
function FileSelection(props: { root: string; files: ProjectFile[]; skipped: SkippedProjectFile[];
|
||||
excluded: string[]; rules: ProjectRule[]; types: EntityType[]; reanalyzeUnchanged: boolean; imagePolicy: ImagePolicy;
|
||||
onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
|
||||
const { push } = useNavigation();
|
||||
const [analysisError, setAnalysisError] = useState<string>();
|
||||
const [selected, setSelected] = useState<Set<string>>(() => new Set(
|
||||
withoutExcludedProjectFiles(props.files, props.excluded).map((file) => file.relPath)));
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -604,6 +395,7 @@ function FileSelection(props: { root: string; files: ProjectFile[]; skipped: Ski
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setAnalysisError(undefined);
|
||||
const toast = await showToast({ style: Toast.Style.Animated, title: "Dateiauswahl wird gespeichert" });
|
||||
try {
|
||||
const visiblePaths = new Set(props.files.map((file) => file.relPath));
|
||||
@@ -618,26 +410,31 @@ function FileSelection(props: { root: string; files: ProjectFile[]; skipped: Ski
|
||||
const skipped = [...props.skipped, ...props.files.filter((file) => !selected.has(file.relPath))
|
||||
.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.imagePolicy);
|
||||
if (!preview.drafts.length && !preview.hits.length && !fileSelectionChanged) {
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = "Alle ausgewählten Projektdateien unverändert";
|
||||
toast.message = `${preview.retained.length} Dateien aus dem letzten Stand übernommen. Keine erneute Analyse nötig.`;
|
||||
return;
|
||||
if (!await readProjectJob(props.root)) {
|
||||
await startProjectAnalysis({ root: props.root, files, rules: props.rules, whitelist,
|
||||
entityTypes: props.types, skipped, reanalyzeUnchanged: props.reanalyzeUnchanged,
|
||||
imagePolicy: props.imagePolicy, fileSelectionChanged });
|
||||
}
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = `${groupReviewHits(preview.hits).length} Zuordnungen zur Prüfung`;
|
||||
push(<HitReview root={props.root} rules={props.rules} whitelist={whitelist} preview={preview}
|
||||
fileSelectionChanged={fileSelectionChanged} onWhitelistChanged={props.onWhitelistChanged} />);
|
||||
toast.title = "Projektauftrag geöffnet";
|
||||
push(<ProjectJobStatus root={props.root} onWhitelistChanged={props.onWhitelistChanged} />);
|
||||
} catch (error) {
|
||||
toast.style = Toast.Style.Failure;
|
||||
toast.title = "Analyse fehlgeschlagen";
|
||||
toast.message = (error as Error).message;
|
||||
toast.message = error instanceof Error ? error.message : String(error);
|
||||
setAnalysisError(toast.message);
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
return <List isLoading={busy} navigationTitle="Projektdateien auswählen"
|
||||
searchBarPlaceholder="Datei oder Ordner suchen">
|
||||
{analysisError && <List.Section title="Analyse fehlgeschlagen">
|
||||
<List.Item icon={Icon.ExclamationMark} title="Fehlerdetails anzeigen" subtitle={analysisError}
|
||||
keywords={props.files.map((file) => file.relPath)}
|
||||
actions={<ActionPanel>
|
||||
<Action.Push title="Fehlerdetails anzeigen" target={<Detail markdown={analysisError.replace(/</g, "<")} />} />
|
||||
<Action.CopyToClipboard title="Fehlermeldung kopieren" content={analysisError} />
|
||||
</ActionPanel>} />
|
||||
</List.Section>}
|
||||
<List.Section title="Auswahl">
|
||||
<List.Item icon={Icon.ArrowRight} title="Dateiauswahl bestätigen und Treffer prüfen"
|
||||
subtitle={`${selected.size} von ${props.files.length} Dateien ausgewählt · ${props.files.length - selected.size} für dieses Projekt ausgeschlossen`}
|
||||
@@ -746,13 +543,18 @@ export default function Command() {
|
||||
const toast = await showToast({ style: Toast.Style.Animated, title: "Projekt wird vorbereitet" });
|
||||
try {
|
||||
if (!(await fs.stat(root)).isDirectory()) throw new Error("Bitte einen Projektordner wählen.");
|
||||
if (await readProjectJob(root)) {
|
||||
await toast.hide();
|
||||
push(<ProjectJobStatus root={root} onWhitelistChanged={setWhitelist} />);
|
||||
return;
|
||||
}
|
||||
if (typesReadyFor !== root) throw new Error("Projektkategorien werden noch geladen oder sind nicht lesbar.");
|
||||
if (!selectedTypes.length) throw new Error("Bitte mindestens eine Kategorie wählen.");
|
||||
const parsed = parseProjectRules(rules);
|
||||
await saveProjectEntityTypes(root, selectedTypes);
|
||||
await saveProjectRules(root, parsed);
|
||||
toast.title = "Dateien werden erfasst";
|
||||
const scan = await scanProjectFiles(root, undefined, false);
|
||||
const scan = await scanProjectFiles(root, undefined, false, { ".docx": 128 * 1024 * 1024 });
|
||||
if (!scan.files.length) {
|
||||
const first = scan.skipped[0];
|
||||
throw new Error(`Keine geeigneten Dateien im Projektordner gefunden.${first ? ` Übersprungen: ${first.path} (${first.reason}).` : ""}`);
|
||||
@@ -766,7 +568,7 @@ export default function Command() {
|
||||
} catch (error) {
|
||||
toast.style = Toast.Style.Failure;
|
||||
toast.title = "Analyse fehlgeschlagen";
|
||||
toast.message = (error as Error).message;
|
||||
toast.message = error instanceof Error ? error.message : String(error);
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
async function useFinderFolder() {
|
||||
@@ -776,7 +578,7 @@ export default function Command() {
|
||||
message: "Bitte den Ordner im Finder öffnen oder unten manuell auswählen." });
|
||||
}
|
||||
return <Form isLoading={busy} actions={<ActionPanel>
|
||||
<Action title="Projektdateien auswählen" onAction={next} />
|
||||
<Action title="Projektdateien auswählen oder Auftrag öffnen" onAction={next} />
|
||||
<Action title="Geöffneten Finder-Ordner übernehmen" icon={Icon.Folder} onAction={useFinderFolder} />
|
||||
<Action.Push title="Projekt-Whitelist bearbeiten" icon={Icon.List}
|
||||
target={<ProjectWhitelist entries={whitelist} onRemove={removeFromWhitelist} />} />
|
||||
@@ -806,6 +608,6 @@ export default function Command() {
|
||||
onChange={setReanalyzeUnchanged}
|
||||
info="Unveränderte Dateien werden nur bei geänderten Kategorien oder unbekanntem altem Prüfstand automatisch neu analysiert. Für neue Projektregeln oder Word-Erkennung diese Option aktivieren." />
|
||||
<Form.Description title="Projekt-Whitelist" text={`${whitelist.length} Begriffe werden bei diesem Ordner nicht mehr vorgeschlagen. Über die Aktionen kannst du sie wieder freigeben.`} />
|
||||
<Form.Description title="Ablauf" text="Dateien und Kategorien wählen, Zuordnungen prüfen und Personen bei Bedarf zusammenfassen. Abgewählte Dateien bleiben für diesen Projektordner ausgeschlossen. Standardmäßig werden die Originaldateien nach Bestätigung ersetzt; Kopien sind als Alternative verfügbar." />
|
||||
<Form.Description title="Ablauf" text="Dateien wählen und Treffer prüfen. Während Analyse und Ausgabe kann Raycast geschlossen werden. Den Status findest du beim erneuten Öffnen des Projektordners." />
|
||||
</Form>;
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import { ContextPicker, type ContextFormValues } from "./context-picker";
|
||||
import { prepareTextInContext } from "./text-context";
|
||||
import { TextHitReview } from "./text-hit-review";
|
||||
import { getPreferences } from "./preferences";
|
||||
import RelocateProjectCommand from "./relocate-project";
|
||||
|
||||
type FormValues = ContextFormValues & {
|
||||
text: string;
|
||||
@@ -33,6 +34,7 @@ type FormValues = ContextFormValues & {
|
||||
export default function Command(props: { initialSource?: "selection" | "clipboard"; autoOutput?: boolean;
|
||||
forcePaste?: boolean } = {}) {
|
||||
const [text, setText] = useState("");
|
||||
const [contextVersion, setContextVersion] = useState(0);
|
||||
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
||||
@@ -151,6 +153,8 @@ export default function Command(props: { initialSource?: "selection" | "clipboar
|
||||
icon={Icon.EyeDisabled}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
<Action.Push title="Projektordner ändern" icon={Icon.Folder}
|
||||
target={<RelocateProjectCommand onMoved={() => setContextVersion((version) => version + 1)} />} />
|
||||
<Action
|
||||
title="Markierten Text übernehmen"
|
||||
icon={Icon.TextSelection}
|
||||
@@ -171,7 +175,7 @@ export default function Command(props: { initialSource?: "selection" | "clipboar
|
||||
onChange={setText}
|
||||
placeholder="Zu pseudonymisierender Text"
|
||||
/>
|
||||
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
|
||||
<ContextPicker key={contextVersion} sessions={sessions} activeSessionId={activeSessionId}
|
||||
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
|
||||
{entityTypes.length > 0 ? (
|
||||
<Form.TagPicker
|
||||
|
||||
34
src/relocate-project.tsx
Normal file
34
src/relocate-project.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Action, ActionPanel, Icon, List, showToast, Toast } from "@raycast/api";
|
||||
import { useEffect, useState } from "react";
|
||||
import { canonicalProjectPath, listAllRuns } from "./lib/velum-project";
|
||||
import { RelocateProjectForm } from "./project-relocation-form";
|
||||
|
||||
export default function Command(props: { onMoved?: () => void } = {}) {
|
||||
const [projects, setProjects] = useState<Array<{ path: string; name: string }>>([]);
|
||||
const [busy, setBusy] = useState(true);
|
||||
async function refresh() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const unique = new Map<string, string>();
|
||||
for (const { run } of await listAllRuns()) {
|
||||
const path = canonicalProjectPath(run.projectPath);
|
||||
if (!unique.has(path)) unique.set(path, run.projectName);
|
||||
}
|
||||
setProjects([...unique].map(([path, name]) => ({ path, name })));
|
||||
} catch (error) {
|
||||
await showToast({ style: Toast.Style.Failure, title: "Projekte nicht lesbar",
|
||||
message: (error as Error).message });
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
useEffect(() => { void refresh(); }, []);
|
||||
return <List isLoading={busy} navigationTitle="Projektordner ändern" searchBarPlaceholder="Projekt oder bisherigen Pfad suchen">
|
||||
<List.EmptyView title="Noch keine gespeicherten Projekte" description="Zuerst ein Projekt mit Velum anlegen." />
|
||||
{projects.map((project) => <List.Item key={project.path} icon={Icon.Folder}
|
||||
title={project.name} subtitle={project.path} keywords={[project.path]}
|
||||
actions={<ActionPanel>
|
||||
<Action.Push title="Neuen Projektordner zuordnen" icon={Icon.Folder}
|
||||
target={<RelocateProjectForm projectName={project.name} oldPath={project.path}
|
||||
onMoved={async () => { await refresh(); props.onMoved?.(); }} />} />
|
||||
</ActionPanel>} />)}
|
||||
</List>;
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Action, ActionPanel, Alert, confirmAlert, Form, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
|
||||
import { Action, ActionPanel, Alert, confirmAlert, Detail, Form, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { basename, dirname, extname, join } from "node:path";
|
||||
import { useEffect, useState } from "react";
|
||||
import { depseudonymizeDocument } from "./velum";
|
||||
import { restoreXlsxFile } from "./lib/xlsx-restoration";
|
||||
import { addProjectMappingEntry, canonicalProjectPath, digest, isMarkdownFile, listAllRuns, mappingForMatchingSnapshots, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, updateProjectMapping, withUnambiguousHistoricalMappings } from "./lib/velum-project";
|
||||
import type { ProjectFile, ProjectRun } from "./lib/velum-project";
|
||||
import type { MappingEntry, PlaceholderMapping } from "./types";
|
||||
@@ -15,7 +16,7 @@ import { releaseProjectMapping } from "./project-mapping-actions";
|
||||
import { projectMappingCreatedAt } from "./lib/mapping-created-at";
|
||||
import { listRestorableFolders, selectRestorableFolder } from "./lib/restore-file-selection";
|
||||
import type { RestorableFolder } from "./lib/restore-file-selection";
|
||||
import { relocateProject } from "./lib/project-relocation";
|
||||
import { RelocateProjectForm } from "./project-relocation-form";
|
||||
|
||||
type SavedRun = { run: ProjectRun; directory: string };
|
||||
type RestoreDecision = MappingEntry | null;
|
||||
@@ -179,17 +180,21 @@ function RevisionReview(props: { saved: SavedRun; onSaved: () => Promise<void> }
|
||||
</List>;
|
||||
}
|
||||
|
||||
function FolderPicker(props: { folders: RestorableFolder[]; onSelect: (folder: string, includeDocuments: boolean) => void }) {
|
||||
function FolderPicker(props: { folders: RestorableFolder[]; onSelect: (folder: string, includeDocuments: boolean, restoreImmediately?: boolean) => void }) {
|
||||
const { pop } = useNavigation();
|
||||
function choose(folder: string, includeDocuments: boolean) {
|
||||
props.onSelect(folder, includeDocuments);
|
||||
function choose(folder: string, includeDocuments: boolean, restoreImmediately = false) {
|
||||
props.onSelect(folder, includeDocuments, restoreImmediately);
|
||||
pop();
|
||||
}
|
||||
return <List navigationTitle="Nur einen Ordner wiederherstellen" searchBarPlaceholder="Ordner suchen">
|
||||
<List.Section title="Ordner samt Unterordnern · Textdateien zuerst">
|
||||
<List.Section title="Ordner samt Unterordnern · Klartext-Kopien in Downloads/Velum">
|
||||
{props.folders.map((folder) => <List.Item key={folder.path} icon={Icon.Folder}
|
||||
title={folder.path} subtitle={`${folder.fileCount} Dateien · ${folder.textCount} Text · ${folder.documentCount} Office`}
|
||||
actions={<ActionPanel>
|
||||
<Action title={folder.documentCount > 0 ? "Ordner inklusive Office wiederherstellen" : "Ordner wiederherstellen"}
|
||||
icon={Icon.Download} onAction={() => choose(folder.path, true, true)} />
|
||||
{folder.documentCount > 0 && folder.textCount > 0 && <Action title="Nur Textdateien wiederherstellen"
|
||||
icon={Icon.Download} onAction={() => choose(folder.path, false, true)} />}
|
||||
{folder.textCount > 0 && <Action title="Nur Textdateien dieses Ordners auswählen" icon={Icon.CheckCircle}
|
||||
onAction={() => choose(folder.path, false)} />}
|
||||
{folder.documentCount > 0 && <Action title="Diesen Ordner inklusive Office auswählen" icon={Icon.Folder}
|
||||
@@ -207,6 +212,7 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
const [skipped, setSkipped] = useState(0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [unresolved, setUnresolved] = useState<Array<{ file: string; id: string }>>([]);
|
||||
const [exportError, setExportError] = useState<{ title: string; message: string }>();
|
||||
const [decisions, setDecisions] = useState<Record<string, Record<string, RestoreDecision>>>({});
|
||||
const mappings = [props.run.mapping, ...props.earlierRuns.map((entry) => entry.run.mapping)]
|
||||
.map(mappingForRestoration);
|
||||
@@ -234,8 +240,10 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
setSelected(new Set(scan.files.filter((file) => file.kind === "text").map((file) => file.relPath)));
|
||||
setSkipped(scan.skipped);
|
||||
}
|
||||
load().catch((error: Error) => showToast({ style: Toast.Style.Failure,
|
||||
title: "Kopienordner nicht lesbar", message: error.message }));
|
||||
load().catch((error: Error) => {
|
||||
setExportError({ title: "Kopienordner nicht lesbar", message: error.message });
|
||||
return showToast({ style: Toast.Style.Failure, title: "Kopienordner nicht lesbar", message: error.message });
|
||||
});
|
||||
return () => { active = false; };
|
||||
}, [props.run, props.directory, props.historical]);
|
||||
function toggle(path: string) {
|
||||
@@ -246,36 +254,54 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
return next;
|
||||
});
|
||||
}
|
||||
async function exportFiles() {
|
||||
async function exportFiles(selection = selected) {
|
||||
if (busy) return;
|
||||
if (!selected.size) {
|
||||
if (!selection.size) {
|
||||
await showToast({ style: Toast.Style.Failure, title: "Keine Dateien ausgewählt" });
|
||||
return;
|
||||
}
|
||||
if (!sourceRoot) return;
|
||||
setBusy(true);
|
||||
setExportError(undefined);
|
||||
const toast = await showToast({ style: Toast.Style.Animated, title: "Klartext-Kopien werden erstellt" });
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const parent = join(homedir(), "Downloads", "Velum");
|
||||
let targetRoot: string | undefined;
|
||||
let activeFile: string | undefined;
|
||||
try {
|
||||
if (!Object.keys(baseMapping).length && !Object.keys(decisions).length) {
|
||||
throw new Error("Dieser Projektstand hat keine Übersetzungstabelle.");
|
||||
}
|
||||
const names = new Set<string>();
|
||||
const planned = files.filter((item) => selected.has(item.relPath));
|
||||
const planned = files.filter((item) => selection.has(item.relPath));
|
||||
let renamedFiles = 0;
|
||||
let contentReplacements = 0;
|
||||
await fs.mkdir(parent, { recursive: true, mode: 0o700 });
|
||||
targetRoot = await fs.mkdtemp(join(parent, `${basename(props.run.projectName)}-${stamp}-`));
|
||||
for (const file of planned) {
|
||||
activeFile = file.relPath;
|
||||
toast.title = "Datei wird wiederhergestellt";
|
||||
toast.message = file.relPath;
|
||||
const source = resolveWithin(sourceRoot, file.relPath);
|
||||
if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Datei: ${file.relPath}`);
|
||||
const data = await fs.readFile(source);
|
||||
const mapping: PlaceholderMapping = { ...baseMapping };
|
||||
const manual = decisions[file.relPath] ?? {};
|
||||
for (const [id, entry] of Object.entries(manual)) if (entry) mapping[id] = entry;
|
||||
let restoredName = restorePath(file.relPath, mapping, props.run.matchModes);
|
||||
if (file.kind === "document" && extname(file.relPath).toLowerCase() === ".xlsx") {
|
||||
if (names.has(restoredName)) throw new Error(`Mehrdeutiger Ausgabename: ${restoredName}`);
|
||||
names.add(restoredName);
|
||||
if (restoredName !== file.relPath) renamedFiles++;
|
||||
const target = resolveWithin(targetRoot, restoredName);
|
||||
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||
const restored = await restoreXlsxFile(source, target, mapping, (percent) => {
|
||||
toast.title = `Excel wird lokal wiederhergestellt · ${percent} %`;
|
||||
toast.message = file.relPath;
|
||||
});
|
||||
contentReplacements += restored.replacements;
|
||||
continue;
|
||||
}
|
||||
const data = await fs.readFile(source);
|
||||
let result: Buffer;
|
||||
if (file.kind === "document") {
|
||||
result = await depseudonymizeDocument(basename(file.relPath), data, mapping);
|
||||
@@ -317,12 +343,12 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
}
|
||||
setUnresolved([]);
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = `${selected.size} Klartext-Dateien in Downloads`;
|
||||
toast.title = `${selection.size} Klartext-Dateien in Downloads`;
|
||||
const deliberatelyKept = planned.reduce((count, file) => count
|
||||
+ Object.values(decisions[file.relPath] ?? {}).filter((entry) => entry === null).length, 0);
|
||||
toast.message = `${contentReplacements} Textersetzungen · ${renamedFiles} Dateinamen geändert`
|
||||
+ (deliberatelyKept ? ` · ${deliberatelyKept} Platzhalter bewusst belassen` : "")
|
||||
+ (planned.some((file) => file.kind === "document") ? " · Office-Inhalte nicht gezählt" : "");
|
||||
+ (planned.some((file) => file.kind === "document" && extname(file.relPath).toLowerCase() !== ".xlsx") ? " · DOCX/PPTX-Inhalte nicht gezählt" : "");
|
||||
await showInFinder(targetRoot).catch(() => undefined);
|
||||
} catch (error) {
|
||||
if (targetRoot) await fs.rm(targetRoot, { recursive: true, force: true });
|
||||
@@ -331,15 +357,19 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
toast.title = error instanceof UnresolvedRestoreError ? "Platzhalter zuordnen" : "Klartext-Export fehlgeschlagen";
|
||||
toast.message = error instanceof UnresolvedRestoreError
|
||||
? `${error.file}: ${error.ids.join(", ")}. Bitte die Einträge unten klären und den Export erneut starten.`
|
||||
: (error as Error).message;
|
||||
: `${activeFile ? activeFile + ": " : ""}${error instanceof Error ? error.message : String(error)}`;
|
||||
setExportError({ title: toast.title, message: toast.message });
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
const textFiles = files.filter((file) => file.kind === "text");
|
||||
const complexFiles = files.filter((file) => file.kind === "document");
|
||||
const folders = listRestorableFolders(files);
|
||||
const allSelected = files.length > 0 && selected.size === files.length;
|
||||
const selectOnlyFolder = (folder: string, includeDocuments = false) =>
|
||||
setSelected(selectRestorableFolder(files, folder, includeDocuments));
|
||||
const selectOnlyFolder = (folder: string, includeDocuments = false, restoreImmediately = false) => {
|
||||
const selection = selectRestorableFolder(files, folder, includeDocuments);
|
||||
setSelected(selection);
|
||||
if (restoreImmediately) void exportFiles(selection);
|
||||
};
|
||||
const openFolderPicker = () => push(<FolderPicker folders={folders} onSelect={selectOnlyFolder} />);
|
||||
const selectionActions = () => <ActionPanel.Section title="Dateiauswahl">
|
||||
<Action title={allSelected ? "Alle Dateien abwählen" : "Alle Dateien auswählen (inklusive Office)"}
|
||||
@@ -363,24 +393,37 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
accessories={file.kind === "document" ? [{ text: "Office · manuell auswählen" }] : []}
|
||||
actions={<ActionPanel>
|
||||
<Action title={selected.has(file.relPath) ? "Datei abwählen" : "Datei auswählen"} onAction={() => toggle(file.relPath)} />
|
||||
<Action title="Auswahl nach Downloads wiederherstellen" icon={Icon.Download} onAction={exportFiles} />
|
||||
<Action title="Auswahl nach Downloads wiederherstellen" icon={Icon.Download} onAction={() => exportFiles()} />
|
||||
{fileFolder && <Action title={fileFolder.textCount > 0
|
||||
? "Nur Textdateien dieses Ordners auswählen" : "Diesen Ordner inklusive Office auswählen"}
|
||||
icon={Icon.Folder} onAction={() => selectOnlyFolder(fileFolder.path, fileFolder.textCount === 0)} />}
|
||||
{selectionActions()}
|
||||
</ActionPanel>} />;
|
||||
};
|
||||
return <List isLoading={busy || !sourceRoot} navigationTitle={`${props.run.projectName}: Dateien für Klartext wählen`}
|
||||
return <List isLoading={busy || (!sourceRoot && !exportError)} navigationTitle={`${props.run.projectName}: Dateien für Klartext wählen`}
|
||||
searchBarPlaceholder="Dateien filtern">
|
||||
<List.Section title={`${selected.size} von ${files.length} Dateien ausgewählt · ${skipped} übersprungen`}>
|
||||
<List.Item key="export" icon={Icon.Download} title="Ausgewählte Dateien wiederherstellen"
|
||||
subtitle="Klartext-Kopien in Downloads/Velum erstellen · Office-Dateien nur nach Auswahl"
|
||||
actions={<ActionPanel><Action title="Auswahl nach Downloads wiederherstellen"
|
||||
icon={Icon.Download} onAction={exportFiles} />{selectionActions()}</ActionPanel>} />
|
||||
icon={Icon.Download} onAction={() => exportFiles()} />{selectionActions()}</ActionPanel>} />
|
||||
{folders.length > 0 && <List.Item key="folders" icon={Icon.Folder}
|
||||
title="Einzelnen Ordner wiederherstellen"
|
||||
subtitle={`${folders.length} Ordner · jeweils inklusive Unterordnern`}
|
||||
actions={<ActionPanel><Action title="Ordner zur Wiederherstellung wählen" icon={Icon.Folder}
|
||||
onAction={openFolderPicker} />{selectionActions()}</ActionPanel>} />}
|
||||
<List.Item key="source" icon={Icon.Folder} title={sourceLabel} subtitle={sourceRoot}
|
||||
actions={<ActionPanel><Action title="Quellordner im Finder anzeigen" onAction={() => showInFinder(sourceRoot)} />
|
||||
{selectionActions()}</ActionPanel>} />
|
||||
</List.Section>
|
||||
{exportError && <List.Section title={exportError.title}>
|
||||
<List.Item icon={Icon.ExclamationMark} title="Fehlerdetails anzeigen" subtitle={exportError.message}
|
||||
keywords={files.map((file) => file.relPath)} actions={<ActionPanel>
|
||||
<Action.Push title="Fehlerdetails anzeigen" target={<Detail markdown={exportError.message.replace(/</g, "<")} />} />
|
||||
<Action.CopyToClipboard title="Fehlermeldung kopieren" content={exportError.message} />
|
||||
<Action title="Wiederherstellung erneut starten" icon={Icon.Download} onAction={() => exportFiles()} />
|
||||
</ActionPanel>} />
|
||||
</List.Section>}
|
||||
{unresolved.some((item) => selected.has(item.file)) && <List.Section title="Platzhalter für diesen Export klären">
|
||||
{unresolved.filter((item) => selected.has(item.file)).map(({ file, id }) => {
|
||||
const candidates = candidatesFor(id);
|
||||
@@ -429,47 +472,6 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) {
|
||||
</List>;
|
||||
}
|
||||
|
||||
function RelocateProjectForm(props: { projectName: string; oldPath: string; onMoved: () => Promise<void> }) {
|
||||
const { pop } = useNavigation();
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function save(values: { newPath: string[] }) {
|
||||
const newPath = values.newPath[0];
|
||||
if (!newPath) {
|
||||
await showToast({ style: Toast.Style.Failure, title: "Bitte den neuen Projektordner wählen" });
|
||||
return;
|
||||
}
|
||||
if (!(await confirmAlert({
|
||||
title: "Projektordner aktualisieren?",
|
||||
message: `Alle gespeicherten Projektstände und Regeln werden künftig ${newPath} zugeordnet. `
|
||||
+ `Bisheriger Pfad: ${props.oldPath}. Die Dateien im gewählten Ordner werden nicht verändert.`,
|
||||
primaryAction: { title: "Projektpfad aktualisieren" },
|
||||
}))) return;
|
||||
setBusy(true);
|
||||
const toast = await showToast({ style: Toast.Style.Animated, title: "Projektpfad wird aktualisiert" });
|
||||
try {
|
||||
const result = await relocateProject(props.oldPath, newPath);
|
||||
await props.onMoved();
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = "Projektordner aktualisiert";
|
||||
toast.message = `${result.runsMoved} Projektstände übernommen`
|
||||
+ (result.copiesRelinked ? ` · ${result.copiesRelinked} Kopienordner neu gefunden` : "")
|
||||
+ (result.copiesMissing ? ` · ${result.copiesMissing} Kopienordner nicht gefunden; gespeicherte Stände bleiben verfügbar` : "");
|
||||
pop();
|
||||
} catch (error) {
|
||||
toast.style = Toast.Style.Failure;
|
||||
toast.title = "Projektpfad nicht aktualisiert";
|
||||
toast.message = (error as Error).message;
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
return <Form isLoading={busy} navigationTitle={`${props.projectName}: Projektordner ändern`}
|
||||
actions={<ActionPanel><Action.SubmitForm title="Projektpfad aktualisieren" icon={Icon.Folder}
|
||||
onSubmit={save} /></ActionPanel>}>
|
||||
<Form.Description title="Bisheriger Projektordner" text={props.oldPath} />
|
||||
<Form.FilePicker id="newPath" title="Neuer Projektordner" allowMultipleSelection={false}
|
||||
canChooseDirectories canChooseFiles={false} />
|
||||
<Form.Description text="Gespeicherte Stände, Ausnahmen und Projektbegriffe bleiben erhalten. Dateien im neuen Ordner werden weder analysiert noch geändert." />
|
||||
</Form>;
|
||||
}
|
||||
|
||||
export default function Command() {
|
||||
const { push } = useNavigation();
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Icon,
|
||||
List,
|
||||
showToast,
|
||||
showInFinder,
|
||||
Toast,
|
||||
useNavigation,
|
||||
} from "@raycast/api";
|
||||
@@ -18,6 +19,10 @@ import type { PlaceholderMapping } from "./types";
|
||||
import { releaseProjectMapping } from "./project-mapping-actions";
|
||||
import { projectMappingCreatedAt, sortMappingRowsByCreatedAt } from "./lib/mapping-created-at";
|
||||
import type { ProjectRun } from "./lib/velum-project";
|
||||
import { RelocateProjectForm } from "./project-relocation-form";
|
||||
|
||||
import { writeMappingExport } from "./lib/mapping-export";
|
||||
import type { MappingExportKind } from "./lib/mapping-export";
|
||||
|
||||
type TableSource = {
|
||||
id: string;
|
||||
@@ -128,6 +133,29 @@ export function TranslationTable({
|
||||
await change(() => onRemove(root), "False Positive freigegeben");
|
||||
}
|
||||
|
||||
async function exportTable(kind: MappingExportKind) {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
const toast = await showToast({ style: Toast.Style.Animated, title: "Textdatei wird exportiert" });
|
||||
try {
|
||||
const result = await writeMappingExport(title, visibleMapping, kind);
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = kind === "terms" ? "Begriffe exportiert" : "Ersetzungen exportiert";
|
||||
toast.message = `${result.count} Einträge · Downloads/Velum`;
|
||||
await showInFinder(result.path).catch(() => undefined);
|
||||
} catch (error) {
|
||||
toast.style = Toast.Style.Failure;
|
||||
toast.title = "Export fehlgeschlagen";
|
||||
toast.message = (error as Error).message;
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
function exportActions() {
|
||||
return <ActionPanel.Section title="Textdatei exportieren">
|
||||
<Action title="Begriffe als Textdatei exportieren" icon={Icon.Download} onAction={() => exportTable("terms")} />
|
||||
<Action title="Ersetzungen als Textdatei exportieren" icon={Icon.Download} onAction={() => exportTable("replacements")} />
|
||||
</ActionPanel.Section>;
|
||||
}
|
||||
|
||||
function renderRow(type: string, placeholder: string, members: string[]) {
|
||||
const roots = groups.get(type)!;
|
||||
const date = visibleDates[placeholder];
|
||||
@@ -169,6 +197,7 @@ export function TranslationTable({
|
||||
onAction={() => remove(placeholder, members)} />}
|
||||
<Action.CopyToClipboard title="Platzhalter kopieren" content={placeholder} />
|
||||
<Action.CopyToClipboard title="Klartext kopieren" content={visibleMapping[placeholder].original} />
|
||||
{exportActions()}
|
||||
</ActionPanel>} />;
|
||||
}
|
||||
|
||||
@@ -190,7 +219,14 @@ export function TranslationTable({
|
||||
<List.Item icon={Icon.Plus} title="Begriff oder fehlenden Platzhalter hinzufügen"
|
||||
subtitle="Neuer Eintrag für diese Übersetzungstabelle"
|
||||
actions={<ActionPanel><Action title="Zuordnung hinzufügen" icon={Icon.Plus}
|
||||
onAction={() => push(<AddMappingForm onAdd={onAdd} onSaved={showMapping} />)} /></ActionPanel>} />
|
||||
onAction={() => push(<AddMappingForm onAdd={onAdd} onSaved={showMapping} />)} />
|
||||
{Object.keys(visibleMapping).length > 0 && exportActions()}</ActionPanel>} />
|
||||
</List.Section>}
|
||||
{Object.keys(visibleMapping).length > 0 && <List.Section title="Export">
|
||||
<List.Item icon={Icon.Download} title="Übersetzungstabelle exportieren"
|
||||
subtitle="Alle Begriffe oder Original → Platzhalter als UTF-8-Textdatei"
|
||||
keywords={["export", "txt", "begriffe", "ersetzungen"]}
|
||||
actions={<ActionPanel>{exportActions()}</ActionPanel>} />
|
||||
</List.Section>}
|
||||
{sortOrder === "category" ? [...groups]
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
@@ -302,6 +338,8 @@ export default function Command() {
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Action.Push title="Projektordner ändern" icon={Icon.Folder}
|
||||
target={<RelocateProjectForm projectName={source.title} oldPath={source.id} onMoved={refresh} />} />
|
||||
</ActionPanel>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -58,7 +58,8 @@ export async function prepareTextInContext(values: ContextFormValues, text: stri
|
||||
if (!selected || selected === CHOOSE_CONTEXT_ID) throw new Error("Bitte ein Projekt oder eine Sitzung wählen.");
|
||||
if (selected === NEW_PROJECT_ID || selected.startsWith("project:")) {
|
||||
const folder = selected === NEW_PROJECT_ID ? values.newProjectPath?.[0] : selected.slice("project:".length);
|
||||
if (!folder || !(await fs.stat(folder).catch(() => undefined))?.isDirectory()) {
|
||||
// Existing projects use their saved mapping even when the source folder is unavailable.
|
||||
if (!folder || (selected === NEW_PROJECT_ID && !(await fs.stat(folder).catch(() => undefined))?.isDirectory())) {
|
||||
throw new Error("Bitte einen vorhandenen Projektordner wählen.");
|
||||
}
|
||||
const path = canonicalProjectPath(folder);
|
||||
@@ -149,7 +150,8 @@ export async function pseudonymizeInContext(values: ContextFormValues, text: str
|
||||
}
|
||||
if (selected === NEW_PROJECT_ID || selected.startsWith("project:")) {
|
||||
const folder = selected === NEW_PROJECT_ID ? values.newProjectPath?.[0] : selected.slice("project:".length);
|
||||
if (!folder || !(await fs.stat(folder).catch(() => undefined))?.isDirectory()) {
|
||||
// Existing projects use their saved mapping even when the source folder is unavailable.
|
||||
if (!folder || (selected === NEW_PROJECT_ID && !(await fs.stat(folder).catch(() => undefined))?.isDirectory())) {
|
||||
throw new Error("Bitte einen vorhandenen Projektordner wählen.");
|
||||
}
|
||||
const path = canonicalProjectPath(folder);
|
||||
|
||||
23
src/velum.ts
23
src/velum.ts
@@ -1,4 +1,5 @@
|
||||
import { fetchWithAuth } from "./auth";
|
||||
import { restoreXlsxBuffer } from "./lib/xlsx-restoration";
|
||||
import { checkProjectCapabilities } from "./lib/project-capabilities";
|
||||
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY } from "./lib/image-policy";
|
||||
import type { ImagePolicy, DocumentImageReport } from "./lib/image-policy";
|
||||
@@ -134,6 +135,27 @@ export async function pseudonymize(
|
||||
return parseJsonResponse<PseudonymizeResponse>(response);
|
||||
}
|
||||
|
||||
export async function analyzeDocxSegments(
|
||||
segments: Array<{ text: string; kind: "text" | "author" | "link" | "email" }>,
|
||||
mapping: PlaceholderMapping,
|
||||
entityTypes: EntityType[],
|
||||
forceMasks: Record<string, string[]>,
|
||||
): Promise<{ mapping: PlaceholderMapping; spans: PseudonymizeResponse["spans"][] }> {
|
||||
const response = await fetchWithAuth(apiUrl("/api/docx/segments"), {
|
||||
method: "POST",
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ segments, mapping, entity_types: entityTypes, force_masks: forceMasks }),
|
||||
});
|
||||
if (response.status === 404 || response.status === 405) {
|
||||
throw new Error("Velum unterstützt die lokale DOCX-Analyse noch nicht. Bitte das Backend aktualisieren.");
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(`Velum konnte das DOCX-Analysepaket nicht verarbeiten (HTTP ${response.status}).`);
|
||||
}
|
||||
return parseJsonResponse(response);
|
||||
}
|
||||
|
||||
export type DocumentHit = {
|
||||
id: string;
|
||||
source: string;
|
||||
@@ -190,6 +212,7 @@ export async function depseudonymizeDocument(
|
||||
data: Buffer,
|
||||
mapping: PlaceholderMapping,
|
||||
): Promise<Buffer> {
|
||||
if (/\.xlsx$/i.test(filename)) return restoreXlsxBuffer(data, mapping);
|
||||
const form = new FormData();
|
||||
form.set("file", new Blob([new Uint8Array(data)]), filename);
|
||||
form.set("mapping", JSON.stringify(mapping));
|
||||
|
||||
Reference in New Issue
Block a user