vomebook commited on
Commit
9cb654f
·
1 Parent(s): 681df39

feat: search PDFs from strict v2 text indexes

Browse files
app.py CHANGED
@@ -1702,8 +1702,8 @@ async def get_reader_bucket_resource(path: str, bucket: str = "vomebook/pdf-page
1702
  return await asyncio.shield(task)
1703
 
1704
 
1705
- def parse_reader_ocr_book(raw: bytes) -> tuple[list[tuple[int, str, str]], int]:
1706
- """Decode and validate the compact per-page OCR text cache off the event loop."""
1707
  with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:
1708
  decoded = stream.read(READER_RESOURCE_MAX_BYTES + 1)
1709
  if len(decoded) > READER_RESOURCE_MAX_BYTES:
@@ -1711,7 +1711,11 @@ def parse_reader_ocr_book(raw: bytes) -> tuple[list[tuple[int, str, str]], int]:
1711
  payload = json.loads(decoded)
1712
  pages = payload.get("pages") if isinstance(payload, dict) else None
1713
  if (not isinstance(pages, list) or len(pages) > 200000
1714
- or payload.get("version") != 1 or payload.get("kind") != "pdf-ocr-book-text"):
 
 
 
 
1715
  raise ValueError("invalid PDF OCR text index")
1716
  output = []
1717
  total_bytes = 0
@@ -1725,12 +1729,28 @@ def parse_reader_ocr_book(raw: bytes) -> tuple[list[tuple[int, str, str]], int]:
1725
  total_bytes += len(text.encode("utf-8"))
1726
  if total_bytes > READER_RESOURCE_MAX_BYTES:
1727
  raise ValueError("PDF OCR text index is too large")
1728
- output.append((item["page"], text, text.casefold()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1729
  previous = item["page"]
1730
  return output, total_bytes
1731
 
1732
 
1733
- async def get_reader_ocr_book(path: str) -> list[tuple[int, str, str]]:
1734
  state = app.state
1735
  if not hasattr(state, "reader_ocr_cache"):
1736
  state.reader_ocr_cache = OrderedDict()
@@ -1974,7 +1994,8 @@ async def api_reader_ocr_search(
1974
  pages = await get_reader_ocr_book(book_path)
1975
  needle = q.casefold()
1976
  matches = []
1977
- for page_number, text, folded in pages:
 
1978
  start = 0
1979
  while True:
1980
  found = folded.find(needle, start)
@@ -1983,16 +2004,20 @@ async def api_reader_ocr_search(
1983
  end = found + len(q)
1984
  snippet_start = max(0, found - 72)
1985
  snippet_end = min(len(text), end + 88)
 
 
 
 
1986
  matches.append({
1987
  "page": page_number, "start": found, "length": len(q),
1988
  "snippet": text[snippet_start:snippet_end],
1989
- "snippet_start": found - snippet_start,
1990
  })
1991
  start = end
1992
  total = len(matches)
1993
  offset = (page - 1) * page_size
1994
  return JSONResponse({
1995
- "version": 1, "page": page, "page_size": page_size, "total": total,
1996
  "results": matches[offset:offset + page_size],
1997
  }, headers={"Cache-Control": "no-store"})
1998
  except (ValueError, TypeError, KeyError, EOFError, gzip.BadGzipFile, zlib.error):
 
1702
  return await asyncio.shield(task)
1703
 
1704
 
1705
+ def parse_reader_ocr_book(raw: bytes) -> tuple[list[dict], int]:
1706
+ """Decode the single v2 book text index and its layout mappings."""
1707
  with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:
1708
  decoded = stream.read(READER_RESOURCE_MAX_BYTES + 1)
1709
  if len(decoded) > READER_RESOURCE_MAX_BYTES:
 
1711
  payload = json.loads(decoded)
1712
  pages = payload.get("pages") if isinstance(payload, dict) else None
1713
  if (not isinstance(pages, list) or len(pages) > 200000
1714
+ or payload.get("version") != 2 or payload.get("kind") != "pdf-book-text"
1715
+ or payload.get("complete") is not True
1716
+ or payload.get("offset_unit") != "unicode-codepoint"
1717
+ or payload.get("page_count") != len(pages)
1718
+ or not re.fullmatch(r"[0-9a-f]{64}", str(payload.get("source_sha256", "")))):
1719
  raise ValueError("invalid PDF OCR text index")
1720
  output = []
1721
  total_bytes = 0
 
1729
  total_bytes += len(text.encode("utf-8"))
1730
  if total_bytes > READER_RESOURCE_MAX_BYTES:
1731
  raise ValueError("PDF OCR text index is too large")
1732
+ layout = item.get("layout")
1733
+ spans = item.get("text_spans")
1734
+ if (not isinstance(layout, dict) or layout.get("offset_unit") != "unicode-codepoint"
1735
+ or not isinstance(spans, list)):
1736
+ raise ValueError("invalid PDF text layout mapping")
1737
+ previous_span_end = 0
1738
+ for span in spans:
1739
+ box = span.get("box") if isinstance(span, dict) else None
1740
+ if (not isinstance(span, dict) or not isinstance(span.get("start"), int)
1741
+ or not isinstance(span.get("end"), int) or span["start"] < previous_span_end
1742
+ or span["end"] <= span["start"] or span["end"] > len(text)
1743
+ or not isinstance(box, list) or len(box) != 4
1744
+ or any(not isinstance(value, (int, float)) or value < 0 or value > 1 for value in box)):
1745
+ raise ValueError("invalid PDF text span")
1746
+ previous_span_end = span["end"]
1747
+ output.append({"page": item["page"], "text": text, "folded": text.casefold(),
1748
+ "layout": layout, "spans": spans})
1749
  previous = item["page"]
1750
  return output, total_bytes
1751
 
1752
 
1753
+ async def get_reader_ocr_book(path: str) -> list[dict]:
1754
  state = app.state
1755
  if not hasattr(state, "reader_ocr_cache"):
1756
  state.reader_ocr_cache = OrderedDict()
 
1994
  pages = await get_reader_ocr_book(book_path)
1995
  needle = q.casefold()
1996
  matches = []
1997
+ for item in pages:
1998
+ page_number, text, folded = item["page"], item["text"], item["folded"]
1999
  start = 0
2000
  while True:
2001
  found = folded.find(needle, start)
 
2004
  end = found + len(q)
2005
  snippet_start = max(0, found - 72)
2006
  snippet_end = min(len(text), end + 88)
2007
+ begin = found
2008
+ end = found + len(q)
2009
+ boxes = [span["box"] for span in item["spans"]
2010
+ if span["end"] > begin and span["start"] < end]
2011
  matches.append({
2012
  "page": page_number, "start": found, "length": len(q),
2013
  "snippet": text[snippet_start:snippet_end],
2014
+ "snippet_start": found - snippet_start, "boxes": boxes,
2015
  })
2016
  start = end
2017
  total = len(matches)
2018
  offset = (page - 1) * page_size
2019
  return JSONResponse({
2020
+ "version": 2, "kind": "pdf-book-text-search", "page": page, "page_size": page_size, "total": total,
2021
  "results": matches[offset:offset + page_size],
2022
  }, headers={"Cache-Control": "no-store"})
2023
  except (ValueError, TypeError, KeyError, EOFError, gzip.BadGzipFile, zlib.error):
static/reader-book-text.js ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // One complete, validated text file per PDF. Offsets in generated mappings are
2
+ // Unicode code points; JavaScript RegExp returns UTF-16 offsets.
3
+ export function validateBookText(book, pageCount, sourceSha = "") {
4
+ if (!book || book.version !== 2 || book.kind !== "pdf-book-text" ||
5
+ book.complete !== true || book.offset_unit !== "unicode-codepoint" ||
6
+ book.page_count !== pageCount || (sourceSha && book.source_sha256 !== sourceSha) ||
7
+ !Array.isArray(book.pages) || book.pages.length !== pageCount)
8
+ throw new Error("PDF_TEXT_INDEX_INCOMPLETE");
9
+ for (const [index, page] of book.pages.entries()) {
10
+ if (page.page !== index + 1 || typeof page.text !== "string" ||
11
+ !page.layout || page.layout.offset_unit !== "unicode-codepoint" ||
12
+ !Array.isArray(page.text_spans))
13
+ throw new Error("PDF_TEXT_INDEX_INVALID");
14
+ const length = Array.from(page.text).length;
15
+ let previousEnd = 0;
16
+ for (const span of page.text_spans) {
17
+ if (!Number.isInteger(span.start) || !Number.isInteger(span.end) ||
18
+ span.start < previousEnd || span.end <= span.start || span.end > length ||
19
+ !Array.isArray(span.box) || span.box.length !== 4 ||
20
+ span.box.some(v => !Number.isFinite(v) || v < 0 || v > 1) ||
21
+ span.box[0] > span.box[2] || span.box[1] > span.box[3])
22
+ throw new Error("PDF_TEXT_MAPPING_INVALID");
23
+ previousEnd = span.end;
24
+ }
25
+ }
26
+ return book;
27
+ }
28
+
29
+ function pattern(query) {
30
+ return new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "giu");
31
+ }
32
+
33
+ export function hitBoxes(page, start, length) {
34
+ const begin = Array.from(page.text.slice(0, start)).length;
35
+ const end = begin + Array.from(page.text.slice(start, start + length)).length;
36
+ return page.text_spans.filter(s => s.end > begin && s.start < end)
37
+ .map(s => ({ box: s.box, block: s.block, precision: s.precision || "block" }));
38
+ }
39
+
40
+ export async function searchBookText(book, query, { current = () => true, yieldTask = () => new Promise(r => setTimeout(r, 0)) } = {}) {
41
+ const counts = [], re = pattern(query);
42
+ let total = 0;
43
+ if (!query) return { total: 0, page: () => ({ total: 0, offset: 0, pageSize: 50, results: [] }) };
44
+ for (let index = 0; index < book.pages.length; index++) {
45
+ if (!current()) throw new DOMException("Search cancelled", "AbortError");
46
+ let count = 0;
47
+ for (const match of book.pages[index].text.matchAll(re)) {
48
+ count++;
49
+ if (count % 2048 === 0) {
50
+ await yieldTask();
51
+ if (!current()) throw new DOMException("Search cancelled", "AbortError");
52
+ }
53
+ }
54
+ counts.push(count);
55
+ total += count;
56
+ if (index % 16 === 0) await yieldTask();
57
+ }
58
+ return { total, page(offset = 0, pageSize = 50) {
59
+ offset = Math.max(0, Math.min(Math.max(0, total - 1), Math.floor(offset)));
60
+ offset = Math.floor(offset / pageSize) * pageSize;
61
+ const results = [];
62
+ let passed = 0;
63
+ for (let index = 0; index < book.pages.length && results.length < pageSize; index++) {
64
+ if (passed + counts[index] <= offset) { passed += counts[index]; continue; }
65
+ const page = book.pages[index];
66
+ for (const match of page.text.matchAll(re)) {
67
+ if (passed++ < offset) continue;
68
+ const begin = Math.max(0, match.index - 72), end = Math.min(page.text.length, match.index + match[0].length + 88);
69
+ results.push({ page: page.page, start: match.index, length: match[0].length,
70
+ boxes: hitBoxes(page, match.index, match[0].length),
71
+ snippet: { text: page.text.slice(begin, end), matchStart: match.index - begin,
72
+ matchLength: match[0].length, prefix: begin ? "…" : "", suffix: end < page.text.length ? "…" : "" } });
73
+ if (results.length === pageSize) break;
74
+ }
75
+ }
76
+ return { total, offset, pageSize, results };
77
+ } };
78
+ }
79
+
80
+ export function createBookTextCache(load) {
81
+ let value = null, pending = null;
82
+ return { async get() {
83
+ if (value) return value;
84
+ if (!pending) pending = Promise.resolve().then(load).then(book => (value = book)).finally(() => { pending = null; });
85
+ return pending;
86
+ }, clear() { value = null; pending = null; } };
87
+ }
88
+
89
+ export function paintTextHit(shell, boxes) {
90
+ shell.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());
91
+ for (const { box } of boxes) {
92
+ const mark = shell.ownerDocument.createElement("span");
93
+ mark.className = "reader-text-hit-box";
94
+ mark.setAttribute("aria-hidden", "true");
95
+ Object.assign(mark.style, { position: "absolute", pointerEvents: "none", zIndex: "4",
96
+ left: `${box[0] * 100}%`, top: `${box[1] * 100}%`, width: `${(box[2] - box[0]) * 100}%`,
97
+ height: `${(box[3] - box[1]) * 100}%`, background: "rgb(240 199 94 / 45%)" });
98
+ shell.appendChild(mark);
99
+ }
100
+ }
static/reader-pdf-text.js CHANGED
@@ -1,45 +1,115 @@
1
- export function populatePdfTextLayer(layer, items, pdfViewport) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  const fragment = layer.ownerDocument.createDocumentFragment();
3
- let positioned = false;
4
- let plainText = "";
5
  for (const item of items) {
6
- const span = layer.ownerDocument.createElement("span");
7
- const value = item.str + (item.hasEOL ? "\n" : " ");
8
- span.textContent = value;
9
- plainText += value;
10
- const point = item.transform && pdfViewport.convertToViewportPoint
11
- ? pdfViewport.convertToViewportPoint(item.transform[4], item.transform[5])
12
- : null;
13
- if (point) {
14
- positioned = true;
15
- const fontHeight = Math.hypot(item.transform[2] || 0, item.transform[3] || 0) || 12;
16
- span.style.left = `${(point[0] / Math.max(1, pdfViewport.width)) * 100}%`;
17
- span.style.top = `${(point[1] / Math.max(1, pdfViewport.height)) * 100}%`;
18
- span.style.fontSize = `${(fontHeight / Math.max(1, pdfViewport.height)) * 100}%`;
19
- } else span.style.position = "static";
20
- fragment.appendChild(span);
 
 
 
 
 
 
 
 
21
  }
22
- if (positioned) {
23
- layer.replaceChildren(fragment);
24
- if (!layer.textContent.trim()) layer.textContent = "此页没有可提取文本";
25
- } else layer.textContent = plainText.trim() || "此页没有可提取文本";
26
  }
27
 
28
  export function populateOcrTextLayer(layer, blocks) {
29
  const fragment = layer.ownerDocument.createDocumentFragment();
 
30
  for (const block of blocks || []) {
31
- const text = String(block?.t || "");
32
- const box = Array.isArray(block?.b) ? block.b : [];
33
- if (!text || box.length !== 4) continue;
34
- const span = layer.ownerDocument.createElement("span");
35
- span.textContent = text;
36
- span.dataset.ocrText = text;
37
- span.style.left = `${Math.max(0, Math.min(1, Number(box[0]) || 0)) * 100}%`;
38
- span.style.top = `${Math.max(0, Math.min(1, Number(box[1]) || 0)) * 100}%`;
39
- span.style.width = `${Math.max(0, Math.min(1, Number(box[2]) - Number(box[0])) * 100)}%`;
40
- span.style.height = `${Math.max(0.5, Math.min(1, Number(box[3]) - Number(box[1])) * 100)}%`;
41
- span.style.fontSize = `${Math.max(8, Math.min(72, Math.abs(Number(box[3]) - Number(box[1])) * 100))}%`;
42
- fragment.appendChild(span);
43
  }
44
  layer.replaceChildren(fragment);
45
  }
 
1
+ // PDF.js already emits word spaces. Adding a space after every item breaks
2
+ // Chinese words and words split across fonts. Keep the source's explicit spaces.
3
+ export function pdfTextContent(items) {
4
+ return items.filter((item) => typeof item.str === "string")
5
+ .map((item) => item.str + (item.hasEOL ? "\n" : "")).join("");
6
+ }
7
+
8
+ // Embedded OCR often spaces individual Han characters, including vertical text.
9
+ // Keep punctuation and Latin word boundaries, and map hits back to source offsets.
10
+ export function pdfSearchText(raw) {
11
+ const removed = /(?<=\p{Script=Han})\s+(?=\p{Script=Han})/gu;
12
+ const offsets = [], chunks = [];
13
+ let start = 0;
14
+ for (const match of raw.matchAll(removed)) {
15
+ chunks.push(raw.slice(start, match.index));
16
+ for (let i = start; i < match.index; i++) offsets.push(i);
17
+ start = match.index + match[0].length;
18
+ }
19
+ chunks.push(raw.slice(start));
20
+ for (let i = start; i < raw.length; i++) offsets.push(i);
21
+ return { text: chunks.join(""), offsets };
22
+ }
23
+
24
+ function textRun(layer, text) {
25
+ const run = layer.ownerDocument.createElement("span");
26
+ run.className = "reader-pdf-text-run";
27
+ run.textContent = text;
28
+ return run;
29
+ }
30
+
31
+ const measurements = new WeakMap();
32
+ function normalizeBox(value) {
33
+ return Math.max(0, Math.min(1, Number(value) || 0));
34
+ }
35
+ function measureRunScale(context, text, family, targetWidth) {
36
+ context.font = `100px ${family}`;
37
+ const measured = context.measureText(text).width / 100;
38
+ return measured > 0 && targetWidth > 0 ? targetWidth / measured : 1;
39
+ }
40
+ function positionedRun(layer, text, x, y, height, width, family, angle = 0, vertical = false) {
41
+ const box = layer.ownerDocument.createElement("span");
42
+ box.className = "reader-pdf-text-position reader-pdf-text-block";
43
+ box.style.left = `${x * 100}%`;
44
+ box.style.top = `${y * 100}%`;
45
+ // cqw uses the page width, so text scales with zoom and responsive layout.
46
+ box.style.fontSize = `${height * 100}cqw`;
47
+ box.style.fontFamily = family;
48
+ if (angle) box.style.transform = `rotate(${angle}rad)`;
49
+ const run = textRun(layer, text);
50
+ let context = measurements.get(layer.ownerDocument);
51
+ if (!context) {
52
+ context = layer.ownerDocument.createElement("canvas").getContext("2d");
53
+ measurements.set(layer.ownerDocument, context);
54
+ }
55
+ if (vertical) {
56
+ run.style.writingMode = "vertical-rl";
57
+ run.style.textOrientation = "upright";
58
+ // Upright vertical layout advances one em for spaces as well as Han glyphs.
59
+ const measured = Array.from(text).length;
60
+ if (width > 0 && measured) run.style.transform = `scaleY(${width / (height * measured)})`;
61
+ } else {
62
+ const scaleX = measureRunScale(context, text, family, width / height);
63
+ run.style.setProperty("--reader-pdf-run-scale-x", String(scaleX));
64
+ run.style.transform = "scaleX(var(--reader-pdf-run-scale-x))";
65
+ }
66
+ box.appendChild(run);
67
+ return box;
68
+ }
69
+
70
+ export function populatePdfTextLayer(layer, items, viewport, styles = {}) {
71
  const fragment = layer.ownerDocument.createDocumentFragment();
72
+ const w = Math.max(1, viewport.width), h = Math.max(1, viewport.height);
 
73
  for (const item of items) {
74
+ if (typeof item.str !== "string") continue;
75
+ if (item.str) {
76
+ const t = item.transform, v = viewport.transform;
77
+ const point = t && viewport.convertToViewportPoint?.(t[4], t[5]);
78
+ if (point && t.every(Number.isFinite)) {
79
+ const style = styles[item.fontName] || {};
80
+ const family = style.fontFamily || "sans-serif";
81
+ const vertical = style.vertical || item.dir === "ttb";
82
+ const scale = viewport.scale || 1;
83
+ const height = Math.hypot(t[2], t[3]) * scale || 12;
84
+ const angle = v ? Math.atan2(v[1] * t[0] + v[3] * t[1], v[0] * t[0] + v[2] * t[1]) : 0;
85
+ const ascent = height * (Number.isFinite(style.ascent) ? style.ascent : 0.8);
86
+ const x = vertical ? point[0] - height / 2 : point[0] + ascent * Math.sin(angle);
87
+ const y = vertical ? point[1] : point[1] - ascent * Math.cos(angle);
88
+ fragment.appendChild(positionedRun(layer, item.str, x / w, y / h, height / w,
89
+ (vertical ? item.height : item.width) * scale / w, family, angle, vertical));
90
+ } else {
91
+ // Text without coordinates remains accessible, but never forms a visible
92
+ // second text panel beneath the page image.
93
+ fragment.appendChild(textRun(layer, item.str));
94
+ }
95
+ }
96
+ if (item.hasEOL) fragment.appendChild(layer.ownerDocument.createTextNode("\n"));
97
  }
98
+ layer.replaceChildren(fragment);
 
 
 
99
  }
100
 
101
  export function populateOcrTextLayer(layer, blocks) {
102
  const fragment = layer.ownerDocument.createDocumentFragment();
103
+ const ratio = layer.parentElement.getBoundingClientRect();
104
  for (const block of blocks || []) {
105
+ const text = String(block?.t || ""), b = block?.b;
106
+ if (!text || !Array.isArray(b) || b.length !== 4 || !b.every(Number.isFinite)) continue;
107
+ const [x1, y1, x2, y2] = b.map(normalizeBox);
108
+ const width = Math.abs(x2 - x1), height = Math.abs(y2 - y1);
109
+ if (!width || !height) continue;
110
+ fragment.appendChild(positionedRun(layer, text, Math.min(x1, x2), Math.min(y1, y2),
111
+ height * ratio.height / Math.max(1, ratio.width), width, "sans-serif"));
112
+ fragment.appendChild(layer.ownerDocument.createTextNode("\n"));
 
 
 
 
113
  }
114
  layer.replaceChildren(fragment);
115
  }
static/reader-resources.js CHANGED
@@ -62,6 +62,7 @@
62
  "reader-format-adapters.js",
63
  "reader-security.js",
64
  "reader-pdf-text.js",
 
65
  "pdf-worker-wrapper.mjs",
66
  "reader.css",
67
  "reader.js"
 
62
  "reader-format-adapters.js",
63
  "reader-security.js",
64
  "reader-pdf-text.js",
65
+ "reader-book-text.js",
66
  "pdf-worker-wrapper.mjs",
67
  "reader.css",
68
  "reader.js"
static/reader-security.js CHANGED
@@ -269,8 +269,13 @@
269
  const PDF_OCR_MANIFEST_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?ocr-manifest\.json$/;
270
  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)$/;
271
  const PDF_OCR_ROOT = /^(objects\/[0-9a-f]{2}\/[0-9a-f]{64}(?:\/[0-9a-f]{16})?)/;
 
 
 
272
  function validatePdfOcrManifest(manifest) {
273
  if (!manifest || manifest.version !== 1 || manifest.kind !== "pdf-ocr" ||
 
 
274
  !Number.isInteger(manifest.page_count) || manifest.page_count < 1 ||
275
  manifest.page_count > LIMITS.pdfPages || !Array.isArray(manifest.pages) ||
276
  manifest.pages.length !== manifest.page_count)
@@ -283,19 +288,24 @@
283
  page.o !== `${pageRoot}/ocr/page-${expected}.json.gz` ||
284
  (page.w !== undefined && (typeof page.w !== "string" || !PDF_OCR_PAGE_PATH.test(page.w) ||
285
  !page.w.endsWith(`/pages/page-${expected}.webp`) ||
286
- !page.w.startsWith(`${pageRoot}/pages/`))) ||
287
  (page.j !== undefined && (typeof page.j !== "string" || !PDF_OCR_PAGE_PATH.test(page.j) ||
288
  !page.j.endsWith(`/pages/page-${expected}.jxl`) ||
289
- !page.j.startsWith(`${pageRoot}/pages/`))) ||
290
- (root && root !== pageRoot))
 
291
  throw error("PDF_OCR_MANIFEST_INVALID");
292
  root = pageRoot;
293
  }
294
  if (!manifest.book_text || typeof manifest.book_text.path !== "string" ||
295
- !PDF_OCR_PATH.test(manifest.book_text.path) || manifest.book_text.path !== `${root}/ocr/book-text.json.gz` ||
 
 
 
296
  (manifest.page_manifest !== undefined &&
297
  (!manifest.page_manifest || typeof manifest.page_manifest.path !== "string" ||
298
- manifest.page_manifest.path !== `${root}/page-manifest.json`)))
 
299
  throw error("PDF_OCR_MANIFEST_INVALID");
300
  return manifest;
301
  }
 
269
  const PDF_OCR_MANIFEST_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?ocr-manifest\.json$/;
270
  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)$/;
271
  const PDF_OCR_ROOT = /^(objects\/[0-9a-f]{2}\/[0-9a-f]{64}(?:\/[0-9a-f]{16})?)/;
272
+ function pdfSourceRoot(path) {
273
+ return typeof path === "string" ? path.split("/").slice(0, 3).join("/") : "";
274
+ }
275
  function validatePdfOcrManifest(manifest) {
276
  if (!manifest || manifest.version !== 1 || manifest.kind !== "pdf-ocr" ||
277
+ manifest.complete !== true || !/^[0-9a-f]{64}$/.test(manifest.source_sha256 || "") ||
278
+ !String(manifest.profile || "").includes("-layout-v1-") ||
279
  !Number.isInteger(manifest.page_count) || manifest.page_count < 1 ||
280
  manifest.page_count > LIMITS.pdfPages || !Array.isArray(manifest.pages) ||
281
  manifest.pages.length !== manifest.page_count)
 
288
  page.o !== `${pageRoot}/ocr/page-${expected}.json.gz` ||
289
  (page.w !== undefined && (typeof page.w !== "string" || !PDF_OCR_PAGE_PATH.test(page.w) ||
290
  !page.w.endsWith(`/pages/page-${expected}.webp`) ||
291
+ pdfSourceRoot(page.w) !== pdfSourceRoot(pageRoot))) ||
292
  (page.j !== undefined && (typeof page.j !== "string" || !PDF_OCR_PAGE_PATH.test(page.j) ||
293
  !page.j.endsWith(`/pages/page-${expected}.jxl`) ||
294
+ pdfSourceRoot(page.j) !== pdfSourceRoot(pageRoot))) ||
295
+ pdfSourceRoot(pageRoot) !== `objects/${manifest.source_sha256.slice(0, 2)}/${manifest.source_sha256}` ||
296
+ (root && pdfSourceRoot(root) !== pdfSourceRoot(pageRoot)))
297
  throw error("PDF_OCR_MANIFEST_INVALID");
298
  root = pageRoot;
299
  }
300
  if (!manifest.book_text || typeof manifest.book_text.path !== "string" ||
301
+ !PDF_OCR_PATH.test(manifest.book_text.path) || !manifest.book_text.path.endsWith('/ocr/book-text.json.gz') ||
302
+ pdfSourceRoot(manifest.book_text.path) !== pdfSourceRoot(root) ||
303
+ !/^[0-9a-f]{64}$/.test(manifest.book_text.sha256 || "") ||
304
+ !Number.isSafeInteger(manifest.book_text.bytes) || manifest.book_text.bytes < 1 ||
305
  (manifest.page_manifest !== undefined &&
306
  (!manifest.page_manifest || typeof manifest.page_manifest.path !== "string" ||
307
+ !/^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?page-manifest\.json$/.test(manifest.page_manifest.path) ||
308
+ pdfSourceRoot(manifest.page_manifest.path) !== pdfSourceRoot(root))))
309
  throw error("PDF_OCR_MANIFEST_INVALID");
310
  return manifest;
311
  }
static/reader.css CHANGED
@@ -835,6 +835,7 @@ body {
835
  }
836
  .reader-page {
837
  position: relative;
 
838
  margin: 0 auto 18px;
839
  background: white;
840
  box-shadow: 0 2px 14px #0008;
@@ -873,18 +874,42 @@ body {
873
  white-space: pre;
874
  border: 0;
875
  color: transparent;
 
 
 
 
876
  }
877
- .reader-pdf-text span {
878
  position: absolute;
 
 
 
 
 
 
879
  color: transparent;
880
  white-space: pre;
881
- transform-origin: left bottom;
882
  user-select: text;
 
883
  cursor: text;
884
  }
885
- .reader-pdf-text span.full-search-highlight {
886
- color: #1d2023;
887
- background: #f0c75e;
 
 
 
 
 
 
 
 
 
 
 
 
 
888
  }
889
  .reader-image {
890
  display: block;
 
835
  }
836
  .reader-page {
837
  position: relative;
838
+ container-type: size;
839
  margin: 0 auto 18px;
840
  background: white;
841
  box-shadow: 0 2px 14px #0008;
 
874
  white-space: pre;
875
  border: 0;
876
  color: transparent;
877
+ z-index: 1;
878
+ line-height: 1;
879
+ text-size-adjust: none;
880
+ -webkit-text-size-adjust: none;
881
  }
882
+ .reader-pdf-text-position {
883
  position: absolute;
884
+ --reader-pdf-font-ratio: 1;
885
+ font-size: calc(var(--reader-pdf-font-ratio) * 100cqw);
886
+ transform-origin: left top;
887
+ }
888
+ .reader-pdf-text-run {
889
+ display: inline-block;
890
  color: transparent;
891
  white-space: pre;
892
+ transform-origin: left top;
893
  user-select: text;
894
+ -webkit-user-select: text;
895
  cursor: text;
896
  }
897
+ .reader-pdf-text-run::selection {
898
+ color: transparent;
899
+ background: #4285f466;
900
+ }
901
+ .reader-pdf-text-run.full-search-highlight {
902
+ color: transparent;
903
+ background: #f0c75e88;
904
+ }
905
+ .reader-pdf-text ::selection,
906
+ .reader-pdf-text-run::selection {
907
+ color: transparent;
908
+ background: #4285f466;
909
+ }
910
+ .reader-pdf-text mark.full-search-highlight {
911
+ color: transparent;
912
+ background: #f0c75e88;
913
  }
914
  .reader-image {
915
  display: block;
static/reader.js CHANGED
@@ -6,7 +6,8 @@ import "/static/reader-scroll-anchor.js";
6
  import "/static/reader-section-virtualizer.js";
7
  import "/static/reader-runtime.js";
8
  import "/static/reader-format-adapters.js";
9
- import { populatePdfTextLayer, populateOcrTextLayer } from "/static/reader-pdf-text.js";
 
10
  // Engines and Reader lifecycle.
11
  const PDFJS_URL = VoiceOfMLReaderResources.vendorUrl("pdf", "/static/");
12
  const PDFJS_WORKER_URL = "/static/pdf-worker-wrapper.mjs";
@@ -371,6 +372,14 @@ let pdfDocument = null;
371
  let pdfPageManifest = null;
372
  let pdfOcrManifest = null;
373
  let pdfOcrManifestPromise = null;
 
 
 
 
 
 
 
 
374
  let pdfActiveRenders = 0;
375
  let pdfShellsReady = Promise.resolve();
376
  const pdfRenderWaiters = [];
@@ -2777,7 +2786,7 @@ async function renderPdfText(page, shell) {
2777
  y: point ? Math.max(0, Math.min(1, point[1] / Math.max(1, pdfViewport.height))) : 0
2778
  };
2779
  });
2780
- populatePdfTextLayer(layer, text.items, pdfViewport);
2781
  shell.dataset.textReady = "1";
2782
  highlightPdfText(shell);
2783
  } catch (error) {
@@ -2787,21 +2796,28 @@ async function renderPdfText(page, shell) {
2787
  }
2788
  function highlightPdfText(shell, query = searchState.query) {
2789
  if (!shell || readerAbortController.signal.aborted || !query) return;
2790
- const pattern = new RegExp(fullSearchEscape(query), "iu");
2791
- const spans = [...shell.querySelectorAll(".reader-pdf-text span")];
2792
- let text = "";
2793
- const ranges = spans.map((span) => {
2794
- const start = text.length;
2795
- text += `${span.textContent || ""} `;
2796
- return { span, start, end: text.length };
2797
- });
2798
- const hit = text.search(pattern);
2799
- for (const { span, start, end } of ranges)
2800
- if (!span.classList.contains("full-search-highlight") &&
2801
- ((hit >= 0 && end > hit && start < hit + query.length) || pattern.test(span.textContent))) {
2802
- span.classList.add("full-search-highlight");
2803
- fullSearchActiveMarks.push(span);
2804
- }
 
 
 
 
 
 
 
2805
  }
2806
 
2807
  function acquirePdfRenderSlot(priority = false) {
@@ -2890,6 +2906,7 @@ function trimPdfCanvases(protectedShell) {
2890
  shell._bookmarkTextItems = [];
2891
  shell.dataset.textReady = "0";
2892
  shell.dataset.renderState = "idle";
 
2893
  }
2894
  }
2895
 
@@ -3566,6 +3583,7 @@ function disposeFormatResources(mode) {
3566
  pdfPageManifest = null;
3567
  pdfOcrManifest = null;
3568
  pdfOcrManifestPromise = null;
 
3569
  pdfFirstPagePreload?.removeAttribute("src");
3570
  pdfFirstPagePreload = null;
3571
  for (const canvas of content.querySelectorAll(".reader-page canvas")) {
@@ -4718,6 +4736,7 @@ fullSearchCancel.addEventListener("click", () => {
4718
  nextReaderGeneration("search");
4719
  beginReaderNavigation();
4720
  chapterSearchClient?.cancel();
 
4721
  chapterSearchPage = null;
4722
  updateSearchState({ results: [], index: -1 });
4723
  renderFullSearchResults();
@@ -4814,21 +4833,27 @@ function updateChapterSearchPagination() {
4814
  input.value = String(Math.floor(page.offset / page.pageSize) + 1);
4815
  input.max = String(Math.max(1, pages));
4816
  chapterSearchPagination.querySelector("#full-search-pages").textContent = `/ ${pages}`;
4817
- chapterSearchPagination.querySelector("#full-search-page-prev").disabled = page.offset === 0;
 
4818
  chapterSearchPagination.querySelector("#full-search-page-next").disabled =
4819
- page.offset + page.pageSize >= page.total;
 
4820
  }
4821
  async function loadChapterSearchPage(offset, selectLast = null) {
4822
- if (!chapterSearchPage || !chapterSearchClient) return;
4823
  const generation = nextReaderGeneration("search");
4824
  beginReaderNavigation();
4825
  fullSearchCancel.hidden = false;
4826
  fullSearchRetry.hidden = true;
4827
  fullSearchStatus.textContent = "正在加载搜索结果…";
4828
  try {
4829
- const page = await chapterSearchClient.page(offset);
 
4830
  if (!isReaderGenerationCurrent("search", generation)) return;
4831
- applyChapterSearchPage(page);
 
 
 
4832
  renderFullSearchResults();
4833
  fullSearchStatus.textContent = `${page.total} 个结果`;
4834
  if (selectLast !== null)
@@ -4872,6 +4897,7 @@ function fullSearchEscape(value) {
4872
  }
4873
  let fullSearchActiveMarks = [];
4874
  function clearFullSearchMarks() {
 
4875
  for (const mark of fullSearchActiveMarks) {
4876
  if (mark.tagName === "MARK") mark.replaceWith(mark.textContent);
4877
  else mark.classList.remove("full-search-highlight");
@@ -5091,35 +5117,103 @@ async function fullSearchPdfApiMatches(query, generation) {
5091
  });
5092
  }
5093
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5094
  async function fullSearchPdfMatches(query, generation) {
5095
  const pdf = pdfDocument,
5096
- output = [],
5097
- pattern = new RegExp(fullSearchEscape(query), "giu");
5098
- if (!pdf) return output;
5099
- for (let page = 1; page <= pdf.numPages && output.length < 100; page++) {
 
5100
  if (!isReaderGenerationCurrent("search", generation)) return [];
5101
  const pdfPage = await awaitReader(pdf.getPage(page));
5102
  if (!isReaderGenerationCurrent("search", generation)) return [];
5103
  const textContent = await awaitReader(pdfPage.getTextContent());
5104
  if (!isReaderGenerationCurrent("search", generation)) return [];
5105
- const text = textContent.items
5106
- .map((item) => item.str + (item.hasEOL ? "\n" : " "))
5107
- .join("")
5108
- .trim();
5109
- let matched = false;
5110
- for (const match of text.matchAll(pattern)) {
5111
- if (output.length >= 100) break;
5112
- matched = true;
5113
- output.push({
5114
- location: `第 ${page} 页`,
5115
- snippet: fullSearchSnippet(text, match.index, match[0].length),
5116
- activate: (navigationGeneration) => goToPage(page, navigationGeneration)
5117
- });
5118
- }
5119
- if (matched)
5120
  highlightPdfText(content.querySelector(`.reader-page[data-page="${page}"]`), query);
 
 
 
 
 
5121
  }
5122
- return output;
 
 
5123
  }
5124
  function renderFullSearchResults() {
5125
  updateChapterSearchPagination();
@@ -5146,9 +5240,11 @@ async function runFullSearch() {
5146
  clearFullSearchMarks();
5147
  updateSearchState({ query, results: [], index: -1 });
5148
  chapterSearchPage = null;
 
5149
  updateChapterSearchPagination();
5150
  fullSearchRetry.hidden = true;
5151
- fullSearchCancel.hidden = capability.mode !== "epub-chapters" || !query;
 
5152
  fullSearchResultsNode.textContent = "";
5153
  fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {
5154
  button.disabled = true;
@@ -5160,15 +5256,8 @@ async function runFullSearch() {
5160
  }
5161
  fullSearchStatus.textContent = "正在搜索正文…";
5162
  try {
5163
- if (capability.mode === "pdf-pages") {
5164
- try {
5165
- publishSearchResults(generation, await fullSearchPdfApiMatches(query, generation));
5166
- } catch (error) {
5167
- publishSearchResults(generation, await fullSearchPdfPageMatches(query, generation));
5168
- }
5169
- }
5170
- else if (capability.mode === "pdf")
5171
- publishSearchResults(generation, await fullSearchPdfMatches(query, generation));
5172
  else if (capability.mode === "foliate")
5173
  publishSearchResults(generation, await fullSearchFoliateMatches(query, generation));
5174
  else if (capability.mode === "epub-chapters") await searchChapterBook(query, generation);
@@ -5191,6 +5280,7 @@ async function runFullSearch() {
5191
  );
5192
  else throw new Error("此格式没有可搜索文本");
5193
  if (!isReaderGenerationCurrent("search", generation)) return;
 
5194
  renderFullSearchResults();
5195
  fullSearchStatus.textContent = chapterSearchPage
5196
  ? chapterSearchPage.total
@@ -5201,10 +5291,13 @@ async function runFullSearch() {
5201
  : "未找到正文匹配";
5202
  } catch (error) {
5203
  if (isReaderGenerationCurrent("search", generation)) {
 
5204
  fullSearchStatus.textContent = error.message || "正文搜索不可用";
5205
- fullSearchRetry.hidden = capability.mode !== "epub-chapters";
5206
  }
5207
  } finally {
 
 
5208
  if (isReaderGenerationCurrent("search", generation)) fullSearchCancel.hidden = true;
5209
  if (isReaderGenerationCurrent("search", generation))
5210
  fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {
@@ -5265,6 +5358,7 @@ function toggleFullSearch() {
5265
  beginReaderNavigation();
5266
  nextReaderGeneration("search");
5267
  chapterSearchClient?.cancel();
 
5268
  chapterSearchPage = null;
5269
  fullSearchCancel.hidden = true;
5270
  fullSearchRetry.hidden = true;
 
6
  import "/static/reader-section-virtualizer.js";
7
  import "/static/reader-runtime.js";
8
  import "/static/reader-format-adapters.js";
9
+ import { populatePdfTextLayer, populateOcrTextLayer, pdfTextContent, pdfSearchText } from "/static/reader-pdf-text.js";
10
+ import { validateBookText, searchBookText, createBookTextCache, paintTextHit } from "/static/reader-book-text.js";
11
  // Engines and Reader lifecycle.
12
  const PDFJS_URL = VoiceOfMLReaderResources.vendorUrl("pdf", "/static/");
13
  const PDFJS_WORKER_URL = "/static/pdf-worker-wrapper.mjs";
 
372
  let pdfPageManifest = null;
373
  let pdfOcrManifest = null;
374
  let pdfOcrManifestPromise = null;
375
+ const pdfBookTextCache = createBookTextCache(async () => {
376
+ const manifest = await loadPdfOcrManifest();
377
+ if (!manifest?.book_text?.path) throw new Error("本书集中全文尚未生成");
378
+ const book = await readPdfOcrJson(pdfOcrSource().assetUrl(manifest.book_text.path),
379
+ VoiceOfMLReaderSecurity.LIMITS.chapterTotalBytes, manifest.book_text.sha256, manifest.book_text.bytes);
380
+ return validateBookText(book, documentState.pageCount, manifest.source_sha256);
381
+ });
382
+ trackReaderResource(() => pdfBookTextCache.clear());
383
  let pdfActiveRenders = 0;
384
  let pdfShellsReady = Promise.resolve();
385
  const pdfRenderWaiters = [];
 
2786
  y: point ? Math.max(0, Math.min(1, point[1] / Math.max(1, pdfViewport.height))) : 0
2787
  };
2788
  });
2789
+ populatePdfTextLayer(layer, text.items, pdfViewport, text.styles);
2790
  shell.dataset.textReady = "1";
2791
  highlightPdfText(shell);
2792
  } catch (error) {
 
2796
  }
2797
  function highlightPdfText(shell, query = searchState.query) {
2798
  if (!shell || readerAbortController.signal.aborted || !query) return;
2799
+ const layer = shell.querySelector(".reader-pdf-text");
2800
+ if (!layer || layer.querySelector("mark")) return;
2801
+ const walker = document.createTreeWalker(layer, NodeFilter.SHOW_TEXT), runs = [];
2802
+ let raw = "";
2803
+ while (walker.nextNode()) {
2804
+ const node = walker.currentNode, start = raw.length;
2805
+ raw += node.data;
2806
+ runs.push({ node, start, end: raw.length });
2807
+ }
2808
+ const mapping = pdfSearchText(raw);
2809
+ const hits = [];
2810
+ for (const hit of mapping.text.matchAll(new RegExp(fullSearchEscape(pdfSearchText(query).text), "giu"))) {
2811
+ hits.push(hit);
2812
+ if (hits.length === 100) break;
2813
+ }
2814
+ // Bound highlights in the displayed page, without limiting searchable results.
2815
+ for (const hit of hits.reverse()) {
2816
+ const start = mapping.offsets[hit.index], end = mapping.offsets[hit.index + hit[0].length - 1] + 1;
2817
+ highlightTextParts(runs.filter((run) => run.end > start && run.start < end).map((run) => ({
2818
+ node: run.node, start: Math.max(start, run.start) - run.start, end: Math.min(end, run.end) - run.start
2819
+ })));
2820
+ }
2821
  }
2822
 
2823
  function acquirePdfRenderSlot(priority = false) {
 
2906
  shell._bookmarkTextItems = [];
2907
  shell.dataset.textReady = "0";
2908
  shell.dataset.renderState = "idle";
2909
+ fullSearchActiveMarks = fullSearchActiveMarks.filter((mark) => mark.isConnected);
2910
  }
2911
  }
2912
 
 
3583
  pdfPageManifest = null;
3584
  pdfOcrManifest = null;
3585
  pdfOcrManifestPromise = null;
3586
+ pdfBookTextCache.clear();
3587
  pdfFirstPagePreload?.removeAttribute("src");
3588
  pdfFirstPagePreload = null;
3589
  for (const canvas of content.querySelectorAll(".reader-page canvas")) {
 
4736
  nextReaderGeneration("search");
4737
  beginReaderNavigation();
4738
  chapterSearchClient?.cancel();
4739
+ pdfSearchInProgress = false;
4740
  chapterSearchPage = null;
4741
  updateSearchState({ results: [], index: -1 });
4742
  renderFullSearchResults();
 
4833
  input.value = String(Math.floor(page.offset / page.pageSize) + 1);
4834
  input.max = String(Math.max(1, pages));
4835
  chapterSearchPagination.querySelector("#full-search-pages").textContent = `/ ${pages}`;
4836
+ chapterSearchPagination.querySelector("#full-search-page-prev").disabled =
4837
+ pdfSearchInProgress || page.offset === 0;
4838
  chapterSearchPagination.querySelector("#full-search-page-next").disabled =
4839
+ pdfSearchInProgress || page.offset + page.pageSize >= page.total;
4840
+ input.disabled = pdfSearchInProgress;
4841
  }
4842
  async function loadChapterSearchPage(offset, selectLast = null) {
4843
+ if (!chapterSearchPage || (!chapterSearchClient && !pdfSearchPageLoader)) return;
4844
  const generation = nextReaderGeneration("search");
4845
  beginReaderNavigation();
4846
  fullSearchCancel.hidden = false;
4847
  fullSearchRetry.hidden = true;
4848
  fullSearchStatus.textContent = "正在加载搜索结果…";
4849
  try {
4850
+ const pdfLoader = pdfSearchPageLoader;
4851
+ const page = await (pdfLoader ? pdfLoader(offset) : chapterSearchClient.page(offset));
4852
  if (!isReaderGenerationCurrent("search", generation)) return;
4853
+ if (pdfLoader) {
4854
+ chapterSearchPage = page;
4855
+ updateSearchState({ results: page.results, index: -1 });
4856
+ } else applyChapterSearchPage(page);
4857
  renderFullSearchResults();
4858
  fullSearchStatus.textContent = `${page.total} 个结果`;
4859
  if (selectLast !== null)
 
4897
  }
4898
  let fullSearchActiveMarks = [];
4899
  function clearFullSearchMarks() {
4900
+ content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());
4901
  for (const mark of fullSearchActiveMarks) {
4902
  if (mark.tagName === "MARK") mark.replaceWith(mark.textContent);
4903
  else mark.classList.remove("full-search-highlight");
 
5117
  });
5118
  }
5119
 
5120
+ let pdfSearchPageLoader = null;
5121
+ let pdfSearchInProgress = false;
5122
+ async function searchConcentratedPdf(query, generation) {
5123
+ const book = await pdfBookTextCache.get();
5124
+ const index = await searchBookText(book, query, {
5125
+ current: () => isReaderGenerationCurrent("search", generation),
5126
+ yieldTask: () => waitForReader(0)
5127
+ });
5128
+ pdfSearchPageLoader = (offset) => {
5129
+ const page = index.page(offset);
5130
+ return { ...page, results: page.results.map(hit => ({
5131
+ ...hit, location: `第 ${hit.page} 页`, activate: async nav => {
5132
+ if (!await goToPage(hit.page, nav) || !isReaderGenerationCurrent("navigation", nav))
5133
+ return false;
5134
+ content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());
5135
+ const shell = content.querySelector(`.reader-page[data-page="${hit.page}"]`);
5136
+ if (shell && hit.boxes.length) {
5137
+ paintTextHit(shell, hit.boxes);
5138
+ shell.querySelector(".reader-text-hit-box")?.scrollIntoView({ block: "center" });
5139
+ }
5140
+ return true;
5141
+ }
5142
+ })) };
5143
+ };
5144
+ chapterSearchPage = pdfSearchPageLoader(0);
5145
+ return chapterSearchPage.results;
5146
+ }
5147
+
5148
+ function makePdfSearchPageLoader(groups, total, pattern) {
5149
+ return (requestedOffset) => {
5150
+ const pageSize = 50, results = [];
5151
+ const offset = Math.max(
5152
+ 0,
5153
+ Math.min(Math.floor(Math.max(0, total - 1) / pageSize) * pageSize, requestedOffset)
5154
+ );
5155
+ let skipped = 0;
5156
+ for (const group of groups) {
5157
+ if (skipped + group.count <= offset) {
5158
+ skipped += group.count;
5159
+ continue;
5160
+ }
5161
+ for (const match of group.text.matchAll(pattern)) {
5162
+ if (skipped++ < offset) continue;
5163
+ results.push({
5164
+ location: `第 ${group.page} 页`,
5165
+ snippet: fullSearchSnippet(group.text, match.index, match[0].length),
5166
+ activate: (navigationGeneration) => goToPage(group.page, navigationGeneration)
5167
+ });
5168
+ if (results.length === pageSize) break;
5169
+ }
5170
+ if (results.length === pageSize) break;
5171
+ }
5172
+ return { total, offset, pageSize, results };
5173
+ };
5174
+ }
5175
+
5176
+ function publishPdfSearchProgress(generation, groups, total, pattern, scanned, pages) {
5177
+ if (!isReaderGenerationCurrent("search", generation)) return false;
5178
+ pdfSearchPageLoader = makePdfSearchPageLoader(groups, total, pattern);
5179
+ chapterSearchPage = pdfSearchPageLoader(0);
5180
+ updateSearchState({ results: chapterSearchPage.results, index: -1 });
5181
+ renderFullSearchResults();
5182
+ fullSearchStatus.textContent = total
5183
+ ? `${total} 个结果(正在搜索… ${scanned} / ${pages} 页)`
5184
+ : `正在搜索正文… ${scanned} / ${pages} 页,暂未找到匹配`;
5185
+ return true;
5186
+ }
5187
+
5188
  async function fullSearchPdfMatches(query, generation) {
5189
  const pdf = pdfDocument,
5190
+ groups = [],
5191
+ pattern = new RegExp(fullSearchEscape(pdfSearchText(query).text), "giu");
5192
+ if (!pdf) return [];
5193
+ let total = 0, hasText = false;
5194
+ for (let page = 1; page <= pdf.numPages; page++) {
5195
  if (!isReaderGenerationCurrent("search", generation)) return [];
5196
  const pdfPage = await awaitReader(pdf.getPage(page));
5197
  if (!isReaderGenerationCurrent("search", generation)) return [];
5198
  const textContent = await awaitReader(pdfPage.getTextContent());
5199
  if (!isReaderGenerationCurrent("search", generation)) return [];
5200
+ const text = pdfSearchText(pdfTextContent(textContent.items)).text;
5201
+ hasText ||= !!text.trim();
5202
+ let count = 0;
5203
+ for (const match of text.matchAll(pattern)) count++;
5204
+ if (count) {
5205
+ groups.push({ page, text, count });
5206
+ total += count;
 
 
 
 
 
 
 
 
5207
  highlightPdfText(content.querySelector(`.reader-page[data-page="${page}"]`), query);
5208
+ }
5209
+ if (page === 1 || page % 8 === 0 || page === pdf.numPages) {
5210
+ if (!publishPdfSearchProgress(generation, groups, total, pattern, page, pdf.numPages)) return [];
5211
+ await waitForReader(0, true);
5212
+ }
5213
  }
5214
+ if (!hasText) throw new Error("此 PDF 尚无可搜索文字层,需要完成 OCR 后才能搜索正文");
5215
+ publishPdfSearchProgress(generation, groups, total, pattern, pdf.numPages, pdf.numPages);
5216
+ return chapterSearchPage.results;
5217
  }
5218
  function renderFullSearchResults() {
5219
  updateChapterSearchPagination();
 
5240
  clearFullSearchMarks();
5241
  updateSearchState({ query, results: [], index: -1 });
5242
  chapterSearchPage = null;
5243
+ pdfSearchPageLoader = null;
5244
  updateChapterSearchPagination();
5245
  fullSearchRetry.hidden = true;
5246
+ fullSearchCancel.hidden = !["epub-chapters", "pdf"].includes(capability.mode) || !query;
5247
+ pdfSearchInProgress = capability.mode === "pdf" && !!query;
5248
  fullSearchResultsNode.textContent = "";
5249
  fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {
5250
  button.disabled = true;
 
5256
  }
5257
  fullSearchStatus.textContent = "正在搜索正文…";
5258
  try {
5259
+ if (["pdf", "pdf-pages"].includes(capability.mode))
5260
+ publishSearchResults(generation, await searchConcentratedPdf(query, generation));
 
 
 
 
 
 
 
5261
  else if (capability.mode === "foliate")
5262
  publishSearchResults(generation, await fullSearchFoliateMatches(query, generation));
5263
  else if (capability.mode === "epub-chapters") await searchChapterBook(query, generation);
 
5280
  );
5281
  else throw new Error("此格式没有可搜索文本");
5282
  if (!isReaderGenerationCurrent("search", generation)) return;
5283
+ if (capability.mode === "pdf") pdfSearchInProgress = false;
5284
  renderFullSearchResults();
5285
  fullSearchStatus.textContent = chapterSearchPage
5286
  ? chapterSearchPage.total
 
5291
  : "未找到正文匹配";
5292
  } catch (error) {
5293
  if (isReaderGenerationCurrent("search", generation)) {
5294
+ if (capability.mode === "pdf") pdfSearchInProgress = false;
5295
  fullSearchStatus.textContent = error.message || "正文搜索不可用";
5296
+ fullSearchRetry.hidden = !["epub-chapters", "pdf"].includes(capability.mode);
5297
  }
5298
  } finally {
5299
+ if (isReaderGenerationCurrent("search", generation) && capability.mode === "pdf")
5300
+ pdfSearchInProgress = false;
5301
  if (isReaderGenerationCurrent("search", generation)) fullSearchCancel.hidden = true;
5302
  if (isReaderGenerationCurrent("search", generation))
5303
  fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {
 
5358
  beginReaderNavigation();
5359
  nextReaderGeneration("search");
5360
  chapterSearchClient?.cancel();
5361
+ pdfSearchInProgress = false;
5362
  chapterSearchPage = null;
5363
  fullSearchCancel.hidden = true;
5364
  fullSearchRetry.hidden = true;
tests/test_fastapi_endpoints.py CHANGED
@@ -50,10 +50,11 @@ class FastApiEndpointTests(unittest.TestCase):
50
  "pages": [{"p": 1, "o": root + "/ocr/page-000001.json.gz"},
51
  {"p": 2, "o": root + "/ocr/page-000002.json.gz"}],
52
  "book_text": {"path": book_path}}
53
- book = gzip.compress(json.dumps({"version": 1, "kind": "pdf-ocr-book-text", "pages": [
54
- {"page": 1, "text": "第一章 手机阅读"},
55
- {"page": 2, "text": "第二章 手机搜索"},
56
- ]}).encode())
 
57
 
58
  async def resource(path):
59
  return json.dumps(manifest).encode() if path == manifest_path else book
 
50
  "pages": [{"p": 1, "o": root + "/ocr/page-000001.json.gz"},
51
  {"p": 2, "o": root + "/ocr/page-000002.json.gz"}],
52
  "book_text": {"path": book_path}}
53
+ pages = [{"page": 1, "text": "第一章 手机阅读", "layout": {"offset_unit": "unicode-codepoint"}, "text_spans": []},
54
+ {"page": 2, "text": "第二章 手机搜索", "layout": {"offset_unit": "unicode-codepoint"}, "text_spans": []}]
55
+ book = gzip.compress(json.dumps({"version": 2, "kind": "pdf-book-text", "complete": True,
56
+ "offset_unit": "unicode-codepoint", "source_sha256": "a" * 64,
57
+ "page_count": 2, "pages": pages}).encode())
58
 
59
  async def resource(path):
60
  return json.dumps(manifest).encode() if path == manifest_path else book