vomebook commited on
Commit ·
d117afd
1
Parent(s): 9c3b322
Improve Reader search responsiveness and PDF outline loading
Browse files- static/reader-book-text.js +37 -4
- static/reader-chapter-search-worker.mjs +20 -14
- static/reader.js +17 -9
- tests/reader_test_selection.py +1 -0
- tests/test_reader_book_text.mjs +41 -0
- tests/test_reader_chapter_search.mjs +8 -1
- tests/test_reader_performance.py +12 -0
- tests/test_reader_refactor.py +44 -0
static/reader-book-text.js
CHANGED
|
@@ -33,33 +33,66 @@ function pattern(query) {
|
|
| 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
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
}
|
| 39 |
|
| 40 |
export async function searchBookText(book, query, { current = () => true, yieldTask = () => new Promise(r => setTimeout(r, 0)), progress = null } = {}) {
|
| 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 |
const indexResult = { get total() { return total; }, page(offset = 0, pageSize = 50) {
|
| 45 |
offset = Math.max(0, Math.min(Math.max(0, total - 1), Math.floor(offset)));
|
| 46 |
offset = Math.floor(offset / pageSize) * pageSize;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
const results = [];
|
| 48 |
let passed = 0;
|
| 49 |
for (let index = 0; index < counts.length && results.length < pageSize; index++) {
|
| 50 |
if (passed + counts[index] <= offset) { passed += counts[index]; continue; }
|
| 51 |
const page = book.pages[index];
|
|
|
|
| 52 |
for (const match of page.text.matchAll(re)) {
|
| 53 |
if (passed++ < offset) continue;
|
| 54 |
const begin = Math.max(0, match.index - 72), end = Math.min(page.text.length, match.index + match[0].length + 88);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
results.push({ page: page.page, start: match.index, length: match[0].length,
|
| 56 |
-
boxes:
|
| 57 |
snippet: { text: page.text.slice(begin, end), matchStart: match.index - begin,
|
| 58 |
matchLength: match[0].length, prefix: begin ? "…" : "", suffix: end < page.text.length ? "…" : "" } });
|
| 59 |
if (results.length === pageSize) break;
|
| 60 |
}
|
| 61 |
}
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
} };
|
| 64 |
for (let index = 0; index < book.pages.length; index++) {
|
| 65 |
if (!current()) throw new DOMException("Search cancelled", "AbortError");
|
|
|
|
| 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 hitBoxesAtOffsets(page, begin, end);
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
function hitBoxesAtOffsets(page, begin, end) {
|
| 40 |
+
const spans = page.text_spans || [], boxes = [];
|
| 41 |
+
let low = 0, high = spans.length;
|
| 42 |
+
while (low < high) {
|
| 43 |
+
const mid = (low + high) >> 1;
|
| 44 |
+
if (spans[mid].end <= begin) low = mid + 1;
|
| 45 |
+
else high = mid;
|
| 46 |
+
}
|
| 47 |
+
for (let index = low; index < spans.length && spans[index].start < end; index++) {
|
| 48 |
+
const span = spans[index];
|
| 49 |
+
boxes.push({ box: span.box, block: span.block, precision: span.precision || "block" });
|
| 50 |
+
}
|
| 51 |
+
return boxes;
|
| 52 |
}
|
| 53 |
|
| 54 |
export async function searchBookText(book, query, { current = () => true, yieldTask = () => new Promise(r => setTimeout(r, 0)), progress = null } = {}) {
|
| 55 |
const counts = [], re = pattern(query);
|
| 56 |
let total = 0;
|
| 57 |
if (!query) return { total: 0, page: () => ({ total: 0, offset: 0, pageSize: 50, results: [] }) };
|
| 58 |
+
const pageCache = new Map();
|
| 59 |
const indexResult = { get total() { return total; }, page(offset = 0, pageSize = 50) {
|
| 60 |
offset = Math.max(0, Math.min(Math.max(0, total - 1), Math.floor(offset)));
|
| 61 |
offset = Math.floor(offset / pageSize) * pageSize;
|
| 62 |
+
const key = `${offset}:${pageSize}`;
|
| 63 |
+
const cached = pageCache.get(key);
|
| 64 |
+
if (cached?.total === total) {
|
| 65 |
+
pageCache.delete(key);
|
| 66 |
+
pageCache.set(key, cached);
|
| 67 |
+
return cached;
|
| 68 |
+
}
|
| 69 |
const results = [];
|
| 70 |
let passed = 0;
|
| 71 |
for (let index = 0; index < counts.length && results.length < pageSize; index++) {
|
| 72 |
if (passed + counts[index] <= offset) { passed += counts[index]; continue; }
|
| 73 |
const page = book.pages[index];
|
| 74 |
+
let previousUnitEnd = 0, previousPointEnd = 0;
|
| 75 |
for (const match of page.text.matchAll(re)) {
|
| 76 |
if (passed++ < offset) continue;
|
| 77 |
const begin = Math.max(0, match.index - 72), end = Math.min(page.text.length, match.index + match[0].length + 88);
|
| 78 |
+
const pointStart = previousPointEnd + Array.from(page.text.slice(previousUnitEnd, match.index)).length;
|
| 79 |
+
const pointEnd = pointStart + Array.from(match[0]).length;
|
| 80 |
+
previousUnitEnd = match.index + match[0].length;
|
| 81 |
+
previousPointEnd = pointEnd;
|
| 82 |
results.push({ page: page.page, start: match.index, length: match[0].length,
|
| 83 |
+
boxes: hitBoxesAtOffsets(page, pointStart, pointEnd),
|
| 84 |
snippet: { text: page.text.slice(begin, end), matchStart: match.index - begin,
|
| 85 |
matchLength: match[0].length, prefix: begin ? "…" : "", suffix: end < page.text.length ? "…" : "" } });
|
| 86 |
if (results.length === pageSize) break;
|
| 87 |
}
|
| 88 |
}
|
| 89 |
+
const page = { total, offset, pageSize, results };
|
| 90 |
+
if (pageSize <= 50) {
|
| 91 |
+
pageCache.delete(key);
|
| 92 |
+
pageCache.set(key, page);
|
| 93 |
+
if (pageCache.size > 4) pageCache.delete(pageCache.keys().next().value);
|
| 94 |
+
}
|
| 95 |
+
return page;
|
| 96 |
} };
|
| 97 |
for (let index = 0; index < book.pages.length; index++) {
|
| 98 |
if (!current()) throw new DOMException("Search cancelled", "AbortError");
|
static/reader-chapter-search-worker.mjs
CHANGED
|
@@ -76,19 +76,32 @@ export async function scanText(text, query, visit, current = () => true, yieldWo
|
|
| 76 |
}
|
| 77 |
|
| 78 |
export async function countMatches(chapters, query, current, progress = null) {
|
| 79 |
-
const counts = [];
|
| 80 |
const yieldWork = cooperativeYield();
|
| 81 |
let total = 0;
|
| 82 |
for (const chapter of chapters) {
|
| 83 |
let count = 0;
|
| 84 |
-
await scanText(chapter.text, query, () => {
|
|
|
|
|
|
|
|
|
|
| 85 |
counts.push(count);
|
| 86 |
total += count;
|
| 87 |
if (progress && (counts.length === 1 || (count && total <= PAGE_SIZE) ||
|
| 88 |
counts.length % 8 === 0 || counts.length === chapters.length))
|
| 89 |
-
await progress({ counts, total, scanned: counts.length });
|
| 90 |
}
|
| 91 |
-
return { counts, total };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
}
|
| 93 |
|
| 94 |
export async function resultPage(chapters, query, counts, offset, current) {
|
|
@@ -101,13 +114,7 @@ export async function resultPage(chapters, query, counts, offset, current) {
|
|
| 101 |
const chapter = chapters[i];
|
| 102 |
await scanText(chapter.text, query, (start, length) => {
|
| 103 |
if (skip) { skip--; return; }
|
| 104 |
-
|
| 105 |
-
results.push({
|
| 106 |
-
chapterIndex: chapter.index, start, length,
|
| 107 |
-
location: `第 ${chapter.index} 章 · ${chapter.title}`,
|
| 108 |
-
snippet: { text: chapter.text.slice(before, after), matchStart: start - before,
|
| 109 |
-
matchLength: length, prefix: before ? "…" : "", suffix: after < chapter.text.length ? "…" : "" }
|
| 110 |
-
});
|
| 111 |
return results.length < PAGE_SIZE;
|
| 112 |
}, current, yieldWork);
|
| 113 |
}
|
|
@@ -164,10 +171,9 @@ if (typeof self !== "undefined" && typeof self.postMessage === "function") {
|
|
| 164 |
if (!current()) return;
|
| 165 |
const counts = await countMatches(book, query, current, async partial => {
|
| 166 |
if (!current()) return;
|
| 167 |
-
const results = await resultPage(book.slice(0, partial.scanned), query, partial.counts, 0, current);
|
| 168 |
if (current()) self.postMessage({ id: data.id, progress: true,
|
| 169 |
total: partial.total, scanned: partial.scanned, chapters: book.length,
|
| 170 |
-
offset: 0, pageSize: PAGE_SIZE, results });
|
| 171 |
});
|
| 172 |
session = { ...counts, query, id: data.id };
|
| 173 |
} else if (data.type === "page") {
|
|
@@ -175,7 +181,7 @@ if (typeof self !== "undefined" && typeof self.postMessage === "function") {
|
|
| 175 |
offset = Math.max(0, Math.min(Math.floor(data.offset / PAGE_SIZE) * PAGE_SIZE,
|
| 176 |
Math.max(0, Math.ceil(session.total / PAGE_SIZE) - 1) * PAGE_SIZE));
|
| 177 |
} else return;
|
| 178 |
-
const result = await resultPage(chapters, session.query, session.counts, offset, current);
|
| 179 |
if (current()) self.postMessage({ id: data.id, session: session.id, total: session.total,
|
| 180 |
offset, pageSize: PAGE_SIZE, results: result });
|
| 181 |
} catch (error) {
|
|
|
|
| 76 |
}
|
| 77 |
|
| 78 |
export async function countMatches(chapters, query, current, progress = null) {
|
| 79 |
+
const counts = [], firstPage = [];
|
| 80 |
const yieldWork = cooperativeYield();
|
| 81 |
let total = 0;
|
| 82 |
for (const chapter of chapters) {
|
| 83 |
let count = 0;
|
| 84 |
+
await scanText(chapter.text, query, (start, length) => {
|
| 85 |
+
count++;
|
| 86 |
+
if (firstPage.length < PAGE_SIZE) firstPage.push(searchResult(chapter, start, length));
|
| 87 |
+
}, current, yieldWork);
|
| 88 |
counts.push(count);
|
| 89 |
total += count;
|
| 90 |
if (progress && (counts.length === 1 || (count && total <= PAGE_SIZE) ||
|
| 91 |
counts.length % 8 === 0 || counts.length === chapters.length))
|
| 92 |
+
await progress({ counts, total, scanned: counts.length, firstPage });
|
| 93 |
}
|
| 94 |
+
return { counts, total, firstPage };
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
function searchResult(chapter, start, length) {
|
| 98 |
+
const before = Math.max(0, start - 72), after = Math.min(chapter.text.length, start + length + 88);
|
| 99 |
+
return {
|
| 100 |
+
chapterIndex: chapter.index, start, length,
|
| 101 |
+
location: `第 ${chapter.index} 章 · ${chapter.title}`,
|
| 102 |
+
snippet: { text: chapter.text.slice(before, after), matchStart: start - before,
|
| 103 |
+
matchLength: length, prefix: before ? "…" : "", suffix: after < chapter.text.length ? "…" : "" }
|
| 104 |
+
};
|
| 105 |
}
|
| 106 |
|
| 107 |
export async function resultPage(chapters, query, counts, offset, current) {
|
|
|
|
| 114 |
const chapter = chapters[i];
|
| 115 |
await scanText(chapter.text, query, (start, length) => {
|
| 116 |
if (skip) { skip--; return; }
|
| 117 |
+
results.push(searchResult(chapter, start, length));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
return results.length < PAGE_SIZE;
|
| 119 |
}, current, yieldWork);
|
| 120 |
}
|
|
|
|
| 171 |
if (!current()) return;
|
| 172 |
const counts = await countMatches(book, query, current, async partial => {
|
| 173 |
if (!current()) return;
|
|
|
|
| 174 |
if (current()) self.postMessage({ id: data.id, progress: true,
|
| 175 |
total: partial.total, scanned: partial.scanned, chapters: book.length,
|
| 176 |
+
offset: 0, pageSize: PAGE_SIZE, results: partial.firstPage.slice() });
|
| 177 |
});
|
| 178 |
session = { ...counts, query, id: data.id };
|
| 179 |
} else if (data.type === "page") {
|
|
|
|
| 181 |
offset = Math.max(0, Math.min(Math.floor(data.offset / PAGE_SIZE) * PAGE_SIZE,
|
| 182 |
Math.max(0, Math.ceil(session.total / PAGE_SIZE) - 1) * PAGE_SIZE));
|
| 183 |
} else return;
|
| 184 |
+
const result = offset ? await resultPage(chapters, session.query, session.counts, offset, current) : session.firstPage.slice();
|
| 185 |
if (current()) self.postMessage({ id: data.id, session: session.id, total: session.total,
|
| 186 |
offset, pageSize: PAGE_SIZE, results: result });
|
| 187 |
} catch (error) {
|
static/reader.js
CHANGED
|
@@ -2821,10 +2821,10 @@ async function renderPdf(prepared) {
|
|
| 2821 |
content.appendChild(firstShell);
|
| 2822 |
await renderPdfShell(firstShell, false, true);
|
| 2823 |
pdfShellsReady = appendShellsBatched(createShell, pdf.numPages, 24);
|
| 2824 |
-
|
| 2825 |
-
|
| 2826 |
try {
|
| 2827 |
-
const outline = await pdf.getOutline(),
|
| 2828 |
entries = [];
|
| 2829 |
const cleanLabel = (value) =>
|
| 2830 |
String(value || "未命名章节")
|
|
@@ -2851,12 +2851,14 @@ async function renderPdf(prepared) {
|
|
| 2851 |
};
|
| 2852 |
await append(outline);
|
| 2853 |
assertReaderActive();
|
| 2854 |
-
setToc(entries);
|
| 2855 |
} catch (error) {
|
| 2856 |
if (!readerAbortController.signal.aborted)
|
| 2857 |
console.warn("PDF outline could not be loaded", error);
|
| 2858 |
}
|
| 2859 |
-
}
|
|
|
|
|
|
|
| 2860 |
assertReaderActive();
|
| 2861 |
}
|
| 2862 |
|
|
@@ -5579,10 +5581,14 @@ let pdfSearchPageLoader = null;
|
|
| 5579 |
let pdfSearchInProgress = false;
|
| 5580 |
async function searchConcentratedPdf(query, generation) {
|
| 5581 |
const book = await pdfBookTextCache.get();
|
|
|
|
| 5582 |
const install = (index) => { pdfSearchPageLoader = (offset) => {
|
| 5583 |
const page = index.page(offset);
|
| 5584 |
-
|
| 5585 |
-
|
|
|
|
|
|
|
|
|
|
| 5586 |
if (!await goToPage(hit.page, nav) || !isReaderGenerationCurrent("navigation", nav))
|
| 5587 |
return false;
|
| 5588 |
content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());
|
|
@@ -5592,8 +5598,10 @@ async function searchConcentratedPdf(query, generation) {
|
|
| 5592 |
shell.querySelector(".reader-text-hit-box")?.scrollIntoView({ block: "center" });
|
| 5593 |
}
|
| 5594 |
return true;
|
| 5595 |
-
}
|
| 5596 |
-
})
|
|
|
|
|
|
|
| 5597 |
}; };
|
| 5598 |
const index = await searchBookText(book, query, {
|
| 5599 |
current: () => isReaderGenerationCurrent("search", generation),
|
|
|
|
| 2821 |
content.appendChild(firstShell);
|
| 2822 |
await renderPdfShell(firstShell, false, true);
|
| 2823 |
pdfShellsReady = appendShellsBatched(createShell, pdf.numPages, 24);
|
| 2824 |
+
const outlineReady = (async () => {
|
| 2825 |
+
if (typeof pdf.getOutline !== "function") return;
|
| 2826 |
try {
|
| 2827 |
+
const outline = await awaitReader(pdf.getOutline()),
|
| 2828 |
entries = [];
|
| 2829 |
const cleanLabel = (value) =>
|
| 2830 |
String(value || "未命名章节")
|
|
|
|
| 2851 |
};
|
| 2852 |
await append(outline);
|
| 2853 |
assertReaderActive();
|
| 2854 |
+
if (entries.length) setToc(entries);
|
| 2855 |
} catch (error) {
|
| 2856 |
if (!readerAbortController.signal.aborted)
|
| 2857 |
console.warn("PDF outline could not be loaded", error);
|
| 2858 |
}
|
| 2859 |
+
})();
|
| 2860 |
+
outlineReady.catch(() => {});
|
| 2861 |
+
await pdfShellsReady;
|
| 2862 |
assertReaderActive();
|
| 2863 |
}
|
| 2864 |
|
|
|
|
| 5581 |
let pdfSearchInProgress = false;
|
| 5582 |
async function searchConcentratedPdf(query, generation) {
|
| 5583 |
const book = await pdfBookTextCache.get();
|
| 5584 |
+
let firstPageResults = [];
|
| 5585 |
const install = (index) => { pdfSearchPageLoader = (offset) => {
|
| 5586 |
const page = index.page(offset);
|
| 5587 |
+
const results = page.results.map((hit, position) => {
|
| 5588 |
+
const previous = page.offset === 0 ? firstPageResults[position] : null;
|
| 5589 |
+
if (previous?.page === hit.page && previous.start === hit.start && previous.length === hit.length)
|
| 5590 |
+
return previous;
|
| 5591 |
+
return { ...hit, location: `第 ${hit.page} 页`, activate: async nav => {
|
| 5592 |
if (!await goToPage(hit.page, nav) || !isReaderGenerationCurrent("navigation", nav))
|
| 5593 |
return false;
|
| 5594 |
content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());
|
|
|
|
| 5598 |
shell.querySelector(".reader-text-hit-box")?.scrollIntoView({ block: "center" });
|
| 5599 |
}
|
| 5600 |
return true;
|
| 5601 |
+
} };
|
| 5602 |
+
});
|
| 5603 |
+
if (page.offset === 0) firstPageResults = results;
|
| 5604 |
+
return { ...page, results };
|
| 5605 |
}; };
|
| 5606 |
const index = await searchBookText(book, query, {
|
| 5607 |
current: () => isReaderGenerationCurrent("search", generation),
|
tests/reader_test_selection.py
CHANGED
|
@@ -84,6 +84,7 @@ CATEGORY_METHODS = {
|
|
| 84 |
"test_reader_starts_with_session_metadata_before_document_load",
|
| 85 |
"test_id_only_reader_falls_back_to_session_source_when_resolve_fails",
|
| 86 |
"test_document_preparation_overlaps_delayed_history_restore",
|
|
|
|
| 87 |
"test_bfcache_pageshow_waits_for_restoration_gate",
|
| 88 |
"test_pagehide_before_restoration_does_not_overwrite_progress",
|
| 89 |
"test_pdf_disposal_destroys_loading_task_and_cancels_render_queue",
|
|
|
|
| 84 |
"test_reader_starts_with_session_metadata_before_document_load",
|
| 85 |
"test_id_only_reader_falls_back_to_session_source_when_resolve_fails",
|
| 86 |
"test_document_preparation_overlaps_delayed_history_restore",
|
| 87 |
+
"test_pdf_outline_does_not_delay_ready",
|
| 88 |
"test_bfcache_pageshow_waits_for_restoration_gate",
|
| 89 |
"test_pagehide_before_restoration_does_not_overwrite_progress",
|
| 90 |
"test_pdf_disposal_destroys_loading_task_and_cancels_render_queue",
|
tests/test_reader_book_text.mjs
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import { hitBoxes, searchBookText } from "../static/reader-book-text.js";
|
| 3 |
+
|
| 4 |
+
const spans = [
|
| 5 |
+
{ start: 0, end: 1, box: [0, 0, 0.2, 1], block: 0 },
|
| 6 |
+
{ start: 1, end: 4, box: [0.2, 0, 0.6, 1], block: 1 },
|
| 7 |
+
{ start: 4, end: 9, box: [0.6, 0, 1, 1], block: 2 }
|
| 8 |
+
];
|
| 9 |
+
const first = { page: 1, text: "😀abcneedle", text_spans: spans };
|
| 10 |
+
assert.deepEqual(hitBoxes(first, 2, 3).map(hit => hit.block), [1]);
|
| 11 |
+
assert.deepEqual(hitBoxes(first, 5, 6).map(hit => hit.block), [2]);
|
| 12 |
+
|
| 13 |
+
const pages = [first, ...Array.from({ length: 5 }, (_, index) => ({
|
| 14 |
+
page: index + 2, text: "needle ".repeat(61), text_spans: []
|
| 15 |
+
}))];
|
| 16 |
+
let partial;
|
| 17 |
+
const index = await searchBookText({ pages }, "needle", {
|
| 18 |
+
yieldTask: async () => {},
|
| 19 |
+
progress: (value, scanned) => {
|
| 20 |
+
if (scanned === 1) partial = value.page(0);
|
| 21 |
+
}
|
| 22 |
+
});
|
| 23 |
+
assert.equal(partial.total, 1);
|
| 24 |
+
assert.equal(index.total, 306);
|
| 25 |
+
const deep = index.page(250);
|
| 26 |
+
assert.equal(deep.results.length, 50);
|
| 27 |
+
assert.equal(deep.results[0].page, 6);
|
| 28 |
+
assert.equal(index.page(250), deep);
|
| 29 |
+
assert.notEqual(index.page(0).total, partial.total);
|
| 30 |
+
assert.equal(index.page(0).results[0].boxes[0].block, 2);
|
| 31 |
+
|
| 32 |
+
const unicodePage = { page: 1, text: "😀needle ".repeat(110), text_spans: Array.from({ length: 110 }, (_, block) => ({
|
| 33 |
+
start: block * 8 + 1, end: block * 8 + 7, box: [0, 0, 1, 1], block
|
| 34 |
+
})) };
|
| 35 |
+
const unicodeIndex = await searchBookText({ pages: [unicodePage] }, "needle", { yieldTask: async () => {} });
|
| 36 |
+
for (const offset of [0, 50, 100]) {
|
| 37 |
+
const result = unicodeIndex.page(offset);
|
| 38 |
+
assert.equal(result.results[0].boxes[0].block, offset);
|
| 39 |
+
assert.equal(result.results.at(-1).boxes[0].block, Math.min(offset + 49, 109));
|
| 40 |
+
}
|
| 41 |
+
console.log("reader book text search contracts passed");
|
tests/test_reader_chapter_search.mjs
CHANGED
|
@@ -5,9 +5,16 @@ const chapters = [
|
|
| 5 |
{ index: 1, title: "开头", path: "chapters/1.xhtml", text: "手机 手。机 a+b [term] " + "needle ".repeat(125) },
|
| 6 |
{ index: 2, title: "结尾", path: "chapters/2.xhtml", text: "needle ".repeat(130) + "远方命中" }
|
| 7 |
];
|
| 8 |
-
const
|
|
|
|
|
|
|
|
|
|
| 9 |
assert.equal(counted.total, 255);
|
| 10 |
assert.deepEqual(counted.counts, [125, 130]);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
const all = [];
|
| 12 |
for (let offset = 0; offset < counted.total; offset += 50) {
|
| 13 |
const page = await resultPage(chapters, "needle", counted.counts, offset, () => true);
|
|
|
|
| 5 |
{ index: 1, title: "开头", path: "chapters/1.xhtml", text: "手机 手。机 a+b [term] " + "needle ".repeat(125) },
|
| 6 |
{ index: 2, title: "结尾", path: "chapters/2.xhtml", text: "needle ".repeat(130) + "远方命中" }
|
| 7 |
];
|
| 8 |
+
const progressPages = [];
|
| 9 |
+
const counted = await countMatches(chapters, "needle", () => true, partial => {
|
| 10 |
+
progressPages.push({ total: partial.total, results: partial.firstPage.slice() });
|
| 11 |
+
});
|
| 12 |
assert.equal(counted.total, 255);
|
| 13 |
assert.deepEqual(counted.counts, [125, 130]);
|
| 14 |
+
assert.equal(progressPages[0].total, 125);
|
| 15 |
+
assert.equal(progressPages[0].results.length, 50);
|
| 16 |
+
assert.equal(progressPages.at(-1).total, 255);
|
| 17 |
+
assert.deepEqual(counted.firstPage, await resultPage(chapters, "needle", counted.counts, 0, () => true));
|
| 18 |
const all = [];
|
| 19 |
for (let offset = 0; offset < counted.total; offset += 50) {
|
| 20 |
const page = await resultPage(chapters, "needle", counted.counts, offset, () => true);
|
tests/test_reader_performance.py
CHANGED
|
@@ -1257,6 +1257,18 @@ class ReaderPerformanceTest(unittest.TestCase):
|
|
| 1257 |
source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/toc.{extension}"; page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext={extension}&title=TOC", wait_until="domcontentloaded"); page.locator("#history").click(); page.locator("#toc-list .panel-item-main").nth(1).click()
|
| 1258 |
page.wait_for_function("() => document.querySelector('iframe') ? document.querySelector('iframe').contentWindow.scrollY > 0 : document.querySelector('#viewport').scrollTop > 0"); context.close()
|
| 1259 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1260 |
def test_pdf_outline_click_navigates_to_declared_page(self):
|
| 1261 |
self.page.add_init_script("window.__pdfOutlineEnabled = true")
|
| 1262 |
module = PDF_MODULE.replace("[{title: '第一章', dest: [{}], items: []}]", "[{title: '第三章', dest: [{}], items: []}]").replace("getPageIndex: () => Promise.resolve(0)", "getPageIndex: () => Promise.resolve(2)"); self.page.unroute("**/static/vendor/pdf.min.*.mjs"); self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route, _request, module=module: route.fulfill(status=200, content_type="text/javascript", body=module)); self.open_pdf(); self.page.locator("#history").click(); self.page.locator("#toc-list .panel-item-main").click(); self.page.wait_for_function("() => document.querySelector('#page-number').value === '3'")
|
|
|
|
| 1257 |
source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/toc.{extension}"; page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext={extension}&title=TOC", wait_until="domcontentloaded"); page.locator("#history").click(); page.locator("#toc-list .panel-item-main").nth(1).click()
|
| 1258 |
page.wait_for_function("() => document.querySelector('iframe') ? document.querySelector('iframe').contentWindow.scrollY > 0 : document.querySelector('#viewport').scrollTop > 0"); context.close()
|
| 1259 |
|
| 1260 |
+
def test_pdf_outline_does_not_delay_ready(self):
|
| 1261 |
+
module = PDF_MODULE.replace("getOutline: () => Promise.resolve(window.__pdfOutlineEnabled ? [{title: '第一章', dest: [{}], items: []}] : null)",
|
| 1262 |
+
"getOutline: () => new Promise(resolve => { window.__releaseOutline = () => resolve([{title: '第一章', dest: [{}], items: []}]); })")
|
| 1263 |
+
self.page.unroute("**/static/vendor/pdf.min.*.mjs")
|
| 1264 |
+
self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(content_type="text/javascript", body=module))
|
| 1265 |
+
self.open_pdf()
|
| 1266 |
+
self.page.locator("html[data-reader-phase='ready']").wait_for()
|
| 1267 |
+
self.page.locator(".reader-page canvas.ready").first.wait_for()
|
| 1268 |
+
self.assertEqual(self.page.locator("#toc-list .toc-item").count(), 0)
|
| 1269 |
+
self.page.evaluate("window.__releaseOutline()")
|
| 1270 |
+
self.page.locator("#toc-list .toc-item").first.wait_for(state="attached")
|
| 1271 |
+
|
| 1272 |
def test_pdf_outline_click_navigates_to_declared_page(self):
|
| 1273 |
self.page.add_init_script("window.__pdfOutlineEnabled = true")
|
| 1274 |
module = PDF_MODULE.replace("[{title: '第一章', dest: [{}], items: []}]", "[{title: '第三章', dest: [{}], items: []}]").replace("getPageIndex: () => Promise.resolve(0)", "getPageIndex: () => Promise.resolve(2)"); self.page.unroute("**/static/vendor/pdf.min.*.mjs"); self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route, _request, module=module: route.fulfill(status=200, content_type="text/javascript", body=module)); self.open_pdf(); self.page.locator("#history").click(); self.page.locator("#toc-list .panel-item-main").click(); self.page.wait_for_function("() => document.querySelector('#page-number').value === '3'")
|
tests/test_reader_refactor.py
CHANGED
|
@@ -723,6 +723,50 @@ class ReaderRefactorTest(unittest.TestCase):
|
|
| 723 |
self.assertEqual(self.page.locator(".full-search-result").count(), 1)
|
| 724 |
self.assertEqual(requests, [manifest_path, book_path])
|
| 725 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 726 |
def test_media_proxy_failure_retries_original_once(self):
|
| 727 |
buffer = io.BytesIO()
|
| 728 |
with wave.open(buffer, 'wb') as audio:
|
|
|
|
| 723 |
self.assertEqual(self.page.locator(".full-search-result").count(), 1)
|
| 724 |
self.assertEqual(requests, [manifest_path, book_path])
|
| 725 |
|
| 726 |
+
def test_pdf_ocr_progress_preserves_full_first_page_and_focus(self):
|
| 727 |
+
def pause_after_first_page(route):
|
| 728 |
+
response = route.fetch()
|
| 729 |
+
needle = "yieldTask: () => waitForReader(0),"
|
| 730 |
+
script = response.text()
|
| 731 |
+
self.assertIn(needle, script)
|
| 732 |
+
route.fulfill(response=response, body=script.replace(needle,
|
| 733 |
+
"yieldTask: () => window.__holdOcrScan ? new Promise(resolve => { "
|
| 734 |
+
"window.__releaseOcrScan = () => { window.__holdOcrScan = false; resolve(); }; "
|
| 735 |
+
"}) : waitForReader(0),"))
|
| 736 |
+
self.page.route("**/static/reader.js?*", pause_after_first_page)
|
| 737 |
+
self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
|
| 738 |
+
content_type="text/javascript", body=support.PDF_MODULE.replace("numPages: 30", "numPages: 3")))
|
| 739 |
+
root = "objects/aa/" + "a" * 64 + "/" + "b" * 16
|
| 740 |
+
manifest_path = root + "/ocr-manifest.json"
|
| 741 |
+
book_path = root + "/ocr/book-text.json.gz"
|
| 742 |
+
texts = ["needle " * 60, "needle", "end"]
|
| 743 |
+
book = gzip.compress(json.dumps({"version": 2, "kind": "pdf-book-text", "complete": True,
|
| 744 |
+
"offset_unit": "unicode-codepoint", "source_sha256": "a" * 64, "page_count": 3,
|
| 745 |
+
"pages": [{"page": i + 1, "text": text, "layout": {"offset_unit": "unicode-codepoint"},
|
| 746 |
+
"text_spans": []} for i, text in enumerate(texts)]}).encode())
|
| 747 |
+
manifest = {"version": 1, "kind": "pdf-ocr", "complete": True,
|
| 748 |
+
"source_sha256": "a" * 64, "profile": "test-layout-v1-index", "page_count": 3,
|
| 749 |
+
"pages": [{"p": i + 1, "o": root + f"/ocr/page-{i + 1:06d}.json.gz"} for i in range(3)],
|
| 750 |
+
"book_text": {"path": book_path, "bytes": len(book), "sha256": hashlib.sha256(book).hexdigest()}}
|
| 751 |
+
def resource(route):
|
| 752 |
+
path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
|
| 753 |
+
if path == manifest_path:
|
| 754 |
+
route.fulfill(json=manifest)
|
| 755 |
+
elif path == book_path:
|
| 756 |
+
route.fulfill(content_type="application/gzip", body=book)
|
| 757 |
+
else:
|
| 758 |
+
route.fulfill(status=404)
|
| 759 |
+
self.page.route("**/api/reader-bucket-resource**", resource)
|
| 760 |
+
self.open(self.reader_url("pdf", ocr_manifest=self.origin + "/api/reader-bucket-resource?path=" + manifest_path))
|
| 761 |
+
self.page.locator("#history").click()
|
| 762 |
+
self.page.locator("#full-search-toggle").click()
|
| 763 |
+
self.page.evaluate("window.__holdOcrScan = true")
|
| 764 |
+
self.page.locator("#full-search-input").fill("needle")
|
| 765 |
+
self.page.wait_for_function("() => !!window.__releaseOcrScan && document.querySelectorAll('.full-search-result').length === 50")
|
| 766 |
+
self.page.evaluate("() => { window.__firstOcrRow = document.querySelector('.full-search-result'); __firstOcrRow.focus(); window.__releaseOcrScan(); }")
|
| 767 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '61 个结果'")
|
| 768 |
+
self.assertTrue(self.page.evaluate("() => document.querySelector('.full-search-result') === window.__firstOcrRow && document.activeElement === window.__firstOcrRow"))
|
| 769 |
+
|
| 770 |
def test_media_proxy_failure_retries_original_once(self):
|
| 771 |
buffer = io.BytesIO()
|
| 772 |
with wave.open(buffer, 'wb') as audio:
|