mirror of
https://github.com/bitbaum/causius.git
synced 2026-12-04 05:07:50 +01:00
* feat(intake): PDF on the quick check, and a deadline eval set - /api/extract-pdf reads a PDF's text layer on the server (unpdf, %PDF magic check, 10 MB, 10 pages, text capped at MAX_TEXT). Nothing stored or logged. Scans answer scanned_pdf; the page then offers the photo picker. - One file input takes a PDF or photos; the text flows into the letter box and the existing redaction and analyze path. Messages in en, de, fr, it. - eval/letters: 17 synthetic Swiss letters (de, fr, en) with expected deadlines; eval/pdf: text and image-only PDFs; `pnpm eval:deadlines` scores stored replies offline, or live with --url on the free chain. - Docs: README quick-check/matter line, ROADMAP ticks, CHANGELOG 2026-12-02, .env.example host path. Co-Authored-By: Claude <noreply@anthropic.com> * feat(eval): optional private letter set, scored separately --private <dir> / CAUSIUS_EVAL_PRIVATE_DIR (default /opt/causius/shared/eval-private). Absent: "private set: not present, skipped". Present: "private: N/M (x%)" and pass/fail by position only; no ids, names, quotes or dates are printed. eval-private/ and eval/private/ ignored. Co-Authored-By: Claude <noreply@anthropic.com> * feat(eval): precision, recall and false-invention rate; answer key for the private set Most letters correctly have no deadline, so each is scored true negative, false invention, true positive, miss or wrong date. Ranges accept any date in them. Private set reads answers.json and letters/*.txt and prints only counts, metrics and pass/fail by position. Four more synthetic traps: open-ended suspension risk, amount with no date, spend-cap reset, 2-3 working days. Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
209 lines
8.8 KiB
TypeScript
209 lines
8.8 KiB
TypeScript
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
import { basename, join } from "node:path";
|
|
import { caseFromReply } from "@/lib/analyze";
|
|
|
|
/**
|
|
* The deadline eval: how often does a reply carry the right deadline, and how
|
|
* often does it invent one?
|
|
*
|
|
* Most letters correctly have NO dated deadline, so plain accuracy flatters a
|
|
* model that says "none" or one that always guesses. Each letter is therefore
|
|
* one of:
|
|
*
|
|
* expected none, predicted none correct (true negative)
|
|
* expected none, predicted a date FALSE INVENTION
|
|
* expected a date, predicted that date true positive
|
|
* expected a date, predicted nothing miss
|
|
* expected a date, predicted another miss, and a false positive too
|
|
*
|
|
* A date that is not a legal duty (a spend-cap or quota reset, a billing
|
|
* cycle) is not a deadline: the expected value is none. A range means any date
|
|
* in it, ends included, is right ("within 2-3 working days").
|
|
*
|
|
* Pure scoring, no network. A reply is the model's raw text (what
|
|
* `caseFromReply` takes in the app), so a stored reply goes through exactly the
|
|
* path a live one does: extractJson, then the case schema. A reply that does
|
|
* not become a case is a miss, never a pass.
|
|
*/
|
|
export type Expected = string | [string, string] | null;
|
|
|
|
export interface LetterCase {
|
|
id: string;
|
|
lang: string;
|
|
/** The reference "today" the deadline is judged against. */
|
|
today: string;
|
|
/** ISO date, or inclusive [from, to] range, a careful reader derives; null when none. */
|
|
expected: Expected;
|
|
kind: "absolute" | "relative" | "range" | "none";
|
|
file: string;
|
|
quote?: string;
|
|
}
|
|
|
|
export interface StoredReply {
|
|
id: string;
|
|
source?: string;
|
|
reply: string;
|
|
}
|
|
|
|
export type Outcome = "true_negative" | "invention" | "true_positive" | "miss" | "wrong_date" | "no_reply" | "unparseable";
|
|
|
|
export interface Scored {
|
|
id: string;
|
|
expected: Expected;
|
|
actual: string | null;
|
|
correct: boolean;
|
|
outcome: Outcome;
|
|
/** Why it is a miss when it is not a plain wrong date. */
|
|
problem?: "no_reply" | "unparseable";
|
|
}
|
|
|
|
/** Exact date match, or inside the inclusive range; no deadline expected and none given is correct too. */
|
|
export function deadlineCorrect(expected: Expected, actual: string | null | undefined): boolean {
|
|
if (expected === null) return (actual ?? null) === null;
|
|
if (actual === null || actual === undefined) return false;
|
|
if (Array.isArray(expected)) return actual >= expected[0] && actual <= expected[1];
|
|
return actual === expected;
|
|
}
|
|
|
|
function outcomeOf(expected: Expected, actual: string | null): Outcome {
|
|
if (expected === null) return actual === null ? "true_negative" : "invention";
|
|
if (actual === null) return "miss";
|
|
return deadlineCorrect(expected, actual) ? "true_positive" : "wrong_date";
|
|
}
|
|
|
|
export function scoreReply(c: { id: string; expected: Expected }, stored: StoredReply | undefined): Scored {
|
|
if (!stored) return { id: c.id, expected: c.expected, actual: null, correct: false, outcome: "no_reply", problem: "no_reply" };
|
|
const parsed = caseFromReply(stored.reply);
|
|
if (!parsed) return { id: c.id, expected: c.expected, actual: null, correct: false, outcome: "unparseable", problem: "unparseable" };
|
|
const actual = parsed.deadline ?? null;
|
|
return { id: c.id, expected: c.expected, actual, correct: deadlineCorrect(c.expected, actual), outcome: outcomeOf(c.expected, actual) };
|
|
}
|
|
|
|
export function scoreAll(cases: { id: string; expected: Expected }[], replies: Map<string, StoredReply>): Scored[] {
|
|
return cases.map((c) => scoreReply(c, replies.get(c.id)));
|
|
}
|
|
|
|
const pct = (n: number, d: number) => (d ? Math.round((n / d) * 100) : null);
|
|
|
|
export interface Metrics {
|
|
correct: number;
|
|
total: number;
|
|
pct: number;
|
|
/** Letters with an expected date, and how many got it right. */
|
|
dated: number;
|
|
truePositives: number;
|
|
/** Dates given that are wrong: inventions plus wrong dates on dated letters. */
|
|
falsePositives: number;
|
|
/** Letters with no deadline, and how many were given one anyway. */
|
|
noDeadline: number;
|
|
inventions: number;
|
|
}
|
|
|
|
export function summary(results: Scored[]): Metrics {
|
|
const count = (o: Outcome) => results.filter((r) => r.outcome === o).length;
|
|
const correct = results.filter((r) => r.correct).length;
|
|
const total = results.length;
|
|
const truePositives = count("true_positive");
|
|
const inventions = count("invention");
|
|
return {
|
|
correct,
|
|
total,
|
|
pct: pct(correct, total) ?? 0,
|
|
dated: results.filter((r) => r.expected !== null).length,
|
|
truePositives,
|
|
falsePositives: inventions + count("wrong_date"),
|
|
noDeadline: results.filter((r) => r.expected === null).length,
|
|
inventions,
|
|
};
|
|
}
|
|
|
|
function ratio(label: string, n: number, d: number): string {
|
|
const p = pct(n, d);
|
|
return `${label} ${n}/${d}${p === null ? " (n/a)" : ` (${p}%)`}`;
|
|
}
|
|
|
|
/** The metric lines, shared by the public and private reports. */
|
|
export function metricLines(m: Metrics, prefix = ""): string[] {
|
|
return [
|
|
`${prefix}deadline accuracy ${m.correct}/${m.total} (${m.pct}%)`,
|
|
ratio(`${prefix}dated-deadline precision`, m.truePositives, m.truePositives + m.falsePositives),
|
|
ratio(`${prefix}dated-deadline recall`, m.truePositives, m.dated),
|
|
ratio(`${prefix}false-invention rate`, m.inventions, m.noDeadline),
|
|
];
|
|
}
|
|
|
|
const show = (e: Expected) => (e === null ? "none" : Array.isArray(e) ? `${e[0]}..${e[1]}` : e);
|
|
|
|
export function report(cases: LetterCase[], results: Scored[]): string {
|
|
void cases;
|
|
const rows = results.map((r) => {
|
|
const mark = r.correct ? "ok " : "MISS";
|
|
const got = r.problem ? `<${r.problem}>` : (r.actual ?? "none");
|
|
const note = r.outcome === "invention" ? " FALSE INVENTION" : "";
|
|
return `${mark} ${r.id.padEnd(34)} expected ${show(r.expected).padEnd(22)} got ${got}${note}`;
|
|
});
|
|
return [...rows, "", ...metricLines(summary(results))].join("\n");
|
|
}
|
|
|
|
export function readCases(dir: string): { cases: LetterCase[]; pdfs: { file: string; layer: "text" | "none"; letter: string }[] } {
|
|
const raw = JSON.parse(readFileSync(join(dir, "cases.json"), "utf8"));
|
|
return { cases: raw.cases, pdfs: raw.pdfs ?? [] };
|
|
}
|
|
|
|
export function readLetter(dir: string, c: LetterCase): string {
|
|
return readFileSync(join(dir, c.file), "utf8");
|
|
}
|
|
|
|
export function readReplies(dir: string): Map<string, StoredReply> {
|
|
const out = new Map<string, StoredReply>();
|
|
for (const f of readdirSync(dir).filter((n) => n.endsWith(".json"))) {
|
|
const r = JSON.parse(readFileSync(join(dir, f), "utf8")) as StoredReply;
|
|
out.set(r.id, r);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** Where an optional private letter set lives unless told otherwise. */
|
|
export const DEFAULT_PRIVATE_DIR = "/opt/causius/shared/eval-private";
|
|
|
|
/**
|
|
* An optional private set: `<dir>/letters/*.txt`, the answer key
|
|
* `<dir>/answers.json` and stored replies in `<dir>/replies/*.json`, each
|
|
* reply's `id` being its letter's path in answers.json ("letters/01.txt") or
|
|
* just its file name without extension ("01"). Scored separately.
|
|
*
|
|
* Nothing about its content is ever returned: only counts, the metrics, and
|
|
* pass/fail by position. No ids, filenames, quotes or dates leave this
|
|
* function, so nothing here can reach a terminal, a log or a CI artefact.
|
|
*/
|
|
export function scorePrivate(dir: string): { lines: string[]; scored?: Metrics } {
|
|
if (!existsSync(dir)) return { lines: ["private set: not present, skipped"] };
|
|
const lettersDir = join(dir, "letters");
|
|
const hasLetters = existsSync(lettersDir) && readdirSync(lettersDir).some((n) => n.endsWith(".txt"));
|
|
if (!hasLetters) return { lines: ["private set: no letters, skipped"] };
|
|
const answersFile = join(dir, "answers.json");
|
|
if (!existsSync(answersFile)) return { lines: ["private set: answers.json missing, skipped"] };
|
|
|
|
let items: { letter: string; deadline: Expected }[];
|
|
let replies = new Map<string, StoredReply>();
|
|
try {
|
|
const raw = JSON.parse(readFileSync(answersFile, "utf8")).items;
|
|
if (!Array.isArray(raw)) throw new Error("items");
|
|
items = raw.map((i: { letter: string; deadline?: Expected }) => ({ letter: String(i.letter), deadline: i.deadline ?? null }));
|
|
const repliesDir = join(dir, "replies");
|
|
if (existsSync(repliesDir)) replies = readReplies(repliesDir);
|
|
} catch {
|
|
return { lines: ["private set: present but unreadable, skipped"] };
|
|
}
|
|
if (items.length === 0) return { lines: ["private set: no letters, skipped"] };
|
|
if (replies.size === 0) return { lines: [`private set: ${items.length} letters, no stored replies, skipped`] };
|
|
|
|
const results = items.map((i) => {
|
|
const stem = basename(i.letter).replace(/\.txt$/, "");
|
|
return scoreReply({ id: i.letter, expected: i.deadline }, replies.get(i.letter) ?? replies.get(stem));
|
|
});
|
|
const m = summary(results);
|
|
const rows = results.map((r, n) => `${r.correct ? "ok " : "MISS"} private #${n + 1}${r.outcome === "invention" ? " FALSE INVENTION" : ""}`);
|
|
return { lines: [...rows, "", ...metricLines(m, "private: ")], scored: m };
|
|
}
|