mirror of
https://github.com/bitbaum/causius.git
synced 2026-12-04 05:30:28 +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>
222 lines
9.9 KiB
TypeScript
222 lines
9.9 KiB
TypeScript
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { describe, expect, it } from "vitest";
|
|
import { POST } from "@/app/api/extract-pdf/route";
|
|
import {
|
|
deadlineCorrect,
|
|
metricLines,
|
|
type Outcome,
|
|
type Scored,
|
|
readCases,
|
|
readLetter,
|
|
readReplies,
|
|
report,
|
|
scoreAll,
|
|
scorePrivate,
|
|
scoreReply,
|
|
summary,
|
|
} from "./score";
|
|
|
|
const letters = new URL("./letters/", import.meta.url).pathname;
|
|
const replies = new URL("./replies/", import.meta.url).pathname;
|
|
const { cases, pdfs } = readCases(letters);
|
|
|
|
describe("deadline scorer", () => {
|
|
it("matches the date exactly", () => {
|
|
expect(deadlineCorrect("2026-12-04", "2026-12-04")).toBe(true);
|
|
expect(deadlineCorrect("2026-12-04", "2026-12-05")).toBe(false);
|
|
});
|
|
|
|
it("counts null against null as correct, and a date against nothing as wrong", () => {
|
|
expect(deadlineCorrect(null, null)).toBe(true);
|
|
expect(deadlineCorrect(null, undefined)).toBe(true);
|
|
expect(deadlineCorrect(null, "2026-12-04")).toBe(false);
|
|
expect(deadlineCorrect("2026-12-04", null)).toBe(false);
|
|
});
|
|
|
|
const wrap = (o: object) => ({ id: "x", reply: `Here you go:\n${JSON.stringify({ title: "T", ...o })}` });
|
|
|
|
it("reads the deadline through caseFromReply, prose around the JSON and all", () => {
|
|
expect(scoreReply({ id: "x", expected: "2026-12-04" }, wrap({ deadline: "2026-12-04" })).correct).toBe(true);
|
|
expect(scoreReply({ id: "x", expected: null }, wrap({})).correct).toBe(true);
|
|
expect(scoreReply({ id: "x", expected: null }, wrap({ deadline: "2026-12-04" })).correct).toBe(false);
|
|
});
|
|
|
|
it("treats a reply that is not a case, or missing, as a miss even when none was expected", () => {
|
|
expect(scoreReply({ id: "x", expected: null }, { id: "x", reply: "sorry, I cannot" })).toMatchObject({
|
|
correct: false,
|
|
problem: "unparseable",
|
|
});
|
|
expect(scoreReply({ id: "x", expected: null }, undefined)).toMatchObject({ correct: false, problem: "no_reply" });
|
|
});
|
|
|
|
it("treats a range as any date inside it, ends included", () => {
|
|
const r: [string, string] = ["2026-12-07", "2026-12-08"];
|
|
expect(deadlineCorrect(r, "2026-12-07")).toBe(true);
|
|
expect(deadlineCorrect(r, "2026-12-08")).toBe(true);
|
|
expect(deadlineCorrect(r, "2026-12-09")).toBe(false);
|
|
expect(deadlineCorrect(r, "2026-12-06")).toBe(false);
|
|
expect(deadlineCorrect(r, null)).toBe(false);
|
|
});
|
|
|
|
it("names each outcome: invention, true positive, miss, wrong date", () => {
|
|
const o = (expected: string | null, actual: string | null) =>
|
|
scoreReply({ id: "x", expected }, { id: "x", reply: JSON.stringify({ title: "T", ...(actual ? { deadline: actual } : {}) }) }).outcome;
|
|
expect(o(null, null)).toBe("true_negative");
|
|
expect(o(null, "2026-12-04")).toBe("invention");
|
|
expect(o("2026-12-04", "2026-12-04")).toBe("true_positive");
|
|
expect(o("2026-12-04", null)).toBe("miss");
|
|
expect(o("2026-12-04", "2026-12-05")).toBe("wrong_date");
|
|
});
|
|
|
|
it("computes precision, recall and the false-invention rate", () => {
|
|
const r = (expected: string | null, actual: string | null, outcome: Outcome): Scored => ({
|
|
id: "x", expected, actual, correct: outcome === "true_negative" || outcome === "true_positive", outcome,
|
|
});
|
|
const rs = [
|
|
r("2026-01-01", "2026-01-01", "true_positive"),
|
|
r("2026-01-02", "2026-01-09", "wrong_date"), // a miss and a false positive
|
|
r("2026-01-03", null, "miss"),
|
|
r(null, "2026-01-04", "invention"),
|
|
r(null, null, "true_negative"),
|
|
];
|
|
const m = summary(rs);
|
|
expect(m).toMatchObject({ correct: 2, total: 5, dated: 3, truePositives: 1, falsePositives: 2, noDeadline: 2, inventions: 1 });
|
|
const text = report([], []).split("\n");
|
|
expect(text).toContain("deadline accuracy 0/0 (0%)");
|
|
expect(text).toContain("false-invention rate 0/0 (n/a)");
|
|
expect(metricLines(m)).toEqual([
|
|
"deadline accuracy 2/5 (40%)",
|
|
"dated-deadline precision 1/3 (33%)",
|
|
"dated-deadline recall 1/3 (33%)",
|
|
"false-invention rate 1/2 (50%)",
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe("the eval set", () => {
|
|
it("has 12 to 25 letters in German, French and English, most of the traps among them", () => {
|
|
expect(cases.length).toBeGreaterThanOrEqual(12);
|
|
expect(cases.length).toBeLessThanOrEqual(25);
|
|
for (const id of ["de-sperrung-ohne-datum", "fr-montant-sans-date", "en-spend-cap-reset", "en-update-2-3-working-days"]) {
|
|
expect(cases.some((c) => c.id === id), id).toBe(true);
|
|
}
|
|
expect(cases.some((c) => Array.isArray(c.expected))).toBe(true);
|
|
expect(new Set(cases.map((c) => c.lang))).toEqual(new Set(["de", "fr", "en"]));
|
|
expect(cases.filter((c) => c.expected === null).length).toBeGreaterThanOrEqual(5);
|
|
expect(cases.filter((c) => c.kind === "relative").length).toBeGreaterThanOrEqual(5);
|
|
});
|
|
|
|
it("has a letter file and an ISO date for every case", () => {
|
|
for (const c of cases) {
|
|
expect(readLetter(letters, c).length).toBeGreaterThan(100);
|
|
expect(c.today).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
|
for (const d of [c.expected ?? []].flat()) expect(d).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
|
}
|
|
});
|
|
|
|
it("states each expected deadline's quote in the letter itself", () => {
|
|
for (const c of cases.filter((x) => x.quote)) {
|
|
expect(readLetter(letters, c).replace(/\s+/g, " ")).toContain(c.quote);
|
|
}
|
|
});
|
|
|
|
it("scores the stored replies offline and reports the accuracy line", () => {
|
|
const stored = readReplies(replies);
|
|
for (const c of cases) expect(stored.has(c.id), `reply for ${c.id}`).toBe(true);
|
|
const results = scoreAll(cases, stored);
|
|
expect(results.every((r) => r.problem === undefined)).toBe(true);
|
|
const { correct, total } = summary(results);
|
|
expect(total).toBe(cases.length);
|
|
expect(report(cases, results)).toContain(`deadline accuracy ${correct}/${total}`);
|
|
// The fixtures hold three deliberate failures (a wrong date, a missing date and one
|
|
// invented deadline on a spend-cap reset), so the scorer is seen to fail too.
|
|
expect(total - correct).toBe(3);
|
|
const m = summary(results);
|
|
expect(m).toMatchObject({ truePositives: 14, falsePositives: 2, dated: 16, inventions: 1, noDeadline: 5 });
|
|
});
|
|
});
|
|
|
|
describe("the eval PDFs", () => {
|
|
async function extract(file: string) {
|
|
const form = new FormData();
|
|
form.set("file", new File([readFileSync(new URL(`./letters/${file}`, import.meta.url))], "letter.pdf"));
|
|
return POST(new Request("http://x/api/extract-pdf", { method: "POST", body: form, headers: { "x-forwarded-for": "10.6.6.6" } }));
|
|
}
|
|
|
|
it("reads the text layer to the letter's words", async () => {
|
|
for (const p of pdfs.filter((x) => x.layer === "text")) {
|
|
const res = await extract(p.file);
|
|
expect(res.status).toBe(200);
|
|
const { text } = await res.json();
|
|
const c = cases.find((x) => x.id === p.letter)!;
|
|
expect(text.replace(/\s+/g, " ")).toContain(c.quote!.slice(0, 30));
|
|
}
|
|
});
|
|
|
|
it("calls the image-only PDF a scan", async () => {
|
|
for (const p of pdfs.filter((x) => x.layer === "none")) {
|
|
const res = await extract(p.file);
|
|
expect(res.status).toBe(422);
|
|
expect((await res.json()).error).toBe("scanned_pdf");
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("the optional private set", () => {
|
|
const fresh = () => mkdtempSync(join(tmpdir(), "eval-private-"));
|
|
const secret = "secret-name";
|
|
const day = "2031-05-17";
|
|
|
|
function make(items: object[], replies: Record<string, object> | null, letters = true) {
|
|
const dir = fresh();
|
|
if (letters) {
|
|
mkdirSync(join(dir, "letters"));
|
|
writeFileSync(join(dir, "letters", `${secret}.txt`), "SECRET LETTER BODY");
|
|
}
|
|
if (items.length || letters) writeFileSync(join(dir, "answers.json"), JSON.stringify({ items }));
|
|
if (replies) {
|
|
mkdirSync(join(dir, "replies"));
|
|
for (const [id, o] of Object.entries(replies)) {
|
|
writeFileSync(join(dir, "replies", `${id}.json`), JSON.stringify({ id, reply: JSON.stringify({ title: "T", ...o }) }));
|
|
}
|
|
}
|
|
return dir;
|
|
}
|
|
|
|
it("is skipped quietly when the directory is absent", () => {
|
|
expect(scorePrivate(join(fresh(), "nope")).lines).toEqual(["private set: not present, skipped"]);
|
|
});
|
|
|
|
it("is skipped when there are no letters, no answer key or no stored replies", () => {
|
|
expect(scorePrivate(fresh()).lines[0]).toContain("no letters");
|
|
const noKey = make([], null);
|
|
rmSync(join(noKey, "answers.json"));
|
|
expect(scorePrivate(noKey).lines).toEqual(["private set: answers.json missing, skipped"]);
|
|
const noReplies = make([{ letter: `letters/${secret}.txt`, today: "2031-05-01", deadline: null }], null);
|
|
expect(scorePrivate(noReplies).lines[0]).toContain("no stored replies");
|
|
});
|
|
|
|
it("scores with the metrics, reads ranges, and prints only counts and positions", () => {
|
|
const dir = make(
|
|
[
|
|
{ letter: `letters/${secret}.txt`, today: "2031-05-01", deadline: day },
|
|
{ letter: "letters/b.txt", today: "2031-05-01", deadline: null },
|
|
{ letter: "letters/c.txt", today: "2031-05-01", deadline: ["2031-06-02", "2031-06-03"] },
|
|
{ letter: "letters/d.txt", today: "2031-05-01", deadline: null },
|
|
],
|
|
{ [secret]: { deadline: "2031-05-18" }, b: {}, c: { deadline: "2031-06-03" }, d: { deadline: "2031-07-09" } },
|
|
);
|
|
const out = scorePrivate(dir);
|
|
expect(out.scored).toMatchObject({ correct: 2, total: 4, truePositives: 1, falsePositives: 2, noDeadline: 2, inventions: 1 });
|
|
const text = out.lines.join("\n");
|
|
expect(text).toContain("private: deadline accuracy 2/4 (50%)");
|
|
expect(text).toContain("private: dated-deadline precision 1/3 (33%)");
|
|
expect(text).toContain("private: false-invention rate 1/2 (50%)");
|
|
expect(text).toContain("MISS private #1");
|
|
expect(text).toContain("MISS private #4 FALSE INVENTION");
|
|
for (const leak of [secret, day, "2031", "SECRET LETTER", "letters/", ".txt"]) expect(text).not.toContain(leak);
|
|
});
|
|
});
|