feat: pilot explicit preview and selection reading with Hitokoto
Browse filesReuse the lazy independent CPU reader through a strict two-origin window/channel bridge. Preserve exact preview text and selection context, require explicit synthesis and active replacement, and keep search/filter/preview independent of the persistent player. No index/corpus/backend/model dependencies or SW cache-name changes.
Files changed (8)
- README.md+3-1
- docs/TTS_PILOT.mdAdded+22
- static/app.js+14-1
- static/index.html+13
- static/style.css+10
- static/tts-client.jsAdded+191
- tests/test_search.py+3
- tests/test_tts_browser.pyAdded+271
8 unmodified lines91011128 unmodified linesshort_description: 给CCRD和CW的TXT提供搜索与全文搜索功能---VOMEBOOK Search is a txt-focused search Space for CCRD and CW bundles.8 unmodified lines910111213148 unmodified linesshort_description: 给CCRD和CW的TXT提供搜索与全文搜索功能---VOMEBOOK Search is a txt-focused search Space for CCRD and CW bundles.CCRD 的选文/预览朗读试点见 [docs/TTS_PILOT.md](docs/TTS_PILOT.md)。
12345678910111213141516171819202122# CCRD 朗读试点
在文章预览上方,可选“朗读选中文字”或“朗读当前预览”。首次点击后才载入Hitokoto 的独立 CPU 播放器;文字通过严格限定来源的浏览器消息传入,不放进 URL。**载入文字不等于提交合成**:在播放器确认正文、音色、合成语速和试验音高后,主动点击“合成并试听”,才分批提交到 Hitokoto API。
- 选文必须完全在当前预览正文里,含原文 Unicode 与有限相邻读音上下文。- 最多两万字;超长请自行选一段,不自动截断、不自动发送整本书。- 当前快照开始朗读后,更换搜索词、排序、过滤、打开另一篇或关闭预览不会替换它。- 播放器内支持暂停、句段跳读、倍速、睡眠定时、试验音高;高亮是句段级。- “收起”或 Escape 保留朗读,“停止并收起”停止。重新载入会要求明确确认替换。- 桌面保留搜索可操作;手机播放器独立弹层,收起后恢复预览。- 试点播放器不自动读取/保存独立试听页的本机正文书签,页面内可续读。- 模型、音色、缓存与任务限制来自 Hitokoto;API 不可用不影响搜索、预览和下载。- 旧 Service Worker 客户端可能需第二次刷新/重开,缓存名不变。- 实际手机后台、锁屏、自动播放限制、人工听感仍需真机确认,不承诺无缝。
生产搜索站:<https://vomebook-search.hf.space/>;语音服务:<https://vomebook-hitokoto.hf.space/tts/>。这次只接入 CCRD,其他三个搜索站未改。
开发/验收命令见 `TESTING.md` 的 CCRD / Hitokoto reader pilot tier。1173 unmodified lines11741175117611771178117917 unmodified lines11971198119912001201120228 unmodified lines12311232123312341235123612372 unmodified lines1240124112421243124412451000 unmodified lines2246224722482249225022515 unmodified lines22572258225922602261226222631173 unmodified lines}function clearPreviewDom() {setPreviewFullscreen(false);DOM.previewPanel.innerHTML = "";DOM.previewPanel.hidden = true;17 unmodified linessyncUrl(history.state && history.state.preview === true);}if (previewController) previewController.abort();pauseSnippetLoadingForPreview();const controller = new AbortController();previewController = controller;28 unmodified lines<button type="button" class="icon-btn-sm" data-action="close-preview" aria-label="关闭预览">×</button><button type="button" class="icon-btn-sm preview-theme-btn" data-action="toggle-preview-theme" aria-label="${STATE.isDark ? "切换到白天模式" : "切换到黑夜模式"}" title="${STATE.isDark ? "白天模式" : "黑夜模式"}">${themeIcon(STATE.isDark)}</button></div></div><pre class="preview-body"></pre>`;const previewTitle = DOM.previewPanel.querySelector(".preview-title");if (previewTitle) previewTitle.id = "preview-title";2 unmodified linesconst previewBody = DOM.previewPanel.querySelector(".preview-body");if (shouldHighlight) previewBody.innerHTML = text;else previewBody.textContent = rawText;DOM.previewPanel.style.display = STATE.isMobile ? "flex" : "block";setPreviewFullscreen(STATE.previewFullscreen);document.body.classList.add("preview-open");1000 unmodified lines}});DOM.previewPanel.addEventListener("click", (event) => {const closeBtn = event.target.closest("[data-action='close-preview']");if (closeBtn) {closePreview();5 unmodified lines}if (event.target.closest("[data-action='toggle-preview-theme']")) toggleTheme();});document.addEventListener("keydown", (event) => {if (STATE.previewDocId && !DOM.previewPanel.hidden && (previewIsModal() || DOM.previewPanel.contains(event.target))) {if (event.key === "Escape") {event.preventDefault();1173 unmodified lines117411751176117711781179118017 unmodified lines119811991200120112021203120428 unmodified lines123312341235123612371238123912402 unmodified lines12431244124512461247124812491000 unmodified lines22502251225222532254225522562257225822592260226122625 unmodified lines2268226922702271227222732274227522761173 unmodified lines}function clearPreviewDom() {window.CCRDSpeech?.previewClosed();setPreviewFullscreen(false);DOM.previewPanel.innerHTML = "";DOM.previewPanel.hidden = true;17 unmodified linessyncUrl(history.state && history.state.preview === true);}if (previewController) previewController.abort();window.CCRDSpeech?.previewClosed();pauseSnippetLoadingForPreview();const controller = new AbortController();previewController = controller;28 unmodified lines<button type="button" class="icon-btn-sm" data-action="close-preview" aria-label="关闭预览">×</button><button type="button" class="icon-btn-sm preview-theme-btn" data-action="toggle-preview-theme" aria-label="${STATE.isDark ? "切换到白天模式" : "切换到黑夜模式"}" title="${STATE.isDark ? "白天模式" : "黑夜模式"}">${themeIcon(STATE.isDark)}</button></div></div><div class="preview-speech-tools"><button type="button" class="text-btn" data-speech="selection">朗读选中文字</button><button type="button" class="text-btn" data-speech="preview">朗读当前预览</button><button type="button" class="text-btn" data-speech="controls">播放器</button></div><pre class="preview-body"></pre>`;const previewTitle = DOM.previewPanel.querySelector(".preview-title");if (previewTitle) previewTitle.id = "preview-title";2 unmodified linesconst previewBody = DOM.previewPanel.querySelector(".preview-body");if (shouldHighlight) previewBody.innerHTML = text;else previewBody.textContent = rawText;window.CCRDSpeech?.previewLoaded({ id: docId, title: data.title, text: rawText });DOM.previewPanel.style.display = STATE.isMobile ? "flex" : "block";setPreviewFullscreen(STATE.previewFullscreen);document.body.classList.add("preview-open");1000 unmodified lines}});DOM.previewPanel.addEventListener("click", (event) => {const speech = event.target.closest("[data-speech]");if (speech) {if (speech.dataset.speech === "controls") document.querySelector("#speech-launch")?.click();else if (window.CCRDSpeech) window.CCRDSpeech.read(speech.dataset.speech);else showToast("朗读组件尚未更新,请刷新页面后重试");return;}const closeBtn = event.target.closest("[data-action='close-preview']");if (closeBtn) {closePreview();5 unmodified lines}if (event.target.closest("[data-action='toggle-preview-theme']")) toggleTheme();});if (!window.CCRDSpeech) $("#speech-launch")?.addEventListener("click", () => showToast("朗读组件加载失败,请刷新重试;搜索仍可使用"));document.addEventListener("keydown", (event) => {if (window.CCRDSpeech?.modal() || window.CCRDSpeech?.owns(event.target)) return;if (STATE.previewDocId && !DOM.previewPanel.hidden && (previewIsModal() || DOM.previewPanel.contains(event.target))) {if (event.key === "Escape") {event.preventDefault();
50 unmodified lines51525354555690 unmodified lines14714814915015115215315450 unmodified lines<label class="multi-toggle" id="multi-toggle-label" style="display:none"><input type="checkbox" id="multi-select-toggle"><span>多选</span></label></div><div class="status-right"><button id="clear-filters-btn" class="text-btn" style="display:none">清空筛选</button><div class="sort-group"><span class="sort-label">排序:</span>90 unmodified lines</footer><div id="overlay" class="overlay" style="display:none"></div><div id="toast" class="toast" role="status" aria-live="polite" style="display:none"></div><script>if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/sw.js", { scope: "/" }); }</script><script src="/static/app.js"></script></body></html>50 unmodified lines5152535455565790 unmodified lines14814915015115215315415515615715815916016116216316416516616750 unmodified lines<label class="multi-toggle" id="multi-toggle-label" style="display:none"><input type="checkbox" id="multi-select-toggle"><span>多选</span></label></div><div class="status-right"><button type="button" id="speech-launch" class="text-btn" aria-controls="speech-dialog" aria-expanded="false">朗读</button><button id="clear-filters-btn" class="text-btn" style="display:none">清空筛选</button><div class="sort-group"><span class="sort-label">排序:</span>90 unmodified lines</footer><div id="overlay" class="overlay" style="display:none"></div><div id="toast" class="toast" role="status" aria-live="polite" style="display:none"></div><dialog id="speech-dialog" class="speech-dialog" aria-labelledby="speech-title"><div class="speech-heading"><strong id="speech-title">CPU 朗读(试点)</strong><button type="button" id="speech-collapse" class="text-btn">收起(保留朗读)</button><button type="button" id="speech-stop" class="text-btn">停止并收起</button></div><p id="speech-status" class="speech-note" role="status">打开后连接 Hitokoto 独立语音服务。</p><button type="button" id="speech-retry" class="text-btn" hidden>重新连接(停止原朗读)</button><div id="speech-frame-host"></div><p class="speech-note">关闭预览或切换搜索不打断朗读。正文通过浏览器交给播放器,点击合成才提交语音 API。手机后台效果待真机确认。</p></dialog><script>if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/sw.js", { scope: "/" }); }</script><script src="/static/tts-client.js"></script><script src="/static/app.js"></script></body></html>
47 unmodified lines48495051525347 unmodified linescolor-scheme: dark;}body.light {--surface: #fdfbff;--surface-variant: #f0eff4;47 unmodified lines4849505152535455565758596061626347 unmodified linescolor-scheme: dark;}.preview-speech-tools { display: flex; flex-wrap: wrap; gap: 8px; padding: 8px 12px; flex-shrink: 0; border-bottom: 1px solid var(--reader-divider); }.speech-dialog { position: fixed; inset: auto 12px 12px auto; margin: 0; width: min(560px, calc(100vw - 24px)); max-height: calc(100dvh - 24px); padding: 10px; background: var(--surface-container); color: var(--on-surface); border: 1px solid var(--outline); border-radius: 12px; box-shadow: var(--shadow-lg); z-index: 180; overflow: auto; user-select: text; }.speech-dialog:not([open]) { display: none; }.speech-dialog::backdrop { background: rgba(0, 0, 0, .45); }.speech-heading { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }.speech-heading strong { margin-right: auto; }.speech-note { font-size: 12px; color: var(--on-surface-variant); margin: 8px 0; overflow-wrap: anywhere; }#speech-frame-host iframe { display: block; width: 100%; height: min(62dvh, 660px); min-height: 220px; border: 0; background: var(--surface); }body.mobile .speech-dialog { inset: 12px; width: auto; margin: auto; max-width: 650px; }body.light {--surface: #fdfbff;--surface-variant: #f0eff4;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191"use strict";// CCRD pilot: shared Hitokoto player in a persistent, isolated browsing context.// No model code, browser speechSynthesis, remote text URLs or automatic TTS POSTs.window.CCRDSpeech = (() => { const ORIGIN = "https://vomebook-hitokoto.hf.space"; const PLAYER = ORIGIN + "/tts/?embed=ccrd-v1"; const $ = (selector) => document.querySelector(selector); const dialog = $("#speech-dialog"); const host = $("#speech-frame-host"); const status = $("#speech-status"); const launch = $("#speech-launch"); const collapse = $("#speech-collapse"); const stopButton = $("#speech-stop"); const retry = $("#speech-retry"); if (!dialog || !host || !launch) return null; // Older cached HTML stays usable. let frame = null, channel = "", connected = false, timeout, modalActive = false; let pending = null, currentPreview = null, selected = null, focusReturn = null;
function notice(message) { status.textContent = message; if (typeof showToast === "function") showToast(message, 4000); } function token() { return Array.from(crypto.getRandomValues(new Uint8Array(24)), (value) => value.toString(16).padStart(2, "0")).join(""); } function send(type, data = {}) { frame?.contentWindow?.postMessage({ type, channel, ...data }, ORIGIN); } function theme() { if (connected) send("ccrd-reader-theme", { dark: !document.body.classList.contains("light") }); } function modal() { return dialog.open && modalActive; } function owns(node) { return !!node && dialog.contains(node); } function outerControls() { return Array.from(dialog.querySelectorAll("button, a[href]")).filter(node => !node.disabled && !node.hidden && node.getClientRects().length); } function show() { if (!dialog.open) { focusReturn = document.activeElement instanceof HTMLElement ? document.activeElement : null; if (document.body.classList.contains("mobile")) dialog.showModal(); else dialog.show(); modalActive = document.body.classList.contains("mobile"); } launch.setAttribute("aria-expanded", "true"); collapse.focus({ preventScroll: true }); if (!frame) createFrame(); else if (connected) send("ccrd-reader-layout", { modal: modal() }); } function hide() { if (dialog.open) dialog.close(); modalActive = false; if (connected) send("ccrd-reader-layout", { modal: false }); launch.setAttribute("aria-expanded", "false"); const previous = focusReturn; if (previous?.isConnected && !previous.closest("[inert]")) previous.focus({ preventScroll: true }); else if (!launch.closest("[inert]")) launch.focus({ preventScroll: true }); } function createFrame() { clearTimeout(timeout); connected = false; channel = token(); frame = document.createElement("iframe"); frame.id = "speech-frame"; frame.title = "Hitokoto CPU 朗读播放器"; frame.allow = "autoplay"; frame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms"); frame.referrerPolicy = "no-referrer"; frame.addEventListener("load", () => { connected = false; send("ccrd-reader-init", { version: 1, modal: modal() }); }); frame.src = PLAYER; // Text/title/capabilities never go in the URL. host.replaceChildren(frame); status.textContent = "正在连接独立语音播放器,搜索和预览仍可使用…"; retry.hidden = true; timeout = setTimeout(() => { if (!connected) { status.textContent = "播放器连接失败或仍在加载。可重连;不会影响搜索和原文预览。"; retry.hidden = false; } }, 20000); } function flush() { if (!connected || !pending) return; const payload = pending; pending = null; send("ccrd-reader-import", payload); } function previewLoaded(value) { currentPreview = value; selected = null; } function previewClosed() { currentPreview = null; selected = null; } function selection() { const body = $("#preview-panel .preview-body"); const value = window.getSelection(); if (!currentPreview || !body || !value || value.rangeCount !== 1) { selected = null; return; } if (value.isCollapsed) { if (!document.activeElement?.matches("[data-speech='selection']")) selected = null; return; } const range = value.getRangeAt(0); if (!body.contains(range.startContainer) || !body.contains(range.endContainer)) { selected = null; return; } const prefix = range.cloneRange(); prefix.selectNodeContents(body); prefix.setEnd(range.startContainer, range.startOffset); const start = prefix.toString().length; const text = range.toString(); if (currentPreview.text.slice(start, start + text.length) === text) selected = { id: currentPreview.id, start, text }; } function read(mode) { selection(); if (!currentPreview) { notice("预览仍在加载,请等待正文出现后重试"); return; } let text = currentPreview.text, before = "", after = ""; if (mode === "selection") { if (!selected || selected.id !== currentPreview.id || !selected.text.trim()) { notice("请先在当前预览正文内选中要朗读的文字"); return; } text = selected.text; before = Array.from(currentPreview.text.slice(Math.max(0, selected.start - 128), selected.start)).slice(-32).join(""); after = Array.from(currentPreview.text.slice(selected.start + text.length, selected.start + text.length + 128)).slice(0, 32).join(""); } let count = 0; for (const _ of text) { if (++count > 20000) break; } if (count > 20000) { notice("单次朗读最多两万字,请选中较短的一部分;不会截掉正文"); return; } if (!text.trim()) { notice("当前预览没有可朗读正文"); return; } pending = { text, title: String(currentPreview.title || "当前预览").slice(0, 200), context_before: before, context_after: after }; show(); flush(); } document.addEventListener("selectionchange", selection); window.addEventListener("message", (event) => { const data = event.data; if (event.origin !== ORIGIN || event.source !== frame?.contentWindow || !data || data.channel !== channel) return; if (data.type === "ccrd-reader-ready" && data.version === 1) { clearTimeout(timeout); connected = true; retry.hidden = true; theme(); status.textContent = "播放器已连接。载入正文后,确认文字并点击合成才向语音 API 提交。"; flush(); } else if (data.type === "ccrd-reader-loaded") { status.textContent = `已载入 ${data.characters} 字。请在播放器确认文字、音色和音高后点击合成。`; } else if (data.type === "ccrd-reader-rejected") { status.textContent = "未替换正在朗读的文字;原朗读保留。"; } else if (data.type === "ccrd-reader-pending") { status.textContent = "播放器正在朗读,请在播放器中选择替换文字或保留原朗读。"; } else if (data.type === "ccrd-reader-stopped") { status.textContent = "朗读已停止,可收起或重新载入文字。"; } else if (data.type === "ccrd-reader-collapse") { hide(); } else if (data.type === "ccrd-reader-focus-out" && modal() && typeof data.reverse === "boolean") { const buttons = outerControls(); (data.reverse ? buttons[buttons.length - 1] : buttons[0])?.focus(); } }); launch.addEventListener("click", show); collapse.addEventListener("click", hide); stopButton.addEventListener("click", () => { if (connected) send("ccrd-reader-stop"); else { clearTimeout(timeout); frame?.remove(); frame = null; connected = false; pending = null; } hide(); }); retry.addEventListener("click", () => { if (!confirm("重新连接会停止此播放器中尚未完成的朗读,是否继续?")) return; frame?.remove(); frame = null; createFrame(); }); dialog.addEventListener("cancel", (event) => { event.preventDefault(); hide(); }); dialog.addEventListener("keydown", (event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); hide(); } if (event.key === "Tab" && modal() && connected) { const buttons = outerControls(); if (event.shiftKey && event.target === buttons[0]) { event.preventDefault(); send("ccrd-reader-focus", { last: true }); } else if (!event.shiftKey && event.target === buttons[buttons.length - 1]) { event.preventDefault(); send("ccrd-reader-focus", { last: false }); } } }); new MutationObserver(() => { theme(); if (dialog.open) { const targetModal = document.body.classList.contains("mobile"); if (modal() !== targetModal) { dialog.close(); targetModal ? dialog.showModal() : dialog.show(); modalActive = targetModal; } if (connected) send("ccrd-reader-layout", { modal: modal() }); } }).observe(document.body, { attributes: true, attributeFilter: ["class"] }); window.addEventListener("pagehide", () => { if (connected) send("ccrd-reader-stop"); }); return { read, previewLoaded, previewClosed, modal, owns };})();966 unmodified lines9679689699709719725 unmodified lines97897998098198298318 unmodified lines100210031004100510061007966 unmodified linesdef test_every_static_control_exists_is_cached_and_has_behavior(self):html = (Path(app.BASE_DIR) / "static" / "index.html").read_text(encoding="utf-8")source = (Path(app.BASE_DIR) / "static" / "app.js").read_text(encoding="utf-8")parser = InteractiveIdParser()parser.feed(html)expected = {5 unmodified lines"folder-toggle-all","source-filter-cancel", "folder-filter-cancel","filter-min-size", "filter-min-unit", "filter-max-size", "filter-max-unit", "random-book-btn",}self.assertEqual(parser.ids, expected)selector_exceptions = {"header-logo", "search-input"}18 unmodified lines"filter-min-size": "DOM.filterMinSize", "filter-min-unit": "DOM.filterMinUnit","filter-max-size": "DOM.filterMaxSize", "filter-max-unit": "DOM.filterMaxUnit","random-book-btn": "DOM.randomBookBtn",}for control_id, object_name in event_objects.items():self.assertIn(f'{object_name}.addEventListener(', source, control_id)966 unmodified lines9679689699709719729735 unmodified lines97998098198298398498518 unmodified lines1004100510061007100810091010966 unmodified linesdef test_every_static_control_exists_is_cached_and_has_behavior(self):html = (Path(app.BASE_DIR) / "static" / "index.html").read_text(encoding="utf-8")source = (Path(app.BASE_DIR) / "static" / "app.js").read_text(encoding="utf-8")source += (Path(app.BASE_DIR) / "static" / "tts-client.js").read_text(encoding="utf-8")parser = InteractiveIdParser()parser.feed(html)expected = {5 unmodified lines"folder-toggle-all","source-filter-cancel", "folder-filter-cancel","filter-min-size", "filter-min-unit", "filter-max-size", "filter-max-unit", "random-book-btn","speech-launch", "speech-collapse", "speech-stop", "speech-retry",}self.assertEqual(parser.ids, expected)selector_exceptions = {"header-logo", "search-input"}18 unmodified lines"filter-min-size": "DOM.filterMinSize", "filter-min-unit": "DOM.filterMinUnit","filter-max-size": "DOM.filterMaxSize", "filter-max-unit": "DOM.filterMaxUnit","random-book-btn": "DOM.randomBookBtn","speech-launch": "launch", "speech-collapse": "collapse", "speech-stop": "stopButton", "speech-retry": "retry",}for control_id, object_name in event_objects.items():self.assertIn(f'{object_name}.addEventListener(', source, control_id)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271"""Explicit offline CCRD/Hitokoto cross-origin bridge and reader acceptance.
Requires Playwright, HITOKOTO_SOURCE_DIR and an existing CCRD_TTS_SAMPLE MP3.Requests are routed fixtures; no production, corpus scan or model loading."""from __future__ import annotations
import jsonimport osfrom pathlib import Pathimport reimport unittestfrom urllib.parse import unquote, urlparse
try: from playwright.sync_api import sync_playwrightexcept ImportError: sync_playwright = None
ROOT = Path(__file__).resolve().parents[1]SEARCH = "https://vomebook-search.hf.space"SPEECH = "https://vomebook-hitokoto.hf.space"
@unittest.skipUnless(sync_playwright and os.environ.get("HITOKOTO_SOURCE_DIR") and os.environ.get("CCRD_TTS_SAMPLE"), "explicit: set HITOKOTO_SOURCE_DIR and CCRD_TTS_SAMPLE, install Playwright/Chromium")class SpeechReaderBrowserTests(unittest.TestCase): def test_preview_selection_player_isolation_and_cross_origin_contract(self): speech_root = Path(os.environ["HITOKOTO_SOURCE_DIR"]) mp3 = Path(os.environ["CCRD_TTS_SAMPLE"]).read_bytes() source_text = "前言。𠮷这是一篇长文,校长文章写得很好,我得亲自处理。\n版本1.2.3与日期2026-10-18。" * 4 sources = [{"slug": "CCRD", "name": "CCRD", "count": 2}] items = [{"doc_id": f"CCRD:{index}", "File": f"朗读测试{index}", "Source": "CCRD", "SourceName": "CCRD", "Folder": ["测试"], "Size": 1234, "snippet": "长文与手机测试", "snippet_complete": True} for index in range(2)] with sync_playwright() as playwright: browser = playwright.chromium.launch(headless=True, args=["--no-sandbox"]) try: for mobile in (False, True): with self.subTest(mobile=mobile): context = browser.new_context(viewport={"width": 390, "height": 844} if mobile else {"width": 1440, "height": 900}, reduced_motion="reduce") context.add_init_script("delete Navigator.prototype.serviceWorker") context.add_init_script("document.addEventListener('DOMContentLoaded',()=>{const audio=document.querySelector('#audio');if(audio)audio.muted=true;})") context.add_init_script("window.__bridge=[];addEventListener('message',event=>{if(event.data?.type?.startsWith('ccrd-reader-'))__bridge.push({origin:event.origin,data:event.data});})") jobs, tts_posts, connections, deleted = {}, [], [], [] blocked = [False] missing_client, old_html = [False], [False] errors = []
def reply(route, data, status=200, headers=None): route.fulfill(status=status, content_type="application/json", body=json.dumps(data), headers=headers or {})
def handler(route): request = route.request parsed = urlparse(request.url) path = unquote(parsed.path) if request.url.startswith(SEARCH): if path == "/": html = (ROOT / "static/index.html").read_text() if old_html[0]: html = re.sub(r'<button[^>]+id="speech-launch"[^>]*>.*?</button>', '', html) html = re.sub(r'<dialog id="speech-dialog".*?</dialog>', '', html, flags=re.S) html = html.replace('<script src="/static/tts-client.js"></script>', '') route.fulfill(content_type="text/html", body=html) elif path.startswith("/static/"): if path == "/static/tts-client.js" and missing_client[0]: route.abort("connectionfailed"); return file = ROOT / path.lstrip("/") if file.is_file(): route.fulfill(path=file) else: reply(route, {}, 404) elif path == "/api/ping": route.fulfill(status=204) elif path == "/api/sources": reply(route, sources) elif path.startswith("/data/sidebar/"): reply(route, {"sources": sources}) elif path.startswith("/data/initial/") or path.startswith("/api/search"): reply(route, {"results": items, "total": 2, "page": 1, "page_size": 100, "q": "", "sort": "relevance", "exact": True, "fulltext": True, "search_paths": True, "source": None}) elif path.startswith("/api/preview/"): id = path.rsplit("/", 1)[-1] reply(route, {"doc_id": id, "title": "朗读测试 <b>原文</b>", "source": "CCRD", "path": "测试/原文.txt", "text": source_text if id == "CCRD:0" else "长"*20001 if id == "CCRD:long" else "另一个预览,不应该打断原朗读。"}) elif path == "/manifest.json": reply(route, {"name": "Test"}) else: reply(route, {}, 404) elif request.url.startswith(SPEECH): connections.append(request.url) if blocked[0] and path == "/tts/": route.abort("connectionfailed"); return if path == "/tts/": route.fulfill(content_type="text/html", body=(speech_root / "static/tts.html").read_bytes(), headers={"Content-Security-Policy": "frame-ancestors " + SEARCH}) elif path in {"/tts/app.js", "/tts/reader.js", "/tts/embed.js", "/tts/style.css"}: name = {"app.js": "tts.js", "style.css": "tts.css"}.get(path.rsplit("/", 1)[-1], path.rsplit("/", 1)[-1]) route.fulfill(path=speech_root / "static" / name) elif path == "/tts/health": reply(route, {"ready": True, "engine": {"threads": 2}, "queued": 0}) elif path == "/tts/voices": reply(route, {"voices": [{"id": id, "name": id} for id in ("zf_001", "zf_017", "zm_010", "zm_029")]}) elif path == "/tts/jobs" and request.method == "POST": body = request.post_data_json tts_posts.append(body) id = f"{len(jobs)+1:032d}" length = len(body["text"].encode("utf-16-le")) // 2 jobs[id] = {"id": id, "state": "ready", "cache_hit": False, "result": { "audio_url": f"/tts/audio/{id}.mp3", "audio_seconds": 10.6, "synthesis_seconds": .2, "pitch_semitones": body["pitch_semitones"]}, "source_segments": [{"start": 0, "end": length}], "progress": {"complete": True, "total_parts": 1, "parts": [{"index": 0, "start": 0, "end": length, "audio_url": f"/tts/audio/{id}/parts/0.mp3", "first_audio_seconds": .2, "audio_seconds": 10.6, "pitch_semitones": body["pitch_semitones"]}]}} reply(route, jobs[id], 202) elif path.startswith("/tts/jobs/"): id = path.rsplit("/", 1)[-1] if request.method == "DELETE": deleted.append(id) reply(route, jobs.get(id, {"state": "error"})) elif path.startswith("/tts/audio/"): route.fulfill(content_type="audio/mpeg", body=mp3) else: reply(route, {}, 404) else: route.fulfill(status=204)
context.route("**/*", handler) page = context.new_page() page.on("pageerror", lambda error: errors.append(str(error))) page.set_default_timeout(30000) try: page.goto(SEARCH + "/", wait_until="domcontentloaded") page.locator(".result-item").first.wait_for() self.assertFalse(connections, "Opening search must not load the speech service") self.assertFalse(tts_posts) page.locator("[data-action=preview]").first.click() page.locator(".preview-body").wait_for() self.assertEqual(page.locator(".preview-body").text_content(), source_text) # No selection is an explicit error, not a fallback to full text. page.locator("[data-speech=selection]").click() self.assertFalse(connections) selected_text = "这是一篇长文,校长文章写得很好,我��亲自处理。" page.evaluate("""text=>{ const body=document.querySelector('.preview-body');const start=body.textContent.indexOf(text); const walker=document.createTreeWalker(body,NodeFilter.SHOW_TEXT);let node;let offset=0; const range=document.createRange();let begun=false; while(node=walker.nextNode()){ if(!begun&&start<offset+node.length){range.setStart(node,start-offset);begun=true;} if(begun&&start+text.length<=offset+node.length){range.setEnd(node,start+text.length-offset);break;}offset+=node.length; } getSelection().removeAllRanges();getSelection().addRange(range); }""", selected_text) page.locator("[data-speech=selection]").click() page.wait_for_function("document.querySelector('#speech-status').textContent.includes('已载入')") frame = page.frame_locator("#speech-frame") self.assertEqual(frame.locator("#speech-text").input_value(), selected_text) self.assertFalse(tts_posts, "Import alone must not submit speech") self.assertFalse(frame.locator("#storage-controls").is_visible()) self.assertFalse(frame.locator("#remember").is_checked()) self.assertTrue(page.evaluate("CCRDSpeech.modal()") if mobile else not page.evaluate("CCRDSpeech.modal()")) self.assertTrue(page.evaluate("document.documentElement.scrollWidth<=innerWidth+1")) self.assertEqual(frame.locator("main b").count(), 0) if mobile: frame.locator("#playback-rate").focus() page.keyboard.press("Tab") page.wait_for_function("document.activeElement.id==='speech-collapse'") # Same-origin spoof from the wrong Window/channel is ignored. page.evaluate("""()=>window.postMessage({type:'ccrd-reader-loaded',channel:'0'.repeat(48),characters:99999},location.origin)""") self.assertNotIn("99999", page.locator("#speech-status").text_content()) bridge_channel = page.evaluate("__bridge.find(event=>event.data.type==='ccrd-reader-ready').data.channel") # The source origin alone is insufficient: a sibling # Window with that origin and nonce is not the parent. page.evaluate("""({channel,target})=>{ const sibling=document.createElement('iframe');sibling.hidden=true;document.body.append(sibling); const data={type:'ccrd-reader-import',channel,text:'不应该载入',title:'伪造',context_before:'',context_after:''}; sibling.contentWindow.eval(`parent.document.querySelector('#speech-frame').contentWindow.postMessage(${JSON.stringify(data)},${JSON.stringify(target)})`); setTimeout(()=>sibling.remove(),100); }""", {"channel": bridge_channel, "target": SPEECH}) page.wait_for_timeout(200) self.assertEqual(frame.locator("#speech-text").input_value(), selected_text) frame.locator("#pitch").evaluate("n=>{n.value=-2;n.dispatchEvent(new Event('input',{bubbles:true}));}") frame.locator("#playback-rate").evaluate("n=>{n.value=.5;n.dispatchEvent(new Event('input',{bubbles:true}));}") frame.locator("#generate").click() page.wait_for_function("document.querySelector('#speech-frame')!==null") speech_page = next(f for f in page.frames if f.url.startswith(SPEECH)) speech_page.wait_for_function("session && document.querySelector('#audio').currentTime>.1") self.assertEqual(tts_posts[0]["text"], selected_text) self.assertEqual(tts_posts[0]["pitch_semitones"], -2) self.assertTrue(tts_posts[0]["context_before"].endswith("前言。𠮷")) self.assertNotIn("原文.txt", json.dumps(tts_posts)) # Hiding/reopening keeps the exact iframe and audio session alive. original_src = page.locator("#speech-frame").get_attribute("src") page.locator("#speech-collapse").click() self.assertFalse(page.locator("#speech-dialog").is_visible()) speech_page.wait_for_function("document.querySelector('#audio').currentTime>.3", polling=100) self.assertFalse(deleted) if mobile: page.locator("[data-action=close-preview]").click() page.wait_for_function("!STATE.previewDocId") page.locator("#search-input").fill("手机") page.wait_for_function("STATE.query==='手机' && !STATE.isLoading") page.locator("#sort-select").select_option("name") page.locator("[data-action=preview]").last.click() page.wait_for_function("STATE.previewDocId==='CCRD:1'") self.assertTrue(speech_page.evaluate("session!==null")) self.assertFalse(deleted) page.locator("[data-speech=controls]").click() self.assertEqual(page.locator("#speech-frame").get_attribute("src"), original_src) self.assertEqual(frame.locator("#speech-text").input_value(), selected_text) page.locator("#speech-collapse").click() page.locator("[data-speech=preview]").click() frame.locator("#embed-keep").wait_for(state="visible") self.assertEqual(frame.locator("#speech-text").input_value(), selected_text) self.assertEqual(len(tts_posts), 1) frame.locator("#embed-keep").click() self.assertTrue(speech_page.evaluate("session!==null")) page.locator("#speech-collapse").click() page.locator("[data-speech=preview]").click() frame.locator("#embed-replace").click() self.assertEqual(frame.locator("#speech-text").input_value(), "另一个预览,不应该打断原朗读。") self.assertEqual(len(tts_posts), 1, "Replacement requires a separate explicit synthesis click") frame.locator("#generate").click() speech_page.wait_for_function("session && document.querySelector('#audio').currentTime>.1") self.assertEqual(tts_posts[-1]["text"], "另一个预览,不应该打断原朗读。") frame.locator("#speech-text").press("Escape") page.wait_for_function("!document.querySelector('#speech-dialog').open") page.locator("[data-speech=controls]").click() page.locator("#speech-stop").click() speech_page.wait_for_function("session===null", polling=100) self.assertTrue(deleted) count = len(tts_posts) page.evaluate("openPreview('CCRD:long','')") page.wait_for_function("document.querySelector('.preview-body').textContent.length===20001") page.locator("[data-speech=preview]").click() self.assertEqual(len(tts_posts), count) self.assertIn("两万字", page.locator("#speech-status").text_content()) # Offline player failure leaves real search/preview # code working; no auto retry loop or speech POST. blocked[0] = True page.goto(SEARCH + "/", wait_until="domcontentloaded") page.locator(".result-item").first.wait_for() page.wait_for_function("!STATE.isLoading") page.evaluate("const native=setTimeout;window.setTimeout=(fn,ms,...args)=>native(fn,ms===20000?100:ms,...args)") if not page.locator(".preview-body").count(): page.locator("[data-action=preview]").first.click() page.locator("[data-speech=preview]").click() page.locator("#speech-retry").wait_for(state="visible") page.locator("#speech-collapse").click() if mobile: page.locator("[data-action=close-preview]").click() page.wait_for_function("!STATE.previewDocId") page.locator("#search-input").fill("朗读故障后仍能搜索") page.wait_for_function("STATE.query==='朗读故障后仍能搜索' && !STATE.isLoading") self.assertEqual(page.locator(".result-item").count(), 2) self.assertEqual(len(tts_posts), count) # New HTML with a missing bridge, and an old cached # shell with new app.js, must both retain search. for mode in ('missing-client', 'old-html'): missing_client[0] = mode == 'missing-client' old_html[0] = mode == 'old-html' page.goto(SEARCH + "/", wait_until="domcontentloaded") page.locator(".result-item").first.wait_for() page.locator("#search-input").fill("缓存兼容") page.wait_for_function("STATE.query==='缓存兼容' && !STATE.isLoading") self.assertEqual(page.locator(".result-item").count(), 2) self.assertEqual(len(tts_posts), count) self.assertFalse(errors, errors) finally: context.close() finally: browser.close()README.md+3-1
docs/TTS_PILOT.mdAdded+22
static/app.js+14-1
static/index.html+13
static/style.css+10
static/tts-client.jsAdded+191
tests/test_search.py+3
tests/test_tts_browser.pyAdded+271