feat: improve Velum hit review and session creation
This commit is contained in:
@@ -52,6 +52,8 @@ export function ContextPicker(props: { sessions: VelumSession[]; activeSessionId
|
||||
icon={session.id === props.activeSessionId ? Icon.CheckCircle : Icon.Circle} />)}
|
||||
<Form.Dropdown.Item value={NEW_SESSION_ID} title="Neue Sitzung" icon={Icon.Plus} />
|
||||
</Form.Dropdown>
|
||||
{selected === NEW_SESSION_ID && <Form.TextField id="newSessionName" title="Sitzungsname"
|
||||
placeholder="Leer lassen für einen automatisch vergebenen Namen" />}
|
||||
{selected === NEW_PROJECT_ID && <Form.FilePicker id="newProjectPath" title="Projektordner"
|
||||
allowMultipleSelection={false} canChooseDirectories canChooseFiles={false} />}
|
||||
</>;
|
||||
|
||||
@@ -3,5 +3,6 @@ export const NEW_PROJECT_ID = "__new_project__";
|
||||
|
||||
export type ContextFormValues = {
|
||||
sessionId: string;
|
||||
newSessionName?: string;
|
||||
newProjectPath?: string[];
|
||||
};
|
||||
|
||||
@@ -121,6 +121,37 @@ export function groupReviewHits<T extends GroupableHit>(hits: T[]): ReviewGroup<
|
||||
return [...groups.values()].sort((a, b) => a.type.localeCompare(b.type) || a.original.localeCompare(b.original));
|
||||
}
|
||||
|
||||
/** Render source text literally, even if it contains Markdown or HTML. */
|
||||
export function literalReviewContext(text: string): string {
|
||||
let longestRun = 2;
|
||||
for (const [run] of text.matchAll(/`+/g)) longestRun = Math.max(longestRun, run.length);
|
||||
const fence = "`".repeat(longestRun + 1);
|
||||
return `${fence}\n${text}\n${fence}`;
|
||||
}
|
||||
|
||||
/** Text API positions count Unicode code points. Mark the exact occurrence in each snippet. */
|
||||
export function textHitContexts(text: string, spans: Array<{ start: number; end: number }>): string[] {
|
||||
const characters = Array.from(text);
|
||||
const contexts: string[] = [];
|
||||
let cursor = 0;
|
||||
let line = 1;
|
||||
for (const { span, index } of spans.map((span, index) => ({ span, index })).sort((a, b) => a.span.start - b.span.start)) {
|
||||
const { start, end } = span;
|
||||
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start >= end || end > characters.length) {
|
||||
contexts[index] = "Ungültige Trefferposition der Velum-API.";
|
||||
continue;
|
||||
}
|
||||
for (; cursor < start; cursor++) {
|
||||
if (characters[cursor] === "\n" || (characters[cursor] === "\r" && characters[cursor + 1] !== "\n")) line++;
|
||||
}
|
||||
const before = characters.slice(Math.max(0, start - 90), start).join("");
|
||||
const match = characters.slice(start, end).join("");
|
||||
const after = characters.slice(end, end + 90).join("");
|
||||
contexts[index] = `**Zeile ${line}**\n\n${literalReviewContext(`${before}⟦${match}⟧${after}`)}`;
|
||||
}
|
||||
return contexts;
|
||||
}
|
||||
|
||||
export function withoutWhitelistedHits<T extends GroupableHit>(hits: T[], whitelist: ProjectWhitelistEntry[]): T[] {
|
||||
const excluded = new Set(whitelist.map(whitelistKey));
|
||||
return hits.filter((hit) => !excluded.has(whitelistKey(hit)));
|
||||
|
||||
76
src/person-merge-targets.tsx
Normal file
76
src/person-merge-targets.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { Action, ActionPanel, Icon, List, useNavigation } from "@raycast/api";
|
||||
import { useState } from "react";
|
||||
|
||||
const PAGE_SIZE = 200;
|
||||
|
||||
export 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.ceil(matching.length / PAGE_SIZE);
|
||||
return (
|
||||
<List
|
||||
navigationTitle="Zusammenführen mit"
|
||||
filtering={false}
|
||||
searchText={query}
|
||||
searchBarPlaceholder="Person oder Platzhalter suchen"
|
||||
onSearchTextChange={(value) => {
|
||||
setQuery(value);
|
||||
setPage(0);
|
||||
}}
|
||||
>
|
||||
{pages > 1 && (
|
||||
<List.Item
|
||||
id="page"
|
||||
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 * PAGE_SIZE, (page + 1) * PAGE_SIZE)
|
||||
.map((person) => (
|
||||
<List.Item
|
||||
key={person.placeholder}
|
||||
id={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>
|
||||
);
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
saveProjectWhitelist, scanProjectFiles, whitelistKey, withoutExcludedProjectFiles,
|
||||
} from "./lib/velum-project";
|
||||
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, SkippedProjectFile } from "./lib/velum-project";
|
||||
import { canonicalPerson, groupReviewHits, mergePeople } from "./lib/project-review";
|
||||
import { canonicalPerson, groupReviewHits, literalReviewContext, 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 {
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "./lib/project-jobs";
|
||||
import type { ProjectJobState } from "./lib/project-jobs";
|
||||
import type { Hit, Preview } from "./lib/project-work";
|
||||
import { PersonMergeTargets } from "./person-merge-targets";
|
||||
|
||||
const run = promisify(execFile);
|
||||
const REVIEW_PAGE_SIZE = 200;
|
||||
@@ -57,34 +58,13 @@ function OccurrenceReview(props: { original: string; placeholder: string; hits:
|
||||
const [page, setPage] = useState(0);
|
||||
const pages = Math.ceil(props.hits.length / REVIEW_PAGE_SIZE);
|
||||
return <List isShowingDetail navigationTitle={`${props.original} → ${props.placeholder}`}>
|
||||
{pages > 1 && <List.Item title={`Vorkommen · Seite ${page + 1}/${pages}`} actions={<ActionPanel>
|
||||
{pages > 1 && <List.Item id="page" 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>} />)}
|
||||
{props.hits.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((hit) => <List.Item
|
||||
key={hit.id} id={hit.id} title={hit.file} subtitle={hit.source === hit.file ? "Dateiinhalt" : hit.source}
|
||||
detail={<List.Item.Detail markdown={literalReviewContext(hit.context)} />} />)}
|
||||
</List>;
|
||||
}
|
||||
|
||||
@@ -251,7 +231,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
|
||||
</List.Section>}
|
||||
{[...byType].map(([type, entries]) => <List.Section key={type}
|
||||
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}
|
||||
{entries.map((group) => <List.Item key={group.key} id={group.hits[0].id}
|
||||
icon={{ source: selectedGroups.has(group.key) ? Icon.CheckCircle : Icon.Circle,
|
||||
tintColor: selectedGroups.has(group.key) ? Color.Green : Color.SecondaryText }}
|
||||
title={group.original} subtitle={`→ ${group.placeholder}`}
|
||||
|
||||
@@ -65,14 +65,17 @@ export async function setActiveSession(id: string): Promise<void> {
|
||||
await LocalStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, id);
|
||||
}
|
||||
|
||||
export async function createSession(name?: string): Promise<VelumSession> {
|
||||
export async function createSession(name?: string,
|
||||
initial?: Pick<VelumSession, "mapping" | "entityTypes" | "excludedTerms">): Promise<VelumSession> {
|
||||
const timestamp = nowIso();
|
||||
const session: VelumSession = {
|
||||
id: randomUUID(),
|
||||
name: name || `Sitzung ${new Date().toLocaleString()}`,
|
||||
name: name?.trim() || `Sitzung ${new Date().toLocaleString()}`,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
mapping: {},
|
||||
...initial,
|
||||
...(initial && { mappingCreatedAt: mappingDates(undefined, initial.mapping, timestamp) }),
|
||||
};
|
||||
|
||||
const sessions = await listSessions();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import { canonicalProjectPath, createRun, forceMasks, listRuns, loadProjectRules,
|
||||
loadProjectWhitelist, replaceSpans, saveProjectWhitelist, saveRun, toUtf16Offsets, updateProjectMapping, whitelistKey } from "./lib/velum-project";
|
||||
import { mappingForRestoration } from "./lib/mapping-groups";
|
||||
import { mappingForRestoration, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups";
|
||||
import type { ProjectWhitelistEntry } from "./lib/velum-project";
|
||||
import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID, type ContextFormValues } from "./context-values";
|
||||
import { createSession, getSession, setActiveSession, updateSessionMapping } from "./sessions";
|
||||
@@ -9,7 +9,7 @@ import type { EntityType, PlaceholderMapping, PseudonymizeResponse, VelumSession
|
||||
import { NEW_SESSION_ID } from "./ui";
|
||||
import { normalizePseudonymizeResponse, pseudonymize } from "./velum";
|
||||
|
||||
function projectMapping(mapping: PlaceholderMapping): PlaceholderMapping {
|
||||
export function bareMapping(mapping: PlaceholderMapping): PlaceholderMapping {
|
||||
return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [
|
||||
key.replace(/^<|>$/g, ""),
|
||||
{ ...entry, merged_into: entry.merged_into?.replace(/^<|>$/g, "") },
|
||||
@@ -47,6 +47,7 @@ export type PreparedText = {
|
||||
previous: PlaceholderMapping;
|
||||
exclusions: ProjectWhitelistEntry[];
|
||||
selected: string;
|
||||
newSessionName?: string;
|
||||
projectPath?: string;
|
||||
projectName?: string;
|
||||
};
|
||||
@@ -83,30 +84,51 @@ export async function prepareTextInContext(values: ContextFormValues, text: stri
|
||||
if (selected !== NEW_SESSION_ID && !session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
|
||||
const previous = session?.mapping ?? {};
|
||||
const exclusions = session?.excludedTerms ?? [];
|
||||
const raw = applyProjectWhitelist(text, await request(text, previous, entityTypes), previous, exclusions);
|
||||
const raw = applyProjectWhitelist(text, await request(text, bareMapping(previous), entityTypes), previous, exclusions);
|
||||
if (!raw.spans.length && raw.pseudonymized_text !== text) {
|
||||
throw new Error("Die Analyse lieferte Maskierungen ohne überprüfbare Treffer. Es wurde nichts gespeichert.");
|
||||
}
|
||||
return { text, raw, previous, exclusions, selected };
|
||||
return { text, raw, previous, exclusions, selected, newSessionName: values.newSessionName };
|
||||
}
|
||||
|
||||
/** Commit only the explicitly selected hits; rejected terms become context-specific exceptions. */
|
||||
export async function commitPreparedText(prepared: PreparedText, selectedHits: Set<number>, forAi = false):
|
||||
export async function commitPreparedText(prepared: PreparedText, selectedHits: Set<number>, forAi = false,
|
||||
personMerges: Record<string, string> = {}):
|
||||
Promise<{ result: PseudonymizeResponse; session: VelumSession }> {
|
||||
const accepted = prepared.raw.spans.filter((_, index) => selectedHits.has(index));
|
||||
const rejected = prepared.raw.spans.filter((_, index) => !selectedHits.has(index));
|
||||
const spans = toUtf16Offsets(prepared.text, accepted).map((span, index) => ({ ...span, id: String(index) }));
|
||||
const known = projectMapping(prepared.previous);
|
||||
const preview = projectMapping(prepared.raw.mapping);
|
||||
const known = bareMapping(prepared.previous);
|
||||
const preview = { ...known, ...bareMapping(prepared.raw.mapping) };
|
||||
const active = new Set(accepted.map((span) => span.placeholder.replace(/^<|>$/g, "")));
|
||||
const mapping: PlaceholderMapping = { ...known };
|
||||
let mapping: PlaceholderMapping = { ...known };
|
||||
for (const key of active) {
|
||||
const entry = preview[key];
|
||||
if (!entry) throw new Error(`Zuordnung für ${key} fehlt. Es wurde nichts gespeichert.`);
|
||||
mapping[key] = entry;
|
||||
if (entry.merged_into) {
|
||||
const root = mappingRoot(key, preview);
|
||||
mapping[key] = { ...entry, merged_into: root };
|
||||
mapping[root] = preview[root];
|
||||
}
|
||||
}
|
||||
const raw: PseudonymizeResponse = { ...prepared.raw, spans: accepted,
|
||||
mapping, entity_count: active.size,
|
||||
const selectedPeople = new Set(accepted.filter((span) => span.type === "PERSON")
|
||||
.map((span) => mappingRoot(span.placeholder.replace(/^<|>$/g, ""), mapping)));
|
||||
for (const [source, target] of Object.entries(personMerges)) {
|
||||
if (!selectedPeople.has(source) || mapping[target]?.type !== "PERSON") {
|
||||
throw new Error("Bitte nur ausgewählte Personen mit vorhandenen Zuordnungen zusammenfassen.");
|
||||
}
|
||||
mapping = mergeMappingGroups(mapping, source, target);
|
||||
}
|
||||
const mergedSpans = accepted.map((span) => {
|
||||
if (span.type !== "PERSON") return span;
|
||||
const key = span.placeholder.replace(/^<|>$/g, "");
|
||||
const root = mappingRoot(key, mapping);
|
||||
if (root === key) return span;
|
||||
return { ...span, placeholder: span.placeholder.startsWith("<") ? `<${root}>` : root };
|
||||
});
|
||||
const spans = toUtf16Offsets(prepared.text, mergedSpans).map((span, index) => ({ ...span, id: String(index) }));
|
||||
const raw: PseudonymizeResponse = { ...prepared.raw, spans: mergedSpans,
|
||||
mapping, entity_count: new Set(mergedSpans.map((span) => span.placeholder.replace(/^<|>$/g, ""))).size,
|
||||
pseudonymized_text: replaceSpans(prepared.text, spans, new Set(spans.map((span) => span.id))) };
|
||||
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
|
||||
const additions = rejected.map(({ type, original }) => ({ type, original }));
|
||||
@@ -120,7 +142,12 @@ export async function commitPreparedText(prepared: PreparedText, selectedHits: S
|
||||
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
|
||||
}
|
||||
if (latest) {
|
||||
await updateProjectMapping(path, () => mapping);
|
||||
await updateProjectMapping(path, (current) => {
|
||||
if (JSON.stringify(current) !== JSON.stringify(prepared.previous)) {
|
||||
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
|
||||
}
|
||||
return mapping;
|
||||
});
|
||||
} else {
|
||||
const created = await createRun(path);
|
||||
created.run.mapping = mapping;
|
||||
@@ -130,9 +157,16 @@ export async function commitPreparedText(prepared: PreparedText, selectedHits: S
|
||||
return { result, session: resultSession(path, prepared.projectName ?? path,
|
||||
mappingForRestoration(result.mapping), result.selected_entity_types) };
|
||||
}
|
||||
const session = prepared.selected === NEW_SESSION_ID ? await createSession() : await getSession(prepared.selected);
|
||||
if (prepared.selected === NEW_SESSION_ID) {
|
||||
const saved = await createSession(prepared.newSessionName, {
|
||||
mapping: result.mapping, entityTypes: result.selected_entity_types, excludedTerms: exclusions,
|
||||
});
|
||||
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };
|
||||
}
|
||||
const session = await getSession(prepared.selected);
|
||||
if (!session) throw new Error("Sitzung nicht gefunden. Bitte erneut analysieren.");
|
||||
if (prepared.selected !== NEW_SESSION_ID && JSON.stringify(session.mapping) !== JSON.stringify(prepared.previous)) {
|
||||
if (JSON.stringify(session.mapping) !== JSON.stringify(prepared.previous)
|
||||
|| JSON.stringify(session.excludedTerms ?? []) !== JSON.stringify(prepared.exclusions)) {
|
||||
throw new Error("Die Sitzung wurde inzwischen geändert. Bitte erneut analysieren.");
|
||||
}
|
||||
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types, exclusions);
|
||||
@@ -169,7 +203,7 @@ export async function pseudonymizeInContext(values: ContextFormValues, text: str
|
||||
}))));
|
||||
const raw = applyProjectWhitelist(text,
|
||||
await request(text, latest?.run.mapping ?? {}, entityTypes, masks), latest?.run.mapping ?? {}, whitelist);
|
||||
const mapping = projectMapping(raw.mapping);
|
||||
const mapping = bareMapping(raw.mapping);
|
||||
if (latest) {
|
||||
await updateProjectMapping(path, (current) => {
|
||||
if (JSON.stringify(current) !== JSON.stringify(latest.run.mapping)) {
|
||||
@@ -188,10 +222,10 @@ export async function pseudonymizeInContext(values: ContextFormValues, text: str
|
||||
mappingForRestoration(resultMapping), result.selected_entity_types) };
|
||||
}
|
||||
|
||||
const session = selected === NEW_SESSION_ID ? await createSession() : await getSession(selected);
|
||||
const session = selected === NEW_SESSION_ID ? await createSession(values.newSessionName) : await getSession(selected);
|
||||
if (!session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
|
||||
await setActiveSession(session.id);
|
||||
const raw = await request(text, session.mapping, entityTypes);
|
||||
const raw = await request(text, bareMapping(session.mapping), entityTypes);
|
||||
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
|
||||
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types);
|
||||
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };
|
||||
|
||||
@@ -1,28 +1,120 @@
|
||||
import { Action, ActionPanel, Icon, List, showToast, Toast } from "@raycast/api";
|
||||
import {
|
||||
Action,
|
||||
ActionPanel,
|
||||
Icon,
|
||||
List,
|
||||
showToast,
|
||||
Toast,
|
||||
useNavigation,
|
||||
} from "@raycast/api";
|
||||
import { useMemo, useState } from "react";
|
||||
import { groupReviewHits } from "./lib/project-review";
|
||||
import { commitPreparedText, type PreparedText } from "./text-context";
|
||||
import { mappingRoot } from "./lib/mapping-groups";
|
||||
import {
|
||||
canonicalPerson,
|
||||
groupReviewHits,
|
||||
mergePeople,
|
||||
textHitContexts,
|
||||
} from "./lib/project-review";
|
||||
import { PersonMergeTargets } from "./person-merge-targets";
|
||||
import {
|
||||
bareMapping,
|
||||
commitPreparedText,
|
||||
type PreparedText,
|
||||
} from "./text-context";
|
||||
import type { PseudonymizeResponse, VelumSession } from "./types";
|
||||
|
||||
export function TextHitReview(props: { prepared: PreparedText; forAi?: boolean;
|
||||
onConfirmed: (result: PseudonymizeResponse, session: VelumSession) => Promise<void> | void }) {
|
||||
export function TextHitReview(props: {
|
||||
prepared: PreparedText;
|
||||
forAi?: boolean;
|
||||
onConfirmed: (
|
||||
result: PseudonymizeResponse,
|
||||
session: VelumSession,
|
||||
) => Promise<void> | void;
|
||||
}) {
|
||||
const { push } = useNavigation();
|
||||
const [selected, setSelected] = useState<Set<number>>(
|
||||
() => new Set(props.prepared.raw.spans.map((_, index) => index)));
|
||||
() => new Set(props.prepared.raw.spans.map((_, index) => index)),
|
||||
);
|
||||
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const groups = useMemo(() => groupReviewHits(props.prepared.raw.spans.map((span, index) => ({
|
||||
...span, id: String(index),
|
||||
}))), [props.prepared]);
|
||||
const byType = new Map<string, typeof groups>();
|
||||
for (const group of groups) {
|
||||
if (!byType.has(group.type)) byType.set(group.type, []);
|
||||
byType.get(group.type)!.push(group);
|
||||
}
|
||||
const { byType, people, personByHit } = useMemo(() => {
|
||||
const { text, raw, previous } = props.prepared;
|
||||
const contexts = textHitContexts(text, raw.spans);
|
||||
const hits = raw.spans.map((span, index) => ({
|
||||
...span,
|
||||
id: String(index),
|
||||
context: contexts[index],
|
||||
}));
|
||||
const groups = groupReviewHits(hits);
|
||||
const byType = new Map<string, typeof groups>();
|
||||
for (const group of groups) {
|
||||
if (!byType.has(group.type)) byType.set(group.type, []);
|
||||
byType.get(group.type)!.push(group);
|
||||
}
|
||||
|
||||
const known = bareMapping(previous);
|
||||
const mapping = { ...known, ...bareMapping(raw.mapping) };
|
||||
const names = new Map<string, Set<string>>();
|
||||
for (const [key, entry] of Object.entries(mapping)) {
|
||||
if (entry.type !== "PERSON") continue;
|
||||
const root = mappingRoot(key, mapping);
|
||||
if (!names.has(root)) names.set(root, new Set([mapping[root].original]));
|
||||
names.get(root)!.add(entry.original);
|
||||
}
|
||||
const personByHit = new Map<number, string>();
|
||||
for (const [index, hit] of hits.entries()) {
|
||||
if (hit.type !== "PERSON") continue;
|
||||
const key = hit.placeholder.replace(/^<|>$/g, "");
|
||||
if (!mapping[key]) continue;
|
||||
const root = mappingRoot(key, mapping);
|
||||
personByHit.set(index, root);
|
||||
names.get(root)?.add(hit.original);
|
||||
}
|
||||
const people = [...names]
|
||||
.map(([placeholder, originals]) => ({
|
||||
placeholder,
|
||||
originals: [...originals],
|
||||
saved: Boolean(known[placeholder]),
|
||||
}))
|
||||
.sort((a, b) => a.originals[0].localeCompare(b.originals[0]));
|
||||
return { byType, people, personByHit };
|
||||
}, [props.prepared]);
|
||||
|
||||
const selectedPeople = new Set(
|
||||
[...personByHit]
|
||||
.filter(([index]) => selected.has(index))
|
||||
.map(([, person]) => person),
|
||||
);
|
||||
const availablePeople = people.filter(
|
||||
(person) => person.saved || selectedPeople.has(person.placeholder),
|
||||
);
|
||||
const availablePlaceholders = new Set(
|
||||
availablePeople.map((person) => person.placeholder),
|
||||
);
|
||||
const activeMerges = Object.fromEntries(
|
||||
Object.entries(personMerges).filter(
|
||||
([source, target]) =>
|
||||
selectedPeople.has(source) && availablePlaceholders.has(target),
|
||||
),
|
||||
);
|
||||
const mergeTargets = availablePeople.filter(
|
||||
({ placeholder }) => !activeMerges[placeholder],
|
||||
);
|
||||
|
||||
async function confirm() {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
const toast = await showToast({ style: Toast.Style.Animated, title: "Auswahl wird übernommen" });
|
||||
const toast = await showToast({
|
||||
style: Toast.Style.Animated,
|
||||
title: "Auswahl wird übernommen",
|
||||
});
|
||||
try {
|
||||
const { result, session } = await commitPreparedText(props.prepared, selected, props.forAi);
|
||||
const { result, session } = await commitPreparedText(
|
||||
props.prepared,
|
||||
selected,
|
||||
props.forAi,
|
||||
activeMerges,
|
||||
);
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = "Auswahl übernommen";
|
||||
toast.message = `${selected.size} Treffer bestätigt`;
|
||||
@@ -31,42 +123,125 @@ export function TextHitReview(props: { prepared: PreparedText; forAi?: boolean;
|
||||
toast.style = Toast.Style.Failure;
|
||||
toast.title = "Auswahl nicht übernommen";
|
||||
toast.message = error instanceof Error ? error.message : String(error);
|
||||
} finally { setBusy(false); }
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
function toggle(ids: number[]) {
|
||||
setSelected((current) => {
|
||||
const next = new Set(current);
|
||||
const all = ids.every((id) => next.has(id));
|
||||
for (const id of ids) { if (all) next.delete(id); else next.add(id); }
|
||||
for (const id of ids) {
|
||||
if (all) next.delete(id);
|
||||
else next.add(id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
return <List isLoading={busy} isShowingDetail navigationTitle="Treffer vor Pseudonymisierung prüfen"
|
||||
searchBarPlaceholder="Begriff, Kategorie oder Platzhalter suchen">
|
||||
<List.Section title="Abschluss">
|
||||
<List.Item icon={Icon.CheckCircle} title="Auswahl bestätigen"
|
||||
subtitle={`${selected.size} von ${props.prepared.raw.spans.length} Treffern werden maskiert · Abgewählte werden als Ausnahme gespeichert`}
|
||||
detail={<List.Item.Detail markdown="Prüfe die erkannten Begriffe unten. Klicke auf einen Treffer, um ihn ab- oder wieder anzuwählen. Erst mit **Auswahl bestätigen** werden die Zuordnungen gespeichert und der nächste Schritt gestartet." />}
|
||||
actions={<ActionPanel><Action title="Auswahl bestätigen und fortfahren" icon={Icon.CheckCircle} onAction={confirm} /></ActionPanel>} />
|
||||
</List.Section>
|
||||
{[...byType].map(([type, typeGroups]) => <List.Section key={type} title={`${type} · ${typeGroups.length} Begriffe`}>
|
||||
{typeGroups.map((group) => {
|
||||
const ids = group.hits.map((hit) => Number(hit.id));
|
||||
const all = ids.every((id) => selected.has(id));
|
||||
const first = group.hits[0];
|
||||
const start = Math.max(0, first.start - 90);
|
||||
const end = Math.min([...props.prepared.text].length, first.end + 90);
|
||||
const context = [...props.prepared.text].slice(start, end).join("");
|
||||
return <List.Item key={group.key} icon={all ? Icon.CheckCircle : Icon.Circle}
|
||||
title={`${group.original} → ${group.placeholder}`}
|
||||
subtitle={group.hits.length > 1 ? `${group.hits.length} Vorkommen` : undefined}
|
||||
detail={<List.Item.Detail markdown={`**Kontext**\n\n${context.replace(/`/g, "'")}`} />}
|
||||
actions={<ActionPanel>
|
||||
<Action title={all ? "Nicht maskieren" : "Maskieren"} icon={all ? Icon.XMarkCircle : Icon.CheckCircle}
|
||||
onAction={() => toggle(ids)} />
|
||||
<Action title="Auswahl bestätigen und fortfahren" icon={Icon.CheckCircle} onAction={confirm} />
|
||||
</ActionPanel>} />;
|
||||
})}
|
||||
</List.Section>)}
|
||||
</List>;
|
||||
return (
|
||||
<List
|
||||
isLoading={busy}
|
||||
isShowingDetail
|
||||
navigationTitle="Treffer vor Pseudonymisierung prüfen"
|
||||
searchBarPlaceholder="Begriff, Kategorie oder Platzhalter suchen"
|
||||
>
|
||||
<List.Section title="Abschluss">
|
||||
<List.Item
|
||||
id="confirm"
|
||||
icon={Icon.CheckCircle}
|
||||
title="Auswahl bestätigen"
|
||||
subtitle={`${selected.size} von ${props.prepared.raw.spans.length} Treffern werden maskiert · Abgewählte werden als Ausnahme gespeichert`}
|
||||
detail={
|
||||
<List.Item.Detail markdown="Wähle einen Begriff aus, um seine Vorkommen zu sehen. Über das Aktionsmenü einer Person kannst du Namensvarianten zusammenfassen. Mit **Auswahl bestätigen** speicherst du deine Änderungen." />
|
||||
}
|
||||
actions={
|
||||
<ActionPanel>
|
||||
<Action
|
||||
title="Auswahl bestätigen und fortfahren"
|
||||
icon={Icon.CheckCircle}
|
||||
onAction={confirm}
|
||||
/>
|
||||
</ActionPanel>
|
||||
}
|
||||
/>
|
||||
</List.Section>
|
||||
{[...byType].map(([type, typeGroups]) => (
|
||||
<List.Section
|
||||
key={type}
|
||||
title={`${type} · ${typeGroups.length} Begriffe`}
|
||||
>
|
||||
{typeGroups.map((group) => {
|
||||
const ids = group.hits.map((hit) => Number(hit.id));
|
||||
const all = ids.every((id) => selected.has(id));
|
||||
const person = personByHit.get(ids[0]);
|
||||
const canonical = person
|
||||
? canonicalPerson(person, activeMerges)
|
||||
: undefined;
|
||||
return (
|
||||
<List.Item
|
||||
key={group.key}
|
||||
id={`hit-${ids[0]}`}
|
||||
icon={all ? Icon.CheckCircle : Icon.Circle}
|
||||
title={`${group.original} → ${canonical ?? group.placeholder}`}
|
||||
subtitle={
|
||||
group.hits.length > 1
|
||||
? `${group.hits.length} Vorkommen`
|
||||
: undefined
|
||||
}
|
||||
detail={
|
||||
<List.Item.Detail
|
||||
markdown={group.hits.map((hit) => hit.context).join("\n\n")}
|
||||
/>
|
||||
}
|
||||
actions={
|
||||
<ActionPanel>
|
||||
<Action
|
||||
title={all ? "Nicht maskieren" : "Maskieren"}
|
||||
icon={all ? Icon.XMarkCircle : Icon.CheckCircle}
|
||||
onAction={() => toggle(ids)}
|
||||
/>
|
||||
{person && all && mergeTargets.length > 1 && (
|
||||
<Action
|
||||
title="Mit Person zusammenfassen"
|
||||
icon={Icon.Link}
|
||||
onAction={() =>
|
||||
push(
|
||||
<PersonMergeTargets
|
||||
people={mergeTargets.filter(
|
||||
({ placeholder }) => placeholder !== canonical,
|
||||
)}
|
||||
onChoose={(target) =>
|
||||
setPersonMerges(
|
||||
mergePeople(activeMerges, person, target),
|
||||
)
|
||||
}
|
||||
/>,
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{person && activeMerges[person] && (
|
||||
<Action
|
||||
title="Zusammenführung lösen"
|
||||
onAction={() => {
|
||||
const next = { ...activeMerges };
|
||||
delete next[person];
|
||||
setPersonMerges(next);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Action
|
||||
title="Auswahl bestätigen und fortfahren"
|
||||
icon={Icon.CheckCircle}
|
||||
onAction={confirm}
|
||||
/>
|
||||
</ActionPanel>
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</List.Section>
|
||||
))}
|
||||
</List>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { expect, it } from "bun:test";
|
||||
import {
|
||||
canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, reconcileDocumentHitIds,
|
||||
spansBySegment, withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
|
||||
canonicalPerson, filenameScanText, groupReviewHits, literalReviewContext, makeTextBatches, mappingForSelection,
|
||||
mergePeople, reconcileDocumentHitIds, spansBySegment, textHitContexts, withoutPlaceholderHits, withoutWhitelistedHits,
|
||||
withoutWhitelistedRules,
|
||||
} from "../src/lib/project-review";
|
||||
|
||||
it("liest Unterstriche in Namen als Leerzeichen und bewahrt bekannte Codebegriffe", () => {
|
||||
@@ -45,6 +46,20 @@ it("zeigt gleiche Zuordnungen einmal mit der Anzahl ihrer Vorkommen", () => {
|
||||
expect(groups.find((group) => group.placeholder === "PERSON_01")?.hits.map((hit) => hit.id)).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("ordnet E-Mail-Vorkommen nach Unicode-Position zu und markiert jeweils genau den ausgewählten Treffer", () => {
|
||||
const [signature, sender, recipient] = textHitContexts("😀 Von: Max\nAn: Mia\nDanke, Max", [
|
||||
{ start: 26, end: 29 }, { start: 7, end: 10 }, { start: 15, end: 18 },
|
||||
]);
|
||||
expect(signature).toContain("**Zeile 3**");
|
||||
expect(signature).toContain("Danke, ⟦Max⟧");
|
||||
expect(sender).toContain("**Zeile 1**");
|
||||
expect(sender).toContain("😀 Von: ⟦Max⟧");
|
||||
expect(recipient).toContain("**Zeile 2**");
|
||||
expect(recipient).toContain("An: ⟦Mia⟧");
|
||||
const source = ["**Von:** <max@example.com>", "```", ""].join("\n");
|
||||
expect(literalReviewContext(source)).toBe(["````", source, "````"].join("\n"));
|
||||
});
|
||||
|
||||
it("ordnet bestätigte Dokumenttreffer nach einem 409 nur bei identischem Vorkommen neu zu", () => {
|
||||
const hit = { id: "alt", source: "Absatz 1", start: 4, end: 7, type: "PERSON",
|
||||
original: "Max", context: "Herr Max antwortet" };
|
||||
|
||||
@@ -91,12 +91,14 @@ it("merkt abgelehnte Sitzungstreffer und schlägt sie im nächsten Lauf nicht er
|
||||
spans: [{ start: 0, end: 11, type: "PERSON", score: 0.8,
|
||||
placeholder: "PERSON_01", original: "Fachbegriff" }],
|
||||
});
|
||||
const prepared = await prepareTextInContext({ sessionId: "__new_session__" },
|
||||
const prepared = await prepareTextInContext({ sessionId: "__new_session__", newSessionName: " Kundenmail " },
|
||||
"Fachbegriff", ["PERSON"], request);
|
||||
expect(await sessions.listSessions()).toHaveLength(0);
|
||||
const { result, session } = await commitPreparedText(prepared, new Set());
|
||||
expect(result.pseudonymized_text).toBe("Fachbegriff");
|
||||
expect(session.name).toBe("Kundenmail");
|
||||
expect(session.mapping).toEqual({});
|
||||
expect(await sessions.getActiveSessionId()).toBe(session.id);
|
||||
expect((await sessions.getSession(session.id))?.excludedTerms).toEqual([
|
||||
{ type: "PERSON", original: "Fachbegriff" },
|
||||
]);
|
||||
@@ -104,6 +106,59 @@ it("merkt abgelehnte Sitzungstreffer und schlägt sie im nächsten Lauf nicht er
|
||||
expect(next.raw.spans).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["session", "project"])("fasst geprüfte Namensvarianten zusammen und speichert sie für Folgeläufe (%s)", async (context) => {
|
||||
let values = { sessionId: "__new_session__", newProjectPath: [] as string[] };
|
||||
if (context === "project") {
|
||||
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-merge-"));
|
||||
roots.push(root);
|
||||
const folder = join(root, "Projekt");
|
||||
await fs.mkdir(folder);
|
||||
values = { sessionId: "__new_project__", newProjectPath: [folder] };
|
||||
}
|
||||
const source = "😀 Max Muster\nMax und Mia";
|
||||
const prepared = await prepareTextInContext(values, source, ["PERSON"], async () => ({
|
||||
pseudonymized_text: "😀 PERSON_01\nPERSON_02 und PERSON_03",
|
||||
selected_entity_types: ["PERSON"], entity_count: 3,
|
||||
mapping: {
|
||||
PERSON_01: { type: "PERSON", original: "Max Muster" },
|
||||
PERSON_02: { type: "PERSON", original: "Max" },
|
||||
PERSON_03: { type: "PERSON", original: "Mia" },
|
||||
},
|
||||
spans: [
|
||||
{ start: 2, end: 12, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max Muster" },
|
||||
{ start: 13, end: 16, type: "PERSON", score: 1, placeholder: "PERSON_02", original: "Max" },
|
||||
{ start: 21, end: 24, type: "PERSON", score: 1, placeholder: "PERSON_03", original: "Mia" },
|
||||
],
|
||||
}));
|
||||
await expect(commitPreparedText(prepared, new Set([0, 1]), true, { PERSON_02: "PERSON_03" }))
|
||||
.rejects.toThrow("ausgewählte Personen");
|
||||
const { result, session } = await commitPreparedText(prepared, new Set([0, 1]), true, { PERSON_02: "PERSON_01" });
|
||||
expect(result.pseudonymized_text).toBe("😀 <PERSON_01>\n<PERSON_01> und Mia");
|
||||
expect(result.entity_count).toBe(1);
|
||||
expect(result.spans.map((span) => span.placeholder)).toEqual(["PERSON_01", "PERSON_01"]);
|
||||
expect(result.mapping["<PERSON_02>"]).toEqual({ type: "PERSON", original: "Max", merged_into: "<PERSON_01>" });
|
||||
expect(result.mapping["<PERSON_03>"]).toBeUndefined();
|
||||
expect(session.mapping["<PERSON_02>"].original).toBe("Max Muster");
|
||||
|
||||
const followup = await prepareTextInContext({ sessionId: session.id }, "Max und Maximilian", ["PERSON"],
|
||||
async (_text, mapping) => {
|
||||
expect(mapping.PERSON_02.merged_into).toBe("PERSON_01");
|
||||
expect(mapping["<PERSON_02>"]).toBeUndefined();
|
||||
return {
|
||||
pseudonymized_text: "PERSON_01 und PERSON_03", selected_entity_types: ["PERSON"], entity_count: 2,
|
||||
mapping: { ...mapping, PERSON_03: { type: "PERSON", original: "Maximilian" } },
|
||||
spans: [
|
||||
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
|
||||
{ start: 8, end: 18, type: "PERSON", score: 1, placeholder: "PERSON_03", original: "Maximilian" },
|
||||
],
|
||||
};
|
||||
});
|
||||
const updated = await commitPreparedText(followup, new Set([0, 1]), false, { PERSON_01: "PERSON_03" });
|
||||
expect(updated.result.pseudonymized_text).toBe("PERSON_03 und PERSON_03");
|
||||
expect(updated.result.mapping.PERSON_02.merged_into).toBe("PERSON_03");
|
||||
expect(updated.session.mapping.PERSON_02.original).toBe("Maximilian");
|
||||
});
|
||||
|
||||
it("entfernt eine False-Positive-Gruppe aus der Sitzung und merkt alle Varianten", async () => {
|
||||
const session = await sessions.createSession("Test");
|
||||
await sessions.updateSessionMapping(session.id, {
|
||||
|
||||
Reference in New Issue
Block a user