vomebook commited on
Commit ·
a4ddaa3
1
Parent(s): 76bdfe9
Fix PDF page stream OCR loading and search
Browse filesFiles changed (3)
117 unmodified lines118119120121122123124117 unmodified linespdf: { toc: true, search: true, zoom: true, bookmarks: true, pagination: true, media: false },"pdf-pages": {toc: true,search: false,zoom: true,bookmarks: true,pagination: true,117 unmodified lines118119120121122123124117 unmodified linespdf: { toc: true, search: true, zoom: true, bookmarks: true, pagination: true, media: false },"pdf-pages": {toc: true,search: true,zoom: true,bookmarks: true,pagination: true,
859 unmodified lines8608618628638648658668678688698704 unmodified lines8758768778788798801483 unmodified lines2364236523662367236823692370123 unmodified lines2494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524178 unmodified lines270327042705270627072708270924 unmodified lines273427352736273727382739243 unmodified lines2983298429852986298729882989299029912073 unmodified lines5065506650675068506950705071964 unmodified lines6036603760386039604060416042859 unmodified linesif (!documentState.pageCount || !isReaderGenerationCurrent("navigation", generation))return false;const page = VoiceOfMLReader.clampNumber(value, 1, documentState.pageCount, 1);await pdfShellsReady;if (!isReaderGenerationCurrent("navigation", generation)) return false;const shell = content.querySelector(`.reader-page[data-page="${page}"], .reader-docx-page[data-page="${page}"]`);if (!shell) return false;const imagePage = capability.mode === "pdf-pages";if (imagePage && shell.dataset.renderState !== "rendered")4 unmodified lines: null;if (!isReaderGenerationCurrent("navigation", generation)) return false;viewport.scrollTop = shell.offsetTop;pageNavigationLockUntil = performance.now() + 500;if (pendingPdf) cancelSpeculativePdfRenders(shell);const pendingImage = imagePage ? renderPdfInBackground(shell, false, true) : null;1483 unmodified lineselse if (!navigator.connection?.saveData) {pdfFirstPagePreload = new Image();pdfFirstPagePreload.decoding = "async";pdfFirstPagePreload.fetchPriority = "low";pdfFirstPagePreload.src = pageUrl.href;}} catch (_) {}123 unmodified linescatch (error) { pdfOcrManifestPromise = null; throw error; }}async function renderPdfOcrText(shell, entry) {if (shell.dataset.textReady === "1" || !entry?.o || !pdfPageManifest) return;if (shell._ocrPromise) return shell._ocrPromise;const layer = shell.querySelector(".reader-pdf-text");if (!layer) return;const epoch = shell._textEpoch || 0;const task = (async () => {await acquirePdfTextSlot(isPdfPageVisible(shell));try {if (epoch !== (shell._textEpoch || 0)) return;const payload = await readPdfOcrJson(pdfOcrSource().assetUrl(entry.o),VoiceOfMLReaderSecurity.LIMITS.chapterBytes, entry.os, entry.ob);assertReaderActive();if (epoch !== (shell._textEpoch || 0)) return;VoiceOfMLReaderSecurity.validatePdfOcrPage(payload, Number(shell.dataset.page));populateOcrTextLayer(layer, payload.blocks);shell._bookmarkTextItems = payload.blocks.map((block) => ({ text: block.t, y: block.b?.[1] || 0 }));shell.dataset.textReady = "1";highlightPdfText(shell);} catch (error) {if (!readerAbortController.signal.aborted)console.warn(`PDF page ${shell.dataset.page} OCR text failed`, error);} finally {releasePdfTextSlot();}})().finally(() => { if (shell._ocrPromise === task) delete shell._ocrPromise; });shell._ocrPromise = task;return task;178 unmodified linesconst totalPages = manifest.page_count;if (!source) throw new Error("PDF_MANIFEST_INVALID");pdfPageManifest = { ...source, pageCount: totalPages };if (ocrManifestUrl) loadPdfOcrManifest().catch(() => {});updateDocumentState({ pageCount: totalPages });pageInput.max = String(totalPages);document.querySelector("#page-total").textContent = `/ ${totalPages}`;24 unmodified linesif (entry.isIntersecting) {promotePdfRenderWaiter(entry.target);renderPdfInBackground(entry.target, false, true);}}},243 unmodified lines});assertReaderActive();shell.style.aspectRatio = `${image.naturalWidth || 1} / ${image.naturalHeight || 1}`;const loadText = pdfOcrManifestPromise? pdfOcrManifestPromise.then(() => renderPdfOcrText(shell, pdfPageEntry(Number(shell.dataset.page)))): renderPdfOcrText(shell, pdfPageEntry(Number(shell.dataset.page)));loadText.catch(() => {});image.classList.add("ready");shell.dataset.renderState = "rendered";2073 unmodified linesconst fullSearchButton = document.querySelector("#full-search-toggle");fullSearchButton.textContent = "全文搜索";fullSearchButton.setAttribute("aria-label", "全文搜索");fullSearchButton.hidden = !capability.features.search;const fullSearchInput = fullSearchView.querySelector("#full-search-input"),fullSearchStatus = fullSearchView.querySelector("#full-search-status"),fullSearchResultsNode = fullSearchView.querySelector("#full-search-results"),964 unmodified linesdocument.querySelector(".page-controls").hidden = !capability.features.pagination;document.querySelector(".zoom-controls").hidden = !capability.features.zoom;mediaTab.hidden = !capability.features.media;fullSearchButton.hidden = !capability.features.search;bookmarkRibbon.hidden = !capability.features.bookmarks;readingProgressSummary.querySelector(".reader-progress-bookmark").hidden =!capability.features.bookmarks;859 unmodified lines8608618628638648658668678688698708718728734 unmodified lines8788798808818828838841483 unmodified lines2368236923702371237223732374123 unmodified lines2498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534178 unmodified lines27132714271527162717271824 unmodified lines2743274427452746274727482749243 unmodified lines29932994299529962997299829992073 unmodified lines5073507450755076507750785079964 unmodified lines6044604560466047604860496050859 unmodified linesif (!documentState.pageCount || !isReaderGenerationCurrent("navigation", generation))return false;const page = VoiceOfMLReader.clampNumber(value, 1, documentState.pageCount, 1);let shell = content.querySelector(`.reader-page[data-page="${page}"], .reader-docx-page[data-page="${page}"]`);if (!shell && capability.mode === "pdf-pages") {await pdfShellsReady;shell = content.querySelector(`.reader-page[data-page="${page}"]`);}if (!isReaderGenerationCurrent("navigation", generation)) return false;if (!shell) return false;const imagePage = capability.mode === "pdf-pages";if (imagePage && shell.dataset.renderState !== "rendered")4 unmodified lines: null;if (!isReaderGenerationCurrent("navigation", generation)) return false;viewport.scrollTop = shell.offsetTop;if (imagePage && shell.dataset.renderState === "rendered") renderPdfOcrText(shell);pageNavigationLockUntil = performance.now() + 500;if (pendingPdf) cancelSpeculativePdfRenders(shell);const pendingImage = imagePage ? renderPdfInBackground(shell, false, true) : null;1483 unmodified lineselse if (!navigator.connection?.saveData) {pdfFirstPagePreload = new Image();pdfFirstPagePreload.decoding = "async";pdfFirstPagePreload.fetchPriority = "high";pdfFirstPagePreload.src = pageUrl.href;}} catch (_) {}123 unmodified linescatch (error) { pdfOcrManifestPromise = null; throw error; }}async function renderPdfOcrText(shell) {if (shell.dataset.textReady === "1" || !pdfPageManifest || !ocrManifestUrl) return;if (shell._ocrPromise) return shell._ocrPromise;const layer = shell.querySelector(".reader-pdf-text");if (!layer) return;const epoch = shell._textEpoch || 0;const task = (async () => {try {const manifest = await loadPdfOcrManifest();if (epoch !== (shell._textEpoch || 0)) return;const page = Number(shell.dataset.page);const entry = manifest.pages[page - 1];await acquirePdfTextSlot(isPdfPageVisible(shell));try {if (epoch !== (shell._textEpoch || 0)) return;const payload = await readPdfOcrJson(pdfOcrSource().assetUrl(entry.o),VoiceOfMLReaderSecurity.LIMITS.chapterBytes, entry.os, entry.ob);assertReaderActive();if (epoch !== (shell._textEpoch || 0)) return;VoiceOfMLReaderSecurity.validatePdfOcrPage(payload, page);populateOcrTextLayer(layer, payload.blocks);shell._bookmarkTextItems = payload.blocks.map((block) => ({ text: block.t, y: block.b?.[1] || 0 }));shell.dataset.textReady = "1";highlightPdfText(shell);} finally {releasePdfTextSlot();}} catch (error) {if (!readerAbortController.signal.aborted)console.warn(`PDF page ${shell.dataset.page} OCR text failed`, error);}})().finally(() => { if (shell._ocrPromise === task) delete shell._ocrPromise; });shell._ocrPromise = task;return task;178 unmodified linesconst totalPages = manifest.page_count;if (!source) throw new Error("PDF_MANIFEST_INVALID");pdfPageManifest = { ...source, pageCount: totalPages };updateDocumentState({ pageCount: totalPages });pageInput.max = String(totalPages);document.querySelector("#page-total").textContent = `/ ${totalPages}`;24 unmodified linesif (entry.isIntersecting) {promotePdfRenderWaiter(entry.target);renderPdfInBackground(entry.target, false, true);if (entry.target.dataset.renderState === "rendered") renderPdfOcrText(entry.target);}}},243 unmodified lines});assertReaderActive();shell.style.aspectRatio = `${image.naturalWidth || 1} / ${image.naturalHeight || 1}`;const loadText = renderPdfOcrText(shell);loadText.catch(() => {});image.classList.add("ready");shell.dataset.renderState = "rendered";2073 unmodified linesconst fullSearchButton = document.querySelector("#full-search-toggle");fullSearchButton.textContent = "全文搜索";fullSearchButton.setAttribute("aria-label", "全文搜索");fullSearchButton.hidden = !capability.features.search || (capability.mode === "pdf-pages" && !ocrManifestUrl);const fullSearchInput = fullSearchView.querySelector("#full-search-input"),fullSearchStatus = fullSearchView.querySelector("#full-search-status"),fullSearchResultsNode = fullSearchView.querySelector("#full-search-results"),964 unmodified linesdocument.querySelector(".page-controls").hidden = !capability.features.pagination;document.querySelector(".zoom-controls").hidden = !capability.features.zoom;mediaTab.hidden = !capability.features.media;fullSearchButton.hidden = !capability.features.search || (capability.mode === "pdf-pages" && !ocrManifestUrl);bookmarkRibbon.hidden = !capability.features.bookmarks;readingProgressSummary.querySelector(".reader-progress-bookmark").hidden =!capability.features.bookmarks;
121 unmodified lines122123124125126127121 unmodified linesimage.wait_for()self.assertEqual(image.get_attribute("src"), source + "/pages/page-000003.webp")self.assertTrue(image.evaluate("image => image.complete && image.naturalWidth > 0"))def test_download_during_prepare_does_not_interrupt_reader(self):pending_content = []121 unmodified lines122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242121 unmodified linesimage.wait_for()self.assertEqual(image.get_attribute("src"), source + "/pages/page-000003.webp")self.assertTrue(image.evaluate("image => image.complete && image.naturalWidth > 0"))self.assertTrue(self.page.locator("#full-search-toggle").evaluate("node => node.hidden"))def test_pdf_pages_recovers_ocr_text_and_searches_valid_index(self):root = "objects/aa/" + "a" * 64 + "/" + "b" * 16source = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/" + rootocr_path = root + "/ocr-manifest.json"book_path = root + "/ocr/book-text.json.gz"book = gzip.compress(json.dumps({"version": 2, "kind": "pdf-book-text", "complete": True,"offset_unit": "unicode-codepoint", "source_sha256": "a" * 64, "page_count": 2,"pages": [{"page": page, "text": "indexed text" if page == 1 else "","layout": {"offset_unit": "unicode-codepoint"}, "text_spans": []}for page in (1, 2)]}).encode())manifest = {"version": 1, "kind": "pdf-ocr", "complete": True,"source_sha256": "a" * 64, "profile": "test-layout-v1-retry", "page_count": 2,"pages": [{"p": page, "o": root + f"/ocr/page-{page:06d}.json.gz"} for page in (1, 2)],"book_text": {"path": book_path, "bytes": len(book), "sha256": hashlib.sha256(book).hexdigest()}}attempts, manifest_attempts, image_requests = [], [], []self.serve(json.dumps({"version": 2, "kind": "pdf-pages", "page_count": 2}), "application/json")def image(route):image_requests.append(route.request.url)route.fulfill(content_type="image/webp", body=support.IMAGE_FIXTURES["webp"][1])def resource(route):path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]if path == ocr_path:manifest_attempts.append(path)if len(manifest_attempts) == 1:route.fulfill(status=503, body="temporarily unavailable")returnroute.fulfill(json=manifest)returnif path == book_path:route.fulfill(content_type="application/gzip", body=book)returnif path.endswith("page-000001.json.gz"):attempts.append(path)if len(attempts) == 1:route.fulfill(status=503, body="temporarily unavailable")returnnumber = int(path.rsplit("page-", 1)[1][:6])payload = {"version": 1, "kind": "pdf-ocr-page", "page": number,"width": 100, "height": 140,"blocks": [{"t": "Recovered text", "b": [0.1, 0.2, 0.8, 0.3]}]}route.fulfill(content_type="application/gzip", body=gzip.compress(json.dumps(payload).encode()))self.page.route(source + "/pages/**", image)self.page.route("**/api/reader-bucket-resource**", resource)self.open(self.reader_url("pdf-pages", url=source + "/page-manifest.json",ocr_manifest=self.origin + "/api/reader-bucket-resource?path=" + ocr_path))self.assertFalse(self.page.locator("#full-search-toggle").evaluate("node => node.hidden"))self.page.wait_for_function("() => document.querySelector('.reader-page[data-page=\"1\"]')?.dataset.renderState === 'rendered' && !document.querySelector('.reader-page[data-page=\"1\"]')._ocrPromise")self.assertEqual(len(manifest_attempts), 2)self.assertEqual(len(attempts), 1)first_image_requests = image_requests.count(source + "/pages/page-000001.webp")self.page.locator("#page-number").fill("2")self.page.locator("#page-number").dispatch_event("change")self.page.wait_for_function("() => document.querySelector('#page-number').value === '2'")self.page.locator("#page-number").fill("1")self.page.locator("#page-number").dispatch_event("change")self.page.locator('.reader-page[data-page="1"][data-text-ready="1"]').wait_for()self.assertEqual(len(attempts), 2)self.assertEqual(image_requests.count(source + "/pages/page-000001.webp"), first_image_requests)self.page.locator("#history").click()self.page.locator("#full-search-toggle").click()self.page.locator("#full-search-input").fill("indexed")self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")self.assertEqual(self.page.locator(".full-search-result").count(), 1)def test_pdf_pages_ocr_uses_versioned_manifest_paths_after_image(self):root = "objects/aa/" + "a" * 64image_root = root + "/" + "1" * 16ocr_root = root + "/" + "2" * 16text_root = root + "/" + "3" * 16source = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/" + image_rootocr_path = ocr_root + "/ocr-manifest.json"payloads = [gzip.compress(json.dumps({"version": 1, "kind": "pdf-ocr-page", "page": number,"width": 100, "height": 140,"blocks": [{"t": f"Page {number} text", "b": [0.2, 0.2, 0.7, 0.3]}]}).encode())for number in (1, 2)]manifest = {"version": 1, "kind": "pdf-ocr", "complete": True,"source_sha256": "a" * 64, "profile": "test-layout-v1-1234567890abcdef","page_count": 2, "pages": [{"p": number, "o": text_root + f"/ocr/page-{number:06d}.json.gz","os": hashlib.sha256(payloads[number - 1]).hexdigest(), "ob": len(payloads[number - 1])}for number in (1, 2)],"book_text": {"path": ocr_root + "/ocr/book-text.json.gz", "bytes": 1,"sha256": "a" * 64},"page_manifest": {"path": image_root + "/page-manifest.json"}}held, requested = [], []self.serve(json.dumps({"version": 2, "kind": "pdf-pages", "page_count": 2}), "application/json")def serve_ocr(route):path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]requested.append(path)if path == ocr_path:held.append(route)elif path in [entry["o"] for entry in manifest["pages"]]:number = int(path.rsplit("page-", 1)[1][:6])route.fulfill(content_type="application/gzip", body=payloads[number - 1])else:route.fulfill(status=404)self.page.route("**/api/reader-bucket-resource**", serve_ocr)self.page.route(source + "/pages/**", lambda route: route.fulfill(content_type="image/webp", body=support.IMAGE_FIXTURES["webp"][1]))self.open(self.reader_url("pdf-pages", url=source + "/page-manifest.json",ocr_manifest=self.origin + "/api/reader-bucket-resource?path=" + ocr_path))self.page.locator('.reader-page[data-page="1"] img.ready').wait_for()self.assertEqual(len(held), 1)self.assertNotEqual(self.page.locator('.reader-page[data-page="1"]').get_attribute("data-text-ready"), "1")held.pop().fulfill(json=manifest)self.page.locator('.reader-page[data-page="1"][data-text-ready="1"]').wait_for()self.assertIn("Page 1 text", self.page.locator('.reader-page[data-page="1"] .reader-pdf-text').text_content())self.page.locator("#page-number").fill("2")self.page.locator("#page-number").dispatch_event("change")self.page.locator('.reader-page[data-page="2"][data-text-ready="1"]').wait_for()self.assertIn("Page 2 text", self.page.locator('.reader-page[data-page="2"] .reader-pdf-text').text_content())self.assertEqual(requested, [ocr_path, text_root + "/ocr/page-000001.json.gz",text_root + "/ocr/page-000002.json.gz"])def test_download_during_prepare_does_not_interrupt_reader(self):pending_content = []
static/reader-contract.js+1-1
static/reader.js+38-30
tests/test_reader_refactor.py+115