feat: group translation mappings and restore canonical terms

This commit is contained in:
muena
2026-10-15 09:41:04 +02:00
parent 4801908faf
commit 65134735f1
7 changed files with 243 additions and 67 deletions

View File

@@ -23,6 +23,7 @@ import type { DepseudonymizeResponse, VelumSession } from "./types";
import { markdownCodeBlock, sessionSubtitle } from "./ui";
import { restoreRichHtml } from "./lib/rich-text";
import { copyRichText } from "./rich-clipboard";
import { mappingForRestoration } from "./lib/mapping-groups";
type FormValues = {
text: string;
@@ -156,9 +157,10 @@ export default function Command(
const projectPath = values.sessionId.slice("project:".length);
const saved = (await listRuns(projectPath))[0];
if (!saved) throw new Error("Projektstand nicht gefunden.");
const restorationMapping = mappingForRestoration(saved.run.mapping);
const restored = restoreTextWithCount(
input,
saved.run.mapping,
restorationMapping,
saved.run.matchModes,
);
result = {
@@ -170,7 +172,7 @@ export default function Command(
richSource.html,
input,
result.original_text,
saved.run.mapping,
restorationMapping,
saved.run.matchModes,
);
}
@@ -179,13 +181,14 @@ export default function Command(
} else {
const session = await getSession(values.sessionId);
if (!session) throw new Error("Sitzung nicht gefunden.");
result = await depseudonymize(input, session.mapping);
const restorationMapping = mappingForRestoration(session.mapping);
result = await depseudonymize(input, restorationMapping);
if (richSource?.text === input) {
richHtml = restoreRichHtml(
richSource.html,
input,
result.original_text,
session.mapping,
restorationMapping,
undefined,
true,
);

43
src/lib/mapping-groups.ts Normal file
View File

@@ -0,0 +1,43 @@
import type { PlaceholderMapping } from "../types";
export function mappingRoot(key: string, mapping: PlaceholderMapping): string {
const initial = mapping[key];
if (!initial) throw new Error(`Unbekannte Zuordnung: ${key}`);
const seen = new Set<string>();
let current = key;
while (mapping[current].merged_into) {
if (seen.has(current)) throw new Error(`Zyklische Zuordnung: ${key}`);
seen.add(current);
const target = mapping[current].merged_into!;
if (!mapping[target] || mapping[target].type !== initial.type) {
throw new Error(`Ungültiger Hauptbegriff für ${key}: ${target}`);
}
current = target;
}
return current;
}
/** Reverse lookups use the group's main term, while the saved variants remain intact. */
export function mappingForRestoration(mapping: PlaceholderMapping): PlaceholderMapping {
return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [key, {
type: entry.type,
original: mapping[mappingRoot(key, mapping)].original,
}]));
}
export function mergeMappingGroups(mapping: PlaceholderMapping, source: string, target: string): PlaceholderMapping {
const from = mappingRoot(source, mapping);
const into = mappingRoot(target, mapping);
if (from === into) throw new Error("Diese Zuordnungen sind bereits zusammengefasst.");
if (mapping[from].type !== mapping[into].type) {
throw new Error("Nur Zuordnungen derselben Kategorie können zusammengefasst werden.");
}
return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [key,
mappingRoot(key, mapping) === from ? { ...entry, merged_into: into } : { ...entry },
]));
}
export function detachMappingGroup(mapping: PlaceholderMapping, key: string): PlaceholderMapping {
if (!mapping[key]?.merged_into) throw new Error("Diese Zuordnung ist kein Verweis.");
return { ...mapping, [key]: { ...mapping[key], merged_into: undefined } };
}

View File

@@ -6,6 +6,7 @@ import type { EntityType, MappingEntry, PlaceholderMapping } from "../types";
import { whitelistKey } from "./project-whitelist";
import type { ProjectWhitelistEntry } from "./project-whitelist";
import { restoreOriginalCase } from "./restore-case";
import { mappingForRestoration } from "./mapping-groups";
export { whitelistKey } from "./project-whitelist";
export type { ProjectWhitelistEntry } from "./project-whitelist";
@@ -415,19 +416,19 @@ export function prepareManualMappingEntry(current: PlaceholderMapping, earlier:
}
/** Save a mapping correction as a new immutable project stand without rewriting project files. */
export async function addProjectMappingEntry(projectPath: string,
input: { original: string; type: string; placeholder?: string }, support = environment.supportPath): Promise<ProjectRun> {
export async function updateProjectMapping(projectPath: string,
change: (current: PlaceholderMapping, earlier: PlaceholderMapping[]) => PlaceholderMapping,
support = environment.supportPath): Promise<ProjectRun> {
const entries = await listRuns(projectPath, support);
const latest = entries[0];
if (!latest) throw new Error("Für dieses Projekt gibt es noch keinen gespeicherten Stand.");
const { placeholder, entry } = prepareManualMappingEntry(latest.run.mapping,
entries.slice(1).map((saved) => saved.run.mapping), input);
const mapping = change(latest.run.mapping, entries.slice(1).map((saved) => saved.run.mapping));
const created = await createRun(projectPath, support);
const { run, directory } = created;
run.createdAt = new Date(Math.max(Date.now(), Date.parse(latest.run.createdAt) + 1)).toISOString();
run.origin = latest.run.origin;
run.revisedFrom = latest.run.id;
run.mapping = { ...latest.run.mapping, [placeholder]: entry };
run.mapping = mapping;
run.matchModes = { ...latest.run.matchModes };
run.files = latest.run.files.map((file) => ({ ...file }));
run.inPlace = latest.run.inPlace;
@@ -454,6 +455,14 @@ export async function addProjectMappingEntry(projectPath: string,
return run;
}
export async function addProjectMappingEntry(projectPath: string,
input: { original: string; type: string; placeholder?: string }, support = environment.supportPath): Promise<ProjectRun> {
return updateProjectMapping(projectPath, (current, earlier) => {
const { placeholder, entry } = prepareManualMappingEntry(current, earlier, input);
return { ...current, [placeholder]: entry };
}, support);
}
export function runCopiesPath(run: ProjectRun, directory: string): string {
return run.copyPath ?? join(directory, "files");
}
@@ -547,7 +556,7 @@ export async function mappingForMatchingSnapshots(relPath: string, currentHash:
const matching = await Promise.all(earlier.filter(({ run }) =>
run.files.some((file) => file.output === relPath))
.map(async ({ run, directory }) => await matchesPreviousOutput(directory, relPath, currentHash)
? run.mapping : undefined));
? mappingForRestoration(run.mapping) : undefined));
return withUnambiguousHistoricalMappings({},
matching.filter((mapping): mapping is PlaceholderMapping => Boolean(mapping)));
}

View File

@@ -4,12 +4,13 @@ import { homedir } from "node:os";
import { basename, dirname, join } from "node:path";
import { useEffect, useState } from "react";
import { depseudonymizeDocument } from "./velum";
import { addProjectMappingEntry, canonicalProjectPath, digest, isMarkdownFile, listAllRuns, mappingForMatchingSnapshots, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, withUnambiguousHistoricalMappings } from "./lib/velum-project";
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";
import { canonicalPerson, mergePeople } from "./lib/project-review";
import { planProjectRevision, reviseProjectRun } from "./lib/project-revision";
import { TranslationTable } from "./show-translation-tables";
import { detachMappingGroup, mappingForRestoration, mergeMappingGroups } from "./lib/mapping-groups";
type SavedRun = { run: ProjectRun; directory: string };
type RestoreDecision = MappingEntry | null;
@@ -182,8 +183,9 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
const [busy, setBusy] = useState(false);
const [unresolved, setUnresolved] = useState<Array<{ file: string; id: string }>>([]);
const [decisions, setDecisions] = useState<Record<string, Record<string, RestoreDecision>>>({});
const mappings = [props.run.mapping, ...props.earlierRuns.map((entry) => entry.run.mapping)];
const baseMapping = withUnambiguousHistoricalMappings(props.run.mapping, mappings.slice(1));
const mappings = [props.run.mapping, ...props.earlierRuns.map((entry) => entry.run.mapping)]
.map(mappingForRestoration);
const baseMapping = withUnambiguousHistoricalMappings(mappings[0], mappings.slice(1));
const candidatesFor = (id: string): MappingEntry[] => {
const unique = new Map<string, MappingEntry>();
for (const mapping of mappings) for (const [key, entry] of Object.entries(mapping)) {
@@ -440,6 +442,18 @@ export default function Command() {
const updated = await addProjectMappingEntry(run.projectPath, input);
await refresh();
return updated.mapping;
}}
onMerge={async (from, into) => {
const updated = await updateProjectMapping(run.projectPath,
(current) => mergeMappingGroups(current, from, into));
await refresh();
return updated.mapping;
}}
onDetach={async (key) => {
const updated = await updateProjectMapping(run.projectPath,
(current) => detachMappingGroup(current, key));
await refresh();
return updated.mapping;
}} />} />
<Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder}
onAction={() => showInFinder(runCopiesPath(run, directory))} />

View File

@@ -1,7 +1,6 @@
import {
Action,
ActionPanel,
Detail,
Form,
Icon,
List,
@@ -10,10 +9,10 @@ import {
useNavigation,
} from "@raycast/api";
import { useCallback, useEffect, useState } from "react";
import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry } from "./lib/velum-project";
import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry, updateProjectMapping } from "./lib/velum-project";
import { detachMappingGroup, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups";
import { getSession, listSessions, updateSessionMapping } from "./sessions";
import type { PlaceholderMapping } from "./types";
import { markdownCodeBlock } from "./ui";
type TableSource = {
id: string;
@@ -54,26 +53,45 @@ export function TranslationTable({
title,
mapping,
onAdd,
onMerge,
onDetach,
}: {
title: string;
mapping: PlaceholderMapping;
onAdd?: (input: ManualEntry) => Promise<PlaceholderMapping>;
onMerge?: (source: string, target: string) => Promise<PlaceholderMapping>;
onDetach?: (key: string) => Promise<PlaceholderMapping>;
}) {
const { push } = useNavigation();
const { push, pop } = useNavigation();
const [visibleMapping, setVisibleMapping] = useState(mapping);
const [busy, setBusy] = useState(false);
useEffect(() => setVisibleMapping(mapping), [mapping]);
const groups = new Map<string, Array<[string, PlaceholderMapping[string]]>>();
for (const entry of Object.entries(visibleMapping).sort(([a], [b]) =>
a.localeCompare(b),
)) {
const type = entry[1].type || "Sonstige";
const entries = groups.get(type) ?? [];
entries.push(entry);
groups.set(type, entries);
const groups = new Map<string, Map<string, string[]>>();
for (const [key, entry] of Object.entries(visibleMapping).sort(([a], [b]) => a.localeCompare(b))) {
const type = entry.type || "Sonstige";
if (!groups.has(type)) groups.set(type, new Map());
const root = mappingRoot(key, visibleMapping);
const members = groups.get(type)!.get(root) ?? [];
members.push(key);
groups.get(type)!.set(root, members);
}
async function change(action: () => Promise<PlaceholderMapping>, success: string): Promise<boolean> {
if (busy) return false;
setBusy(true);
try {
setVisibleMapping(await action());
await showToast({ style: Toast.Style.Success, title: success });
return true;
} catch (error) {
await showToast({ style: Toast.Style.Failure, title: "Zuordnungen nicht geändert",
message: (error as Error).message });
return false;
} finally { setBusy(false); }
}
return (
<List
isLoading={busy}
navigationTitle={`Übersetzungstabelle · ${title}`}
searchBarPlaceholder="Platzhalter oder Klartext suchen"
>
@@ -89,64 +107,47 @@ export function TranslationTable({
</List.Section>}
{[...groups]
.sort(([a], [b]) => a.localeCompare(b))
.map(([type, entries]) => (
<List.Section key={type} title={`${type} · ${entries.length}`}>
{entries.map(([placeholder, entry]) => (
.map(([type, roots]) => (
<List.Section key={type} title={`${type} · ${roots.size} Gruppen / ${[...roots.values()].reduce((n, members) => n + members.length, 0)} Zuordnungen`}>
{[...roots].map(([placeholder, members]) => (
<List.Item
key={placeholder}
icon={Icon.ArrowRight}
title={placeholder}
subtitle={entry.original}
keywords={[entry.original, entry.type, entry.merged_into ?? ""]}
accessories={
entry.merged_into ? [{ text: `→ ${entry.merged_into}` }] : []
}
subtitle={visibleMapping[placeholder].original}
keywords={members.flatMap((key) => [key, visibleMapping[key].original])}
accessories={members.length > 1 ? [{ text: `${members.length} Zuordnungen` }] : []}
actions={
<ActionPanel>
<Action.Push
title="Eintrag vollständig anzeigen"
title="Gruppe und Varianten anzeigen"
icon={Icon.Eye}
target={
<Detail
navigationTitle={placeholder}
markdown={[
`# ${entry.type}`,
"",
"Platzhalter",
markdownCodeBlock(placeholder),
"",
"Klartext",
markdownCodeBlock(entry.original),
...(entry.merged_into
? [
"",
"Zusammengeführt mit",
markdownCodeBlock(entry.merged_into),
]
: []),
].join("\n")}
actions={
<ActionPanel>
<Action.CopyToClipboard
title="Platzhalter kopieren"
content={placeholder}
/>
<Action.CopyToClipboard
title="Klartext kopieren"
content={entry.original}
/>
</ActionPanel>
}
/>
<List navigationTitle={`${type} · ${placeholder}`} searchBarPlaceholder="Variante suchen">
{members.map((key) => <List.Item key={key} title={key}
subtitle={visibleMapping[key].original}
accessories={key === placeholder ? [{ text: "Hauptbegriff" }] : [{ text: `→ ${placeholder}` }]}
actions={<ActionPanel>
{key !== placeholder && onDetach && <Action title="Aus Gruppe lösen" icon={Icon.ArrowLeft}
onAction={async () => { if (await change(() => onDetach(key), "Zuordnung aus Gruppe gelöst")) pop(); }} />}
<Action.CopyToClipboard title="Platzhalter kopieren" content={key} />
<Action.CopyToClipboard title="Klartext kopieren" content={visibleMapping[key].original} />
</ActionPanel>} />)}
</List>
}
/>
{onMerge && roots.size > 1 && <ActionPanel.Submenu title="Mit Hauptbegriff zusammenfassen" icon={Icon.Link}>
{[...roots.keys()].filter((target) => target !== placeholder).map((target) =>
<Action key={target} title={`${visibleMapping[target].original} · ${target}`}
onAction={() => change(() => onMerge(placeholder, target), "Zuordnungen zusammengefasst")} />)}
</ActionPanel.Submenu>}
<Action.CopyToClipboard
title="Platzhalter kopieren"
content={placeholder}
/>
<Action.CopyToClipboard
title="Klartext kopieren"
content={entry.original}
content={visibleMapping[placeholder].original}
/>
</ActionPanel>
}
@@ -230,6 +231,18 @@ export default function Command() {
await refresh();
return run.mapping;
}}
onMerge={async (from, into) => {
const run = await updateProjectMapping(source.id,
(current) => mergeMappingGroups(current, from, into));
await refresh();
return run.mapping;
}}
onDetach={async (key) => {
const run = await updateProjectMapping(source.id,
(current) => detachMappingGroup(current, key));
await refresh();
return run.mapping;
}}
/>
}
/>
@@ -267,6 +280,22 @@ export default function Command() {
await refresh();
return updated.mapping;
}}
onMerge={async (from, into) => {
const session = await getSession(source.id);
if (!session) throw new Error("Sitzung nicht gefunden.");
const updated = await updateSessionMapping(session.id,
mergeMappingGroups(session.mapping, from, into), session.entityTypes);
await refresh();
return updated.mapping;
}}
onDetach={async (key) => {
const session = await getSession(source.id);
if (!session) throw new Error("Sitzung nicht gefunden.");
const updated = await updateSessionMapping(session.id,
detachMappingGroup(session.mapping, key), session.entityTypes);
await refresh();
return updated.mapping;
}}
/>
}
/>

View File

@@ -0,0 +1,42 @@
import { describe, expect, it } from "bun:test";
import { detachMappingGroup, mappingForRestoration, mergeMappingGroups } from "../src/lib/mapping-groups";
import type { PlaceholderMapping } from "../src/types";
describe("Zuordnungen gruppieren und wiederherstellen", () => {
const original: PlaceholderMapping = {
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
PERSON_02: { type: "PERSON", original: "Franz F.", merged_into: "PERSON_01" },
PERSON_03: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_02" },
PERSON_04: { type: "PERSON", original: "Mara Muster" },
ORG_01: { type: "ORG", original: "Muster GmbH" },
};
it("verwendet für alle Verweise den Hauptbegriff ohne die gespeicherten Varianten zu ändern", () => {
const restored = mappingForRestoration(original);
expect(restored.PERSON_01.original).toBe("Franz Fuchs");
expect(restored.PERSON_02.original).toBe("Franz Fuchs");
expect(restored.PERSON_03.original).toBe("Franz Fuchs");
expect(restored.PERSON_03.merged_into).toBeUndefined();
expect(original.PERSON_03.original).toBe("Hr. Fuchs");
});
it("fasst ganze Gruppen zusammen und kann einen einzelnen Verweis wieder lösen", () => {
const merged = mergeMappingGroups(original, "PERSON_02", "PERSON_04");
expect(merged.PERSON_01.merged_into).toBe("PERSON_04");
expect(merged.PERSON_02.merged_into).toBe("PERSON_04");
expect(merged.PERSON_03.merged_into).toBe("PERSON_04");
expect(mappingForRestoration(merged).PERSON_03.original).toBe("Mara Muster");
expect(detachMappingGroup(merged, "PERSON_03").PERSON_03.merged_into).toBeUndefined();
expect(original.PERSON_01.merged_into).toBeUndefined();
expect(() => mergeMappingGroups(original, "PERSON_01", "ORG_01")).toThrow("derselben Kategorie");
});
it("stoppt defekte oder zyklische Verweise vor dem Klartext-Export", () => {
expect(() => mappingForRestoration({ PERSON_01: { type: "PERSON", original: "A", merged_into: "PERSON_99" } }))
.toThrow("Ungültiger Hauptbegriff");
expect(() => mappingForRestoration({
PERSON_01: { type: "PERSON", original: "A", merged_into: "PERSON_02" },
PERSON_02: { type: "PERSON", original: "B", merged_into: "PERSON_01" },
})).toThrow("Zyklische Zuordnung");
});
});

View File

@@ -6,6 +6,8 @@ import type { RunFile } from "../src/lib/velum-project";
mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() } }));
const project = await import("../src/lib/velum-project");
const { mappingForRestoration } = await import("../src/lib/mapping-groups");
const { mergeMappingGroups } = await import("../src/lib/mapping-groups");
const roots: string[] = [];
afterEach(async () => { await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); });
@@ -186,6 +188,15 @@ describe("Velum-Projektstände", () => {
expect(() => project.safeRelativePath("../geheim.txt")).toThrow();
});
it("stellt alte Personen-Verweise in Text und Dateiname mit dem Hauptbegriff wieder her", () => {
const mapping = mappingForRestoration({
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
PERSON_02: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
});
expect(project.restoreText("PERSON_02 und PERSON_01", mapping)).toBe("Franz Fuchs und Franz Fuchs");
expect(project.restorePath("PERSON_02_Entwurf.md", mapping)).toBe("Franz Fuchs_Entwurf.md");
});
it("verwendet ältere Zuordnungen nur bei übereinstimmender Bedeutung und meldet übrig gebliebene Markdown-Platzhalter", () => {
const current = { PERSON_01: { original: "Alex Beispiel", type: "PERSON" } };
const older = [
@@ -209,7 +220,10 @@ describe("Velum-Projektstände", () => {
const relPath = "Fragenliste.md";
first.run.files = [{ source: relPath, output: relPath, kind: "text" }];
second.run.files = [{ source: relPath, output: relPath, kind: "text" }];
first.run.mapping = { PERSON_61: { original: "Alex Beispiel", type: "PERSON" } };
first.run.mapping = {
PERSON_60: { original: "Alex Beispiel", type: "PERSON" },
PERSON_61: { original: "Hr. Beispiel", type: "PERSON", merged_into: "PERSON_60" },
};
second.run.mapping = { PERSON_61: { original: "Mara Muster", type: "PERSON" } };
const source = Buffer.from("Kommentar PERSON_61");
await fs.writeFile(join(first.directory, "files", relPath), source);
@@ -242,6 +256,28 @@ describe("Velum-Projektstände", () => {
{ original: "Weiterer Begriff", type: "PERSON" }).placeholder).toBe("PERSON_62");
});
it("speichert eine Gruppierung als neuen Projektstand und lässt frühere Dateien unverändert", async () => {
const root = await fs.mkdtemp(join(tmpdir(), "velum-group-mapping-"));
roots.push(root);
const source = join(root, "Quelle");
await fs.mkdir(source);
const saved = await project.createRun(source, root);
saved.run.mapping = {
PERSON_01: { original: "Franz Fuchs", type: "PERSON" },
PERSON_02: { original: "Hr. Fuchs", type: "PERSON" },
};
saved.run.files = [{ source: "Notiz.md", output: "Notiz.md", kind: "text" }];
await fs.writeFile(join(saved.directory, "files", "Notiz.md"), "PERSON_02");
await project.saveRun(saved.directory, saved.run);
const updated = await project.updateProjectMapping(source,
(mapping) => mergeMappingGroups(mapping, "PERSON_02", "PERSON_01"), root);
expect(updated.mapping.PERSON_02.merged_into).toBe("PERSON_01");
expect((await project.listRuns(source, root))[1].run.mapping.PERSON_02.merged_into).toBeUndefined();
expect(await fs.readFile(join(project.projectDataRoot(source, root), "runs", updated.id, "files", "Notiz.md"), "utf8"))
.toBe("PERSON_02");
expect(project.restoreText("PERSON_02", mappingForRestoration(updated.mapping))).toBe("Franz Fuchs");
});
it("verhindert eine neue projektweite Zuordnung für eine früher anders belegte ID", () => {
expect(() => project.prepareManualMappingEntry({}, [
{ PERSON_61: { original: "Alex Beispiel", type: "PERSON" } },