diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f3fb1b..09d21ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,36 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), the numbering [SemVer](https://semver.org/). +## [1.5.0] — 2026-10-16 + +### Added + +- **Optional translation of the whole book.** A **Translate** control in the + panel, above the formats — Off by default — takes one of thirteen target + languages and translates the book between reading it and writing the file, so + EPUB, MOBI, FB2 and TXT all get it. Chapters go out block by block with their + inline markup (italics, bold, line breaks), and what comes back is sanitised + again, so the writers still get well-formed XHTML; chapter titles, notes, the + title and the summary are translated too, the author, tags and fandom are not, + and the book's language becomes the target. A book already in that language is + recognised from the first chapter (by the language Google reports, not by the + site's label) and then left alone. Only chapter bodies vote, not notes or + titles. A chapter the engine keeps refusing stays in the original language + instead of failing the build, and the panel reports how many stayed that way. The choice is remembered in `chrome.storage.sync` as `translateTo`. + + The engine is Google Translate's unofficial web endpoint behind a small + `Translator` interface (`src/translate/`), so another one is a single file. + Requests are batched under a character budget, spaced out, retried with backoff + on 429/5xx (honouring `Retry-After`) and stop on cancel; the stray space the + engine leaves before punctuation after a closing tag is removed. No new + permission and no new dependency. + + **This is the first thing the extension sends anywhere**, which is why it is + opt-in: with translation on, chapter text goes to `translate.googleapis.com`. + The panel says so under the control, and the README's privacy section is updated. + With translation on, a site's own ready-made file (AO3's) is bypassed — it could + not be translated. + ## [1.4.0] — 2026-10-16 ### Changed @@ -166,6 +196,7 @@ In full under "Honest limitations" in the README. the known structure and was not exercised live. - Images do not make it into the book — text only. +[1.5.0]: https://github.com/pruffit/VireBook/releases/tag/v1.5.0 [1.4.0]: https://github.com/pruffit/VireBook/releases/tag/v1.4.0 [1.3.0]: https://github.com/pruffit/VireBook/releases/tag/v1.3.0 [1.2.0]: https://github.com/pruffit/VireBook/releases/tag/v1.2.0 diff --git a/README.md b/README.md index a3d3749..72da43e 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ DOM, not a CSS shadow. The pane can be thrown into any corner of the window. |---|---| | **Formats** | EPUB · MOBI · FB2 · TXT | | **Sites** | ficbook.net · AO3 · fanfics.me · fanfiction.net · wattpad.com · royalroad.com · [any other](#which-sites) | -| **Sends outwards** | nothing — no ``, no screenshots, no network calls | +| **Sends outwards** | nothing by default — no ``, no screenshots. Only if you turn on [translation](#translating-a-book), chapter text goes to Google Translate | | **Licence** | [MIT](LICENSE) | ## Installing @@ -60,6 +60,28 @@ toolbar and choose **Show the button on this page**. The same popup is where the default format is set — it moves to the top of the list. +## Translating a book + +Reading a book that is not in your language? In the panel, **Translate** (above the +formats) takes a target language — Русский, English, Українська, Deutsch, Français, +Español, Italiano, Português, Polski, Türkçe, 日本語, 中文, 한국어. It is **Off** by +default, and the choice is remembered. + +With a language picked, the book is read as usual and then translated before the +file is written, so EPUB, MOBI, FB2 and TXT all get it: chapter text (paragraphs, +italics and bold intact), chapter titles, author's notes, the book's title and its +summary. The author, tags and fandom stay as they are, and the file's language is +set to the target. The first chapter is translated first, and if Google reports +that the chapter text was already in the target language, the rest is not sent and +the book is downloaded as it is. If Google keeps refusing some chapters, those stay +in the original language, the rest is translated, and the panel says how many. + +**This is the one thing that leaves the machine.** The chapter text is sent to +Google Translate's public web endpoint, in batches, spaced out; nothing is sent +unless translation is on. The panel says so under the control. With +translation on, a site's own ready-made file (AO3's) is not used, since it cannot +be translated. + ## Getting the file onto a Kindle 11 **EPUB is the main route.** Amazon converts it itself, and the table of contents @@ -115,6 +137,12 @@ Worth knowing before you rely on it: browser: requests carry the reader's own cookies, that is, exactly what is already on their screen. +- **Translation is machine translation, over an unofficial endpoint.** It reads + like Google Translate reads, and the endpoint has no key and no promise: Google + can slow it down or turn it off, in which case the panel says it was refused — + set Translate to Off to download the book as before. A long book takes a minute + or two longer. + ## If something breaks Sites get restyled — that is normal and is fixed one file at a time. @@ -290,6 +318,8 @@ src/lib/ — formats and utilities epub.ts mobi.ts — assembling the book fb2.ts txt.ts util.ts — pacing, backoff, filenames +src/translate/ — optional translation: the engine interface, the Google engine, + batching, and translating a whole Book src/adapters/ — one file per site, plus base.ts, generic.ts and the registry src/glass.ts — the material: vireglass/dom's renderer, ported into a shadow tree src/core.ts — choosing an adapter, fetching chapters, saving the file @@ -313,12 +343,15 @@ Version history is in [CHANGELOG.md](CHANGELOG.md). ## Privacy The extension reads exactly the pages that are already open in the browser and -**sends nothing anywhere**: neither the assembly nor the file leaves the machine. -There are no outbound network calls at all — verifiable by searching for `fetch` -and `XMLHttpRequest`. Downloading is for personal reading. - -Permissions are the minimum: `storage` (the default format and the corner the -pane sits in), `activeTab` and `scripting` (the "show the button on this page" +**sends nothing anywhere by default**: neither the assembly nor the file leaves the +machine, and the only requests are to the book's own site. The exception is +translation, which is off until you turn it on: then the chapter text (and the +title and summary) goes to `translate.googleapis.com`, and nowhere else. Every +request is in `src/core.ts`, `src/translate/google.ts` and the adapters — +verifiable by searching for `fetch`. Downloading is for personal reading. + +Permissions are the minimum: `storage` (the default format, the translation +language and the corner the pane sits in), `activeTab` and `scripting` (the "show the button on this page" action). No ``, no screenshots — the glass makes do with the live DOM. ## Licence diff --git a/dist/content.js b/dist/content.js index e35790e..28d82df 100644 --- a/dist/content.js +++ b/dist/content.js @@ -130,7 +130,7 @@ } } function sanitize(rootNode, opts = {}) { - const { baseUrl = "", keepImages = true, dropSelectors = [] } = opts; + const { baseUrl = "", keepImages = true, dropSelectors = [], wrapBare = true } = opts; const images = []; const working = rootNode.cloneNode(true); for (const sel of dropSelectors) { @@ -188,7 +188,7 @@ for (const child of Array.from(working.childNodes)) walk(child); let xhtml = out.join(""); xhtml = xhtml.replace(/<(p|div|span|em|i|strong|b)>(\s| | )*<\/\1>/g, "").replace(/(\s*){3,}/g, "

").replace(/\s+\n/g, "\n").trim(); - if (!/<(p|div|h[1-6]|blockquote|ul|ol|pre)[\s>]/.test(xhtml) && xhtml) { + if (wrapBare && !/<(p|div|h[1-6]|blockquote|ul|ol|pre)[\s>]/.test(xhtml) && xhtml) { xhtml = `

${xhtml}

`; } return { xhtml, images: Array.from(new Set(images)) }; @@ -1860,10 +1860,403 @@ ${stripTags(c.xhtml)}`).join("\n"); return new Blob(["\uFEFF", head, summary, body, "\n"], { type: "text/plain;charset=utf-8" }); } - // src/core.ts + // src/translate/text.ts + var VOID2 = /* @__PURE__ */ new Set(["br", "hr", "img"]); + var SENTENCE_END = /[.!?…。!?]["'»”’)\]」』]*\s+/g; + function splitSegment(html, budget) { + if (html.length <= budget) return [html]; + const atoms = []; + let cur = ""; + let depth = 0; + for (const token of html.match(/<[^>]*>|[^<]+/g) ?? []) { + if (token.startsWith("<")) { + const m = /^<(\/?)([a-z0-9]+)/i.exec(token); + const name = m ? m[2].toLowerCase() : ""; + cur += token; + if (m && !VOID2.has(name) && !token.endsWith("/>")) depth = Math.max(0, depth + (m[1] ? -1 : 1)); + else if (name === "br" && depth === 0) { + atoms.push(cur); + cur = ""; + } + continue; + } + if (depth > 0) { + cur += token; + continue; + } + let from = 0; + for (const m of token.matchAll(SENTENCE_END)) { + const end = m.index + m[0].length; + atoms.push(cur + token.slice(from, end)); + cur = ""; + from = end; + } + cur += token.slice(from); + } + if (cur) atoms.push(cur); + const pieces = []; + let piece = ""; + for (const atom of atoms) { + if (piece && piece.length + atom.length > budget) { + pieces.push(piece); + piece = ""; + } + piece += atom; + } + if (piece) pieces.push(piece); + return pieces; + } + function joinPieces(pieces) { + let out = ""; + for (const piece of pieces) { + if (!out) out = piece; + else if (/\s*$/i.test(out)) out += piece; + else out = `${out.replace(/\s+$/, "")} ${piece.replace(/^\s+/, "")}`; + } + return out; + } + function planBatches(pieces, budget, maxSegments) { + const groups = []; + let group = []; + let size = 0; + pieces.forEach((piece, i) => { + if (group.length && (group.length >= maxSegments || size + piece.length > budget)) { + groups.push(group); + group = []; + size = 0; + } + group.push(i); + size += piece.length; + }); + if (group.length) groups.push(group); + return groups; + } + var STRAY = /(<\/[a-z0-9]+>) +(?=[.,…)\]}。、!?;:」』!?;:»”’])/gi; + var STRAY_FRENCH = /(<\/[a-z0-9]+>) +(?=[.,…)\]}])/gi; + function normalizeSpacing(html, target) { + return html.replace(target.toLowerCase().startsWith("fr") ? STRAY_FRENCH : STRAY, "$1"); + } + + // src/translate/google.ts + var ENDPOINT = "https://translate.googleapis.com/translate_a/t"; var RETRY_STATUS = /* @__PURE__ */ new Set([408, 425, 429, 500, 502, 503, 504]); - var MAX_ATTEMPTS = 5; var MAX_WAIT = 6e4; + function refusal(status) { + if (status === 429) { + return new Error("Google Translate is limiting requests. Wait a few minutes, or download without translation."); + } + return new Error(`Google Translate refused the request (HTTP ${status}). Try later, or download without translation.`); + } + function textsOf(data, expected) { + if (Array.isArray(data)) { + const texts = data.map((item) => Array.isArray(item) ? item[0] : item); + if (texts.length === expected && texts.every((t) => typeof t === "string")) { + const detected = data.map((item) => Array.isArray(item) && typeof item[1] === "string" ? item[1] : ""); + return { texts, detected }; + } + } + throw new Error("Google Translate answered in a shape we do not understand."); + } + function createGoogleTranslator(options = {}) { + const { budget = 4500, maxSegments = 40, gap = 350, maxAttempts = 5, backoffBase = 1200 } = options; + const doFetch = options.fetch ?? ((input, init) => fetch(input, init)); + const limiter = createRateLimiter({ interval: gap, maxInterval: 15e3 }); + async function send(queries, from, to, signal) { + const url = `${ENDPOINT}?client=gtx&sl=${encodeURIComponent(from)}&tl=${encodeURIComponent(to)}&format=html`; + const body = new URLSearchParams(); + for (const q of queries) body.append("q", q); + let refused = null; + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { + await limiter.acquire(signal); + if (signal?.aborted) throw abortError(); + let res; + try { + res = await doFetch(url, { method: "POST", body, signal }); + } catch (err) { + if (signal?.aborted) throw err; + refused = new Error("The network is not responding \u2014 check your connection."); + limiter.penalize(0); + if (attempt < maxAttempts - 1) await sleep(backoffDelay(attempt, { base: backoffBase, max: MAX_WAIT }), signal); + continue; + } + if (res.ok) { + limiter.reward(); + return textsOf(await res.json(), queries.length); + } + if (!RETRY_STATUS.has(res.status)) throw refusal(res.status); + const floor = Math.min(MAX_WAIT, parseRetryAfter(res.headers.get("Retry-After"))); + refused = refusal(res.status); + limiter.penalize(floor); + if (attempt < maxAttempts - 1) { + await sleep(backoffDelay(attempt, { base: backoffBase, max: MAX_WAIT, floor }), signal); + } + } + throw refused ?? new Error("Google Translate did not answer."); + } + return { + id: "google", + async translate(segments, from, to, signal) { + const results = segments.map((s) => s.trim() ? "" : s); + const owners = []; + const pieces = []; + segments.forEach((s, i) => { + if (!s.trim()) return; + for (const piece of splitSegment(s, budget)) { + owners.push(i); + pieces.push(piece); + } + }); + const translated = new Array(pieces.length); + const langs = new Array(pieces.length).fill(""); + for (const group of planBatches(pieces, budget, maxSegments)) { + const answer = await send(group.map((i) => pieces[i]), from || "auto", to, signal); + group.forEach((pieceIndex, k) => { + translated[pieceIndex] = normalizeSpacing(answer.texts[k], to); + langs[pieceIndex] = answer.detected[k]; + }); + } + const detected = segments.map(() => ""); + segments.forEach((s, i) => { + if (!s.trim()) return; + const mine = []; + owners.forEach((owner, k) => { + if (owner === i) mine.push(translated[k]); + }); + results[i] = joinPieces(mine); + detected[i] = langs[owners.indexOf(i)]; + }); + return { texts: results, detected }; + } + }; + } + + // src/translate/types.ts + var LANGUAGES = [ + { code: "ru", label: "\u0420\u0443\u0441\u0441\u043A\u0438\u0439" }, + { code: "en", label: "English" }, + { code: "uk", label: "\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430" }, + { code: "de", label: "Deutsch" }, + { code: "fr", label: "Fran\xE7ais" }, + { code: "es", label: "Espa\xF1ol" }, + { code: "it", label: "Italiano" }, + { code: "pt", label: "Portugu\xEAs" }, + { code: "pl", label: "Polski" }, + { code: "tr", label: "T\xFCrk\xE7e" }, + { code: "ja", label: "\u65E5\u672C\u8A9E" }, + { code: "zh-CN", label: "\u4E2D\u6587" }, + { code: "ko", label: "\uD55C\uAD6D\uC5B4" } + ]; + function normalizeTarget(value) { + return LANGUAGES.some((l) => l.code === value) ? value : ""; + } + + // src/translate/book.ts + var TRANSLATE_FROM = 40; + var TRANSLATE_TO = 88; + var STRUCTURAL = /* @__PURE__ */ new Set([ + "p", + "div", + "section", + "article", + "blockquote", + "pre", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "ul", + "ol", + "li", + "hr", + "tr", + "figure", + "figcaption", + "dl", + "dt", + "dd", + "center", + "table", + "thead", + "tbody", + "td", + "th", + "caption" + ]); + var STRUCTURAL_SELECTOR = [...STRUCTURAL].join(","); + var LETTER = new RegExp("\\p{L}", "u"); + var hasText = (html) => LETTER.test(html.replace(/<[^>]*>/g, "")); + function plan(xhtml, segments) { + const doc = new DOMParser().parseFromString(`${xhtml}`, "text/html"); + const out = []; + function emit(nodes, open, close, keepEmpty) { + const holder = doc.createElement("div"); + for (const n of nodes) holder.append(n.cloneNode(true)); + const original = sanitize(holder, { wrapBare: false }).xhtml; + if (!original && !keepEmpty) { + if (holder.textContent?.includes("\n")) out.push("\n"); + return; + } + if (!hasText(holder.innerHTML)) { + if (keepEmpty || /]/.test(original)) out.push(open + original + close); + return; + } + out.push({ seg: segments.push(holder.innerHTML) - 1, open, close, original }); + } + function walk(parent, topLevel) { + let run = []; + const flush = () => { + if (run.length) emit(run, topLevel ? "

" : "", topLevel ? "

" : "", false); + run = []; + }; + for (const node of Array.from(parent.childNodes)) { + const tag = node.nodeType === 1 ? node.tagName.toLowerCase() : ""; + if (!STRUCTURAL.has(tag)) { + run.push(node); + continue; + } + flush(); + const el = node; + if (tag === "hr") out.push("
"); + else if (el.querySelector(STRUCTURAL_SELECTOR)) { + out.push(`<${tag}>`); + walk(el, false); + out.push(``); + } else emit(Array.from(el.childNodes), `<${tag}>`, ``, true); + } + flush(); + } + walk(doc.body, true); + return out; + } + function cleanInline(html) { + const body = new DOMParser().parseFromString(`${html}`, "text/html").body; + return sanitize(body, { wrapBare: false }).xhtml; + } + function render(pieces, translated) { + return pieces.map((p) => { + if (typeof p === "string") return p; + const clean = cleanInline(translated[p.seg] ?? ""); + return p.open + (clean || p.original) + p.close; + }).join(""); + } + var textSegment = (text) => hasText(text) ? escapeText(text) : ""; + function textBack(translated, original) { + if (!translated) return original; + const body = new DOMParser().parseFromString(`${translated}`, "text/html").body; + return normalizeSpace(body.textContent) || original; + } + var baseOf = (code) => code.toLowerCase().split("-")[0]; + function alreadyIn(target) { + const name = LANGUAGES.find((l) => l.code === target)?.label ?? target; + return `The book is already in ${name} \u2014 not translated.`; + } + var MIN_VOTE = 20; + function dominantLanguage(sent, detected) { + const weight = /* @__PURE__ */ new Map(); + sent.forEach((html, i) => { + const code = detected[i]; + const size = html.replace(/<[^>]*>/g, "").trim().length; + if (code && size >= MIN_VOTE) weight.set(baseOf(code), (weight.get(baseOf(code)) ?? 0) + size); + }); + let best = ""; + let most = 0; + for (const [code, w] of weight) { + if (w > most) { + best = code; + most = w; + } + } + return best; + } + var isAbort = (err, signal) => Boolean(signal?.aborted) || err?.name === "AbortError"; + async function translateBook(book, target, translator, progress, signal, report = {}) { + const check = () => { + if (signal?.aborted) throw abortError(); + }; + const run = (segments) => translator.translate(segments, "auto", target, signal); + const band = (done, of) => TRANSLATE_FROM + done / Math.max(1, of) * (TRANSLATE_TO - TRANSLATE_FROM); + const total = book.chapters.length; + async function chapterAt(i) { + check(); + progress(`Translating chapter ${i + 1} of ${total}\u2026`, band(i, total)); + const chapter = book.chapters[i]; + const segments = []; + const titleSeg = segments.push(textSegment(chapter.title)) - 1; + const body = plan(chapter.xhtml, segments); + const bodyEnd = segments.length; + const notes = chapter.notesXhtml ? plan(chapter.notesXhtml, segments) : null; + const { texts, detected } = await run(segments); + return { + vote: dominantLanguage(segments.slice(titleSeg + 1, bodyEnd), detected.slice(titleSeg + 1, bodyEnd)), + chapter: { + ...chapter, + title: textBack(texts[titleSeg], chapter.title), + xhtml: render(body, texts), + ...notes ? { notesXhtml: render(notes, texts) } : {} + } + }; + } + async function frontMatter() { + check(); + progress("Translating the title and summary\u2026", band(1, total)); + const front2 = []; + const titleAt = front2.push(textSegment(book.title)) - 1; + const summaryTextAt = book.summaryText ? front2.push(textSegment(book.summaryText)) - 1 : -1; + const summaryPlan = book.summaryXhtml ? plan(book.summaryXhtml, front2) : []; + const out = (await run(front2)).texts; + return { + title: textBack(out[titleAt], book.title), + ...book.summaryXhtml ? { summaryXhtml: render(summaryPlan, out) } : {}, + ...book.summaryText ? { summaryText: textBack(out[summaryTextAt], book.summaryText) } : {} + }; + } + const chapters = []; + let decided = false; + let front = null; + let failed = 0; + let firstError = null; + async function tryFront() { + try { + front = await frontMatter(); + } catch (err) { + if (isAbort(err, signal)) throw err; + } + } + for (let i = 0; i < total; i += 1) { + try { + const { chapter, vote } = await chapterAt(i); + chapters.push(chapter); + if (!decided && vote) { + if (vote === baseOf(target)) { + progress(alreadyIn(target), TRANSLATE_TO); + return book; + } + decided = true; + await tryFront(); + } + } catch (err) { + if (isAbort(err, signal)) throw err; + failed += 1; + firstError ??= err; + chapters.push(book.chapters[i]); + progress(`Chapter ${i + 1} could not be translated, continuing\u2026`, band(i + 1, total)); + } + } + if (failed === total) throw firstError; + if (!decided) await tryFront(); + if (failed) { + report.failedChapters = failed; + report.failure = `${failed} of ${total} chapters stayed untranslated \u2014 ${firstError.message} Try again later for a full translation.`; + } + return { ...book, ...front ?? {}, language: target, chapters }; + } + + // src/core.ts + var RETRY_STATUS2 = /* @__PURE__ */ new Set([408, 425, 429, 500, 502, 503, 504]); + var MAX_ATTEMPTS = 5; + var MAX_WAIT2 = 6e4; var SLOW_DOWN = /* @__PURE__ */ new Set([429, 503]); function netError(message) { const err = new Error(message); @@ -1887,7 +2280,7 @@ ${stripTags(c.xhtml)}`).join("\n"); }); const aborted = () => Boolean(signal && signal.aborted); async function pause(attempt, floor, status) { - const delay = backoffDelay(attempt, { floor, max: MAX_WAIT }); + const delay = backoffDelay(attempt, { floor, max: MAX_WAIT2 }); if (SLOW_DOWN.has(status)) { report(`The site asked us to slow down \u2014 continuing in ${Math.ceil(delay / 1e3)} s\u2026`); } @@ -1912,8 +2305,8 @@ ${stripTags(c.xhtml)}`).join("\n"); limiter.reward(); return res; } - if (!RETRY_STATUS.has(res.status)) throw netError(httpMessage(res.status)); - const floor = Math.min(MAX_WAIT, parseRetryAfter(res.headers.get("Retry-After"))); + if (!RETRY_STATUS2.has(res.status)) throw netError(httpMessage(res.status)); + const floor = Math.min(MAX_WAIT2, parseRetryAfter(res.headers.get("Retry-After"))); last = netError(httpMessage(res.status)); limiter.penalize(floor); if (attempt < MAX_ATTEMPTS - 1) await pause(attempt, floor, res.status); @@ -1940,9 +2333,18 @@ ${stripTags(c.xhtml)}`).join("\n"); fb2: { build: build2, ext: "fb2" }, txt: { build: build4, ext: "txt" } }; - async function buildBook({ doc, url, format, progress, signal }) { + async function buildBook({ + doc, + url, + format, + progress, + signal, + translateTo, + translator + }) { const adapter = resolveAdapter(url); - const ctx = makeContext({ progress, signal, pacing: adapter.pacing }); + const reading = translateTo ? (text, percent) => progress(text, percent === void 0 ? void 0 : percent * 0.4) : progress; + const ctx = makeContext({ progress: reading, signal, pacing: adapter.pacing }); progress(`Reading the page (${siteLabel(url)})\u2026`, 2); let book; try { @@ -1961,6 +2363,14 @@ ${stripTags(c.xhtml)}`).join("\n"); `Only ${book.chapters.length} of ${expected} chapters could be read \u2014 the book would come out incomplete. Try again.` ); } + let untranslated; + if (translateTo) { + const before = book; + const report = {}; + book = await translateBook(book, translateTo, translator ?? createGoogleTranslator(), progress, signal, report); + if (book === before) untranslated = alreadyIn(translateTo); + else if (report.failure) untranslated = report.failure; + } const builder = BUILDERS[format] || BUILDERS.epub; progress(`Assembling ${builder.ext.toUpperCase()} (${book.chapters.length} ch.)\u2026`, 90); const blob = await builder.build(book); @@ -1968,7 +2378,7 @@ ${stripTags(c.xhtml)}`).join("\n"); book.author ? `${book.title} \u2014 ${book.author}` : book.title, builder.ext ); - return { blob, filename, book, adapter: adapter.id, missing }; + return { blob, filename, book, adapter: adapter.id, missing, untranslated }; } function saveBlob(blob, filename) { const url = URL.createObjectURL(blob); @@ -4624,7 +5034,11 @@ half4 main(float2 xy) { } .head .site { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .head .grip { flex: none; margin-left: auto; opacity: .55; } -.fmt { display: flex; flex-direction: column; } +.fmt { + display: flex; flex-direction: column; + margin-top: 4px; padding-top: 4px; + border-top: 1px solid color-mix(in oklch, var(--vg-ink) 10%, transparent); +} /* Concentric: sheet radius 20 = item radius 14 + padding 6. */ .fmt button { display: flex; align-items: baseline; gap: 8px; width: 100%; @@ -4639,6 +5053,34 @@ half4 main(float2 xy) { } .fmt .hint { color: var(--vg-dim); font-size: 11.5px; } +/* The translation row sits above the formats and is read as a setting, not as an + action: the value is dim until a language is picked. */ +.tr { + display: flex; align-items: center; justify-content: space-between; gap: 8px; + padding: 2px 4px 2px 10px; color: var(--vg-ink); font-size: 14px; +} +.tr .pick { position: relative; display: flex; align-items: center; min-width: 0; } +.tr select { + appearance: none; -webkit-appearance: none; + background: transparent; border: 0; cursor: pointer; color: var(--vg-dim); + font: inherit; font-size: 13.5px; text-align: right; text-align-last: right; + padding: 7px 22px 7px 10px; border-radius: 14px; max-width: 150px; + color-scheme: dark; + /* Hugs the chosen language instead of the widest one in the list; older engines just stay wide. */ + field-sizing: content; + transition: color .13s var(--ease), background .13s var(--ease); +} +.root.ink-dark .tr select { color-scheme: light; } +.tr.on select { color: var(--vg-ink); } +.tr select:hover, .tr select:focus-visible { + color: var(--vg-ink); + background: color-mix(in oklch, var(--vg-ink) 9%, transparent); + outline: none; +} +.tr .chev { position: absolute; right: 8px; pointer-events: none; opacity: .7; color: var(--vg-dim); } +.tr-note { padding: 0 10px 6px; color: var(--vg-dim); font-size: 11.5px; line-height: 1.4; } +.tr-note[hidden] { display: none; } + .pad { width: 268px; padding: 13px 14px 14px; } .label { font-size: 13px; color: var(--vg-ink); margin-bottom: 10px; min-height: 17px; } .bar { height: 4px; border-radius: 99px; overflow: hidden; background: color-mix(in oklch, var(--vg-ink) 10%, transparent); } @@ -4661,6 +5103,7 @@ half4 main(float2 xy) { } `; var ICON = ''; + var CHEVRON = ''; var GRIP = ''; var FORMATS = [ { id: "epub", label: "EPUB", hint: "for Send to Kindle" }, @@ -4679,6 +5122,8 @@ half4 main(float2 xy) { defaultFormat, corner, onCornerChange, + translateTo: initialTranslateTo, + onTranslateChange, onDownload }) { const host = document.createElement("div"); @@ -4723,6 +5168,7 @@ half4 main(float2 xy) { shell.classList.add("flat"); } let at = normalizeCorner(corner); + let translateTo = normalizeTarget(initialTranslateTo); function applyCorner() { rootEl.classList.toggle("x-right", at[1] === "r"); rootEl.classList.toggle("x-left", at[1] === "l"); @@ -4987,7 +5433,7 @@ half4 main(float2 xy) { setView(fab, true); if (focus) fab.focus(); } - function renderMenu() { + function renderMenu(focusTranslate = false) { settled = false; mode = "menu"; const panel = document.createElement("div"); @@ -5027,9 +5473,31 @@ half4 main(float2 xy) { const i = items.indexOf(shadow.activeElement); items[(i + delta + items.length) % items.length].focus(); }); - panel.append(head, list); + const tr = document.createElement("label"); + tr.className = "tr" + (translateTo ? " on" : ""); + const trLabel = document.createElement("span"); + trLabel.textContent = "Translate"; + const pick2 = document.createElement("span"); + pick2.className = "pick"; + const select = document.createElement("select"); + select.setAttribute("aria-label", "Translate the book into"); + select.append(new Option("Off", ""), ...LANGUAGES.map((l) => new Option(l.label, l.code))); + select.value = translateTo; + pick2.append(select); + pick2.insertAdjacentHTML("beforeend", CHEVRON); + tr.append(trLabel, pick2); + const note = document.createElement("div"); + note.className = "tr-note"; + note.textContent = "Chapter text is sent to Google Translate."; + note.hidden = !translateTo; + select.addEventListener("change", () => { + translateTo = normalizeTarget(select.value); + if (onTranslateChange) onTranslateChange(translateTo); + renderMenu(true); + }); + panel.append(head, tr, note, list); setView(panel, false); - const first = list.querySelector("button"); + const first = focusTranslate ? select : list.querySelector("button"); if (first) first.focus(); } function renderProgress() { @@ -5101,7 +5569,7 @@ half4 main(float2 xy) { } }; try { - const result = await onDownload({ format, progress, signal: controller.signal }); + const result = await onDownload({ format, translateTo, progress, signal: controller.signal }); ui.fill.style.width = "100%"; renderResult({ filename: result.filename, note: result.note }); } catch (err) { @@ -5154,16 +5622,25 @@ half4 main(float2 xy) { setTimeout(() => a.remove(), 15e3); return { filename: `${format.toUpperCase()} from the site` }; } - async function onDownload({ format, progress, signal }) { - progress("Checking for a ready-made file on the site\u2026", 3); - const native2 = await nativeDownload(format); - if (native2) return native2; - const result = await buildBook({ doc: document, url, format, progress, signal }); + async function onDownload({ format, translateTo, progress, signal }) { + if (!translateTo) { + progress("Checking for a ready-made file on the site\u2026", 3); + const native2 = await nativeDownload(format); + if (native2) return native2; + } + const result = await buildBook({ + doc: document, + url, + format, + progress, + signal, + translateTo: translateTo || void 0 + }); progress("Saving the file\u2026", 99); saveBlob(result.blob, result.filename); return { filename: result.filename, - note: result.missing ? `Chapters not parsed: ${result.missing}` : "" + note: [result.missing ? `Chapters not parsed: ${result.missing}` : "", result.untranslated ?? ""].filter(Boolean).join(" ") }; } function mount(prefs) { @@ -5180,13 +5657,20 @@ half4 main(float2 xy) { } catch { } }, + translateTo: prefs?.translateTo, + onTranslateChange: (code) => { + try { + chrome.storage.sync.set({ translateTo: code }); + } catch { + } + }, onDownload }); document.documentElement.appendChild(widget.host); window.__VIREBOOK_WIDGET__ = widget; } try { - chrome.storage.sync.get({ defaultFormat: "epub", widgetCorner: "br" }, (s) => mount(s)); + chrome.storage.sync.get({ defaultFormat: "epub", widgetCorner: "br", translateTo: "" }, (s) => mount(s)); } catch { mount(null); } diff --git a/manifest.json b/manifest.json index 8ed3dee..9a4fcae 100644 --- a/manifest.json +++ b/manifest.json @@ -2,7 +2,7 @@ "manifest_version": 3, "name": "VireBook", "description": "Downloads a whole book as EPUB, MOBI, FB2 or TXT in one press — assembled right in the browser, with nothing to wait for.", - "version": "1.4.0", + "version": "1.5.0", "icons": { "16": "icons/icon16.png", "32": "icons/icon32.png", diff --git a/package-lock.json b/package-lock.json index 2582ee3..7e585f0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "virebook", - "version": "1.4.0", + "version": "1.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "virebook", - "version": "1.4.0", + "version": "1.5.0", "license": "MIT", "dependencies": { "vireglass": "^2.2.0" diff --git a/package.json b/package.json index 7a07182..8df9cb6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "virebook", - "version": "1.4.0", + "version": "1.5.0", "private": true, "license": "MIT", "description": "Browser extension: a whole book as EPUB/MOBI/FB2/TXT in one press", @@ -9,9 +9,10 @@ "build": "node scripts/build.mjs", "build:watch": "node scripts/build.mjs --watch", "typecheck": "tsc --noEmit", - "test": "node test/run.ts && node test/adapters.ts", + "test": "node test/run.ts && node test/adapters.ts && node test/translate.ts", "test:formats": "node test/run.ts", "test:adapters": "node test/adapters.ts", + "test:translate": "node test/translate.ts", "check": "npm run typecheck && npm run build && npm test", "demo": "node scripts/serve.mjs", "icons": "node scripts/make-icons.mjs" diff --git a/src/content.ts b/src/content.ts index 2663e44..ae1f136 100644 --- a/src/content.ts +++ b/src/content.ts @@ -52,24 +52,36 @@ function main(): void { return { filename: `${format.toUpperCase()} from the site` }; } - async function onDownload({ format, progress, signal }: DownloadRequest): Promise { + async function onDownload({ format, translateTo, progress, signal }: DownloadRequest): Promise { // If the site already serves a ready-made file behind a direct link, take // it: that is instant and no worse in quality (AO3 builds books with the // same kindlegen). - progress('Checking for a ready-made file on the site…', 3); - const native = await nativeDownload(format); - if (native) return native; + // A translated book has to be assembled here, so the site's own file is skipped. + if (!translateTo) { + progress('Checking for a ready-made file on the site…', 3); + const native = await nativeDownload(format); + if (native) return native; + } - const result = await buildBook({ doc: document, url, format, progress, signal }); + const result = await buildBook({ + doc: document, + url, + format, + progress, + signal, + translateTo: translateTo || undefined, + }); progress('Saving the file…', 99); saveBlob(result.blob, result.filename); return { filename: result.filename, - note: result.missing ? `Chapters not parsed: ${result.missing}` : '', + note: [result.missing ? `Chapters not parsed: ${result.missing}` : '', result.untranslated ?? ''] + .filter(Boolean) + .join(' '), }; } - function mount(prefs: { defaultFormat?: Format; widgetCorner?: string } | null): void { + function mount(prefs: { defaultFormat?: Format; widgetCorner?: string; translateTo?: string } | null): void { const widget = create({ siteName: siteLabel(url), defaultFormat: prefs?.defaultFormat || 'epub', @@ -84,6 +96,14 @@ function main(): void { /* no storage (page not opened as an extension) — the corner lives until reload */ } }, + translateTo: prefs?.translateTo, + onTranslateChange: (code: string) => { + try { + chrome.storage.sync.set({ translateTo: code }); + } catch { + /* no storage — the choice lives until reload */ + } + }, onDownload, }); document.documentElement.appendChild(widget.host); @@ -91,7 +111,7 @@ function main(): void { } try { - chrome.storage.sync.get({ defaultFormat: 'epub' as Format, widgetCorner: 'br' }, (s) => mount(s)); + chrome.storage.sync.get({ defaultFormat: 'epub' as Format, widgetCorner: 'br', translateTo: '' }, (s) => mount(s)); } catch { mount(null); } diff --git a/src/core.ts b/src/core.ts index 4545b15..169bd31 100644 --- a/src/core.ts +++ b/src/core.ts @@ -6,6 +6,9 @@ import * as epub from './lib/epub.ts'; import * as fb2 from './lib/fb2.ts'; import * as mobi from './lib/mobi.ts'; import * as txt from './lib/txt.ts'; +import { createGoogleTranslator } from './translate/google.ts'; +import { alreadyIn, translateBook, type TranslateReport } from './translate/book.ts'; +import type { Translator } from './translate/types.ts'; import { abortError, backoffDelay, createRateLimiter, parseRetryAfter, safeFilename, sleep } from './lib/util.ts'; export { resolveAdapter }; @@ -124,6 +127,10 @@ export interface BuildRequest { format: Format; progress: ProgressFn; signal?: AbortSignal; + /** Language code to translate the book into; omitted means the book is left as it is. */ + translateTo?: string; + /** Which engine to translate with; Google Translate when omitted. */ + translator?: Translator; } export interface BuildResult { @@ -132,11 +139,25 @@ export interface BuildResult { book: Book; adapter: string; missing: number; + /** Set when translation was asked for but did not (fully) happen: already in that language, or chapters the engine refused. */ + untranslated?: string; } -export async function buildBook({ doc, url, format, progress, signal }: BuildRequest): Promise { +export async function buildBook({ + doc, + url, + format, + progress, + signal, + translateTo, + translator, +}: BuildRequest): Promise { const adapter = resolveAdapter(url); - const ctx = makeContext({ progress, signal, pacing: adapter.pacing }); + // Reading takes the first part of the bar and translation the next, so the bar never runs backwards. + const reading: ProgressFn = translateTo + ? (text, percent) => progress(text, percent === undefined ? undefined : percent * 0.4) + : progress; + const ctx = makeContext({ progress: reading, signal, pacing: adapter.pacing }); progress(`Reading the page (${siteLabel(url)})…`, 2); let book: Book; @@ -164,6 +185,16 @@ export async function buildBook({ doc, url, format, progress, signal }: BuildReq ); } + let untranslated: string | undefined; + if (translateTo) { + const before = book; + const report: TranslateReport = {}; + book = await translateBook(book, translateTo, translator ?? createGoogleTranslator(), progress, signal, report); + // Assembling replaces the progress label at once, so the reader is told in the result instead. + if (book === before) untranslated = alreadyIn(translateTo); + else if (report.failure) untranslated = report.failure; + } + const builder = BUILDERS[format] || BUILDERS.epub; progress(`Assembling ${builder.ext.toUpperCase()} (${book.chapters.length} ch.)…`, 90); const blob = await builder.build(book); @@ -172,7 +203,7 @@ export async function buildBook({ doc, url, format, progress, signal }: BuildReq builder.ext, ); - return { blob, filename, book, adapter: adapter.id, missing }; + return { blob, filename, book, adapter: adapter.id, missing, untranslated }; } export function saveBlob(blob: Blob, filename: string): void { diff --git a/src/lib/html.ts b/src/lib/html.ts index 6a660e6..1e87a08 100644 --- a/src/lib/html.ts +++ b/src/lib/html.ts @@ -73,6 +73,8 @@ export interface SanitizeOptions { baseUrl?: string; keepImages?: boolean; dropSelectors?: string[]; + /** Inline-only content gets no

around it; for fragments that are not a whole chapter. */ + wrapBare?: boolean; } export interface SanitizeResult { @@ -83,7 +85,7 @@ export interface SanitizeResult { /** Walks a subtree and builds XHTML out of it. */ export function sanitize(rootNode: Element, opts: SanitizeOptions = {}): SanitizeResult { - const { baseUrl = '', keepImages = true, dropSelectors = [] } = opts; + const { baseUrl = '', keepImages = true, dropSelectors = [], wrapBare = true } = opts; const images: string[] = []; const working = rootNode.cloneNode(true) as Element; @@ -162,7 +164,7 @@ export function sanitize(rootNode: Element, opts: SanitizeOptions = {}): Sanitiz .replace(/\s+\n/g, '\n') .trim(); - if (!/<(p|div|h[1-6]|blockquote|ul|ol|pre)[\s>]/.test(xhtml) && xhtml) { + if (wrapBare && !/<(p|div|h[1-6]|blockquote|ul|ol|pre)[\s>]/.test(xhtml) && xhtml) { xhtml = `

${xhtml}

`; } diff --git a/src/translate/book.ts b/src/translate/book.ts new file mode 100644 index 0000000..97c7477 --- /dev/null +++ b/src/translate/book.ts @@ -0,0 +1,242 @@ +// Translates an assembled Book. The text goes out block by block with its inline +// markup, and what comes back is run through `sanitize` again: the writers take +// XHTML that is well-formed, and an engine is not a thing to trust with that. +import type { Book, Chapter, ProgressFn } from '../types.ts'; +import { LANGUAGES, type Translator } from './types.ts'; +import { escapeText, sanitize } from '../lib/html.ts'; +import { abortError, normalizeSpace } from '../lib/util.ts'; + +/** Where translation sits on the progress bar: after reading, before assembling. */ +export const TRANSLATE_FROM = 40; +export const TRANSLATE_TO = 88; + +const STRUCTURAL = new Set([ + 'p', 'div', 'section', 'article', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', + 'ul', 'ol', 'li', 'hr', 'tr', 'figure', 'figcaption', 'dl', 'dt', 'dd', 'center', 'table', + 'thead', 'tbody', 'td', 'th', 'caption', +]); +const STRUCTURAL_SELECTOR = [...STRUCTURAL].join(','); +const LETTER = /\p{L}/u; + +const hasText = (html: string): boolean => LETTER.test(html.replace(/<[^>]*>/g, '')); + +/** A literal stretch of the book, or a hole to be filled with the translation of `segments[seg]`. */ +type Piece = string | { seg: number; open: string; close: string; original: string }; + +/** + * Splits sanitised XHTML into blocks that go to the engine one by one, keeping + * the wrapping elements out of the request. Blocks with nothing to read — a + * scene break, an image — stay as they are. + */ +function plan(xhtml: string, segments: string[]): Piece[] { + const doc = new DOMParser().parseFromString(`${xhtml}`, 'text/html'); + const out: Piece[] = []; + + function emit(nodes: Node[], open: string, close: string, keepEmpty: boolean): void { + const holder = doc.createElement('div'); + for (const n of nodes) holder.append(n.cloneNode(true)); + const original = sanitize(holder, { wrapBare: false }).xhtml; + if (!original && !keepEmpty) { + if (holder.textContent?.includes('\n')) out.push('\n'); + return; + } + if (!hasText(holder.innerHTML)) { + if (keepEmpty || /]/.test(original)) out.push(open + original + close); + return; + } + out.push({ seg: segments.push(holder.innerHTML) - 1, open, close, original }); + } + + function walk(parent: Element, topLevel: boolean): void { + let run: Node[] = []; + const flush = (): void => { + if (run.length) emit(run, topLevel ? '

' : '', topLevel ? '

' : '', false); + run = []; + }; + for (const node of Array.from(parent.childNodes)) { + const tag = node.nodeType === 1 ? (node as Element).tagName.toLowerCase() : ''; + if (!STRUCTURAL.has(tag)) { + run.push(node); + continue; + } + flush(); + const el = node as Element; + if (tag === 'hr') out.push('
'); + else if (el.querySelector(STRUCTURAL_SELECTOR)) { + out.push(`<${tag}>`); + walk(el, false); + out.push(``); + } else emit(Array.from(el.childNodes), `<${tag}>`, ``, true); + } + flush(); + } + + walk(doc.body, true); + return out; +} + +function cleanInline(html: string): string { + const body = new DOMParser().parseFromString(`${html}`, 'text/html').body; + return sanitize(body, { wrapBare: false }).xhtml; +} + +function render(pieces: Piece[], translated: string[]): string { + return pieces + .map((p) => { + if (typeof p === 'string') return p; + const clean = cleanInline(translated[p.seg] ?? ''); + return p.open + (clean || p.original) + p.close; + }) + .join(''); +} + +/** Plain text goes out as HTML (the engine is asked for HTML), so it is escaped on the way and read back. */ +const textSegment = (text: string): string => (hasText(text) ? escapeText(text) : ''); + +function textBack(translated: string | undefined, original: string): string { + if (!translated) return original; + const body = new DOMParser().parseFromString(`${translated}`, 'text/html').body; + return normalizeSpace(body.textContent) || original; +} + +const baseOf = (code: string): string => code.toLowerCase().split('-')[0]!; + +export function alreadyIn(target: string): string { + const name = LANGUAGES.find((l) => l.code === target)?.label ?? target; + return `The book is already in ${name} — not translated.`; +} + +/** Segments shorter than this say little about a language and must not outvote the prose. */ +const MIN_VOTE = 20; + +/** The language the engine heard most of, by amount of text; '' when it heard none. */ +function dominantLanguage(sent: string[], detected: string[]): string { + const weight = new Map(); + sent.forEach((html, i) => { + const code = detected[i]; + const size = html.replace(/<[^>]*>/g, '').trim().length; + if (code && size >= MIN_VOTE) weight.set(baseOf(code), (weight.get(baseOf(code)) ?? 0) + size); + }); + let best = ''; + let most = 0; + for (const [code, w] of weight) { + if (w > most) { + best = code; + most = w; + } + } + return best; +} + +export interface TranslateReport { + /** Chapters left in the original language because the engine kept failing. */ + failedChapters?: number; + /** A sentence for the reader, set when some chapters stayed untranslated. */ + failure?: string; +} + +const isAbort = (err: unknown, signal?: AbortSignal): boolean => + Boolean(signal?.aborted) || (err as Error)?.name === 'AbortError'; + +/** + * The source language is not taken from `book.language`, which is a two-way guess + * (ru or en): chapters are translated in order and the engine's own detection, + * over the chapter bodies only, decides whether the book was in the target + * language already. A chapter the engine keeps refusing stays as it was — hundreds + * of requests are not thrown away over one — and `report` says how many. + */ +export async function translateBook( + book: Book, + target: string, + translator: Translator, + progress: ProgressFn, + signal?: AbortSignal, + report: TranslateReport = {}, +): Promise { + const check = (): void => { + if (signal?.aborted) throw abortError(); + }; + const run = (segments: string[]) => translator.translate(segments, 'auto', target, signal); + const band = (done: number, of: number): number => + TRANSLATE_FROM + (done / Math.max(1, of)) * (TRANSLATE_TO - TRANSLATE_FROM); + const total = book.chapters.length; + + async function chapterAt(i: number): Promise<{ chapter: Chapter; vote: string }> { + check(); + progress(`Translating chapter ${i + 1} of ${total}…`, band(i, total)); + const chapter = book.chapters[i]!; + const segments: string[] = []; + const titleSeg = segments.push(textSegment(chapter.title)) - 1; + const body = plan(chapter.xhtml, segments); + const bodyEnd = segments.length; + const notes = chapter.notesXhtml ? plan(chapter.notesXhtml, segments) : null; + const { texts, detected } = await run(segments); + return { + vote: dominantLanguage(segments.slice(titleSeg + 1, bodyEnd), detected.slice(titleSeg + 1, bodyEnd)), + chapter: { + ...chapter, + title: textBack(texts[titleSeg], chapter.title), + xhtml: render(body, texts), + ...(notes ? { notesXhtml: render(notes, texts) } : {}), + }, + }; + } + + async function frontMatter(): Promise> { + check(); + progress('Translating the title and summary…', band(1, total)); + const front: string[] = []; + const titleAt = front.push(textSegment(book.title)) - 1; + const summaryTextAt = book.summaryText ? front.push(textSegment(book.summaryText)) - 1 : -1; + const summaryPlan = book.summaryXhtml ? plan(book.summaryXhtml, front) : []; + const out = (await run(front)).texts; + return { + title: textBack(out[titleAt], book.title), + ...(book.summaryXhtml ? { summaryXhtml: render(summaryPlan, out) } : {}), + ...(book.summaryText ? { summaryText: textBack(out[summaryTextAt], book.summaryText) } : {}), + }; + } + + const chapters: Chapter[] = []; + let decided = false; + let front: Awaited> | null = null; + let failed = 0; + let firstError: Error | null = null; + + async function tryFront(): Promise { + try { + front = await frontMatter(); + } catch (err) { + if (isAbort(err, signal)) throw err; + } + } + + for (let i = 0; i < total; i += 1) { + try { + const { chapter, vote } = await chapterAt(i); + chapters.push(chapter); + if (!decided && vote) { + if (vote === baseOf(target)) { + progress(alreadyIn(target), TRANSLATE_TO); + return book; + } + decided = true; + await tryFront(); + } + } catch (err) { + if (isAbort(err, signal)) throw err; + failed += 1; + firstError ??= err as Error; + chapters.push(book.chapters[i]!); + progress(`Chapter ${i + 1} could not be translated, continuing…`, band(i + 1, total)); + } + } + if (failed === total) throw firstError!; + if (!decided) await tryFront(); + + if (failed) { + report.failedChapters = failed; + report.failure = `${failed} of ${total} chapters stayed untranslated — ${firstError!.message} Try again later for a full translation.`; + } + return { ...book, ...(front ?? {}), language: target, chapters }; +} diff --git a/src/translate/google.ts b/src/translate/google.ts new file mode 100644 index 0000000..73dd2ce --- /dev/null +++ b/src/translate/google.ts @@ -0,0 +1,122 @@ +// Google Translate's unofficial web endpoint. It is not an API anyone promised +// to keep: it needs no key, answers with CORS open, and can say no at any time. +import type { TranslateResult, Translator } from './types.ts'; +import { joinPieces, normalizeSpacing, planBatches, splitSegment } from './text.ts'; +import { abortError, backoffDelay, createRateLimiter, parseRetryAfter, sleep } from '../lib/util.ts'; + +const ENDPOINT = 'https://translate.googleapis.com/translate_a/t'; +const RETRY_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]); +const MAX_WAIT = 60000; + +export interface GoogleOptions { + fetch?: typeof fetch; + /** Characters of source text per request. */ + budget?: number; + maxSegments?: number; + /** Pause between requests, ms. */ + gap?: number; + maxAttempts?: number; + /** First backoff step, ms. */ + backoffBase?: number; +} + +function refusal(status: number): Error { + if (status === 429) { + return new Error('Google Translate is limiting requests. Wait a few minutes, or download without translation.'); + } + return new Error(`Google Translate refused the request (HTTP ${status}). Try later, or download without translation.`); +} + +/** One entry per query: a bare string, or `[text, detectedLanguage]` when the source is `auto`. */ +function textsOf(data: unknown, expected: number): TranslateResult { + if (Array.isArray(data)) { + const texts = data.map((item) => (Array.isArray(item) ? item[0] : item)); + if (texts.length === expected && texts.every((t) => typeof t === 'string')) { + const detected = data.map((item) => (Array.isArray(item) && typeof item[1] === 'string' ? item[1] : '')); + return { texts: texts as string[], detected }; + } + } + throw new Error('Google Translate answered in a shape we do not understand.'); +} + +export function createGoogleTranslator(options: GoogleOptions = {}): Translator { + const { budget = 4500, maxSegments = 40, gap = 350, maxAttempts = 5, backoffBase = 1200 } = options; + const doFetch: typeof fetch = options.fetch ?? ((input, init) => fetch(input, init)); + const limiter = createRateLimiter({ interval: gap, maxInterval: 15000 }); + + async function send(queries: string[], from: string, to: string, signal?: AbortSignal): Promise { + const url = `${ENDPOINT}?client=gtx&sl=${encodeURIComponent(from)}&tl=${encodeURIComponent(to)}&format=html`; + const body = new URLSearchParams(); + for (const q of queries) body.append('q', q); + + let refused: Error | null = null; + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { + await limiter.acquire(signal); + if (signal?.aborted) throw abortError(); + + let res: Response; + try { + res = await doFetch(url, { method: 'POST', body, signal }); + } catch (err) { + if (signal?.aborted) throw err; + refused = new Error('The network is not responding — check your connection.'); + limiter.penalize(0); + if (attempt < maxAttempts - 1) await sleep(backoffDelay(attempt, { base: backoffBase, max: MAX_WAIT }), signal); + continue; + } + + if (res.ok) { + limiter.reward(); + return textsOf(await res.json(), queries.length); + } + if (!RETRY_STATUS.has(res.status)) throw refusal(res.status); + + const floor = Math.min(MAX_WAIT, parseRetryAfter(res.headers.get('Retry-After'))); + refused = refusal(res.status); + limiter.penalize(floor); + if (attempt < maxAttempts - 1) { + await sleep(backoffDelay(attempt, { base: backoffBase, max: MAX_WAIT, floor }), signal); + } + } + throw refused ?? new Error('Google Translate did not answer.'); + } + + return { + id: 'google', + async translate(segments, from, to, signal) { + // An empty query would be dropped by the server and shift every answer after it. + const results = segments.map((s) => (s.trim() ? '' : s)); + const owners: number[] = []; + const pieces: string[] = []; + segments.forEach((s, i) => { + if (!s.trim()) return; + for (const piece of splitSegment(s, budget)) { + owners.push(i); + pieces.push(piece); + } + }); + + const translated: string[] = new Array(pieces.length); + const langs: string[] = new Array(pieces.length).fill(''); + for (const group of planBatches(pieces, budget, maxSegments)) { + const answer = await send(group.map((i) => pieces[i]!), from || 'auto', to, signal); + group.forEach((pieceIndex, k) => { + translated[pieceIndex] = normalizeSpacing(answer.texts[k]!, to); + langs[pieceIndex] = answer.detected[k]!; + }); + } + const detected = segments.map(() => ''); + + segments.forEach((s, i) => { + if (!s.trim()) return; + const mine: string[] = []; + owners.forEach((owner, k) => { + if (owner === i) mine.push(translated[k]!); + }); + results[i] = joinPieces(mine); + detected[i] = langs[owners.indexOf(i)]!; + }); + return { texts: results, detected }; + }, + }; +} diff --git a/src/translate/text.ts b/src/translate/text.ts new file mode 100644 index 0000000..0a6c989 --- /dev/null +++ b/src/translate/text.ts @@ -0,0 +1,95 @@ +// Pure helpers around the text an engine is handed: where to cut it, how to +// group it into requests, and what to tidy in what comes back. + +const VOID = new Set(['br', 'hr', 'img']); +const SENTENCE_END = /[.!?…。!?]["'»”’)\]」』]*\s+/g; + +/** + * Cuts an over-long fragment at sentence ends and
, but only where no inline + * tag is open: a cut inside … would hand the engine two broken halves. + * A stretch with no such place is left whole — a long request beats a mangled one. + */ +export function splitSegment(html: string, budget: number): string[] { + if (html.length <= budget) return [html]; + + const atoms: string[] = []; + let cur = ''; + let depth = 0; + for (const token of html.match(/<[^>]*>|[^<]+/g) ?? []) { + if (token.startsWith('<')) { + const m = /^<(\/?)([a-z0-9]+)/i.exec(token); + const name = m ? m[2]!.toLowerCase() : ''; + cur += token; + if (m && !VOID.has(name) && !token.endsWith('/>')) depth = Math.max(0, depth + (m[1] ? -1 : 1)); + else if (name === 'br' && depth === 0) { + atoms.push(cur); + cur = ''; + } + continue; + } + if (depth > 0) { + cur += token; + continue; + } + let from = 0; + for (const m of token.matchAll(SENTENCE_END)) { + const end = m.index + m[0].length; + atoms.push(cur + token.slice(from, end)); + cur = ''; + from = end; + } + cur += token.slice(from); + } + if (cur) atoms.push(cur); + + const pieces: string[] = []; + let piece = ''; + for (const atom of atoms) { + if (piece && piece.length + atom.length > budget) { + pieces.push(piece); + piece = ''; + } + piece += atom; + } + if (piece) pieces.push(piece); + return pieces; +} + +/** Puts translated pieces of one fragment back together. */ +export function joinPieces(pieces: string[]): string { + let out = ''; + for (const piece of pieces) { + if (!out) out = piece; + else if (/\s*$/i.test(out)) out += piece; + else out = `${out.replace(/\s+$/, '')} ${piece.replace(/^\s+/, '')}`; + } + return out; +} + +/** Groups pieces into requests: indices into `pieces`, each group under the budget and the cap. */ +export function planBatches(pieces: string[], budget: number, maxSegments: number): number[][] { + const groups: number[][] = []; + let group: number[] = []; + let size = 0; + pieces.forEach((piece, i) => { + if (group.length && (group.length >= maxSegments || size + piece.length > budget)) { + groups.push(group); + group = []; + size = 0; + } + group.push(i); + size += piece.length; + }); + if (group.length) groups.push(group); + return groups; +} + +// The engine leaves a space before punctuation that follows a closing inline +// tag (" ."). Only that case is touched, so ordinary spaces survive. +const STRAY = /(<\/[a-z0-9]+>) +(?=[.,…)\]}。、!?;:」』!?;:»”’])/gi; +// French sets these off with a space on purpose. +const STRAY_FRENCH = /(<\/[a-z0-9]+>) +(?=[.,…)\]}])/gi; + +export function normalizeSpacing(html: string, target: string): string { + return html.replace(target.toLowerCase().startsWith('fr') ? STRAY_FRENCH : STRAY, '$1'); +} diff --git a/src/translate/types.ts b/src/translate/types.ts new file mode 100644 index 0000000..4f651b8 --- /dev/null +++ b/src/translate/types.ts @@ -0,0 +1,44 @@ +// An engine only moves HTML fragments between languages. Which fragments, and +// what becomes of the book afterwards, is book.ts's business — so a second +// engine is one file that implements this. + +export interface TranslateResult { + /** One translated string per input, in order, inline markup preserved. */ + texts: string[]; + /** The source language the engine detected for each input; '' where it did not say. */ + detected: string[]; +} + +export interface Translator { + /** Technical identifier, for logic and tests — never shown to anyone. */ + id: string; + /** `from` may be `auto`. Batching and pacing are the engine's own concern. */ + translate(htmlSegments: string[], from: string, to: string, signal?: AbortSignal): Promise; +} + +export interface TranslateLanguage { + code: string; + /** The language's own name for itself — what a reader looks for in the list. */ + label: string; +} + +export const LANGUAGES: TranslateLanguage[] = [ + { code: 'ru', label: 'Русский' }, + { code: 'en', label: 'English' }, + { code: 'uk', label: 'Українська' }, + { code: 'de', label: 'Deutsch' }, + { code: 'fr', label: 'Français' }, + { code: 'es', label: 'Español' }, + { code: 'it', label: 'Italiano' }, + { code: 'pt', label: 'Português' }, + { code: 'pl', label: 'Polski' }, + { code: 'tr', label: 'Türkçe' }, + { code: 'ja', label: '日本語' }, + { code: 'zh-CN', label: '中文' }, + { code: 'ko', label: '한국어' }, +]; + +/** Anything that is not a known language code means "off". */ +export function normalizeTarget(value: string | null | undefined): string { + return LANGUAGES.some((l) => l.code === value) ? (value as string) : ''; +} diff --git a/src/ui.ts b/src/ui.ts index 0a19f91..b0a8751 100644 --- a/src/ui.ts +++ b/src/ui.ts @@ -11,6 +11,7 @@ // which spot is in the way. import type { Format } from './types.ts'; import { createGlass, type GlassAnchor, type GlassSurface } from './glass.ts'; +import { LANGUAGES, normalizeTarget } from './translate/types.ts'; /** How long a throw into another corner takes. Shared with the CSS below, because the material * has to be read again once the pane lands and the wait is measured from here. */ @@ -196,7 +197,11 @@ const CSS = ` } .head .site { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .head .grip { flex: none; margin-left: auto; opacity: .55; } -.fmt { display: flex; flex-direction: column; } +.fmt { + display: flex; flex-direction: column; + margin-top: 4px; padding-top: 4px; + border-top: 1px solid color-mix(in oklch, var(--vg-ink) 10%, transparent); +} /* Concentric: sheet radius 20 = item radius 14 + padding 6. */ .fmt button { display: flex; align-items: baseline; gap: 8px; width: 100%; @@ -211,6 +216,34 @@ const CSS = ` } .fmt .hint { color: var(--vg-dim); font-size: 11.5px; } +/* The translation row sits above the formats and is read as a setting, not as an + action: the value is dim until a language is picked. */ +.tr { + display: flex; align-items: center; justify-content: space-between; gap: 8px; + padding: 2px 4px 2px 10px; color: var(--vg-ink); font-size: 14px; +} +.tr .pick { position: relative; display: flex; align-items: center; min-width: 0; } +.tr select { + appearance: none; -webkit-appearance: none; + background: transparent; border: 0; cursor: pointer; color: var(--vg-dim); + font: inherit; font-size: 13.5px; text-align: right; text-align-last: right; + padding: 7px 22px 7px 10px; border-radius: 14px; max-width: 150px; + color-scheme: dark; + /* Hugs the chosen language instead of the widest one in the list; older engines just stay wide. */ + field-sizing: content; + transition: color .13s var(--ease), background .13s var(--ease); +} +.root.ink-dark .tr select { color-scheme: light; } +.tr.on select { color: var(--vg-ink); } +.tr select:hover, .tr select:focus-visible { + color: var(--vg-ink); + background: color-mix(in oklch, var(--vg-ink) 9%, transparent); + outline: none; +} +.tr .chev { position: absolute; right: 8px; pointer-events: none; opacity: .7; color: var(--vg-dim); } +.tr-note { padding: 0 10px 6px; color: var(--vg-dim); font-size: 11.5px; line-height: 1.4; } +.tr-note[hidden] { display: none; } + .pad { width: 268px; padding: 13px 14px 14px; } .label { font-size: 13px; color: var(--vg-ink); margin-bottom: 10px; min-height: 17px; } .bar { height: 4px; border-radius: 99px; overflow: hidden; background: color-mix(in oklch, var(--vg-ink) 10%, transparent); } @@ -235,6 +268,8 @@ const CSS = ` const ICON = ''; +const CHEVRON = + ''; const GRIP = ''; @@ -264,6 +299,8 @@ function normalizeCorner(value: string | null | undefined): GlassAnchor { export interface DownloadRequest { format: Format; + /** Language code to translate into, or empty for no translation. */ + translateTo: string; progress: (text: string, percent?: number) => void; signal: AbortSignal; } @@ -278,6 +315,8 @@ export interface WidgetOptions { defaultFormat?: Format; corner?: string | null; onCornerChange?: (corner: GlassAnchor) => void; + translateTo?: string; + onTranslateChange?: (code: string) => void; onDownload: (request: DownloadRequest) => Promise; } @@ -294,6 +333,8 @@ export function create({ defaultFormat, corner, onCornerChange, + translateTo: initialTranslateTo, + onTranslateChange, onDownload, }: WidgetOptions): Widget { const host = document.createElement('div'); @@ -343,6 +384,7 @@ export function create({ } let at = normalizeCorner(corner); + let translateTo = normalizeTarget(initialTranslateTo); function applyCorner(): void { rootEl.classList.toggle('x-right', at[1] === 'r'); @@ -714,7 +756,7 @@ export function create({ if (focus) fab.focus(); } - function renderMenu(): void { + function renderMenu(focusTranslate = false): void { settled = false; mode = 'menu'; const panel = document.createElement('div'); @@ -756,9 +798,31 @@ export function create({ const i = items.indexOf(shadow.activeElement as HTMLButtonElement); items[(i + delta + items.length) % items.length]!.focus(); }); - panel.append(head, list); + const tr = document.createElement('label'); + tr.className = 'tr' + (translateTo ? ' on' : ''); + const trLabel = document.createElement('span'); + trLabel.textContent = 'Translate'; + const pick = document.createElement('span'); + pick.className = 'pick'; + const select = document.createElement('select'); + select.setAttribute('aria-label', 'Translate the book into'); + select.append(new Option('Off', ''), ...LANGUAGES.map((l) => new Option(l.label, l.code))); + select.value = translateTo; + pick.append(select); + pick.insertAdjacentHTML('beforeend', CHEVRON); + tr.append(trLabel, pick); + const note = document.createElement('div'); + note.className = 'tr-note'; + note.textContent = 'Chapter text is sent to Google Translate.'; + note.hidden = !translateTo; + select.addEventListener('change', () => { + translateTo = normalizeTarget(select.value); + if (onTranslateChange) onTranslateChange(translateTo); + renderMenu(true); + }); + panel.append(head, tr, note, list); setView(panel, false); - const first = list.querySelector('button'); + const first = focusTranslate ? select : list.querySelector('button'); if (first) first.focus(); } @@ -834,7 +898,7 @@ export function create({ } }; try { - const result = await onDownload({ format, progress, signal: controller.signal }); + const result = await onDownload({ format, translateTo, progress, signal: controller.signal }); ui.fill.style.width = '100%'; renderResult({ filename: result.filename, note: result.note }); } catch (err) { diff --git a/test/translate.ts b/test/translate.ts new file mode 100644 index 0000000..93e3dc2 --- /dev/null +++ b/test/translate.ts @@ -0,0 +1,546 @@ +// Translation, with no network: the engine runs against a fake fetch and the +// book layer against a fake engine. What is under test is what happens to the +// book — structure, inline markup, batching, retries — not Google's opinion +// of a sentence. +import { inflateRawSync } from 'node:zlib'; +import { JSDOM } from 'jsdom'; + +import type { Book } from '../src/types.ts'; +import { createGoogleTranslator } from '../src/translate/google.ts'; +import { translateBook, TRANSLATE_FROM, TRANSLATE_TO } from '../src/translate/book.ts'; +import { joinPieces, normalizeSpacing, planBatches, splitSegment } from '../src/translate/text.ts'; +import { normalizeTarget, type TranslateResult, type Translator } from '../src/translate/types.ts'; +import * as epub from '../src/lib/epub.ts'; + +const dom = new JSDOM(); +globalThis.DOMParser = dom.window.DOMParser; +globalThis.Node = dom.window.Node; + +let passed = 0; +const failures: string[] = []; + +async function test(name: string, fn: () => Promise | void): Promise { + try { + await fn(); + passed += 1; + } catch (err) { + failures.push(`${name}: ${(err as Error).message}`); + } +} + +function assert(cond: unknown, msg: string): asserts cond { + if (!cond) throw new Error(msg); +} + +function assertEq(a: T, b: T, msg: string): void { + if (a !== b) throw new Error(`${msg}: expected ${JSON.stringify(b)}, got ${JSON.stringify(a)}`); +} + +async function rejects(p: Promise, pattern: RegExp, msg: string): Promise { + try { + await p; + } catch (err) { + assert(pattern.test((err as Error).message + (err as Error).name), `${msg}: wrong error ${(err as Error).message}`); + return; + } + throw new Error(`${msg}: did not throw`); +} + +const said = (texts: string[], lang = ''): TranslateResult => ({ texts, detected: texts.map(() => lang) }); + +// ---------- a stand-in for the endpoint ---------- +interface Call { + url: URL; + q: string[]; +} + +/** Answers every query with "ПЕРЕВОД " in front of each text run, the way a translation changes text and leaves tags. */ +const translateText = (html: string): string => html.replace(/(^|>)([^<>]*[A-Za-z][^<>]*)/g, '$1ПЕРЕВОД $2'); + +function fakeFetch(handler: (call: Call, n: number) => Response | Promise) { + const calls: Call[] = []; + const fn: typeof fetch = async (input, init) => { + const body = init?.body as URLSearchParams; + const call = { url: new URL(String(input)), q: body.getAll('q') }; + calls.push(call); + assertEq(init?.method, 'POST', 'the endpoint is called with POST'); + return handler(call, calls.length); + }; + return { fn, calls }; +} + +const ok = (call: Call): Response => Response.json(call.q.map(translateText)); +const engine = (f: typeof fetch, extra = {}): Translator => + createGoogleTranslator({ fetch: f, gap: 0, backoffBase: 1, ...extra }); + +// ================== text helpers ================== + +await test('spacing: the stray space after a closing tag goes, other spaces stay', () => { + assertEq(normalizeSpacing('остался .', 'ru'), 'остался.', 'period'); + assertEq(normalizeSpacing('да , нет !', 'ru'), 'да, нет!', 'comma and bang'); + assertEq(normalizeSpacing('а ? б ; в :', 'ru'), 'а? б; в:', 'question, semicolon, colon'); + assertEq(normalizeSpacing('«да» ” и (нет )', 'ru'), '«да»” и (нет)', 'closing quote and bracket'); + assertEq(normalizeSpacing('слово . и тире — дальше', 'ru'), 'слово . и тире — дальше', 'no tag, no change'); + assertEq(normalizeSpacing('он и она .', 'ru'), 'он и она.', 'only the space before punctuation'); +}); + +await test('spacing: French keeps its space before ? ! : ;', () => { + assertEq(normalizeSpacing('Quoi ? Non .', 'fr'), 'Quoi ? Non.', 'fr'); +}); + +await test('batches stay under the character budget and the segment cap', () => { + const pieces = Array.from({ length: 50 }, (_, i) => 'x'.repeat(100 + (i % 7) * 40)); + const groups = planBatches(pieces, 1000, 6); + assertEq(groups.flat().length, 50, 'every piece lands in a batch'); + assertEq(groups.flat().join(), Array.from({ length: 50 }, (_, i) => i).join(), 'order is kept'); + for (const g of groups) { + assert(g.length <= 6, `a batch of ${g.length} segments`); + const size = g.reduce((n, i) => n + pieces[i]!.length, 0); + assert(size <= 1000 || g.length === 1, `a batch of ${size} characters`); + } + const huge = planBatches(['a', 'b'.repeat(5000), 'c'], 1000, 6); + assertEq(huge.length, 3, 'an oversized piece travels alone'); +}); + +await test('a long fragment is cut at sentence ends, never inside an inline tag', () => { + const sentence = 'The rain kept falling on the old roof. '; + const html = `${sentence.repeat(30)} ${sentence.repeat(30)}and that was it.`; + const pieces = splitSegment(html, 400); + assert(pieces.length > 1, 'it should have been cut'); + assertEq(pieces.join(''), html, 'nothing lost, nothing added'); + assert(pieces.every((p) => p.length <= 400 || p.startsWith('')), 'a piece over the budget that is not the stretch'); + for (const p of pieces) { + assertEq((p.match(//g) || []).length, (p.match(/<\/i>/g) || []).length, 'a piece with an unclosed '); + } + assertEq(joinPieces(['One. ', 'Two.']), 'One. Two.', 'join keeps one space'); +}); + +await test('only known language codes switch translation on', () => { + assertEq(normalizeTarget('ru'), 'ru', 'ru'); + assertEq(normalizeTarget('zh-CN'), 'zh-CN', 'zh-CN'); + assertEq(normalizeTarget('klingon'), '', 'unknown'); + assertEq(normalizeTarget(undefined), '', 'missing'); +}); + +// ================== the engine ================== + +await test('google: one POST with several q, the right language pair, html format', async () => { + const f = fakeFetch(ok); + const out = (await engine(f.fn).translate(['

Hello there

', 'Plain'], 'auto', 'ru')).texts; + assertEq(f.calls.length, 1, 'requests'); + const u = f.calls[0]!.url; + assertEq(u.origin + u.pathname, 'https://translate.googleapis.com/translate_a/t', 'endpoint'); + assertEq(u.searchParams.get('client'), 'gtx', 'client'); + assertEq(u.searchParams.get('sl'), 'auto', 'source'); + assertEq(u.searchParams.get('tl'), 'ru', 'target'); + assertEq(u.searchParams.get('format'), 'html', 'format'); + assertEq(f.calls[0]!.q.length, 2, 'q count'); + assertEq(out[0], '

ПЕРЕВОД Hello ПЕРЕВОД there

', 'first'); + assertEq(out[1], 'ПЕРЕВОД Plain', 'second'); +}); + +await test('google: pairs [text, detected language] are understood too', async () => { + const f = fakeFetch((c) => Response.json(c.q.map((q) => [`T ${q}`, 'en']))); + const out = (await engine(f.fn).translate(['a', 'b'], 'auto', 'de')).texts; + assertEq(out.join('|'), 'T a|T b', 'answers'); +}); + +await test('google: the detected source language is surfaced, empty when the engine does not say', async () => { + const f = fakeFetch((c) => Response.json(c.q.map((q) => [`T ${q}`, 'uk']))); + const r = await engine(f.fn).translate(['a', '', 'b'], 'auto', 'ru'); + assertEq(r.detected.join('|'), 'uk||uk', 'detected'); + const g = fakeFetch((c) => Response.json(c.q.map((q) => `T ${q}`))); + assertEq((await engine(g.fn).translate(['a'], 'en', 'ru')).detected.join('|'), '', 'bare strings'); +}); + +await test('google: requests respect the budget and the segment cap, and the order survives', async () => { + const f = fakeFetch(ok); + const segments = Array.from({ length: 95 }, (_, i) => `

Segment ${i} ${'word '.repeat(20)}

`); + const out = (await engine(f.fn, { budget: 1500, maxSegments: 10 }).translate(segments, 'auto', 'ru')).texts; + assertEq(out.length, 95, 'answers'); + assert(f.calls.length >= 10, `${f.calls.length} requests is too few for the cap`); + for (const c of f.calls) { + assert(c.q.length <= 10, `${c.q.length} segments in one request`); + const size = c.q.reduce((n, q) => n + q.length, 0); + assert(size <= 1500 || c.q.length === 1, `${size} characters in one request`); + } + out.forEach((o, i) => assert(o.includes(`Segment ${i} `), `segment ${i} came back out of order`)); +}); + +await test('google: a segment over the budget is cut, translated in parts and put back together', async () => { + const f = fakeFetch(ok); + const long = `${'The night was long and quiet. '.repeat(60)}`; + const out = (await engine(f.fn, { budget: 500 }).translate([long], 'auto', 'ru')).texts; + assert(f.calls.length > 1, 'it should have taken several requests'); + assert(f.calls.every((c) => c.q.every((q) => q.length <= 500)), 'a piece over the budget'); + assertEq(out.length, 1, 'one answer for one segment'); + assert(out[0]!.startsWith('ПЕРЕВОД The night'), 'start'); + assertEq((out[0]!.match(/ПЕРЕВОД/g) || []).length, f.calls.reduce((n, c) => n + c.q.length, 0), 'every piece is in'); +}); + +await test('google: empty segments are not sent and do not shift the answers', async () => { + const f = fakeFetch(ok); + const out = (await engine(f.fn).translate(['One', '', ' ', 'Two'], 'auto', 'ru')).texts; + assertEq(f.calls[0]!.q.length, 2, 'only the two real ones go out'); + assertEq(out.join('|'), 'ПЕРЕВОД One|| |ПЕРЕВОД Two', 'places kept'); +}); + +await test('google: 429 is retried and the retry succeeds', async () => { + const f = fakeFetch((c, n) => (n === 1 ? new Response('', { status: 429, headers: { 'Retry-After': '0' } }) : ok(c))); + const out = (await engine(f.fn).translate(['Hello'], 'auto', 'ru')).texts; + assertEq(f.calls.length, 2, 'attempts'); + assertEq(out[0], 'ПЕРЕВОД Hello', 'answer'); +}); + +await test('google: 503 and a dropped connection are retried as well', async () => { + let n = 0; + const f = fakeFetch((c) => { + n += 1; + if (n === 1) return new Response('', { status: 503 }); + if (n === 2) throw new TypeError('Failed to fetch'); + return ok(c); + }); + const out = (await engine(f.fn).translate(['Hello'], 'auto', 'ru')).texts; + assertEq(out[0], 'ПЕРЕВОД Hello', 'answer'); + assertEq(f.calls.length, 3, 'attempts'); +}); + +await test('google: a persistent refusal ends in a clear error', async () => { + const f = fakeFetch(() => new Response('', { status: 429, headers: { 'Retry-After': '0' } })); + await rejects(engine(f.fn, { maxAttempts: 3 }).translate(['Hello'], 'auto', 'ru'), /limiting requests/, '429'); + assertEq(f.calls.length, 3, 'it gave up after the allowed attempts'); + const g = fakeFetch(() => new Response('', { status: 403 })); + await rejects(engine(g.fn).translate(['Hello'], 'auto', 'ru'), /HTTP 403/, '403'); + assertEq(g.calls.length, 1, 'a 403 is not retried'); +}); + +await test('google: an answer of the wrong length is refused, not misaligned', async () => { + const f = fakeFetch(() => Response.json(['only one'])); + await rejects(engine(f.fn).translate(['a', 'b'], 'auto', 'ru'), /shape/, 'mismatch'); +}); + +await test('google: an aborted signal stops it before and between requests', async () => { + const f = fakeFetch(ok); + const ac = new AbortController(); + ac.abort(); + await rejects(engine(f.fn).translate(['Hello'], 'auto', 'ru', ac.signal), /Abort|Cancelled/, 'before'); + assertEq(f.calls.length, 0, 'no request after abort'); + + const g = fakeFetch(ok); + const mid = new AbortController(); + const slow: typeof fetch = async (input, init) => { + const res = await g.fn(input, init); + mid.abort(); + return res; + }; + const many = Array.from({ length: 6 }, (_, i) => `Seg ${i} ${'x'.repeat(50)}`); + await rejects( + engine(slow, { budget: 100, maxSegments: 1 }).translate(many, 'auto', 'ru', mid.signal), + /Abort|Cancelled/, + 'between', + ); + assertEq(g.calls.length, 1, 'it stopped after the first request'); +}); + +// ================== the book ================== + +function makeBook(): Book { + return { + title: 'River & House', + author: 'TestAuthor', + language: 'en', + uuid: '11111111-2222-3333-4444-555555555555', + tags: ['Slow Burn', 'AU'], + fandom: 'Original Work', + summaryText: 'A house by the river.', + summaryXhtml: '

A house by the river.

', + chapters: [ + { + title: 'Chapter 1: Arrival', + xhtml: + '

She said, "Don\'t go." And he stayed.

' + + '

* * *

' + + '

Quoted line.

' + + '
  • One item
  • Two
' + + '

Scene

Fish & chips.
Second line.

', + notesXhtml: '

Thanks for reading.

', + }, + { title: 'Chapter 2', xhtml: '

The rain had started.

' }, + ], + }; +} + +function recorder(lang = ''): { tr: Translator; sent: string[]; to: string[] } { + const sent: string[] = []; + const to: string[] = []; + const tr: Translator = { + id: 'fake', + async translate(segments, _from, target) { + sent.push(...segments); + to.push(target); + return said(segments.map(translateText), lang); + }, + }; + return { tr, sent, to }; +} + +await test('translateBook: blocks and inline markup survive, the wrappers stay', async () => { + const { tr, sent } = recorder(); + const out = await translateBook(makeBook(), 'ru', tr, () => {}); + const c1 = out.chapters[0]!.xhtml; + assert(c1.startsWith('

ПЕРЕВОД She said, '), `paragraph: ${c1.slice(0, 200)}`); + assert(/ПЕРЕВОД "Don't go\."<\/i>/.test(c1), `italic: ${c1}`); + assert(/ПЕРЕВОД stayed<\/b>/.test(c1), 'bold'); + assert(/

ПЕРЕВОД Quoted ПЕРЕВОД line<\/em>.<\/p><\/blockquote>/.test(c1), `blockquote: ${c1}`); + assert(/

  • ПЕРЕВОД One ПЕРЕВОД item<\/em><\/li>
  • ПЕРЕВОД Two<\/li><\/ul>/.test(c1), `list: ${c1}`); + assert(c1.includes('
    '), 'the rule'); + assert(c1.includes('

    ПЕРЕВОД Scene

    '), 'the heading stays a heading'); + assert(c1.includes('

    * * *

    '), 'a scene break is left as it was'); + assert(/

    ПЕРЕВОД Fish & chips\.ПЕРЕВОД Second line\.<\/p>/.test(c1), `br and entity: ${c1}`); + assert(!sent.some((s) => s === '* * *' || s.includes('

    ')), 'wrappers and letterless blocks do not go out'); + assert(sent.includes('Fish & chips.
    Second line.'), `the block goes out with its inline markup: ${JSON.stringify(sent)}`); + assert(out.chapters[0]!.notesXhtml!.includes('ПЕРЕВОД reading'), 'notes'); +}); + +await test('translateBook: titles, summary and language change; author, tags and fandom do not', async () => { + const { tr } = recorder(); + const book = makeBook(); + const out = await translateBook(book, 'ru', tr, () => {}); + assertEq(out.title, 'ПЕРЕВОД River & House', 'title (read back as text, not as markup)'); + assertEq(out.chapters[0]!.title, 'ПЕРЕВОД Chapter 1: Arrival', 'chapter title'); + assertEq(out.summaryText, 'ПЕРЕВОД A house by the river.', 'summary text'); + assertEq(out.summaryXhtml, '

    ПЕРЕВОД A house by the ПЕРЕВОД river.

    ', 'summary markup'); + assertEq(out.language, 'ru', 'language'); + assertEq(out.author, 'TestAuthor', 'author'); + assertEq(out.tags.join(), 'Slow Burn,AU', 'tags'); + assertEq(out.fandom, 'Original Work', 'fandom'); + assertEq(book.language, 'en', 'the input book is not mutated'); + assertEq(book.chapters[0]!.title, 'Chapter 1: Arrival', 'nor its chapters'); +}); + +await test('translateBook: output is well-formed even when the engine returns loose markup', async () => { + const sloppy: Translator = { + id: 'sloppy', + async translate(segments) { + return said(segments.map((s) => `${s} unclosed
    tail
    `)); + }, + }; + const out = await translateBook(makeBook(), 'ru', sloppy, () => {}); + const xml = `${out.chapters[0]!.xhtml}`; + const parsed = new dom.window.DOMParser().parseFromString(`${xml}`, 'application/xml'); + assert(!parsed.querySelector('parsererror'), `not well-formed: ${out.chapters[0]!.xhtml.slice(0, 300)}`); + assert(!/ { + const dropper: Translator = { id: 'drop', async translate(s) { return said(s.map(() => '')); } }; + const out = await translateBook(makeBook(), 'ru', dropper, () => {}); + assert(out.chapters[1]!.xhtml.includes('The rain had started.'), 'text lost'); + assertEq(out.title, 'River & House', 'title falls back'); +}); + +await test('translateBook: a Ukrainian book labelled ru is still translated into Russian', async () => { + const { tr } = recorder('uk'); + const book = makeBook(); + book.language = 'ru'; + const out = await translateBook(book, 'ru', tr, () => {}); + assert(out !== book, 'the book was skipped'); + assertEq(out.title, 'ПЕРЕВОД River & House', 'title translated'); + assert(out.chapters[1]!.xhtml.includes('ПЕРЕВОД The rain'), 'second chapter translated'); + assertEq(out.language, 'ru', 'language set to the target'); +}); + +await test('translateBook: a book already in the target language is skipped after the first chapter', async () => { + const { tr, sent } = recorder('en'); + const lines: string[] = []; + const book = makeBook(); + const out = await translateBook(book, 'en', tr, (t) => lines.push(t)); + assertEq(out, book, 'the very same book'); + assert(!sent.includes('River & House') && !sent.some((x) => x.includes('rain had started')), `only chapter 1 was sent: ${JSON.stringify(sent)}`); + assert(sent.some((x) => x.includes('Fish & chips')), 'chapter 1 was sent'); + assert(lines.some((l) => /already in English/.test(l)), `progress: ${lines}`); + assert(!lines.some((l) => /title and summary|chapter 2/.test(l)), 'it went on after deciding'); +}); + +await test('translateBook: subtags compare by primary language (zh vs zh-CN, pt-BR vs pt)', async () => { + for (const [detected, target] of [['zh', 'zh-CN'], ['pt-BR', 'pt'], ['zh-CN', 'zh-CN']]) { + const book = makeBook(); + const out = await translateBook(book, target!, recorder(detected).tr, () => {}); + assertEq(out, book, `${detected} → ${target} should be skipped`); + } +}); + +await test('translateBook: short and minority segments do not flip the decision', async () => { + // Long prose is English; titles and one-liners are guessed as Russian. + const byLength: Translator = { + id: 'len', + async translate(segments) { + return { texts: segments.map(translateText), detected: segments.map((x) => (x.length > 30 ? 'en' : 'ru')) }; + }, + }; + const book = makeBook(); + assertEq(await translateBook(book, 'en', byLength, () => {}), book, 'English prose wins: skipped for en'); + const out = await translateBook(book, 'ru', byLength, () => {}); + assert(out !== book && out.language === 'ru', 'English prose wins: translated for ru'); +}); + +await test('translateBook: no detection from the engine means no skip', async () => { + const book = makeBook(); + book.language = 'en'; + const out = await translateBook(book, 'en', recorder().tr, () => {}); + assert(out !== book, 'skipped without any evidence'); +}); + +const detectScript: Translator = { + id: 'script', + async translate(segments) { + return { texts: segments.map(translateText), detected: segments.map((x) => (/[а-яё]/i.test(x) ? 'ru' : 'en')) }; + }, +}; + +const LONG_EN = '

    She walked down to the river and watched the water for a long while.

    '; +const LONG_RU = '

    Спасибо всем, кто читает эту историю и оставляет свои отзывы под главами.

    '; + +await test('translateBook: author notes in another language do not decide the vote', async () => { + const book = makeBook(); + book.chapters = [{ title: 'One', xhtml: LONG_EN, notesXhtml: LONG_RU.repeat(3) }]; + const out = await translateBook(book, 'ru', detectScript, () => {}); + assert(out !== book, 'the Russian notes made it look like a Russian book'); + assert(out.chapters[0]!.xhtml.includes('ПЕРЕВОД She walked'), 'body translated'); +}); + +await test('translateBook: a first chapter too small to vote hands the decision to the next one', async () => { + const book = makeBook(); + book.chapters = [ + { title: 'One', xhtml: '

    Hi there.

    ' }, + { title: 'Two', xhtml: LONG_EN }, + ]; + assertEq(await translateBook(book, 'en', detectScript, () => {}), book, 'chapter 2 says English: skipped'); + const out = await translateBook(book, 'ru', detectScript, () => {}); + assert(out !== book && out.chapters[0]!.xhtml.includes('ПЕРЕВОД Hi there'), 'translated, small chapter included'); +}); + +await test('translateBook: when no chapter is big enough to vote, everything is translated', async () => { + const book = makeBook(); + book.chapters = [{ title: 'One', xhtml: '

    Hi.

    ' }, { title: 'Two', xhtml: '

    Bye.

    ' }]; + const out = await translateBook(book, 'en', detectScript, () => {}); + assert(out !== book && out.language === 'en', 'skipped on no evidence'); + assert(out.chapters[1]!.xhtml.includes('ПЕРЕВОД Bye'), 'second chapter translated'); +}); + +function threeChapters(): Book { + const book = makeBook(); + book.chapters = ['One', 'Two', 'Three'].map((t) => ({ title: t, xhtml: LONG_EN.replace('river', 'river ' + t) })); + return book; +} + +/** An engine that refuses whatever mentions `marker`, the way a persistent 429 refuses a request. */ +function refusing(marker: string, error = new Error('Google Translate is limiting requests.')): Translator { + return { + id: 'refusing', + async translate(segments) { + if (segments.some((x) => x.includes(marker))) throw error; + return said(segments.map(translateText)); + }, + }; +} + +await test('translateBook: a chapter the engine keeps refusing stays original, the rest is translated and counted', async () => { + const report: { failedChapters?: number; failure?: string } = {}; + const out = await translateBook(threeChapters(), 'ru', refusing('river Two'), () => {}, undefined, report); + assert(out.chapters[0]!.xhtml.includes('ПЕРЕВОД She walked'), 'chapter 1 translated'); + assert(out.chapters[1]!.xhtml.includes('She walked down to the river Two'), 'chapter 2 original'); + assert(!out.chapters[1]!.xhtml.includes('ПЕРЕВОД'), 'chapter 2 half-translated'); + assert(out.chapters[2]!.xhtml.includes('ПЕРЕВОД She walked'), 'chapter 3 translated'); + assertEq(out.language, 'ru', 'language'); + assertEq(report.failedChapters, 1, 'count'); + assert(/1 of 3 chapters stayed untranslated/.test(report.failure ?? '') && /limiting requests/.test(report.failure ?? ''), `message: ${report.failure}`); +}); + +await test('translateBook: a failed front matter keeps the original title and summary', async () => { + const out = await translateBook(makeBook(), 'ru', refusing('River & House'), () => {}); + assertEq(out.title, 'River & House', 'title'); + assertEq(out.summaryText, 'A house by the river.', 'summary'); + assert(out.chapters[1]!.xhtml.includes('ПЕРЕВОД The rain'), 'chapters translated'); +}); + +await test('translateBook: with every chapter refused it throws, not a book with no translation', async () => { + await rejects(translateBook(threeChapters(), 'ru', refusing('river'), () => {}), /limiting requests/, 'all refused'); +}); + +await test('translateBook: an abort is never swallowed as a failed chapter', async () => { + const err = new Error('Cancelled'); + err.name = 'AbortError'; + await rejects(translateBook(threeChapters(), 'ru', refusing('river Two', err), () => {}), /Cancelled|Abort/, 'abort'); +}); + +await test('translateBook: progress counts chapters inside its band, before assembling', async () => { + const { tr } = recorder(); + const seen: [string, number | undefined][] = []; + await translateBook(makeBook(), 'ru', tr, (t, p) => seen.push([t, p])); + const chapters = seen.filter(([t]) => /^Translating chapter/.test(t)); + assertEq(chapters.map(([t]) => t).join('|'), 'Translating chapter 1 of 2…|Translating chapter 2 of 2…', 'labels'); + for (const [, p] of seen) { + assert(p !== undefined && p >= TRANSLATE_FROM && p < TRANSLATE_TO, `percent ${p} is outside the band`); + } + assert(TRANSLATE_TO < 90, 'the band must end before "Assembling…"'); + assert(chapters[1]![1]! > chapters[0]![1]!, 'the bar moves forward'); +}); + +await test('translateBook: abort stops the work between chapters', async () => { + const ac = new AbortController(); + let calls = 0; + const tr: Translator = { + id: 'abort', + async translate(segments) { + calls += 1; + if (calls === 2) ac.abort(); + return said(segments.map(translateText)); + }, + }; + await rejects(translateBook(makeBook(), 'ru', tr, () => {}, ac.signal), /Abort|Cancelled/, 'abort'); + assertEq(calls, 2, 'front matter, chapter 1, and then it stopped'); +}); + +// ================== a file built from a translated book ================== + +function readZip(buf: Buffer): Map { + const files = new Map(); + let i = 0; + while (i + 30 <= buf.length && buf.readUInt32LE(i) === 0x04034b50) { + const method = buf.readUInt16LE(i + 8); + const packed = buf.readUInt32LE(i + 18); + const nameLen = buf.readUInt16LE(i + 26); + const extraLen = buf.readUInt16LE(i + 28); + const name = buf.subarray(i + 30, i + 30 + nameLen).toString('utf8'); + const start = i + 30 + nameLen + extraLen; + const payload = buf.subarray(start, start + packed); + files.set(name, method === 8 ? inflateRawSync(payload) : payload); + i = start + packed; + } + return files; +} + +await test('EPUB from a translated book: translated text, target dc:language, well-formed', async () => { + const f = fakeFetch(ok); + const out = await translateBook(makeBook(), 'ru', engine(f.fn), () => {}); + const files = readZip(Buffer.from(await (await epub.build(out)).arrayBuffer())); + const opf = files.get('OEBPS/content.opf')!.toString('utf8'); + assert(opf.includes('ru'), 'dc:language is not ru'); + assert(opf.includes('ПЕРЕВОД River & House'), 'translated title in the package'); + + const ch = files.get('OEBPS/ch001.xhtml')!.toString('utf8'); + assert(ch.includes('ПЕРЕВОД She said'), 'chapter text is not translated'); + assert(ch.includes('ПЕРЕВОД "Don\'t go."'), 'italics lost'); + for (const [name, bytes] of files) { + if (!/\.(xhtml|opf|ncx)$/.test(name)) continue; + const parsed = new dom.window.DOMParser().parseFromString(bytes.toString('utf8'), 'application/xml'); + assert(!parsed.querySelector('parsererror'), `${name} is not well-formed XML`); + } +}); + +console.log(`\npassed: ${passed}, failed: ${failures.length}`); +if (failures.length) { + for (const f of failures) console.error(` ✗ ${f}`); + process.exit(1); +}