Files
subcast/scripts/eval-translate.mjs
向阳乔木 eaf574e08b feat(eval): --refine mode, and document the refine tier
eval-translate.mjs --refine runs src/lib/refine.ts over a fixture's translation
(or --translate's) through the existing apiStub; REFINE_MODEL / REVIEW_MODEL pick
the writer and reviewer. ARCHITECTURE.md, the plan (§V.9) and eval/CLAUDE.md
describe the refine tier and its gaps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 07:46:16 -08:00

119 lines
7.0 KiB
JavaScript

#!/usr/bin/env node
/**
* [INPUT]: depends on eval/fixtures/<id>/{transcript,translation?,ctx?,reference?,<candidate>?}.json;
* on eval/lib/metrics.mjs (deterministic), eval/lib/judge.mjs (--judge), eval/lib/appTranslate.mjs (--translate, --refine).
* [OUTPUT]: writes eval/reports/<date>-<label>.json and prints one table row per fixture.
* [POS]: the entry point of the subtitle evaluation harness (docs/SUBTITLE_TRANSLATION_PLAN.md §2). Every
* pipeline change runs it before and after; the numbers go into the PR description.
* [PROTOCOL]: Update this header on change, then check CLAUDE.md
*
* Usage:
* node scripts/eval-translate.mjs [--label baseline] [--fixtures a,b] [--candidate segments.json]
* [--translate [--polish]] [--refine] [--judge [--judge-limit 200]] [--no-write]
* --refine runs the refine tier (src/lib/refine.ts) over the translation (the fixture's, or --translate's).
* Env: TRANSLATE_BASE_URL / TRANSLATE_API_KEY / TRANSLATE_MODEL for --translate and --refine
* (REFINE_MODEL / REVIEW_MODEL pick other models on that endpoint for --refine);
* EVAL_BASE_URL / EVAL_API_KEY / EVAL_MODEL for --judge (skipped with a note when unset).
*/
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { chrF, segmentationMetrics, translationMetrics } from "../eval/lib/metrics.mjs";
import { judgeConfig, mqmJudge } from "../eval/lib/judge.mjs";
const root = fileURLToPath(new URL("..", import.meta.url));
const FIXTURES = join(root, "eval/fixtures"), REPORTS = join(root, "eval/reports");
const args = process.argv.slice(2);
const flag = (name) => args.includes(`--${name}`);
const opt = (name, fallback) => { const i = args.indexOf(`--${name}`); return i >= 0 && args[i + 1] && !args[i + 1].startsWith("--") ? args[i + 1] : fallback; };
const readJson = (dir, name) => (existsSync(join(dir, name)) ? JSON.parse(readFileSync(join(dir, name), "utf8")) : null);
const label = opt("label", "baseline").replace(/[^\w.-]+/g, "-");
const only = opt("fixtures", "")?.split(",").filter(Boolean);
const ids = readdirSync(FIXTURES, { withFileTypes: true }).filter((d) => d.isDirectory() && (!only?.length || only.includes(d.name))).map((d) => d.name).sort();
if (!ids.length) { console.error("no fixtures"); process.exit(1); }
const judging = flag("judge") && judgeConfig();
if (flag("judge") && !judging) console.warn("--judge skipped: set EVAL_BASE_URL and EVAL_MODEL (and EVAL_API_KEY)");
const translate = flag("translate") ? (await import("../eval/lib/appTranslate.mjs")).translateWithApp : null;
const refine = flag("refine") ? (await import("../eval/lib/appTranslate.mjs")).refineWithApp : null;
const results = [];
for (const id of ids) {
const dir = join(FIXTURES, id);
const tr = readJson(dir, "transcript.json");
const ctx = readJson(dir, "ctx.json");
const ref = readJson(dir, "reference.json");
// The cues judged: a candidate segmentation (later pipeline stages) or the transcript as it is.
const cand = opt("candidate") ? readJson(dir, opt("candidate")) : null;
const cues = cand?.segments ?? tr.segments;
let items = cand?.items ?? readJson(dir, "translation.json")?.items ?? null;
let engine = cand ? "candidate" : readJson(dir, "translation.json")?.engine ?? null;
let run = null;
if (translate) {
process.stdout.write(`translating ${id}…\n`);
run = await translate({ ...tr, segments: cues }, ctx, { polish: flag("polish") });
items = run.items;
engine = `llm:${run.model}`;
}
let refined = null;
if (refine && items) {
process.stdout.write(`refining ${id}…\n`);
refined = await refine({ ...tr, segments: cues }, ctx, items);
items = refined.items;
engine = `${engine ?? "fixture"}+refine:${refined.model}/${refined.reviewer}`;
}
const row = {
id, kind: tr.kind, source: tr.source, cues: cues.length, engine,
segmentation: segmentationMetrics(tr.segments, cues),
translation: items ? translationMetrics(cues, items, ctx?.terms ?? []) : null,
chrF: ref?.items && items ? chrF(items, ref.items) : null,
run: run && { ms: run.ms, firstBatchMs: run.firstBatchMs, calls: run.calls, inputTokens: run.inputTokens, outputTokens: run.outputTokens, cachedTokens: run.cachedTokens },
refine: refined && { ms: refined.ms, calls: refined.calls, inputTokens: refined.inputTokens, outputTokens: refined.outputTokens, cachedTokens: refined.cachedTokens, ...refined.refine },
mqm: null,
};
if (judging && items) {
process.stdout.write(`judging ${id}…\n`);
row.mqm = await mqmJudge(cues, items, ctx, { limit: Number(opt("judge-limit", 200)) });
}
if (run || refined) row.items = items;
results.push(row);
}
// ---- table -------------------------------------------------------------------------------------------------
const cols = [
["fixture", (r) => r.id],
["cues", (r) => r.cues],
["cover%", (r) => r.segmentation.coveragePct],
["words avg/p95/max", (r) => `${r.segmentation.words.avg}/${r.segmentation.words.p95}/${r.segmentation.words.max}`],
["sec avg/p95/max", (r) => `${r.segmentation.seconds.avg}/${r.segmentation.seconds.p95}/${r.segmentation.seconds.max}`],
["<1s", (r) => r.segmentation.under1s],
[">1s gap", (r) => r.segmentation.overSilence1s ?? "—"],
["engine", (r) => r.engine ?? "—"],
["done%", (r) => r.translation?.translatedPct ?? "—"],
["half%", (r) => r.translation?.halfSentencePct ?? "—"],
[">16字%", (r) => r.translation?.over16Pct ?? "—"],
[">32字%", (r) => r.translation?.over32Pct ?? "—"],
[">9字/s%", (r) => r.translation?.over9cpsPct ?? "—"],
["term%", (r) => (r.translation?.terms.checked ? `${r.translation.terms.consistentPct} (${r.translation.terms.checked})` : "—")],
["MQM/100w", (r) => r.mqm?.per100Words ?? "—"],
];
const width = (s) => [...String(s)].reduce((n, ch) => n + (/[ -鿿＀-￯]/.test(ch) ? 2 : 1), 0);
const pad = (s, w) => String(s) + " ".repeat(Math.max(0, w - width(s)));
const rows = [cols.map(([h]) => h), ...results.map((r) => cols.map(([, f]) => f(r)))];
const widths = cols.map((_, c) => Math.max(...rows.map((r) => width(r[c]))));
for (const [i, r] of rows.entries()) {
console.log(r.map((v, c) => pad(v, widths[c])).join(" "));
if (i === 0) console.log(widths.map((w) => "-".repeat(w)).join(" "));
}
for (const r of results) if (r.translation?.terms.inconsistent.length) console.log(` ${r.id} inconsistent terms: ${r.translation.terms.inconsistent.join(", ")}`);
if (!flag("no-write")) {
mkdirSync(REPORTS, { recursive: true });
const date = new Date().toISOString().slice(0, 10);
const file = join(REPORTS, `${date}-${label}.json`);
const report = { label, date, node: process.version, translate: translate ? { polish: flag("polish") } : null, refine: refine ? true : null, judge: judging ? { model: judging.model } : null, fixtures: results };
writeFileSync(file, JSON.stringify(report, null, 1) + "\n");
console.log(`\nreport → ${file.replace(root, "")}`);
}