Transcribe through OpenRouter when OPENROUTER_API_KEY is set
A Claude subscription can't be used by the app, so let it use any cheap
vision model on OpenRouter instead (default google/gemini-3.1-flash-lite,
OPENROUTER_MODEL to change). The Anthropic API stays available as the
second choice. Both providers share the prompt and live behind one
{ name, model, transcribe } interface in server/providers.mjs; OpenRouter
retries 408/429/5xx and network errors and turns 401/402/404 into
messages the editor can show.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
This commit is contained in:
parent
46aa1236ed
commit
f353c14619
11 changed files with 258 additions and 91 deletions
|
|
@ -10,16 +10,16 @@ import { createStore } from "../server/store.mjs";
|
|||
const PASS = "tajne-heslo";
|
||||
const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
|
||||
const replies = ["=-1-\n~JEDNÁNÍ PRVNÍ\n@LÍDA\nDobrý den.", "=2\nještě já.\n@Mise\nAno."];
|
||||
const client = { messages: { create: async (p) => ({ stop_reason: "end_turn", content: [{ type: "text", text: replies.shift() }], usage: {} }) } };
|
||||
const provider = { name: "stub", model: "stub-model", transcribe: async () => replies.shift() };
|
||||
|
||||
let dir, server, base;
|
||||
test.before(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "tr-"));
|
||||
Object.assign(config, { dataDir: dir, password: PASS, apiKey: "test", dailyPageLimit: 3 });
|
||||
Object.assign(config, { dataDir: dir, password: PASS, dailyPageLimit: 3 });
|
||||
const store = createStore(dir);
|
||||
await store.init();
|
||||
await store.seed(config.seedDir);
|
||||
server = createServer(store, client).listen(0);
|
||||
server = createServer(store, provider).listen(0);
|
||||
base = `http://127.0.0.1:${server.address().port}`;
|
||||
});
|
||||
test.after(async () => { server.close(); await rm(dir, { recursive: true, force: true }); });
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { splitPage, normalizeSpeakers, assemble, transcribePage, PageError } from "../server/transcribe.mjs";
|
||||
import { splitPage, normalizeSpeakers, assemble } from "../server/transcribe.mjs";
|
||||
import { anthropicProvider, openRouterProvider, makeProvider, PageError } from "../server/providers.mjs";
|
||||
import { parsePlay, lint } from "../public/parse.js";
|
||||
|
||||
test("splitPage takes the page number from the first line", () => {
|
||||
|
|
@ -30,17 +31,71 @@ test("assemble numbers pages, marks gaps and failed pages", () => {
|
|||
});
|
||||
|
||||
const stub = (response) => ({ messages: { create: async (params) => { stub.last = params; return response; } } });
|
||||
const JPEG = Buffer.from([0xff, 0xd8, 1]);
|
||||
|
||||
test("transcribePage sends the image and reads text blocks", async () => {
|
||||
test("anthropic: sends the image and reads text blocks", async () => {
|
||||
const client = stub({ stop_reason: "end_turn", content: [{ type: "thinking", thinking: "" }, { type: "text", text: "=1\n@A\nx" }], usage: {} });
|
||||
const { text } = await transcribePage(client, "claude-haiku-5-5", Buffer.from([0xff, 0xd8, 1]));
|
||||
const text = await anthropicProvider({ client, model: "claude-haiku-5-5" }).transcribe(JPEG);
|
||||
assert.equal(text, "=1\n@A\nx");
|
||||
const img = stub.last.messages[0].content[0];
|
||||
assert.equal(img.source.media_type, "image/jpeg");
|
||||
assert.equal(stub.last.messages[0].content[0].source.media_type, "image/jpeg");
|
||||
assert.equal(stub.last.model, "claude-haiku-5-5");
|
||||
});
|
||||
|
||||
test("transcribePage reports refusals and truncation", async () => {
|
||||
await assert.rejects(transcribePage(stub({ stop_reason: "refusal", content: [] }), "m", Buffer.alloc(2)), PageError);
|
||||
await assert.rejects(transcribePage(stub({ stop_reason: "max_tokens", content: [{ type: "text", text: "x" }] }), "m", Buffer.alloc(2)), PageError);
|
||||
test("anthropic: refusals and truncation become page errors", async () => {
|
||||
const p = (r) => anthropicProvider({ client: stub(r), model: "m" }).transcribe(JPEG);
|
||||
await assert.rejects(p({ stop_reason: "refusal", content: [] }), PageError);
|
||||
await assert.rejects(p({ stop_reason: "max_tokens", content: [{ type: "text", text: "x" }] }), PageError);
|
||||
});
|
||||
|
||||
// fake fetch: returns the queued responses in order and records the requests
|
||||
function fakeFetch(...responses) {
|
||||
const calls = [];
|
||||
const f = async (url, init) => {
|
||||
calls.push({ url, init, body: JSON.parse(init.body) });
|
||||
const r = responses.shift();
|
||||
if (r instanceof Error) throw r;
|
||||
return new Response(JSON.stringify(r.body), { status: r.status || 200, headers: { "content-type": "application/json" } });
|
||||
};
|
||||
f.calls = calls;
|
||||
return f;
|
||||
}
|
||||
const ok = (text, finish = "stop") => ({ body: { choices: [{ finish_reason: finish, message: { role: "assistant", content: text } }] } });
|
||||
|
||||
test("openrouter: sends a data-URL image with the key and reads the answer", async () => {
|
||||
const f = fakeFetch(ok("=2\n@Lída\nAno."));
|
||||
const p = openRouterProvider({ apiKey: "sk-or-test", model: "google/gemini-3.1-flash-lite", fetchImpl: f });
|
||||
assert.equal(await p.transcribe(JPEG), "=2\n@Lída\nAno.");
|
||||
const [{ url, init, body }] = f.calls;
|
||||
assert.equal(url, "https://openrouter.ai/api/v1/chat/completions");
|
||||
assert.equal(init.headers.Authorization, "Bearer sk-or-test");
|
||||
assert.equal(body.model, "google/gemini-3.1-flash-lite");
|
||||
assert.equal(body.messages[0].role, "system");
|
||||
assert.match(body.messages[1].content[0].image_url.url, /^data:image\/jpeg;base64,/);
|
||||
});
|
||||
|
||||
test("openrouter: retries rate limits and network errors, then gives up with a readable message", async () => {
|
||||
const f = fakeFetch({ status: 429, body: { error: { code: 429, message: "slow down" } } }, new Error("ECONNRESET"), ok("=1\nx"));
|
||||
assert.equal(await openRouterProvider({ apiKey: "k", model: "m", fetchImpl: f, retryDelayMs: 1 }).transcribe(JPEG), "=1\nx");
|
||||
assert.equal(f.calls.length, 3);
|
||||
|
||||
const g = fakeFetch({ status: 402, body: { error: { code: 402, message: "Insufficient credits" } } });
|
||||
await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: g, retryDelayMs: 1 }).transcribe(JPEG), /out of credit/);
|
||||
assert.equal(g.calls.length, 1); // not retried
|
||||
|
||||
// an error inside a 200 body counts too
|
||||
const h = fakeFetch({ body: { error: { code: 401, message: "No auth" } } });
|
||||
await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: h }).transcribe(JPEG), /key rejected/);
|
||||
});
|
||||
|
||||
test("openrouter: truncated, filtered or empty answers are page errors", async () => {
|
||||
for (const r of [ok("x", "length"), ok("x", "content_filter"), ok(""), { body: { choices: [] } }])
|
||||
await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: fakeFetch(r) }).transcribe(JPEG), PageError);
|
||||
});
|
||||
|
||||
test("provider choice: OpenRouter first, then Anthropic, else off", () => {
|
||||
assert.equal(makeProvider({}), null);
|
||||
assert.equal(makeProvider({ ANTHROPIC_API_KEY: "a" }).name, "anthropic");
|
||||
const p = makeProvider({ ANTHROPIC_API_KEY: "a", OPENROUTER_API_KEY: "o" });
|
||||
assert.deepEqual([p.name, p.model], ["openrouter", "google/gemini-3.1-flash-lite"]);
|
||||
assert.equal(makeProvider({ OPENROUTER_API_KEY: "o", OPENROUTER_MODEL: "qwen/x" }).model, "qwen/x");
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue