vomebook commited on
Commit ·
9cb654f
1
Parent(s): 681df39
feat: search PDFs from strict v2 text indexes
Browse filesFiles changed (8)
- app.py+33-8
- static/reader-book-text.jsAdded+100
- static/reader-pdf-text.js+104-34
- static/reader-resources.js+1
- static/reader-security.js+15-5
- static/reader.css+30-5
- static/reader.js+147-53
- tests/test_fastapi_endpoints.py+5-4
1701 unmodified lines170217031704170517061707170817091 unmodified line17111712171317141715171617177 unmodified lines172517261727172817291730173117321733173417351736237 unmodified lines19741975197619771978197919802 unmodified lines19831984198519861987198819891990199119921993199419951996199719981701 unmodified linesreturn await asyncio.shield(task)def parse_reader_ocr_book(raw: bytes) -> tuple[list[tuple[int, str, str]], int]:"""Decode and validate the compact per-page OCR text cache off the event loop."""with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:decoded = stream.read(READER_RESOURCE_MAX_BYTES + 1)if len(decoded) > READER_RESOURCE_MAX_BYTES:1 unmodified linepayload = json.loads(decoded)pages = payload.get("pages") if isinstance(payload, dict) else Noneif (not isinstance(pages, list) or len(pages) > 200000or payload.get("version") != 1 or payload.get("kind") != "pdf-ocr-book-text"):raise ValueError("invalid PDF OCR text index")output = []total_bytes = 07 unmodified linestotal_bytes += len(text.encode("utf-8"))if total_bytes > READER_RESOURCE_MAX_BYTES:raise ValueError("PDF OCR text index is too large")output.append((item["page"], text, text.casefold()))previous = item["page"]return output, total_bytesasync def get_reader_ocr_book(path: str) -> list[tuple[int, str, str]]:state = app.stateif not hasattr(state, "reader_ocr_cache"):state.reader_ocr_cache = OrderedDict()237 unmodified linespages = await get_reader_ocr_book(book_path)needle = q.casefold()matches = []for page_number, text, folded in pages:start = 0while True:found = folded.find(needle, start)2 unmodified linesend = found + len(q)snippet_start = max(0, found - 72)snippet_end = min(len(text), end + 88)matches.append({"page": page_number, "start": found, "length": len(q),"snippet": text[snippet_start:snippet_end],"snippet_start": found - snippet_start,})start = endtotal = len(matches)offset = (page - 1) * page_sizereturn JSONResponse({"version": 1, "page": page, "page_size": page_size, "total": total,"results": matches[offset:offset + page_size],}, headers={"Cache-Control": "no-store"})except (ValueError, TypeError, KeyError, EOFError, gzip.BadGzipFile, zlib.error):1701 unmodified lines170217031704170517061707170817091 unmodified line171117121713171417151716171717181719172017217 unmodified lines1729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756237 unmodified lines199419951996199719981999200020012 unmodified lines200420052006200720082009201020112012201320142015201620172018201920202021202220231701 unmodified linesreturn await asyncio.shield(task)def parse_reader_ocr_book(raw: bytes) -> tuple[list[dict], int]:"""Decode the single v2 book text index and its layout mappings."""with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:decoded = stream.read(READER_RESOURCE_MAX_BYTES + 1)if len(decoded) > READER_RESOURCE_MAX_BYTES:1 unmodified linepayload = json.loads(decoded)pages = payload.get("pages") if isinstance(payload, dict) else Noneif (not isinstance(pages, list) or len(pages) > 200000or payload.get("version") != 2 or payload.get("kind") != "pdf-book-text"or payload.get("complete") is not Trueor payload.get("offset_unit") != "unicode-codepoint"or payload.get("page_count") != len(pages)or not re.fullmatch(r"[0-9a-f]{64}", str(payload.get("source_sha256", "")))):raise ValueError("invalid PDF OCR text index")output = []total_bytes = 07 unmodified linestotal_bytes += len(text.encode("utf-8"))if total_bytes > READER_RESOURCE_MAX_BYTES:raise ValueError("PDF OCR text index is too large")layout = item.get("layout")spans = item.get("text_spans")if (not isinstance(layout, dict) or layout.get("offset_unit") != "unicode-codepoint"or not isinstance(spans, list)):raise ValueError("invalid PDF text layout mapping")previous_span_end = 0for span in spans:box = span.get("box") if isinstance(span, dict) else Noneif (not isinstance(span, dict) or not isinstance(span.get("start"), int)or not isinstance(span.get("end"), int) or span["start"] < previous_span_endor span["end"] <= span["start"] or span["end"] > len(text)or not isinstance(box, list) or len(box) != 4or any(not isinstance(value, (int, float)) or value < 0 or value > 1 for value in box)):raise ValueError("invalid PDF text span")previous_span_end = span["end"]output.append({"page": item["page"], "text": text, "folded": text.casefold(),"layout": layout, "spans": spans})previous = item["page"]return output, total_bytesasync def get_reader_ocr_book(path: str) -> list[dict]:state = app.stateif not hasattr(state, "reader_ocr_cache"):state.reader_ocr_cache = OrderedDict()237 unmodified linespages = await get_reader_ocr_book(book_path)needle = q.casefold()matches = []for item in pages:page_number, text, folded = item["page"], item["text"], item["folded"]start = 0while True:found = folded.find(needle, start)2 unmodified linesend = found + len(q)snippet_start = max(0, found - 72)snippet_end = min(len(text), end + 88)begin = foundend = found + len(q)boxes = [span["box"] for span in item["spans"]if span["end"] > begin and span["start"] < end]matches.append({"page": page_number, "start": found, "length": len(q),"snippet": text[snippet_start:snippet_end],"snippet_start": found - snippet_start, "boxes": boxes,})start = endtotal = len(matches)offset = (page - 1) * page_sizereturn JSONResponse({"version": 2, "kind": "pdf-book-text-search", "page": page, "page_size": page_size, "total": total,"results": matches[offset:offset + page_size],}, headers={"Cache-Control": "no-store"})except (ValueError, TypeError, KeyError, EOFError, gzip.BadGzipFile, zlib.error):
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100// One complete, validated text file per PDF. Offsets in generated mappings are// Unicode code points; JavaScript RegExp returns UTF-16 offsets.export function validateBookText(book, pageCount, sourceSha = "") { if (!book || book.version !== 2 || book.kind !== "pdf-book-text" || book.complete !== true || book.offset_unit !== "unicode-codepoint" || book.page_count !== pageCount || (sourceSha && book.source_sha256 !== sourceSha) || !Array.isArray(book.pages) || book.pages.length !== pageCount) throw new Error("PDF_TEXT_INDEX_INCOMPLETE"); for (const [index, page] of book.pages.entries()) { if (page.page !== index + 1 || typeof page.text !== "string" || !page.layout || page.layout.offset_unit !== "unicode-codepoint" || !Array.isArray(page.text_spans)) throw new Error("PDF_TEXT_INDEX_INVALID"); const length = Array.from(page.text).length; let previousEnd = 0; for (const span of page.text_spans) { if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < previousEnd || span.end <= span.start || span.end > length || !Array.isArray(span.box) || span.box.length !== 4 || span.box.some(v => !Number.isFinite(v) || v < 0 || v > 1) || span.box[0] > span.box[2] || span.box[1] > span.box[3]) throw new Error("PDF_TEXT_MAPPING_INVALID"); previousEnd = span.end; } } return book;}
function pattern(query) { return new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "giu");}
export function hitBoxes(page, start, length) { const begin = Array.from(page.text.slice(0, start)).length; const end = begin + Array.from(page.text.slice(start, start + length)).length; return page.text_spans.filter(s => s.end > begin && s.start < end) .map(s => ({ box: s.box, block: s.block, precision: s.precision || "block" }));}
export async function searchBookText(book, query, { current = () => true, yieldTask = () => new Promise(r => setTimeout(r, 0)) } = {}) { const counts = [], re = pattern(query); let total = 0; if (!query) return { total: 0, page: () => ({ total: 0, offset: 0, pageSize: 50, results: [] }) }; for (let index = 0; index < book.pages.length; index++) { if (!current()) throw new DOMException("Search cancelled", "AbortError"); let count = 0; for (const match of book.pages[index].text.matchAll(re)) { count++; if (count % 2048 === 0) { await yieldTask(); if (!current()) throw new DOMException("Search cancelled", "AbortError"); } } counts.push(count); total += count; if (index % 16 === 0) await yieldTask(); } return { total, page(offset = 0, pageSize = 50) { offset = Math.max(0, Math.min(Math.max(0, total - 1), Math.floor(offset))); offset = Math.floor(offset / pageSize) * pageSize; const results = []; let passed = 0; for (let index = 0; index < book.pages.length && results.length < pageSize; index++) { if (passed + counts[index] <= offset) { passed += counts[index]; continue; } const page = book.pages[index]; for (const match of page.text.matchAll(re)) { if (passed++ < offset) continue; const begin = Math.max(0, match.index - 72), end = Math.min(page.text.length, match.index + match[0].length + 88); results.push({ page: page.page, start: match.index, length: match[0].length, boxes: hitBoxes(page, match.index, match[0].length), snippet: { text: page.text.slice(begin, end), matchStart: match.index - begin, matchLength: match[0].length, prefix: begin ? "…" : "", suffix: end < page.text.length ? "…" : "" } }); if (results.length === pageSize) break; } } return { total, offset, pageSize, results }; } };}
export function createBookTextCache(load) { let value = null, pending = null; return { async get() { if (value) return value; if (!pending) pending = Promise.resolve().then(load).then(book => (value = book)).finally(() => { pending = null; }); return pending; }, clear() { value = null; pending = null; } };}
export function paintTextHit(shell, boxes) { shell.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove()); for (const { box } of boxes) { const mark = shell.ownerDocument.createElement("span"); mark.className = "reader-text-hit-box"; mark.setAttribute("aria-hidden", "true"); Object.assign(mark.style, { position: "absolute", pointerEvents: "none", zIndex: "4", left: `${box[0] * 100}%`, top: `${box[1] * 100}%`, width: `${(box[2] - box[0]) * 100}%`, height: `${(box[3] - box[1]) * 100}%`, background: "rgb(240 199 94 / 45%)" }); shell.appendChild(mark); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445export function populatePdfTextLayer(layer, items, pdfViewport) {const fragment = layer.ownerDocument.createDocumentFragment();let positioned = false;let plainText = "";for (const item of items) {const span = layer.ownerDocument.createElement("span");const value = item.str + (item.hasEOL ? "\n" : " ");span.textContent = value;plainText += value;const point = item.transform && pdfViewport.convertToViewportPoint? pdfViewport.convertToViewportPoint(item.transform[4], item.transform[5]): null;if (point) {positioned = true;const fontHeight = Math.hypot(item.transform[2] || 0, item.transform[3] || 0) || 12;span.style.left = `${(point[0] / Math.max(1, pdfViewport.width)) * 100}%`;span.style.top = `${(point[1] / Math.max(1, pdfViewport.height)) * 100}%`;span.style.fontSize = `${(fontHeight / Math.max(1, pdfViewport.height)) * 100}%`;} else span.style.position = "static";fragment.appendChild(span);}if (positioned) {layer.replaceChildren(fragment);if (!layer.textContent.trim()) layer.textContent = "此页没有可提取文本";} else layer.textContent = plainText.trim() || "此页没有可提取文本";}export function populateOcrTextLayer(layer, blocks) {const fragment = layer.ownerDocument.createDocumentFragment();for (const block of blocks || []) {const text = String(block?.t || "");const box = Array.isArray(block?.b) ? block.b : [];if (!text || box.length !== 4) continue;const span = layer.ownerDocument.createElement("span");span.textContent = text;span.dataset.ocrText = text;span.style.left = `${Math.max(0, Math.min(1, Number(box[0]) || 0)) * 100}%`;span.style.top = `${Math.max(0, Math.min(1, Number(box[1]) || 0)) * 100}%`;span.style.width = `${Math.max(0, Math.min(1, Number(box[2]) - Number(box[0])) * 100)}%`;span.style.height = `${Math.max(0.5, Math.min(1, Number(box[3]) - Number(box[1])) * 100)}%`;span.style.fontSize = `${Math.max(8, Math.min(72, Math.abs(Number(box[3]) - Number(box[1])) * 100))}%`;fragment.appendChild(span);}layer.replaceChildren(fragment);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115// PDF.js already emits word spaces. Adding a space after every item breaks// Chinese words and words split across fonts. Keep the source's explicit spaces.export function pdfTextContent(items) {return items.filter((item) => typeof item.str === "string").map((item) => item.str + (item.hasEOL ? "\n" : "")).join("");}// Embedded OCR often spaces individual Han characters, including vertical text.// Keep punctuation and Latin word boundaries, and map hits back to source offsets.export function pdfSearchText(raw) {const removed = /(?<=\p{Script=Han})\s+(?=\p{Script=Han})/gu;const offsets = [], chunks = [];let start = 0;for (const match of raw.matchAll(removed)) {chunks.push(raw.slice(start, match.index));for (let i = start; i < match.index; i++) offsets.push(i);start = match.index + match[0].length;}chunks.push(raw.slice(start));for (let i = start; i < raw.length; i++) offsets.push(i);return { text: chunks.join(""), offsets };}function textRun(layer, text) {const run = layer.ownerDocument.createElement("span");run.className = "reader-pdf-text-run";run.textContent = text;return run;}const measurements = new WeakMap();function normalizeBox(value) {return Math.max(0, Math.min(1, Number(value) || 0));}function measureRunScale(context, text, family, targetWidth) {context.font = `100px ${family}`;const measured = context.measureText(text).width / 100;return measured > 0 && targetWidth > 0 ? targetWidth / measured : 1;}function positionedRun(layer, text, x, y, height, width, family, angle = 0, vertical = false) {const box = layer.ownerDocument.createElement("span");box.className = "reader-pdf-text-position reader-pdf-text-block";box.style.left = `${x * 100}%`;box.style.top = `${y * 100}%`;// cqw uses the page width, so text scales with zoom and responsive layout.box.style.fontSize = `${height * 100}cqw`;box.style.fontFamily = family;if (angle) box.style.transform = `rotate(${angle}rad)`;const run = textRun(layer, text);let context = measurements.get(layer.ownerDocument);if (!context) {context = layer.ownerDocument.createElement("canvas").getContext("2d");measurements.set(layer.ownerDocument, context);}if (vertical) {run.style.writingMode = "vertical-rl";run.style.textOrientation = "upright";// Upright vertical layout advances one em for spaces as well as Han glyphs.const measured = Array.from(text).length;if (width > 0 && measured) run.style.transform = `scaleY(${width / (height * measured)})`;} else {const scaleX = measureRunScale(context, text, family, width / height);run.style.setProperty("--reader-pdf-run-scale-x", String(scaleX));run.style.transform = "scaleX(var(--reader-pdf-run-scale-x))";}box.appendChild(run);return box;}export function populatePdfTextLayer(layer, items, viewport, styles = {}) {const fragment = layer.ownerDocument.createDocumentFragment();const w = Math.max(1, viewport.width), h = Math.max(1, viewport.height);for (const item of items) {if (typeof item.str !== "string") continue;if (item.str) {const t = item.transform, v = viewport.transform;const point = t && viewport.convertToViewportPoint?.(t[4], t[5]);if (point && t.every(Number.isFinite)) {const style = styles[item.fontName] || {};const family = style.fontFamily || "sans-serif";const vertical = style.vertical || item.dir === "ttb";const scale = viewport.scale || 1;const height = Math.hypot(t[2], t[3]) * scale || 12;const angle = v ? Math.atan2(v[1] * t[0] + v[3] * t[1], v[0] * t[0] + v[2] * t[1]) : 0;const ascent = height * (Number.isFinite(style.ascent) ? style.ascent : 0.8);const x = vertical ? point[0] - height / 2 : point[0] + ascent * Math.sin(angle);const y = vertical ? point[1] : point[1] - ascent * Math.cos(angle);fragment.appendChild(positionedRun(layer, item.str, x / w, y / h, height / w,(vertical ? item.height : item.width) * scale / w, family, angle, vertical));} else {// Text without coordinates remains accessible, but never forms a visible// second text panel beneath the page image.fragment.appendChild(textRun(layer, item.str));}}if (item.hasEOL) fragment.appendChild(layer.ownerDocument.createTextNode("\n"));}layer.replaceChildren(fragment);}export function populateOcrTextLayer(layer, blocks) {const fragment = layer.ownerDocument.createDocumentFragment();const ratio = layer.parentElement.getBoundingClientRect();for (const block of blocks || []) {const text = String(block?.t || ""), b = block?.b;if (!text || !Array.isArray(b) || b.length !== 4 || !b.every(Number.isFinite)) continue;const [x1, y1, x2, y2] = b.map(normalizeBox);const width = Math.abs(x2 - x1), height = Math.abs(y2 - y1);if (!width || !height) continue;fragment.appendChild(positionedRun(layer, text, Math.min(x1, x2), Math.min(y1, y2),height * ratio.height / Math.max(1, ratio.width), width, "sans-serif"));fragment.appendChild(layer.ownerDocument.createTextNode("\n"));}layer.replaceChildren(fragment);}
61 unmodified lines62636465666761 unmodified lines"reader-format-adapters.js","reader-security.js","reader-pdf-text.js","pdf-worker-wrapper.mjs","reader.css","reader.js"61 unmodified lines6263646566676861 unmodified lines"reader-format-adapters.js","reader-security.js","reader-pdf-text.js","reader-book-text.js","pdf-worker-wrapper.mjs","reader.css","reader.js"
268 unmodified lines2692702712722732742752766 unmodified lines283284285286287288289290291292293294295296297298299300301268 unmodified linesconst PDF_OCR_MANIFEST_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?ocr-manifest\.json$/;const PDF_OCR_PAGE_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?pages\/page-[0-9]{6}\.(?:webp|jxl)$/;const PDF_OCR_ROOT = /^(objects\/[0-9a-f]{2}\/[0-9a-f]{64}(?:\/[0-9a-f]{16})?)/;function validatePdfOcrManifest(manifest) {if (!manifest || manifest.version !== 1 || manifest.kind !== "pdf-ocr" ||!Number.isInteger(manifest.page_count) || manifest.page_count < 1 ||manifest.page_count > LIMITS.pdfPages || !Array.isArray(manifest.pages) ||manifest.pages.length !== manifest.page_count)6 unmodified linespage.o !== `${pageRoot}/ocr/page-${expected}.json.gz` ||(page.w !== undefined && (typeof page.w !== "string" || !PDF_OCR_PAGE_PATH.test(page.w) ||!page.w.endsWith(`/pages/page-${expected}.webp`) ||!page.w.startsWith(`${pageRoot}/pages/`))) ||(page.j !== undefined && (typeof page.j !== "string" || !PDF_OCR_PAGE_PATH.test(page.j) ||!page.j.endsWith(`/pages/page-${expected}.jxl`) ||!page.j.startsWith(`${pageRoot}/pages/`))) ||(root && root !== pageRoot))throw error("PDF_OCR_MANIFEST_INVALID");root = pageRoot;}if (!manifest.book_text || typeof manifest.book_text.path !== "string" ||!PDF_OCR_PATH.test(manifest.book_text.path) || manifest.book_text.path !== `${root}/ocr/book-text.json.gz` ||(manifest.page_manifest !== undefined &&(!manifest.page_manifest || typeof manifest.page_manifest.path !== "string" ||manifest.page_manifest.path !== `${root}/page-manifest.json`)))throw error("PDF_OCR_MANIFEST_INVALID");return manifest;}268 unmodified lines2692702712722732742752762772782792802816 unmodified lines288289290291292293294295296297298299300301302303304305306307308309310311268 unmodified linesconst PDF_OCR_MANIFEST_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?ocr-manifest\.json$/;const PDF_OCR_PAGE_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?pages\/page-[0-9]{6}\.(?:webp|jxl)$/;const PDF_OCR_ROOT = /^(objects\/[0-9a-f]{2}\/[0-9a-f]{64}(?:\/[0-9a-f]{16})?)/;function pdfSourceRoot(path) {return typeof path === "string" ? path.split("/").slice(0, 3).join("/") : "";}function validatePdfOcrManifest(manifest) {if (!manifest || manifest.version !== 1 || manifest.kind !== "pdf-ocr" ||manifest.complete !== true || !/^[0-9a-f]{64}$/.test(manifest.source_sha256 || "") ||!String(manifest.profile || "").includes("-layout-v1-") ||!Number.isInteger(manifest.page_count) || manifest.page_count < 1 ||manifest.page_count > LIMITS.pdfPages || !Array.isArray(manifest.pages) ||manifest.pages.length !== manifest.page_count)6 unmodified linespage.o !== `${pageRoot}/ocr/page-${expected}.json.gz` ||(page.w !== undefined && (typeof page.w !== "string" || !PDF_OCR_PAGE_PATH.test(page.w) ||!page.w.endsWith(`/pages/page-${expected}.webp`) ||pdfSourceRoot(page.w) !== pdfSourceRoot(pageRoot))) ||(page.j !== undefined && (typeof page.j !== "string" || !PDF_OCR_PAGE_PATH.test(page.j) ||!page.j.endsWith(`/pages/page-${expected}.jxl`) ||pdfSourceRoot(page.j) !== pdfSourceRoot(pageRoot))) ||pdfSourceRoot(pageRoot) !== `objects/${manifest.source_sha256.slice(0, 2)}/${manifest.source_sha256}` ||(root && pdfSourceRoot(root) !== pdfSourceRoot(pageRoot)))throw error("PDF_OCR_MANIFEST_INVALID");root = pageRoot;}if (!manifest.book_text || typeof manifest.book_text.path !== "string" ||!PDF_OCR_PATH.test(manifest.book_text.path) || !manifest.book_text.path.endsWith('/ocr/book-text.json.gz') ||pdfSourceRoot(manifest.book_text.path) !== pdfSourceRoot(root) ||!/^[0-9a-f]{64}$/.test(manifest.book_text.sha256 || "") ||!Number.isSafeInteger(manifest.book_text.bytes) || manifest.book_text.bytes < 1 ||(manifest.page_manifest !== undefined &&(!manifest.page_manifest || typeof manifest.page_manifest.path !== "string" ||!/^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?page-manifest\.json$/.test(manifest.page_manifest.path) ||pdfSourceRoot(manifest.page_manifest.path) !== pdfSourceRoot(root))))throw error("PDF_OCR_MANIFEST_INVALID");return manifest;}
834 unmodified lines83583683783883984032 unmodified lines873874875876877878879880881882883884885886887888889890834 unmodified lines}.reader-page {position: relative;margin: 0 auto 18px;background: white;box-shadow: 0 2px 14px #0008;32 unmodified lineswhite-space: pre;border: 0;color: transparent;}.reader-pdf-text span {position: absolute;color: transparent;white-space: pre;transform-origin: left bottom;user-select: text;cursor: text;}.reader-pdf-text span.full-search-highlight {color: #1d2023;background: #f0c75e;}.reader-image {display: block;834 unmodified lines83583683783883984084132 unmodified lines874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915834 unmodified lines}.reader-page {position: relative;container-type: size;margin: 0 auto 18px;background: white;box-shadow: 0 2px 14px #0008;32 unmodified lineswhite-space: pre;border: 0;color: transparent;z-index: 1;line-height: 1;text-size-adjust: none;-webkit-text-size-adjust: none;}.reader-pdf-text-position {position: absolute;--reader-pdf-font-ratio: 1;font-size: calc(var(--reader-pdf-font-ratio) * 100cqw);transform-origin: left top;}.reader-pdf-text-run {display: inline-block;color: transparent;white-space: pre;transform-origin: left top;user-select: text;-webkit-user-select: text;cursor: text;}.reader-pdf-text-run::selection {color: transparent;background: #4285f466;}.reader-pdf-text-run.full-search-highlight {color: transparent;background: #f0c75e88;}.reader-pdf-text ::selection,.reader-pdf-text-run::selection {color: transparent;background: #4285f466;}.reader-pdf-text mark.full-search-highlight {color: transparent;background: #f0c75e88;}.reader-image {display: block;
5 unmodified lines6789101112358 unmodified lines3713723733743753762400 unmodified lines27772778277927802781278227833 unmodified lines27872788278927902791279227932794279527962797279827992800280128022803280428052806280782 unmodified lines289028912892289328942895670 unmodified lines3566356735683569357035711146 unmodified lines47184719472047214722472390 unmodified lines48144815481648174818481948204821482248234824482548264827482848294830483148324833483437 unmodified lines487248734874487548764877213 unmodified lines5091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512520 unmodified lines5146514751485149515051515152515351545 unmodified lines51605161516251635164516551665167516851695170517151725173517416 unmodified lines5191519251935194519551964 unmodified lines520152025203520452055206520752085209521054 unmodified lines5265526652675268526952705 unmodified linesimport "/static/reader-section-virtualizer.js";import "/static/reader-runtime.js";import "/static/reader-format-adapters.js";import { populatePdfTextLayer, populateOcrTextLayer } from "/static/reader-pdf-text.js";// Engines and Reader lifecycle.const PDFJS_URL = VoiceOfMLReaderResources.vendorUrl("pdf", "/static/");const PDFJS_WORKER_URL = "/static/pdf-worker-wrapper.mjs";358 unmodified lineslet pdfPageManifest = null;let pdfOcrManifest = null;let pdfOcrManifestPromise = null;let pdfActiveRenders = 0;let pdfShellsReady = Promise.resolve();const pdfRenderWaiters = [];2400 unmodified linesy: point ? Math.max(0, Math.min(1, point[1] / Math.max(1, pdfViewport.height))) : 0};});populatePdfTextLayer(layer, text.items, pdfViewport);shell.dataset.textReady = "1";highlightPdfText(shell);} catch (error) {3 unmodified lines}function highlightPdfText(shell, query = searchState.query) {if (!shell || readerAbortController.signal.aborted || !query) return;const pattern = new RegExp(fullSearchEscape(query), "iu");const spans = [...shell.querySelectorAll(".reader-pdf-text span")];let text = "";const ranges = spans.map((span) => {const start = text.length;text += `${span.textContent || ""} `;return { span, start, end: text.length };});const hit = text.search(pattern);for (const { span, start, end } of ranges)if (!span.classList.contains("full-search-highlight") &&((hit >= 0 && end > hit && start < hit + query.length) || pattern.test(span.textContent))) {span.classList.add("full-search-highlight");fullSearchActiveMarks.push(span);}}function acquirePdfRenderSlot(priority = false) {82 unmodified linesshell._bookmarkTextItems = [];shell.dataset.textReady = "0";shell.dataset.renderState = "idle";}}670 unmodified linespdfPageManifest = null;pdfOcrManifest = null;pdfOcrManifestPromise = null;pdfFirstPagePreload?.removeAttribute("src");pdfFirstPagePreload = null;for (const canvas of content.querySelectorAll(".reader-page canvas")) {1146 unmodified linesnextReaderGeneration("search");beginReaderNavigation();chapterSearchClient?.cancel();chapterSearchPage = null;updateSearchState({ results: [], index: -1 });renderFullSearchResults();90 unmodified linesinput.value = String(Math.floor(page.offset / page.pageSize) + 1);input.max = String(Math.max(1, pages));chapterSearchPagination.querySelector("#full-search-pages").textContent = `/ ${pages}`;chapterSearchPagination.querySelector("#full-search-page-prev").disabled = page.offset === 0;chapterSearchPagination.querySelector("#full-search-page-next").disabled =page.offset + page.pageSize >= page.total;}async function loadChapterSearchPage(offset, selectLast = null) {if (!chapterSearchPage || !chapterSearchClient) return;const generation = nextReaderGeneration("search");beginReaderNavigation();fullSearchCancel.hidden = false;fullSearchRetry.hidden = true;fullSearchStatus.textContent = "正在加载搜索结果…";try {const page = await chapterSearchClient.page(offset);if (!isReaderGenerationCurrent("search", generation)) return;applyChapterSearchPage(page);renderFullSearchResults();fullSearchStatus.textContent = `${page.total} 个结果`;if (selectLast !== null)37 unmodified lines}let fullSearchActiveMarks = [];function clearFullSearchMarks() {for (const mark of fullSearchActiveMarks) {if (mark.tagName === "MARK") mark.replaceWith(mark.textContent);else mark.classList.remove("full-search-highlight");213 unmodified lines});}async function fullSearchPdfMatches(query, generation) {const pdf = pdfDocument,output = [],pattern = new RegExp(fullSearchEscape(query), "giu");if (!pdf) return output;for (let page = 1; page <= pdf.numPages && output.length < 100; page++) {if (!isReaderGenerationCurrent("search", generation)) return [];const pdfPage = await awaitReader(pdf.getPage(page));if (!isReaderGenerationCurrent("search", generation)) return [];const textContent = await awaitReader(pdfPage.getTextContent());if (!isReaderGenerationCurrent("search", generation)) return [];const text = textContent.items.map((item) => item.str + (item.hasEOL ? "\n" : " ")).join("").trim();let matched = false;for (const match of text.matchAll(pattern)) {if (output.length >= 100) break;matched = true;output.push({location: `第 ${page} 页`,snippet: fullSearchSnippet(text, match.index, match[0].length),activate: (navigationGeneration) => goToPage(page, navigationGeneration)});}if (matched)highlightPdfText(content.querySelector(`.reader-page[data-page="${page}"]`), query);}return output;}function renderFullSearchResults() {updateChapterSearchPagination();20 unmodified linesclearFullSearchMarks();updateSearchState({ query, results: [], index: -1 });chapterSearchPage = null;updateChapterSearchPagination();fullSearchRetry.hidden = true;fullSearchCancel.hidden = capability.mode !== "epub-chapters" || !query;fullSearchResultsNode.textContent = "";fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {button.disabled = true;5 unmodified lines}fullSearchStatus.textContent = "正在搜索正文…";try {if (capability.mode === "pdf-pages") {try {publishSearchResults(generation, await fullSearchPdfApiMatches(query, generation));} catch (error) {publishSearchResults(generation, await fullSearchPdfPageMatches(query, generation));}}else if (capability.mode === "pdf")publishSearchResults(generation, await fullSearchPdfMatches(query, generation));else if (capability.mode === "foliate")publishSearchResults(generation, await fullSearchFoliateMatches(query, generation));else if (capability.mode === "epub-chapters") await searchChapterBook(query, generation);16 unmodified lines);else throw new Error("此格式没有可搜索文本");if (!isReaderGenerationCurrent("search", generation)) return;renderFullSearchResults();fullSearchStatus.textContent = chapterSearchPage? chapterSearchPage.total4 unmodified lines: "未找到正文匹配";} catch (error) {if (isReaderGenerationCurrent("search", generation)) {fullSearchStatus.textContent = error.message || "正文搜索不可用";fullSearchRetry.hidden = capability.mode !== "epub-chapters";}} finally {if (isReaderGenerationCurrent("search", generation)) fullSearchCancel.hidden = true;if (isReaderGenerationCurrent("search", generation))fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {54 unmodified linesbeginReaderNavigation();nextReaderGeneration("search");chapterSearchClient?.cancel();chapterSearchPage = null;fullSearchCancel.hidden = true;fullSearchRetry.hidden = true;5 unmodified lines678910111213358 unmodified lines3723733743753763773783793803813823833843852400 unmodified lines27862787278827892790279127923 unmodified lines279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282382 unmodified lines2906290729082909291029112912670 unmodified lines35833584358535863587358835891146 unmodified lines473647374738473947404741474290 unmodified lines48334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485937 unmodified lines4897489848994900490149024903213 unmodified lines511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521920 unmodified lines524052415242524352445245524652475248524952505 unmodified lines5256525752585259526052615262526316 unmodified lines52805281528252835284528552864 unmodified lines529152925293529452955296529752985299530053015302530354 unmodified lines53585359536053615362536353645 unmodified linesimport "/static/reader-section-virtualizer.js";import "/static/reader-runtime.js";import "/static/reader-format-adapters.js";import { populatePdfTextLayer, populateOcrTextLayer, pdfTextContent, pdfSearchText } from "/static/reader-pdf-text.js";import { validateBookText, searchBookText, createBookTextCache, paintTextHit } from "/static/reader-book-text.js";// Engines and Reader lifecycle.const PDFJS_URL = VoiceOfMLReaderResources.vendorUrl("pdf", "/static/");const PDFJS_WORKER_URL = "/static/pdf-worker-wrapper.mjs";358 unmodified lineslet pdfPageManifest = null;let pdfOcrManifest = null;let pdfOcrManifestPromise = null;const pdfBookTextCache = createBookTextCache(async () => {const manifest = await loadPdfOcrManifest();if (!manifest?.book_text?.path) throw new Error("本书集中全文尚未生成");const book = await readPdfOcrJson(pdfOcrSource().assetUrl(manifest.book_text.path),VoiceOfMLReaderSecurity.LIMITS.chapterTotalBytes, manifest.book_text.sha256, manifest.book_text.bytes);return validateBookText(book, documentState.pageCount, manifest.source_sha256);});trackReaderResource(() => pdfBookTextCache.clear());let pdfActiveRenders = 0;let pdfShellsReady = Promise.resolve();const pdfRenderWaiters = [];2400 unmodified linesy: point ? Math.max(0, Math.min(1, point[1] / Math.max(1, pdfViewport.height))) : 0};});populatePdfTextLayer(layer, text.items, pdfViewport, text.styles);shell.dataset.textReady = "1";highlightPdfText(shell);} catch (error) {3 unmodified lines}function highlightPdfText(shell, query = searchState.query) {if (!shell || readerAbortController.signal.aborted || !query) return;const layer = shell.querySelector(".reader-pdf-text");if (!layer || layer.querySelector("mark")) return;const walker = document.createTreeWalker(layer, NodeFilter.SHOW_TEXT), runs = [];let raw = "";while (walker.nextNode()) {const node = walker.currentNode, start = raw.length;raw += node.data;runs.push({ node, start, end: raw.length });}const mapping = pdfSearchText(raw);const hits = [];for (const hit of mapping.text.matchAll(new RegExp(fullSearchEscape(pdfSearchText(query).text), "giu"))) {hits.push(hit);if (hits.length === 100) break;}// Bound highlights in the displayed page, without limiting searchable results.for (const hit of hits.reverse()) {const start = mapping.offsets[hit.index], end = mapping.offsets[hit.index + hit[0].length - 1] + 1;highlightTextParts(runs.filter((run) => run.end > start && run.start < end).map((run) => ({node: run.node, start: Math.max(start, run.start) - run.start, end: Math.min(end, run.end) - run.start})));}}function acquirePdfRenderSlot(priority = false) {82 unmodified linesshell._bookmarkTextItems = [];shell.dataset.textReady = "0";shell.dataset.renderState = "idle";fullSearchActiveMarks = fullSearchActiveMarks.filter((mark) => mark.isConnected);}}670 unmodified linespdfPageManifest = null;pdfOcrManifest = null;pdfOcrManifestPromise = null;pdfBookTextCache.clear();pdfFirstPagePreload?.removeAttribute("src");pdfFirstPagePreload = null;for (const canvas of content.querySelectorAll(".reader-page canvas")) {1146 unmodified linesnextReaderGeneration("search");beginReaderNavigation();chapterSearchClient?.cancel();pdfSearchInProgress = false;chapterSearchPage = null;updateSearchState({ results: [], index: -1 });renderFullSearchResults();90 unmodified linesinput.value = String(Math.floor(page.offset / page.pageSize) + 1);input.max = String(Math.max(1, pages));chapterSearchPagination.querySelector("#full-search-pages").textContent = `/ ${pages}`;chapterSearchPagination.querySelector("#full-search-page-prev").disabled =pdfSearchInProgress || page.offset === 0;chapterSearchPagination.querySelector("#full-search-page-next").disabled =pdfSearchInProgress || page.offset + page.pageSize >= page.total;input.disabled = pdfSearchInProgress;}async function loadChapterSearchPage(offset, selectLast = null) {if (!chapterSearchPage || (!chapterSearchClient && !pdfSearchPageLoader)) return;const generation = nextReaderGeneration("search");beginReaderNavigation();fullSearchCancel.hidden = false;fullSearchRetry.hidden = true;fullSearchStatus.textContent = "正在加载搜索结果…";try {const pdfLoader = pdfSearchPageLoader;const page = await (pdfLoader ? pdfLoader(offset) : chapterSearchClient.page(offset));if (!isReaderGenerationCurrent("search", generation)) return;if (pdfLoader) {chapterSearchPage = page;updateSearchState({ results: page.results, index: -1 });} else applyChapterSearchPage(page);renderFullSearchResults();fullSearchStatus.textContent = `${page.total} 个结果`;if (selectLast !== null)37 unmodified lines}let fullSearchActiveMarks = [];function clearFullSearchMarks() {content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());for (const mark of fullSearchActiveMarks) {if (mark.tagName === "MARK") mark.replaceWith(mark.textContent);else mark.classList.remove("full-search-highlight");213 unmodified lines});}let pdfSearchPageLoader = null;let pdfSearchInProgress = false;async function searchConcentratedPdf(query, generation) {const book = await pdfBookTextCache.get();const index = await searchBookText(book, query, {current: () => isReaderGenerationCurrent("search", generation),yieldTask: () => waitForReader(0)});pdfSearchPageLoader = (offset) => {const page = index.page(offset);return { ...page, results: page.results.map(hit => ({...hit, location: `第 ${hit.page} 页`, activate: async nav => {if (!await goToPage(hit.page, nav) || !isReaderGenerationCurrent("navigation", nav))return false;content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());const shell = content.querySelector(`.reader-page[data-page="${hit.page}"]`);if (shell && hit.boxes.length) {paintTextHit(shell, hit.boxes);shell.querySelector(".reader-text-hit-box")?.scrollIntoView({ block: "center" });}return true;}})) };};chapterSearchPage = pdfSearchPageLoader(0);return chapterSearchPage.results;}function makePdfSearchPageLoader(groups, total, pattern) {return (requestedOffset) => {const pageSize = 50, results = [];const offset = Math.max(0,Math.min(Math.floor(Math.max(0, total - 1) / pageSize) * pageSize, requestedOffset));let skipped = 0;for (const group of groups) {if (skipped + group.count <= offset) {skipped += group.count;continue;}for (const match of group.text.matchAll(pattern)) {if (skipped++ < offset) continue;results.push({location: `第 ${group.page} 页`,snippet: fullSearchSnippet(group.text, match.index, match[0].length),activate: (navigationGeneration) => goToPage(group.page, navigationGeneration)});if (results.length === pageSize) break;}if (results.length === pageSize) break;}return { total, offset, pageSize, results };};}function publishPdfSearchProgress(generation, groups, total, pattern, scanned, pages) {if (!isReaderGenerationCurrent("search", generation)) return false;pdfSearchPageLoader = makePdfSearchPageLoader(groups, total, pattern);chapterSearchPage = pdfSearchPageLoader(0);updateSearchState({ results: chapterSearchPage.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = total? `${total} 个结果(正在搜索… ${scanned} / ${pages} 页)`: `正在搜索正文… ${scanned} / ${pages} 页,暂未找到匹配`;return true;}async function fullSearchPdfMatches(query, generation) {const pdf = pdfDocument,groups = [],pattern = new RegExp(fullSearchEscape(pdfSearchText(query).text), "giu");if (!pdf) return [];let total = 0, hasText = false;for (let page = 1; page <= pdf.numPages; page++) {if (!isReaderGenerationCurrent("search", generation)) return [];const pdfPage = await awaitReader(pdf.getPage(page));if (!isReaderGenerationCurrent("search", generation)) return [];const textContent = await awaitReader(pdfPage.getTextContent());if (!isReaderGenerationCurrent("search", generation)) return [];const text = pdfSearchText(pdfTextContent(textContent.items)).text;hasText ||= !!text.trim();let count = 0;for (const match of text.matchAll(pattern)) count++;if (count) {groups.push({ page, text, count });total += count;highlightPdfText(content.querySelector(`.reader-page[data-page="${page}"]`), query);}if (page === 1 || page % 8 === 0 || page === pdf.numPages) {if (!publishPdfSearchProgress(generation, groups, total, pattern, page, pdf.numPages)) return [];await waitForReader(0, true);}}if (!hasText) throw new Error("此 PDF 尚无可搜索文字层,需要完成 OCR 后才能搜索正文");publishPdfSearchProgress(generation, groups, total, pattern, pdf.numPages, pdf.numPages);return chapterSearchPage.results;}function renderFullSearchResults() {updateChapterSearchPagination();20 unmodified linesclearFullSearchMarks();updateSearchState({ query, results: [], index: -1 });chapterSearchPage = null;pdfSearchPageLoader = null;updateChapterSearchPagination();fullSearchRetry.hidden = true;fullSearchCancel.hidden = !["epub-chapters", "pdf"].includes(capability.mode) || !query;pdfSearchInProgress = capability.mode === "pdf" && !!query;fullSearchResultsNode.textContent = "";fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {button.disabled = true;5 unmodified lines}fullSearchStatus.textContent = "正在搜索正文…";try {if (["pdf", "pdf-pages"].includes(capability.mode))publishSearchResults(generation, await searchConcentratedPdf(query, generation));else if (capability.mode === "foliate")publishSearchResults(generation, await fullSearchFoliateMatches(query, generation));else if (capability.mode === "epub-chapters") await searchChapterBook(query, generation);16 unmodified lines);else throw new Error("此格式没有可搜索文本");if (!isReaderGenerationCurrent("search", generation)) return;if (capability.mode === "pdf") pdfSearchInProgress = false;renderFullSearchResults();fullSearchStatus.textContent = chapterSearchPage? chapterSearchPage.total4 unmodified lines: "未找到正文匹配";} catch (error) {if (isReaderGenerationCurrent("search", generation)) {if (capability.mode === "pdf") pdfSearchInProgress = false;fullSearchStatus.textContent = error.message || "正文搜索不可用";fullSearchRetry.hidden = !["epub-chapters", "pdf"].includes(capability.mode);}} finally {if (isReaderGenerationCurrent("search", generation) && capability.mode === "pdf")pdfSearchInProgress = false;if (isReaderGenerationCurrent("search", generation)) fullSearchCancel.hidden = true;if (isReaderGenerationCurrent("search", generation))fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {54 unmodified linesbeginReaderNavigation();nextReaderGeneration("search");chapterSearchClient?.cancel();pdfSearchInProgress = false;chapterSearchPage = null;fullSearchCancel.hidden = true;fullSearchRetry.hidden = true;
49 unmodified lines5051525354555657585949 unmodified lines"pages": [{"p": 1, "o": root + "/ocr/page-000001.json.gz"},{"p": 2, "o": root + "/ocr/page-000002.json.gz"}],"book_text": {"path": book_path}}book = gzip.compress(json.dumps({"version": 1, "kind": "pdf-ocr-book-text", "pages": [{"page": 1, "text": "第一章 手机阅读"},{"page": 2, "text": "第二章 手机搜索"},]}).encode())async def resource(path):return json.dumps(manifest).encode() if path == manifest_path else book49 unmodified lines505152535455565758596049 unmodified lines"pages": [{"p": 1, "o": root + "/ocr/page-000001.json.gz"},{"p": 2, "o": root + "/ocr/page-000002.json.gz"}],"book_text": {"path": book_path}}pages = [{"page": 1, "text": "第一章 手机阅读", "layout": {"offset_unit": "unicode-codepoint"}, "text_spans": []},{"page": 2, "text": "第二章 手机搜索", "layout": {"offset_unit": "unicode-codepoint"}, "text_spans": []}]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": pages}).encode())async def resource(path):return json.dumps(manifest).encode() if path == manifest_path else book
app.py+33-8
static/reader-book-text.jsAdded+100
static/reader-pdf-text.js+104-34
static/reader-resources.js+1
static/reader-security.js+15-5
static/reader.css+30-5
static/reader.js+147-53
tests/test_fastapi_endpoints.py+5-4