vomebook commited on
Commit ยท
74afd5e
1
Parent(s): cef0553
perf: optimize search indexes and response paths
Browse files- .gitignore +1 -0
- Dockerfile +10 -0
- app.py +112 -45
- reader_assets.py +11 -0
- record_metadata.py +4 -1
- scripts/build_search_index_native.py +20 -0
- search_execution.py +8 -1
- search_index_native.c +121 -0
- search_indexes.py +18 -8
- static/app.js +62 -14
- static/reader-contract.js +5 -1
- static/reader.css +7 -0
- static/reader.js +193 -24
- tests/test_api_contract.py +17 -0
- tests/test_cache_and_malformed.py +36 -2
- tests/test_native_search_indexes.py +68 -0
- tests/test_paging_recovery.py +27 -0
- tests/test_reader_architecture.js +1 -1
- tests/test_reader_backend.py +131 -0
- tests/test_reader_index_warming.py +41 -3
- tests/test_reader_pdf_hybrid.py +280 -0
- tests/test_search.py +25 -0
- tests/test_search_execution.py +34 -0
.gitignore
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
__pycache__/
|
| 2 |
*.py[cod]
|
|
|
|
| 3 |
static/vendor/
|
| 4 |
tests/__pycache__/
|
| 5 |
tests/benchmark-results.json
|
|
|
|
| 1 |
__pycache__/
|
| 2 |
*.py[cod]
|
| 3 |
+
_search_index_native*.so
|
| 4 |
static/vendor/
|
| 5 |
tests/__pycache__/
|
| 6 |
tests/benchmark-results.json
|
Dockerfile
CHANGED
|
@@ -29,6 +29,15 @@ RUN mkdir -p /out \
|
|
| 29 |
&& mv /out/sw.min.js /out/sw.js
|
| 30 |
RUN node /build/check_reader_release.mjs --project hf --root /build --artifact-root /out
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
FROM python:3.11-slim
|
| 33 |
|
| 34 |
WORKDIR /app
|
|
@@ -41,6 +50,7 @@ COPY requirements.txt .
|
|
| 41 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 42 |
|
| 43 |
COPY app.py data_formats.py proxy_streams.py record_metadata.py upstream_http.py search_execution.py search_indexes.py reader_assets.py .
|
|
|
|
| 44 |
COPY --from=static-assets /out/ static/
|
| 45 |
COPY data/ data/
|
| 46 |
COPY txt/ txt/
|
|
|
|
| 29 |
&& mv /out/sw.min.js /out/sw.js
|
| 30 |
RUN node /build/check_reader_release.mjs --project hf --root /build --artifact-root /out
|
| 31 |
|
| 32 |
+
FROM python:3.11-slim AS search-index-build
|
| 33 |
+
|
| 34 |
+
WORKDIR /build
|
| 35 |
+
RUN apt-get update && apt-get install -y --no-install-recommends gcc libc6-dev \
|
| 36 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 37 |
+
COPY search_index_native.c .
|
| 38 |
+
COPY scripts/build_search_index_native.py scripts/build_search_index_native.py
|
| 39 |
+
RUN python scripts/build_search_index_native.py --output-dir /native
|
| 40 |
+
|
| 41 |
FROM python:3.11-slim
|
| 42 |
|
| 43 |
WORKDIR /app
|
|
|
|
| 50 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 51 |
|
| 52 |
COPY app.py data_formats.py proxy_streams.py record_metadata.py upstream_http.py search_execution.py search_indexes.py reader_assets.py .
|
| 53 |
+
COPY --from=search-index-build /native/ /app/
|
| 54 |
COPY --from=static-assets /out/ static/
|
| 55 |
COPY data/ data/
|
| 56 |
COPY txt/ txt/
|
app.py
CHANGED
|
@@ -97,15 +97,21 @@ reader_record_key_indices = {}
|
|
| 97 |
reader_source_id_indices = {}
|
| 98 |
_reader_indexes_ready = False
|
| 99 |
_reader_indexes_lock = threading.Lock()
|
|
|
|
|
|
|
|
|
|
| 100 |
READER_INDEX_WARM_DELAY_SECONDS = 5
|
| 101 |
READER_INDEX_IDLE_SECONDS = 5
|
| 102 |
initial_payload_global = None
|
| 103 |
initial_payload_by_repo = {}
|
| 104 |
API_CACHE_TTL_SECONDS = 120
|
|
|
|
|
|
|
|
|
|
| 105 |
api_response_cache = {}
|
| 106 |
_data_generation = 0
|
| 107 |
SEARCH_CACHE_TTL_SECONDS = 120
|
| 108 |
-
_search_cache: dict[tuple, tuple[float, dict]] = {}
|
| 109 |
_search_instance = uuid4().hex
|
| 110 |
# Bump when matching, filtering, ordering or public record semantics change.
|
| 111 |
SEARCH_SEMANTICS_VERSION = "hf-search-v2"
|
|
@@ -132,17 +138,35 @@ def _cached(store, key, builder, ttl, limit):
|
|
| 132 |
now = time.monotonic()
|
| 133 |
cached = store.get(key)
|
| 134 |
if cached and now - cached[0] < ttl:
|
|
|
|
| 135 |
return cached[1]
|
| 136 |
value = builder()
|
| 137 |
-
store
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
return value
|
| 142 |
|
| 143 |
|
| 144 |
def cached_payload(key, builder):
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
|
| 148 |
async def get_reader_assets(*, wait: bool = True) -> dict:
|
|
@@ -226,20 +250,30 @@ def literal_candidates(query: str, repos=None) -> set[int] | None:
|
|
| 226 |
postings = ngram_postings.get(width)
|
| 227 |
if not postings or len(query) < width:
|
| 228 |
return None
|
| 229 |
-
|
| 230 |
-
for index in range(len(query) - width + 1):
|
| 231 |
-
encoded = postings.get(
|
| 232 |
if encoded is None:
|
| 233 |
return set()
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
|
|
|
| 238 |
if repos:
|
| 239 |
allowed = set()
|
| 240 |
for repo in repos:
|
| 241 |
allowed.update(repo_records_map.get(repo, []))
|
| 242 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
return candidates or set()
|
| 244 |
INITIAL_PAGE_SIZE = 100
|
| 245 |
SIDEBAR_DATA_PATH = Path("data/sidebar")
|
|
@@ -466,31 +500,49 @@ def build_vocab_by_len():
|
|
| 466 |
vocab_by_len.setdefault(len(word), []).append(word)
|
| 467 |
|
| 468 |
|
| 469 |
-
def
|
| 470 |
global reader_record_indices, repo_reader_record_indices
|
| 471 |
global reader_record_key_indices, reader_source_id_indices, _reader_indexes_ready
|
|
|
|
| 472 |
with _reader_indexes_lock:
|
| 473 |
if _reader_indexes_ready:
|
| 474 |
-
return
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 480 |
repo = rec.get("Repo", "")
|
| 481 |
-
|
| 482 |
source_id = reader_short_id(rec.get("Link") or build_record_link(rec))
|
| 483 |
-
|
| 484 |
if rec.get("_ext_lower", "") in READER_EXTENSIONS:
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 493 |
_reader_indexes_ready = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
|
| 495 |
|
| 496 |
def ensure_reader_indexes():
|
|
@@ -507,11 +559,17 @@ async def ensure_reader_indexes_async():
|
|
| 507 |
task = getattr(app.state, "reader_index_build_task", None)
|
| 508 |
if task is None or task.done():
|
| 509 |
async def build():
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 515 |
task = asyncio.create_task(build())
|
| 516 |
app.state.reader_index_build_task = task
|
| 517 |
await asyncio.shield(task)
|
|
@@ -530,6 +588,7 @@ async def warm_reader_indexes():
|
|
| 530 |
|
| 531 |
|
| 532 |
def build_indexes(build_words=True, build_reader=True):
|
|
|
|
| 533 |
global reader_source_id_indices, _search_generation
|
| 534 |
global _data_generation, word_index, folder_index, extension_counts, repo_counts, repo_list, extension_list, repo_extension_counts, repo_records_map, sorted_by_name, sorted_by_size, repo_sorted_by_name, repo_sorted_by_size, txt_record_indices, repo_txt_record_indices, reader_record_indices, repo_reader_record_indices, reader_record_key_indices, _reader_indexes_ready
|
| 535 |
_data_generation += 1
|
|
@@ -551,6 +610,7 @@ def build_indexes(build_words=True, build_reader=True):
|
|
| 551 |
reader_record_key_indices = {}
|
| 552 |
reader_source_id_indices = {}
|
| 553 |
_reader_indexes_ready = False
|
|
|
|
| 554 |
for idx, rec in enumerate(records):
|
| 555 |
repo = rec.get("Repo", "")
|
| 556 |
repo_counts[repo] = repo_counts.get(repo, 0) + 1
|
|
@@ -1048,7 +1108,11 @@ def _search_order_uncached(q="", repos=None, extensions=None, folders=None, min_
|
|
| 1048 |
query_tokens = tokenize(q)
|
| 1049 |
fuzzy_candidate_limit = 200 if len(query_tokens) == 1 else None
|
| 1050 |
|
| 1051 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1052 |
|
| 1053 |
exact_constraint = None
|
| 1054 |
for tok in query_tokens:
|
|
@@ -1319,15 +1383,16 @@ async def lifespan(app: FastAPI):
|
|
| 1319 |
try:
|
| 1320 |
yield
|
| 1321 |
finally:
|
| 1322 |
-
await app.state.search_executor.close()
|
| 1323 |
-
del app.state.search_executor
|
| 1324 |
if app.state.reader_index_warm_task is not None:
|
| 1325 |
app.state.reader_index_warm_task.cancel()
|
| 1326 |
await asyncio.gather(app.state.reader_index_warm_task, return_exceptions=True)
|
| 1327 |
app.state.reader_index_warm_task = None
|
| 1328 |
if app.state.reader_index_build_task is not None:
|
|
|
|
| 1329 |
await asyncio.gather(app.state.reader_index_build_task, return_exceptions=True)
|
| 1330 |
app.state.reader_index_build_task = None
|
|
|
|
|
|
|
| 1331 |
if app.state.reader_assets_task is not None:
|
| 1332 |
app.state.reader_assets_task.cancel()
|
| 1333 |
await asyncio.gather(app.state.reader_assets_task, return_exceptions=True)
|
|
@@ -1394,7 +1459,7 @@ def normalize_search_list(values: list[str] | None, lowercase: bool = False) ->
|
|
| 1394 |
return list(dict.fromkeys(value.strip().lower() if lowercase else value.strip() for value in values))
|
| 1395 |
|
| 1396 |
|
| 1397 |
-
async def build_search_api_response(body: SearchRequest, repos: list[str] | None) ->
|
| 1398 |
params = body.model_dump(exclude={"repos"})
|
| 1399 |
for name in ("extensions", "folders", "folder_selfs", "folder_subtrees"):
|
| 1400 |
params[name] = normalize_search_list(params[name], lowercase=name == "extensions")
|
|
@@ -1414,7 +1479,9 @@ async def build_search_api_response(body: SearchRequest, repos: list[str] | None
|
|
| 1414 |
assets = await get_reader_assets(wait=False)
|
| 1415 |
assets_ms = (time.perf_counter() - started) * 1000
|
| 1416 |
started = time.perf_counter()
|
| 1417 |
-
|
|
|
|
|
|
|
| 1418 |
response.headers["Server-Timing"] = (
|
| 1419 |
f"queue;dur={queued_ms:.2f}, search;dur={search_ms:.2f}, "
|
| 1420 |
f"reader_assets;dur={assets_ms:.2f}, response;dur={(time.perf_counter() - started) * 1000:.2f}")
|
|
@@ -1437,7 +1504,7 @@ async def api_search_repo(repo_name: str, body: SearchRequest):
|
|
| 1437 |
@app.get("/api/repos")
|
| 1438 |
|
| 1439 |
def api_repos():
|
| 1440 |
-
return
|
| 1441 |
@app.get("/api/reader-assets")
|
| 1442 |
|
| 1443 |
async def api_reader_assets():
|
|
@@ -1455,21 +1522,21 @@ def api_extensions(repo: Optional[str] = Query(default=None)):
|
|
| 1455 |
ext_count = extension_counts
|
| 1456 |
sorted_exts = sorted(ext_count.keys())
|
| 1457 |
return [{"name": e, "count": ext_count[e]} for e in sorted_exts]
|
| 1458 |
-
return
|
| 1459 |
@app.get("/api/folders/{repo_name}")
|
| 1460 |
|
| 1461 |
def api_folders(repo_name: str):
|
| 1462 |
full_repo = f"VoiceOfML/{repo_name}"
|
| 1463 |
if full_repo not in repo_counts:
|
| 1464 |
return JSONResponse({"error": f"ไปๅบ {full_repo} ไธๅญๅจ"}, status_code=404)
|
| 1465 |
-
return
|
| 1466 |
@app.get("/api/folders/{repo_name}/contents")
|
| 1467 |
|
| 1468 |
def api_folder_contents(repo_name: str, path: str = Query(default="")):
|
| 1469 |
full_repo = f"VoiceOfML/{repo_name}"
|
| 1470 |
if full_repo not in repo_counts:
|
| 1471 |
return JSONResponse({"error": f"ไปๅบ {full_repo} ไธๅญๅจ"}, status_code=404)
|
| 1472 |
-
return
|
| 1473 |
@app.get("/api/random")
|
| 1474 |
|
| 1475 |
def api_random(repo: Optional[str] = Query(default=None)):
|
|
|
|
| 97 |
reader_source_id_indices = {}
|
| 98 |
_reader_indexes_ready = False
|
| 99 |
_reader_indexes_lock = threading.Lock()
|
| 100 |
+
_reader_index_build = None
|
| 101 |
+
READER_INDEX_BATCH_RECORDS = 256
|
| 102 |
+
READER_INDEX_BATCH_SECONDS = .008
|
| 103 |
READER_INDEX_WARM_DELAY_SECONDS = 5
|
| 104 |
READER_INDEX_IDLE_SECONDS = 5
|
| 105 |
initial_payload_global = None
|
| 106 |
initial_payload_by_repo = {}
|
| 107 |
API_CACHE_TTL_SECONDS = 120
|
| 108 |
+
RESPONSE_CACHE_BYTES_MAX = 16 * 1024 * 1024
|
| 109 |
+
RESPONSE_CACHE_ENTRY_BYTES_MAX = 2 * 1024 * 1024
|
| 110 |
+
_api_response_cache_lock = threading.Lock()
|
| 111 |
api_response_cache = {}
|
| 112 |
_data_generation = 0
|
| 113 |
SEARCH_CACHE_TTL_SECONDS = 120
|
| 114 |
+
_search_cache: dict[tuple, tuple[float, dict, int]] = {}
|
| 115 |
_search_instance = uuid4().hex
|
| 116 |
# Bump when matching, filtering, ordering or public record semantics change.
|
| 117 |
SEARCH_SEMANTICS_VERSION = "hf-search-v2"
|
|
|
|
| 138 |
now = time.monotonic()
|
| 139 |
cached = store.get(key)
|
| 140 |
if cached and now - cached[0] < ttl:
|
| 141 |
+
store[key] = store.pop(key)
|
| 142 |
return cached[1]
|
| 143 |
value = builder()
|
| 144 |
+
store.pop(key, None)
|
| 145 |
+
for old_key, entry in list(store.items()):
|
| 146 |
+
if now - entry[0] >= ttl:
|
| 147 |
+
del store[old_key]
|
| 148 |
+
size = (len(value) if isinstance(value, bytes) else len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))) + len(str(key).encode("utf-8"))
|
| 149 |
+
if size > RESPONSE_CACHE_ENTRY_BYTES_MAX:
|
| 150 |
+
return value
|
| 151 |
+
total = sum(entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8")) for entry in store.values())
|
| 152 |
+
while store and (len(store) >= limit or total + size > RESPONSE_CACHE_BYTES_MAX):
|
| 153 |
+
oldest_key = next(iter(store))
|
| 154 |
+
entry = store.pop(oldest_key)
|
| 155 |
+
total -= entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8"))
|
| 156 |
+
if size <= RESPONSE_CACHE_BYTES_MAX:
|
| 157 |
+
store[key] = (now, value, size)
|
| 158 |
return value
|
| 159 |
|
| 160 |
|
| 161 |
def cached_payload(key, builder):
|
| 162 |
+
with _api_response_cache_lock:
|
| 163 |
+
return _cached(api_response_cache, key, builder, API_CACHE_TTL_SECONDS, 500)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def cached_json_response(key, builder, headers=None):
|
| 167 |
+
# Encode once, measure the actual body and reuse it within the existing budget.
|
| 168 |
+
body = cached_payload(("json", key), lambda: JSONResponse(builder()).body)
|
| 169 |
+
return Response(body, media_type="application/json", headers=headers)
|
| 170 |
|
| 171 |
|
| 172 |
async def get_reader_assets(*, wait: bool = True) -> dict:
|
|
|
|
| 250 |
postings = ngram_postings.get(width)
|
| 251 |
if not postings or len(query) < width:
|
| 252 |
return None
|
| 253 |
+
entries = []
|
| 254 |
+
for gram in dict.fromkeys(query[index:index + width] for index in range(len(query) - width + 1)):
|
| 255 |
+
encoded = postings.get(gram)
|
| 256 |
if encoded is None:
|
| 257 |
return set()
|
| 258 |
+
entries.append(encoded)
|
| 259 |
+
# VNG3 entries carry validated counts; materialized test postings have lengths.
|
| 260 |
+
entries.sort(key=lambda entry: entry[2] if isinstance(entry, tuple) else len(entry))
|
| 261 |
+
candidates = None
|
| 262 |
+
allowed = None
|
| 263 |
if repos:
|
| 264 |
allowed = set()
|
| 265 |
for repo in repos:
|
| 266 |
allowed.update(repo_records_map.get(repo, []))
|
| 267 |
+
for encoded in entries:
|
| 268 |
+
matches = resolve_postings(encoded, ngram_posting_buffers.get(width, b""))
|
| 269 |
+
if candidates is None:
|
| 270 |
+
candidates = matches
|
| 271 |
+
if allowed is not None:
|
| 272 |
+
candidates.intersection_update(allowed)
|
| 273 |
+
else:
|
| 274 |
+
candidates.intersection_update(matches)
|
| 275 |
+
if not candidates:
|
| 276 |
+
return set()
|
| 277 |
return candidates or set()
|
| 278 |
INITIAL_PAGE_SIZE = 100
|
| 279 |
SIDEBAR_DATA_PATH = Path("data/sidebar")
|
|
|
|
| 500 |
vocab_by_len.setdefault(len(word), []).append(word)
|
| 501 |
|
| 502 |
|
| 503 |
+
def _advance_reader_indexes(limit=READER_INDEX_BATCH_RECORDS, budget=READER_INDEX_BATCH_SECONDS):
|
| 504 |
global reader_record_indices, repo_reader_record_indices
|
| 505 |
global reader_record_key_indices, reader_source_id_indices, _reader_indexes_ready
|
| 506 |
+
global _reader_index_build
|
| 507 |
with _reader_indexes_lock:
|
| 508 |
if _reader_indexes_ready:
|
| 509 |
+
return True
|
| 510 |
+
if _reader_index_build is None or _reader_index_build["generation"] != _data_generation:
|
| 511 |
+
_reader_index_build = {"generation": _data_generation, "records": records, "next": 0,
|
| 512 |
+
"indices": [], "repos": {}, "keys": {}, "ids": {}}
|
| 513 |
+
build = _reader_index_build
|
| 514 |
+
deadline = time.perf_counter() + budget
|
| 515 |
+
end = min(len(build["records"]), build["next"] + limit)
|
| 516 |
+
while build["next"] < end:
|
| 517 |
+
idx = build["next"]
|
| 518 |
+
rec = build["records"][idx]
|
| 519 |
repo = rec.get("Repo", "")
|
| 520 |
+
build["keys"][build_reader_asset_key(rec)] = idx
|
| 521 |
source_id = reader_short_id(rec.get("Link") or build_record_link(rec))
|
| 522 |
+
build["ids"].setdefault(source_id, []).append(idx)
|
| 523 |
if rec.get("_ext_lower", "") in READER_EXTENSIONS:
|
| 524 |
+
build["indices"].append(idx)
|
| 525 |
+
build["repos"].setdefault(repo, []).append(idx)
|
| 526 |
+
build["next"] += 1
|
| 527 |
+
if time.perf_counter() >= deadline:
|
| 528 |
+
break
|
| 529 |
+
if build["next"] < len(build["records"]):
|
| 530 |
+
return False
|
| 531 |
+
if build["generation"] != _data_generation or build["records"] is not records:
|
| 532 |
+
_reader_index_build = None
|
| 533 |
+
return False
|
| 534 |
+
reader_record_indices = array('I', build["indices"])
|
| 535 |
+
repo_reader_record_indices = {key: array('I', indices) for key, indices in build["repos"].items()}
|
| 536 |
+
reader_record_key_indices = build["keys"]
|
| 537 |
+
reader_source_id_indices = build["ids"]
|
| 538 |
_reader_indexes_ready = True
|
| 539 |
+
_reader_index_build = None
|
| 540 |
+
return True
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def _build_reader_indexes():
|
| 544 |
+
while not _advance_reader_indexes(len(records), float("inf")):
|
| 545 |
+
pass
|
| 546 |
|
| 547 |
|
| 548 |
def ensure_reader_indexes():
|
|
|
|
| 559 |
task = getattr(app.state, "reader_index_build_task", None)
|
| 560 |
if task is None or task.done():
|
| 561 |
async def build():
|
| 562 |
+
while not _reader_indexes_ready:
|
| 563 |
+
executor = getattr(app.state, "search_executor", None)
|
| 564 |
+
if executor is None:
|
| 565 |
+
await asyncio.to_thread(_advance_reader_indexes)
|
| 566 |
+
else:
|
| 567 |
+
try:
|
| 568 |
+
await executor.run(_advance_reader_indexes, background=True)
|
| 569 |
+
except SearchBusy:
|
| 570 |
+
await asyncio.sleep(.02)
|
| 571 |
+
continue
|
| 572 |
+
await asyncio.sleep(0)
|
| 573 |
task = asyncio.create_task(build())
|
| 574 |
app.state.reader_index_build_task = task
|
| 575 |
await asyncio.shield(task)
|
|
|
|
| 588 |
|
| 589 |
|
| 590 |
def build_indexes(build_words=True, build_reader=True):
|
| 591 |
+
global _reader_index_build
|
| 592 |
global reader_source_id_indices, _search_generation
|
| 593 |
global _data_generation, word_index, folder_index, extension_counts, repo_counts, repo_list, extension_list, repo_extension_counts, repo_records_map, sorted_by_name, sorted_by_size, repo_sorted_by_name, repo_sorted_by_size, txt_record_indices, repo_txt_record_indices, reader_record_indices, repo_reader_record_indices, reader_record_key_indices, _reader_indexes_ready
|
| 594 |
_data_generation += 1
|
|
|
|
| 610 |
reader_record_key_indices = {}
|
| 611 |
reader_source_id_indices = {}
|
| 612 |
_reader_indexes_ready = False
|
| 613 |
+
_reader_index_build = None
|
| 614 |
for idx, rec in enumerate(records):
|
| 615 |
repo = rec.get("Repo", "")
|
| 616 |
repo_counts[repo] = repo_counts.get(repo, 0) + 1
|
|
|
|
| 1108 |
query_tokens = tokenize(q)
|
| 1109 |
fuzzy_candidate_limit = 200 if len(query_tokens) == 1 else None
|
| 1110 |
|
| 1111 |
+
posting_cache = {}
|
| 1112 |
+
def query_postings(token):
|
| 1113 |
+
if token not in posting_cache:
|
| 1114 |
+
posting_cache[token] = scoped_word_postings(token, search_folders=search_folders)
|
| 1115 |
+
return posting_cache[token]
|
| 1116 |
|
| 1117 |
exact_constraint = None
|
| 1118 |
for tok in query_tokens:
|
|
|
|
| 1383 |
try:
|
| 1384 |
yield
|
| 1385 |
finally:
|
|
|
|
|
|
|
| 1386 |
if app.state.reader_index_warm_task is not None:
|
| 1387 |
app.state.reader_index_warm_task.cancel()
|
| 1388 |
await asyncio.gather(app.state.reader_index_warm_task, return_exceptions=True)
|
| 1389 |
app.state.reader_index_warm_task = None
|
| 1390 |
if app.state.reader_index_build_task is not None:
|
| 1391 |
+
app.state.reader_index_build_task.cancel()
|
| 1392 |
await asyncio.gather(app.state.reader_index_build_task, return_exceptions=True)
|
| 1393 |
app.state.reader_index_build_task = None
|
| 1394 |
+
await app.state.search_executor.close()
|
| 1395 |
+
del app.state.search_executor
|
| 1396 |
if app.state.reader_assets_task is not None:
|
| 1397 |
app.state.reader_assets_task.cancel()
|
| 1398 |
await asyncio.gather(app.state.reader_assets_task, return_exceptions=True)
|
|
|
|
| 1459 |
return list(dict.fromkeys(value.strip().lower() if lowercase else value.strip() for value in values))
|
| 1460 |
|
| 1461 |
|
| 1462 |
+
async def build_search_api_response(body: SearchRequest, repos: list[str] | None) -> Response:
|
| 1463 |
params = body.model_dump(exclude={"repos"})
|
| 1464 |
for name in ("extensions", "folders", "folder_selfs", "folder_subtrees"):
|
| 1465 |
params[name] = normalize_search_list(params[name], lowercase=name == "extensions")
|
|
|
|
| 1479 |
assets = await get_reader_assets(wait=False)
|
| 1480 |
assets_ms = (time.perf_counter() - started) * 1000
|
| 1481 |
started = time.perf_counter()
|
| 1482 |
+
key = ("search", _data_generation, reader_assets_revision, READER_ASSET_ROUTING_CONTRACT_VERSION, tuple(repos or ()),
|
| 1483 |
+
json.dumps(params, sort_keys=True, ensure_ascii=False))
|
| 1484 |
+
response = cached_json_response(key, lambda: add_reader_assets(payload, assets))
|
| 1485 |
response.headers["Server-Timing"] = (
|
| 1486 |
f"queue;dur={queued_ms:.2f}, search;dur={search_ms:.2f}, "
|
| 1487 |
f"reader_assets;dur={assets_ms:.2f}, response;dur={(time.perf_counter() - started) * 1000:.2f}")
|
|
|
|
| 1504 |
@app.get("/api/repos")
|
| 1505 |
|
| 1506 |
def api_repos():
|
| 1507 |
+
return cached_json_response(("repos", _data_generation), lambda: repo_list, METADATA_CACHE_HEADERS)
|
| 1508 |
@app.get("/api/reader-assets")
|
| 1509 |
|
| 1510 |
async def api_reader_assets():
|
|
|
|
| 1522 |
ext_count = extension_counts
|
| 1523 |
sorted_exts = sorted(ext_count.keys())
|
| 1524 |
return [{"name": e, "count": ext_count[e]} for e in sorted_exts]
|
| 1525 |
+
return cached_json_response(("extensions", _data_generation, repo or ""), build, METADATA_CACHE_HEADERS)
|
| 1526 |
@app.get("/api/folders/{repo_name}")
|
| 1527 |
|
| 1528 |
def api_folders(repo_name: str):
|
| 1529 |
full_repo = f"VoiceOfML/{repo_name}"
|
| 1530 |
if full_repo not in repo_counts:
|
| 1531 |
return JSONResponse({"error": f"ไปๅบ {full_repo} ไธๅญๅจ"}, status_code=404)
|
| 1532 |
+
return cached_json_response(("folders", _data_generation, full_repo), lambda: build_filter_folder_tree(full_repo))
|
| 1533 |
@app.get("/api/folders/{repo_name}/contents")
|
| 1534 |
|
| 1535 |
def api_folder_contents(repo_name: str, path: str = Query(default="")):
|
| 1536 |
full_repo = f"VoiceOfML/{repo_name}"
|
| 1537 |
if full_repo not in repo_counts:
|
| 1538 |
return JSONResponse({"error": f"ไปๅบ {full_repo} ไธๅญๅจ"}, status_code=404)
|
| 1539 |
+
return cached_json_response(("folder_contents", _data_generation, full_repo, path), lambda: get_folder_contents(full_repo, path))
|
| 1540 |
@app.get("/api/random")
|
| 1541 |
|
| 1542 |
def api_random(repo: Optional[str] = Query(default=None)):
|
reader_assets.py
CHANGED
|
@@ -72,6 +72,16 @@ def decode_reader_assets(
|
|
| 72 |
ocr_manifest = entry.get("o")
|
| 73 |
chapter_bucket = entry.get("cb")
|
| 74 |
bucket = entry.get("b")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
if chapter_manifest is not None and (
|
| 76 |
mode not in {"e", "p"}
|
| 77 |
or not isinstance(chapter_manifest, str)
|
|
@@ -116,6 +126,7 @@ def decode_reader_assets(
|
|
| 116 |
"m": mode,
|
| 117 |
"p": path,
|
| 118 |
**({"b": bucket} if bucket else {}),
|
|
|
|
| 119 |
**({"c": chapter_manifest} if chapter_manifest else {}),
|
| 120 |
**({"cb": chapter_bucket} if chapter_bucket else {}),
|
| 121 |
**({"f": fallback} if fallback else {}),
|
|
|
|
| 72 |
ocr_manifest = entry.get("o")
|
| 73 |
chapter_bucket = entry.get("cb")
|
| 74 |
bucket = entry.get("b")
|
| 75 |
+
document_path, document_bucket = entry.get("pd"), entry.get("pdb")
|
| 76 |
+
if (document_path is not None or document_bucket is not None) and (
|
| 77 |
+
mode != "p" or not path.endswith("/page-manifest.json")
|
| 78 |
+
or not isinstance(document_bucket, str)
|
| 79 |
+
or document_bucket not in READER_ALLOWED_BUCKETS
|
| 80 |
+
or not isinstance(document_path, str)
|
| 81 |
+
or not READER_BUCKET_PATH_RE.fullmatch(document_path)
|
| 82 |
+
or not document_path.endswith("/document.pdf")
|
| 83 |
+
):
|
| 84 |
+
continue
|
| 85 |
if chapter_manifest is not None and (
|
| 86 |
mode not in {"e", "p"}
|
| 87 |
or not isinstance(chapter_manifest, str)
|
|
|
|
| 126 |
"m": mode,
|
| 127 |
"p": path,
|
| 128 |
**({"b": bucket} if bucket else {}),
|
| 129 |
+
**({"pd": document_path, "pdb": document_bucket} if document_path else {}),
|
| 130 |
**({"c": chapter_manifest} if chapter_manifest else {}),
|
| 131 |
**({"cb": chapter_bucket} if chapter_bucket else {}),
|
| 132 |
**({"f": fallback} if fallback else {}),
|
record_metadata.py
CHANGED
|
@@ -112,6 +112,8 @@ def reader_asset_fields(asset: dict, original_extension: str) -> dict:
|
|
| 112 |
if asset.get("s") != 2 or asset.get("m") not in READER_ASSET_MODES or not asset.get("p"):
|
| 113 |
return fields
|
| 114 |
fields.update({"url": reader_asset_url(asset), "extension": reader_extension_for_asset(asset, original_extension)})
|
|
|
|
|
|
|
| 115 |
if ocr_path and ocr_path.endswith("/ocr-manifest.json"):
|
| 116 |
fields["ocr_manifest"] = (
|
| 117 |
f"https://voiceofml-search.hf.space/api/reader-bucket-resource?path={quote(ocr_path, safe='/')}"
|
|
@@ -148,7 +150,8 @@ def enrich_reader_record(record: dict, asset: dict) -> dict:
|
|
| 148 |
if fields:
|
| 149 |
for source, target in (("url", "ReaderLink"), ("extension", "ReaderExtension"),
|
| 150 |
("chapter_manifest", "ReaderChapterManifest"), ("fallback", "ReaderFallback"),
|
| 151 |
-
|
|
|
|
| 152 |
if source in fields:
|
| 153 |
result[target] = fields[source]
|
| 154 |
result["DownloadLink"] = record.get("Link") or build_record_link(record)
|
|
|
|
| 112 |
if asset.get("s") != 2 or asset.get("m") not in READER_ASSET_MODES or not asset.get("p"):
|
| 113 |
return fields
|
| 114 |
fields.update({"url": reader_asset_url(asset), "extension": reader_extension_for_asset(asset, original_extension)})
|
| 115 |
+
if asset.get("pd") and asset.get("pdb") in {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}:
|
| 116 |
+
fields["pdf_document"] = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + quote(asset["pd"], safe="/")
|
| 117 |
if ocr_path and ocr_path.endswith("/ocr-manifest.json"):
|
| 118 |
fields["ocr_manifest"] = (
|
| 119 |
f"https://voiceofml-search.hf.space/api/reader-bucket-resource?path={quote(ocr_path, safe='/')}"
|
|
|
|
| 150 |
if fields:
|
| 151 |
for source, target in (("url", "ReaderLink"), ("extension", "ReaderExtension"),
|
| 152 |
("chapter_manifest", "ReaderChapterManifest"), ("fallback", "ReaderFallback"),
|
| 153 |
+
("ocr_manifest", "ReaderOcrManifest"), ("ocr_mode", "ReaderOcrMode"),
|
| 154 |
+
("pdf_document", "ReaderPdfDocument")):
|
| 155 |
if source in fields:
|
| 156 |
result[target] = fields[source]
|
| 157 |
result["DownloadLink"] = record.get("Link") or build_record_link(record)
|
scripts/build_search_index_native.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build the optional decoder with the current interpreter's headers and ABI."""
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import shlex
|
| 6 |
+
import subprocess
|
| 7 |
+
import sysconfig
|
| 8 |
+
|
| 9 |
+
parser = argparse.ArgumentParser()
|
| 10 |
+
parser.add_argument("--output-dir", required=True)
|
| 11 |
+
args = parser.parse_args()
|
| 12 |
+
output = Path(args.output_dir)
|
| 13 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 14 |
+
source = Path(__file__).resolve().parents[1] / "search_index_native.c"
|
| 15 |
+
target = output / ("_search_index_native" + sysconfig.get_config_var("EXT_SUFFIX"))
|
| 16 |
+
compiler = shlex.split(os.environ.get("CC") or sysconfig.get_config_var("CC") or "cc")
|
| 17 |
+
subprocess.run([*compiler, "-O3", "-shared", "-fPIC", "-Wall", "-Wextra",
|
| 18 |
+
"-Wno-unused-parameter", "-I" + sysconfig.get_paths()["include"],
|
| 19 |
+
str(source), "-o", str(target)], check=True)
|
| 20 |
+
print(target)
|
search_execution.py
CHANGED
|
@@ -15,6 +15,7 @@ class SearchExecutor:
|
|
| 15 |
self._lock = asyncio.Lock()
|
| 16 |
self._tasks = set()
|
| 17 |
self._closing = False
|
|
|
|
| 18 |
|
| 19 |
async def __aenter__(self):
|
| 20 |
return self
|
|
@@ -22,11 +23,12 @@ class SearchExecutor:
|
|
| 22 |
async def __aexit__(self, *args):
|
| 23 |
await self.close()
|
| 24 |
|
| 25 |
-
async def run(self, function):
|
| 26 |
if self._closing or len(self._tasks) >= self.capacity:
|
| 27 |
raise SearchBusy()
|
| 28 |
job = {"started": False}
|
| 29 |
queued = time.perf_counter()
|
|
|
|
| 30 |
|
| 31 |
def compute():
|
| 32 |
started = time.perf_counter()
|
|
@@ -34,15 +36,20 @@ class SearchExecutor:
|
|
| 34 |
return result, (started - queued) * 1000, (time.perf_counter() - started) * 1000
|
| 35 |
|
| 36 |
async def execute():
|
|
|
|
|
|
|
| 37 |
async with self._lock:
|
| 38 |
job["started"] = True
|
| 39 |
return await asyncio.get_running_loop().run_in_executor(self._pool, compute)
|
| 40 |
|
| 41 |
task = asyncio.create_task(execute())
|
| 42 |
self._tasks.add(task)
|
|
|
|
|
|
|
| 43 |
|
| 44 |
def finished(done):
|
| 45 |
self._tasks.discard(done)
|
|
|
|
| 46 |
if not done.cancelled():
|
| 47 |
done.exception() # Consume failures when the requester has left.
|
| 48 |
|
|
|
|
| 15 |
self._lock = asyncio.Lock()
|
| 16 |
self._tasks = set()
|
| 17 |
self._closing = False
|
| 18 |
+
self._foreground = set()
|
| 19 |
|
| 20 |
async def __aenter__(self):
|
| 21 |
return self
|
|
|
|
| 23 |
async def __aexit__(self, *args):
|
| 24 |
await self.close()
|
| 25 |
|
| 26 |
+
async def run(self, function, *, background=False):
|
| 27 |
if self._closing or len(self._tasks) >= self.capacity:
|
| 28 |
raise SearchBusy()
|
| 29 |
job = {"started": False}
|
| 30 |
queued = time.perf_counter()
|
| 31 |
+
predecessors = tuple(self._foreground) if background else ()
|
| 32 |
|
| 33 |
def compute():
|
| 34 |
started = time.perf_counter()
|
|
|
|
| 36 |
return result, (started - queued) * 1000, (time.perf_counter() - started) * 1000
|
| 37 |
|
| 38 |
async def execute():
|
| 39 |
+
if predecessors:
|
| 40 |
+
await asyncio.wait(predecessors)
|
| 41 |
async with self._lock:
|
| 42 |
job["started"] = True
|
| 43 |
return await asyncio.get_running_loop().run_in_executor(self._pool, compute)
|
| 44 |
|
| 45 |
task = asyncio.create_task(execute())
|
| 46 |
self._tasks.add(task)
|
| 47 |
+
if not background:
|
| 48 |
+
self._foreground.add(task)
|
| 49 |
|
| 50 |
def finished(done):
|
| 51 |
self._tasks.discard(done)
|
| 52 |
+
self._foreground.discard(done)
|
| 53 |
if not done.cancelled():
|
| 54 |
done.exception() # Consume failures when the requester has left.
|
| 55 |
|
search_index_native.c
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#define PY_SSIZE_T_CLEAN
|
| 2 |
+
#include <Python.h>
|
| 3 |
+
#include <stdint.h>
|
| 4 |
+
|
| 5 |
+
/* Generated IDs are small; unsupported integer widths use the Python parser. */
|
| 6 |
+
static int read_varint(const unsigned char *data, Py_ssize_t length,
|
| 7 |
+
Py_ssize_t *offset, uint64_t *value) {
|
| 8 |
+
unsigned int shift = 0;
|
| 9 |
+
*value = 0;
|
| 10 |
+
while (*offset < length) {
|
| 11 |
+
unsigned char byte = data[(*offset)++];
|
| 12 |
+
if (shift >= 63) {
|
| 13 |
+
PyErr_SetString(PyExc_OverflowError, "wide varint needs Python decoder");
|
| 14 |
+
return -1;
|
| 15 |
+
}
|
| 16 |
+
*value |= (uint64_t)(byte & 127) << shift;
|
| 17 |
+
if (!(byte & 128)) return 0;
|
| 18 |
+
shift += 7;
|
| 19 |
+
}
|
| 20 |
+
PyErr_SetString(PyExc_ValueError, "truncated varint");
|
| 21 |
+
return -1;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
static int bounded_end(Py_ssize_t offset, uint64_t size, Py_ssize_t length,
|
| 25 |
+
Py_ssize_t *end) {
|
| 26 |
+
if (size > (uint64_t)(length - offset)) {
|
| 27 |
+
PyErr_SetString(PyExc_ValueError, "truncated postings");
|
| 28 |
+
return -1;
|
| 29 |
+
}
|
| 30 |
+
*end = offset + (Py_ssize_t)size;
|
| 31 |
+
return 0;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
static PyObject *read_entries(PyObject *self, PyObject *args) {
|
| 35 |
+
Py_buffer buffer;
|
| 36 |
+
Py_ssize_t offset, record_count;
|
| 37 |
+
int materialize;
|
| 38 |
+
unsigned long long entries;
|
| 39 |
+
if (!PyArg_ParseTuple(args, "y*nKnp", &buffer, &offset, &entries,
|
| 40 |
+
&record_count, &materialize)) return NULL;
|
| 41 |
+
PyObject *output = NULL, *key = NULL, *ids = NULL, *entry = NULL;
|
| 42 |
+
const unsigned char *data = buffer.buf;
|
| 43 |
+
if (offset < 0 || offset > buffer.len || record_count < 0) {
|
| 44 |
+
PyErr_SetString(PyExc_ValueError, "invalid posting bounds");
|
| 45 |
+
goto done;
|
| 46 |
+
}
|
| 47 |
+
output = PyDict_New();
|
| 48 |
+
if (!output) goto done;
|
| 49 |
+
for (unsigned long long i = 0; i < entries; i++) {
|
| 50 |
+
uint64_t key_size, expected, size;
|
| 51 |
+
Py_ssize_t end, start;
|
| 52 |
+
if (read_varint(data, buffer.len, &offset, &key_size) < 0 ||
|
| 53 |
+
bounded_end(offset, key_size, buffer.len, &end) < 0) goto failed;
|
| 54 |
+
key = PyUnicode_DecodeUTF8((const char *)data + offset, end - offset, "strict");
|
| 55 |
+
if (!key) goto failed;
|
| 56 |
+
offset = end;
|
| 57 |
+
if (read_varint(data, buffer.len, &offset, &expected) < 0 ||
|
| 58 |
+
read_varint(data, buffer.len, &offset, &size) < 0 ||
|
| 59 |
+
bounded_end(offset, size, buffer.len, &end) < 0) goto failed;
|
| 60 |
+
start = offset;
|
| 61 |
+
uint64_t previous = 0, count = 0;
|
| 62 |
+
int first = 1;
|
| 63 |
+
if (materialize) {
|
| 64 |
+
ids = PySet_New(NULL);
|
| 65 |
+
if (!ids) goto failed;
|
| 66 |
+
}
|
| 67 |
+
while (offset < end) {
|
| 68 |
+
uint64_t delta;
|
| 69 |
+
if (read_varint(data, end, &offset, &delta) < 0) goto failed;
|
| 70 |
+
if (previous >= (uint64_t)record_count ||
|
| 71 |
+
delta >= (uint64_t)record_count - previous) {
|
| 72 |
+
PyErr_SetString(PyExc_ValueError, "posting record id out of range");
|
| 73 |
+
goto failed;
|
| 74 |
+
}
|
| 75 |
+
previous += delta;
|
| 76 |
+
if (first || delta) {
|
| 77 |
+
count++;
|
| 78 |
+
if (materialize) {
|
| 79 |
+
PyObject *id = PyLong_FromUnsignedLongLong(previous);
|
| 80 |
+
if (!id) goto failed;
|
| 81 |
+
int status = PySet_Add(ids, id);
|
| 82 |
+
Py_DECREF(id);
|
| 83 |
+
if (status < 0) goto failed;
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
first = 0;
|
| 87 |
+
}
|
| 88 |
+
if (count != expected) {
|
| 89 |
+
PyErr_SetString(PyExc_ValueError, "posting count mismatch");
|
| 90 |
+
goto failed;
|
| 91 |
+
}
|
| 92 |
+
if (materialize) { entry = ids; ids = NULL; }
|
| 93 |
+
else entry = Py_BuildValue("nnK", start, end, (unsigned long long)expected);
|
| 94 |
+
if (!entry || PyDict_SetItem(output, key, entry) < 0) goto failed;
|
| 95 |
+
Py_CLEAR(entry);
|
| 96 |
+
Py_CLEAR(key);
|
| 97 |
+
}
|
| 98 |
+
if (offset != buffer.len) {
|
| 99 |
+
PyErr_SetString(PyExc_ValueError, "trailing postings");
|
| 100 |
+
goto failed;
|
| 101 |
+
}
|
| 102 |
+
goto done;
|
| 103 |
+
failed:
|
| 104 |
+
Py_CLEAR(output);
|
| 105 |
+
done:
|
| 106 |
+
Py_XDECREF(key);
|
| 107 |
+
Py_XDECREF(ids);
|
| 108 |
+
Py_XDECREF(entry);
|
| 109 |
+
PyBuffer_Release(&buffer);
|
| 110 |
+
return output;
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
static PyMethodDef methods[] = {
|
| 114 |
+
{"read_entries", read_entries, METH_VARARGS, "Decode and fully validate posting entries."},
|
| 115 |
+
{NULL, NULL, 0, NULL}
|
| 116 |
+
};
|
| 117 |
+
static struct PyModuleDef module = {
|
| 118 |
+
PyModuleDef_HEAD_INIT, "_search_index_native", NULL, -1, methods,
|
| 119 |
+
NULL, NULL, NULL, NULL
|
| 120 |
+
};
|
| 121 |
+
PyMODINIT_FUNC PyInit__search_index_native(void) { return PyModule_Create(&module); }
|
search_indexes.py
CHANGED
|
@@ -8,6 +8,11 @@ handling testable without importing application state.
|
|
| 8 |
import gzip
|
| 9 |
from pathlib import Path
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
NGRAM_MAGIC = b"VNG3"
|
| 13 |
WORD_INDEX_MAGIC = b"VWI2"
|
|
@@ -96,6 +101,17 @@ def _read_posting_entries(data: bytes, offset: int, count: int, record_count: in
|
|
| 96 |
raise ValueError("trailing postings")
|
| 97 |
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
def load_ngram_index(
|
| 100 |
path: Path,
|
| 101 |
width: int,
|
|
@@ -113,10 +129,7 @@ def load_ngram_index(
|
|
| 113 |
count, offset = decode_varint(data, offset)
|
| 114 |
if stored_record_count != record_count:
|
| 115 |
return {}, b""
|
| 116 |
-
postings =
|
| 117 |
-
key: location
|
| 118 |
-
for key, location, _ in _read_posting_entries(data, offset, count, record_count, materialize=False)
|
| 119 |
-
}
|
| 120 |
return postings, data
|
| 121 |
except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError):
|
| 122 |
return {}, b""
|
|
@@ -138,10 +151,7 @@ def load_word_index(path: Path, record_count: int, expected_digest: bytes) -> di
|
|
| 138 |
count, offset = decode_varint(data, offset)
|
| 139 |
if stored_record_count != record_count:
|
| 140 |
return {}
|
| 141 |
-
return
|
| 142 |
-
key: decoded
|
| 143 |
-
for key, _, decoded in _read_posting_entries(data, offset, count, record_count)
|
| 144 |
-
}
|
| 145 |
except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError):
|
| 146 |
return {}
|
| 147 |
|
|
|
|
| 8 |
import gzip
|
| 9 |
from pathlib import Path
|
| 10 |
|
| 11 |
+
try:
|
| 12 |
+
from _search_index_native import read_entries as _native_read_entries
|
| 13 |
+
except ImportError:
|
| 14 |
+
_native_read_entries = None
|
| 15 |
+
|
| 16 |
|
| 17 |
NGRAM_MAGIC = b"VNG3"
|
| 18 |
WORD_INDEX_MAGIC = b"VWI2"
|
|
|
|
| 101 |
raise ValueError("trailing postings")
|
| 102 |
|
| 103 |
|
| 104 |
+
def _load_posting_entries(data, offset, count, record_count, materialize):
|
| 105 |
+
if _native_read_entries is not None:
|
| 106 |
+
try:
|
| 107 |
+
return _native_read_entries(data, offset, count, record_count, materialize)
|
| 108 |
+
except OverflowError:
|
| 109 |
+
# Retain arbitrary-width varint behavior for unusual valid inputs.
|
| 110 |
+
pass
|
| 111 |
+
return {key: decoded if materialize else location
|
| 112 |
+
for key, location, decoded in _read_posting_entries(data, offset, count, record_count, materialize)}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
def load_ngram_index(
|
| 116 |
path: Path,
|
| 117 |
width: int,
|
|
|
|
| 129 |
count, offset = decode_varint(data, offset)
|
| 130 |
if stored_record_count != record_count:
|
| 131 |
return {}, b""
|
| 132 |
+
postings = _load_posting_entries(data, offset, count, record_count, False)
|
|
|
|
|
|
|
|
|
|
| 133 |
return postings, data
|
| 134 |
except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError):
|
| 135 |
return {}, b""
|
|
|
|
| 151 |
count, offset = decode_varint(data, offset)
|
| 152 |
if stored_record_count != record_count:
|
| 153 |
return {}
|
| 154 |
+
return _load_posting_entries(data, offset, count, record_count, True)
|
|
|
|
|
|
|
|
|
|
| 155 |
except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError):
|
| 156 |
return {}
|
| 157 |
|
static/app.js
CHANGED
|
@@ -1,3 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
const ORDERED_EXTENSIONS = [
|
| 2 |
"pdf", "djvu",
|
| 3 |
"txt", "md",
|
|
@@ -120,7 +155,7 @@ const KEEPALIVE_MIN_GAP_MS = 30 * 1000;
|
|
| 120 |
const sidebarRetryCounts = new Map();
|
| 121 |
const SEARCH_CACHE_TTL = 8 * 60 * 1000;
|
| 122 |
const SEARCH_CACHE_MAX = 60;
|
| 123 |
-
const searchResponseCache = new
|
| 124 |
const initialPayloadCache = new Map();
|
| 125 |
const sidebarInitialCache = new Map();
|
| 126 |
const sidebarInitialPending = new Map();
|
|
@@ -1245,16 +1280,11 @@ function getCachedSearchResponse(key) {
|
|
| 1245 |
searchResponseCache.delete(key);
|
| 1246 |
return null;
|
| 1247 |
}
|
| 1248 |
-
searchResponseCache.delete(key);
|
| 1249 |
-
searchResponseCache.set(key, cached);
|
| 1250 |
return cloneSearchData(cached.data);
|
| 1251 |
}
|
| 1252 |
|
| 1253 |
function setCachedSearchResponse(key, data) {
|
| 1254 |
searchResponseCache.set(key, { time: Date.now(), data: cloneSearchData(data) });
|
| 1255 |
-
while (searchResponseCache.size > SEARCH_CACHE_MAX) {
|
| 1256 |
-
searchResponseCache.delete(searchResponseCache.keys().next().value);
|
| 1257 |
-
}
|
| 1258 |
}
|
| 1259 |
|
| 1260 |
function warmConnection(force = false) {
|
|
@@ -2043,7 +2073,7 @@ function getReaderLink(rec, returnUrl = location.href, cacheMetadata = true) {
|
|
| 2043 |
readerRecord.OcrUrl = `/txt/${encodeRecordPath(VoiceOfMLReader.txtRelativePath(relPath))}`;
|
| 2044 |
}
|
| 2045 |
const readerUrl = VoiceOfMLReader.readerUrl(readerRecord, "/static/reader.html");
|
| 2046 |
-
if (cacheMetadata) try { const readerId = new URL(readerUrl, location.origin).searchParams.get("id"); if (readerId) { const sourceData = { url: readerRecord.ReaderLink || readerRecord.Link, download: readerRecord.Link, title: readerRecord.File, extension: readerRecord.ReaderExtension || readerRecord.Extension, original_extension: readerRecord.Extension, repo: String(readerRecord.Repo || "").split("/").pop(), folder: readerRecord.Folder, chapter_manifest: readerRecord.ReaderChapterManifest || "", fallback: readerRecord.ReaderFallback || "" }; cacheReaderMetadata(readerId, sourceData, true); } } catch (_) {}
|
| 2047 |
return readerUrl;
|
| 2048 |
}
|
| 2049 |
|
|
@@ -2356,7 +2386,7 @@ const API = {
|
|
| 2356 |
getFolders(repo) { return fetchMetadataList(`/api/folders/${repo}`); },
|
| 2357 |
async getContents(repo, path) {
|
| 2358 |
const cacheKey = repo + "|" + (path || "");
|
| 2359 |
-
if (!this._browserCache) this._browserCache = new
|
| 2360 |
if (!this._browserPending) this._browserPending = new Map();
|
| 2361 |
if (this._browserCache.has(cacheKey)) return this._browserCache.get(cacheKey);
|
| 2362 |
if (this._browserPending.has(cacheKey)) return this._browserPending.get(cacheKey);
|
|
@@ -2367,10 +2397,6 @@ const API = {
|
|
| 2367 |
throw new Error("Invalid folder contents response");
|
| 2368 |
}
|
| 2369 |
this._browserCache.set(cacheKey, data);
|
| 2370 |
-
if (this._browserCache.size > 200) {
|
| 2371 |
-
const firstKey = this._browserCache.keys().next().value;
|
| 2372 |
-
this._browserCache.delete(firstKey);
|
| 2373 |
-
}
|
| 2374 |
return data;
|
| 2375 |
})
|
| 2376 |
.finally(() => {
|
|
@@ -3710,10 +3736,13 @@ function prefetchNextPage() {
|
|
| 3710 |
}
|
| 3711 |
|
| 3712 |
function appendSearchResults(page, results = STATE._pageCache[page]) {
|
| 3713 |
-
|
|
|
|
|
|
|
| 3714 |
delete STATE._pageCache[page];
|
| 3715 |
STATE._loadedPage = page;
|
| 3716 |
STATE.hasMore = STATE.results.length < STATE.total;
|
|
|
|
| 3717 |
}
|
| 3718 |
|
| 3719 |
function deferSearchAppend() {
|
|
@@ -3725,7 +3754,26 @@ function deferSearchAppend() {
|
|
| 3725 |
}
|
| 3726 |
|
| 3727 |
// Network and cached pages share the same state transition.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3728 |
function applySearchPage(data, append) {
|
|
|
|
|
|
|
| 3729 |
STATE.total = data.total;
|
| 3730 |
if (append) {
|
| 3731 |
STATE._pageCache[data.page] = data.results;
|
|
@@ -3742,7 +3790,7 @@ function applySearchPage(data, append) {
|
|
| 3742 |
|
| 3743 |
function consumeCachedAppendPage() {
|
| 3744 |
if (!STATE._pageCache[STATE.page]) return false;
|
| 3745 |
-
appendSearchResults(STATE.page);
|
| 3746 |
STATE.page = STATE._loadedPage;
|
| 3747 |
STATE._pendingPage = 0;
|
| 3748 |
STATE.isLoading = false;
|
|
|
|
| 1 |
+
class BoundedResponseCache extends Map {
|
| 2 |
+
constructor(limit, ttl, budget = 8 * 1024 * 1024) {
|
| 3 |
+
super();
|
| 4 |
+
this.limit = limit; this.ttl = ttl; this.budget = budget;
|
| 5 |
+
this.bytes = 0; this.entriesInfo = new Map();
|
| 6 |
+
}
|
| 7 |
+
delete(key) {
|
| 8 |
+
this.bytes -= this.entriesInfo.get(key)?.bytes || 0;
|
| 9 |
+
this.entriesInfo.delete(key);
|
| 10 |
+
return super.delete(key);
|
| 11 |
+
}
|
| 12 |
+
clear() { super.clear(); this.entriesInfo.clear(); this.bytes = 0; }
|
| 13 |
+
get(key) {
|
| 14 |
+
const info = this.entriesInfo.get(key);
|
| 15 |
+
if (!info) return undefined;
|
| 16 |
+
if (Date.now() - info.time >= this.ttl) { this.delete(key); return undefined; }
|
| 17 |
+
const value = super.get(key);
|
| 18 |
+
super.delete(key); super.set(key, value);
|
| 19 |
+
return value;
|
| 20 |
+
}
|
| 21 |
+
has(key) { return this.get(key) !== undefined; }
|
| 22 |
+
set(key, value) {
|
| 23 |
+
this.delete(key);
|
| 24 |
+
const now = Date.now();
|
| 25 |
+
for (const [oldKey, info] of this.entriesInfo) if (now - info.time >= this.ttl) this.delete(oldKey);
|
| 26 |
+
// UTF-16 serialized content budget, not an engine-specific heap estimate.
|
| 27 |
+
const bytes = 2 * (JSON.stringify(value).length + String(key).length);
|
| 28 |
+
if (bytes > Math.min(this.budget, 1024 * 1024)) return this;
|
| 29 |
+
while (this.size && (this.size >= this.limit || this.bytes + bytes > this.budget)) this.delete(this.keys().next().value);
|
| 30 |
+
super.set(key, value);
|
| 31 |
+
this.entriesInfo.set(key, {bytes, time: now}); this.bytes += bytes;
|
| 32 |
+
return this;
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
const ORDERED_EXTENSIONS = [
|
| 37 |
"pdf", "djvu",
|
| 38 |
"txt", "md",
|
|
|
|
| 155 |
const sidebarRetryCounts = new Map();
|
| 156 |
const SEARCH_CACHE_TTL = 8 * 60 * 1000;
|
| 157 |
const SEARCH_CACHE_MAX = 60;
|
| 158 |
+
const searchResponseCache = new BoundedResponseCache(SEARCH_CACHE_MAX, SEARCH_CACHE_TTL);
|
| 159 |
const initialPayloadCache = new Map();
|
| 160 |
const sidebarInitialCache = new Map();
|
| 161 |
const sidebarInitialPending = new Map();
|
|
|
|
| 1280 |
searchResponseCache.delete(key);
|
| 1281 |
return null;
|
| 1282 |
}
|
|
|
|
|
|
|
| 1283 |
return cloneSearchData(cached.data);
|
| 1284 |
}
|
| 1285 |
|
| 1286 |
function setCachedSearchResponse(key, data) {
|
| 1287 |
searchResponseCache.set(key, { time: Date.now(), data: cloneSearchData(data) });
|
|
|
|
|
|
|
|
|
|
| 1288 |
}
|
| 1289 |
|
| 1290 |
function warmConnection(force = false) {
|
|
|
|
| 2073 |
readerRecord.OcrUrl = `/txt/${encodeRecordPath(VoiceOfMLReader.txtRelativePath(relPath))}`;
|
| 2074 |
}
|
| 2075 |
const readerUrl = VoiceOfMLReader.readerUrl(readerRecord, "/static/reader.html");
|
| 2076 |
+
if (cacheMetadata) try { const readerId = new URL(readerUrl, location.origin).searchParams.get("id"); if (readerId) { const sourceData = { url: readerRecord.ReaderLink || readerRecord.Link, download: readerRecord.Link, title: readerRecord.File, extension: readerRecord.ReaderExtension || readerRecord.Extension, original_extension: readerRecord.Extension, repo: String(readerRecord.Repo || "").split("/").pop(), folder: readerRecord.Folder, chapter_manifest: readerRecord.ReaderChapterManifest || "", fallback: readerRecord.ReaderFallback || "", pdf_document: readerRecord.ReaderPdfDocument || "" }; cacheReaderMetadata(readerId, sourceData, true); } } catch (_) {}
|
| 2077 |
return readerUrl;
|
| 2078 |
}
|
| 2079 |
|
|
|
|
| 2386 |
getFolders(repo) { return fetchMetadataList(`/api/folders/${repo}`); },
|
| 2387 |
async getContents(repo, path) {
|
| 2388 |
const cacheKey = repo + "|" + (path || "");
|
| 2389 |
+
if (!this._browserCache) this._browserCache = new BoundedResponseCache(200, 5 * 60 * 1000);
|
| 2390 |
if (!this._browserPending) this._browserPending = new Map();
|
| 2391 |
if (this._browserCache.has(cacheKey)) return this._browserCache.get(cacheKey);
|
| 2392 |
if (this._browserPending.has(cacheKey)) return this._browserPending.get(cacheKey);
|
|
|
|
| 2397 |
throw new Error("Invalid folder contents response");
|
| 2398 |
}
|
| 2399 |
this._browserCache.set(cacheKey, data);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2400 |
return data;
|
| 2401 |
})
|
| 2402 |
.finally(() => {
|
|
|
|
| 3736 |
}
|
| 3737 |
|
| 3738 |
function appendSearchResults(page, results = STATE._pageCache[page]) {
|
| 3739 |
+
const metadata = searchPageMetadata.get(results?.[0]);
|
| 3740 |
+
if (!checkSearchPageAppend({ ...metadata, results, total: metadata?.total ?? STATE.total })) return false;
|
| 3741 |
+
for (const record of results) STATE.results.push(record);
|
| 3742 |
delete STATE._pageCache[page];
|
| 3743 |
STATE._loadedPage = page;
|
| 3744 |
STATE.hasMore = STATE.results.length < STATE.total;
|
| 3745 |
+
return true;
|
| 3746 |
}
|
| 3747 |
|
| 3748 |
function deferSearchAppend() {
|
|
|
|
| 3754 |
}
|
| 3755 |
|
| 3756 |
// Network and cached pages share the same state transition.
|
| 3757 |
+
function checkSearchPageAppend(data) {
|
| 3758 |
+
const expected = searchPageMetadata.get(STATE.results[0]);
|
| 3759 |
+
const generation = data.generation ?? searchPageMetadata.get(data.results?.[0])?.generation;
|
| 3760 |
+
if (data.total === STATE.total && (!expected?.generation || generation === expected.generation)) return true;
|
| 3761 |
+
const key = getSearchViewKey(), scroll = captureReaderReturnScroll();
|
| 3762 |
+
const record = STATE.results[scroll.index] || STATE.results[0];
|
| 3763 |
+
const position = { version: 1, key, index: scroll.index, offset: scroll.offset,
|
| 3764 |
+
anchorId: getResultStableId(record), loadedPage: STATE._loadedPage, savedAt: Date.now() };
|
| 3765 |
+
const returnTarget = getReturnPositionTarget(key);
|
| 3766 |
+
searchResponseCache.clear();
|
| 3767 |
+
searchViewSnapshots.delete(key);
|
| 3768 |
+
STATE._pageCache = {};
|
| 3769 |
+
tryRestoreSearchPosition(key, { position, viewport: null });
|
| 3770 |
+
if (returnTarget) setReturnPositionTarget(returnTarget);
|
| 3771 |
+
return false;
|
| 3772 |
+
}
|
| 3773 |
+
|
| 3774 |
function applySearchPage(data, append) {
|
| 3775 |
+
if (append && !checkSearchPageAppend(data)) return false;
|
| 3776 |
+
rememberSearchPageMetadata(data);
|
| 3777 |
STATE.total = data.total;
|
| 3778 |
if (append) {
|
| 3779 |
STATE._pageCache[data.page] = data.results;
|
|
|
|
| 3790 |
|
| 3791 |
function consumeCachedAppendPage() {
|
| 3792 |
if (!STATE._pageCache[STATE.page]) return false;
|
| 3793 |
+
if (!appendSearchResults(STATE.page)) return false;
|
| 3794 |
STATE.page = STATE._loadedPage;
|
| 3795 |
STATE._pendingPage = 0;
|
| 3796 |
STATE.isLoading = false;
|
static/reader-contract.js
CHANGED
|
@@ -391,7 +391,10 @@
|
|
| 391 |
: "",
|
| 392 |
ReaderFallback: asset.f ? assetBase + asset.f : "",
|
| 393 |
ReaderOcrManifest: ocrUrl || (ocrPath.endsWith("/ocr-manifest.json") ? assetBase + ocrPath : ""),
|
| 394 |
-
ReaderOcrMode: String(asset.om || "")
|
|
|
|
|
|
|
|
|
|
| 395 |
};
|
| 396 |
}
|
| 397 |
|
|
@@ -422,6 +425,7 @@
|
|
| 422 |
params.set("ocr_manifest", record.ReaderOcrManifest || record.readerOcrManifest);
|
| 423 |
if (!shortId && (record.ReaderFallback || record.readerFallback))
|
| 424 |
params.set("fallback", record.ReaderFallback || record.readerFallback);
|
|
|
|
| 425 |
if (
|
| 426 |
!shortId &&
|
| 427 |
(record.ReaderChapterManifest ||
|
|
|
|
| 391 |
: "",
|
| 392 |
ReaderFallback: asset.f ? assetBase + asset.f : "",
|
| 393 |
ReaderOcrManifest: ocrUrl || (ocrPath.endsWith("/ocr-manifest.json") ? assetBase + ocrPath : ""),
|
| 394 |
+
ReaderOcrMode: String(asset.om || ""),
|
| 395 |
+
ReaderPdfDocument: asset.pd && ["vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"].includes(asset.pdb) &&
|
| 396 |
+
isBucketPath(asset.pd, true, asset.pdb) && asset.pd.endsWith("/document.pdf")
|
| 397 |
+
? `${bucketBase}?path=${encodeURIComponent(asset.pd)}` : ""
|
| 398 |
};
|
| 399 |
}
|
| 400 |
|
|
|
|
| 425 |
params.set("ocr_manifest", record.ReaderOcrManifest || record.readerOcrManifest);
|
| 426 |
if (!shortId && (record.ReaderFallback || record.readerFallback))
|
| 427 |
params.set("fallback", record.ReaderFallback || record.readerFallback);
|
| 428 |
+
if (!shortId && record.ReaderPdfDocument) params.set("pdf_document", record.ReaderPdfDocument);
|
| 429 |
if (
|
| 430 |
!shortId &&
|
| 431 |
(record.ReaderChapterManifest ||
|
static/reader.css
CHANGED
|
@@ -127,6 +127,13 @@ body {
|
|
| 127 |
text-align: right;
|
| 128 |
font: inherit;
|
| 129 |
outline: none;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
}
|
| 131 |
.icon-button {
|
| 132 |
width: 32px;
|
|
|
|
| 127 |
text-align: right;
|
| 128 |
font: inherit;
|
| 129 |
outline: none;
|
| 130 |
+
padding: 0 2px;
|
| 131 |
+
appearance: textfield;
|
| 132 |
+
}
|
| 133 |
+
.compact-input input::-webkit-inner-spin-button,
|
| 134 |
+
.compact-input input::-webkit-outer-spin-button {
|
| 135 |
+
appearance: none;
|
| 136 |
+
margin: 0;
|
| 137 |
}
|
| 138 |
.icon-button {
|
| 139 |
width: 32px;
|
static/reader.js
CHANGED
|
@@ -53,15 +53,15 @@ function stopReaderWork() {
|
|
| 53 |
}
|
| 54 |
readerRuntime.track(stopReaderWork);
|
| 55 |
trackReaderResource(() => window.__VOICE_READER_RESOLVE__?.dispose());
|
| 56 |
-
function awaitReader(promise) {
|
| 57 |
return new Promise((resolve, reject) => {
|
| 58 |
-
const
|
| 59 |
abort = () => reject(readerAbortError());
|
| 60 |
Promise.resolve(promise)
|
| 61 |
.then(resolve, reject)
|
| 62 |
-
.finally(() => signal.removeEventListener("abort", abort));
|
| 63 |
-
if (signal.aborted) abort();
|
| 64 |
-
else signal.addEventListener("abort", abort, { once: true });
|
| 65 |
});
|
| 66 |
}
|
| 67 |
function waitForReader(delay = 0, animationFrame = false) {
|
|
@@ -191,6 +191,9 @@ let cachedReaderData = null;
|
|
| 191 |
let pdfFirstPagePreload = null;
|
| 192 |
let pdfFirstPagePreloadPage = 1;
|
| 193 |
let pdfEnginePreload = null;
|
|
|
|
|
|
|
|
|
|
| 194 |
let pdfWorker = null;
|
| 195 |
let releasePdfWorker = null;
|
| 196 |
if (localReaderData) {
|
|
@@ -816,6 +819,9 @@ document.querySelector("#back").addEventListener("click", async () => {
|
|
| 816 |
let zoomChangedByUser = false;
|
| 817 |
function setZoom(percent, persist = true) {
|
| 818 |
const anchor = foliateScrollAnchors.capture();
|
|
|
|
|
|
|
|
|
|
| 819 |
const normalized = VoiceOfMLReader.clampNumber(percent, 25, 400, 100);
|
| 820 |
const horizontalCenter = viewport.scrollWidth
|
| 821 |
? (viewport.scrollLeft + viewport.clientWidth / 2) / viewport.scrollWidth
|
|
@@ -824,6 +830,10 @@ function setZoom(percent, persist = true) {
|
|
| 824 |
content.style.setProperty("--reader-zoom", String(documentState.zoom));
|
| 825 |
zoomInput.value = String(normalized);
|
| 826 |
pdfShellWindow?.resize();
|
|
|
|
|
|
|
|
|
|
|
|
|
| 827 |
if (htmlFrame && htmlFrame.contentDocument)
|
| 828 |
htmlFrame.contentDocument.documentElement.style.zoom = String(documentState.zoom);
|
| 829 |
if (pdfDocument) rerenderVisiblePdfPages();
|
|
@@ -2740,6 +2750,7 @@ function prioritizePdfManifestPrefetch(target) {
|
|
| 2740 |
if (record && pdfManifestPrefetchActive.has(record)) record.image.fetchPriority = "high";
|
| 2741 |
}
|
| 2742 |
function schedulePdfManifestPrefetch(page) {
|
|
|
|
| 2743 |
if (!["pdf-pages", "image-pages"].includes(capability.mode) || !pdfPageManifest) return;
|
| 2744 |
const origin = Math.max(1, Math.min(documentState.pageCount + 1, page + 1));
|
| 2745 |
if (pdfManifestPrefetchOrigin === origin && pdfManifestPrefetchNext) {
|
|
@@ -2918,7 +2929,8 @@ async function renderPdfOcrText(shell) {
|
|
| 2918 |
return task;
|
| 2919 |
}
|
| 2920 |
function trimPdfManifestImages(protectedShell) {
|
| 2921 |
-
const images = [...content.querySelectorAll('.reader-page[data-render-state="rendered"]')]
|
|
|
|
| 2922 |
if (images.length <= 25) return;
|
| 2923 |
images.sort(
|
| 2924 |
(a, b) =>
|
|
@@ -3182,6 +3194,7 @@ function createPdfShellWindow(total, firstShell, createShell, unobserve, default
|
|
| 3182 |
if (bounds.width && bounds.height) ratios.set(page, bounds.height / bounds.width);
|
| 3183 |
shell._textEpoch = (shell._textEpoch || 0) + 1;
|
| 3184 |
shell._renderCancel?.();
|
|
|
|
| 3185 |
unobserve(shell);
|
| 3186 |
pdfManifestShells[page] = undefined;
|
| 3187 |
}
|
|
@@ -3261,6 +3274,21 @@ async function renderPdfPages(prepared) {
|
|
| 3261 |
const totalPages = manifest.page_count;
|
| 3262 |
if (!source) throw new Error("PDF_MANIFEST_INVALID");
|
| 3263 |
pdfPageManifest = { ...source, pageCount: totalPages };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3264 |
updateDocumentState({ pageCount: totalPages });
|
| 3265 |
pageInput.max = String(totalPages);
|
| 3266 |
document.querySelector("#page-total").textContent = `/ ${totalPages}`;
|
|
@@ -3328,6 +3356,7 @@ async function renderPdfPages(prepared) {
|
|
| 3328 |
const shell = document.createElement("section");
|
| 3329 |
shell.className = "reader-page";
|
| 3330 |
shell.dataset.page = String(page);
|
|
|
|
| 3331 |
shell.style.aspectRatio = "1 / 1.414";
|
| 3332 |
pdfManifestShells[page] = shell;
|
| 3333 |
shell.tabIndex = 0;
|
|
@@ -3571,7 +3600,10 @@ function renderPdfInBackground(shell, force = false, priority = pdfPagePriority(
|
|
| 3571 |
const image = shell.querySelector("img");
|
| 3572 |
if (image) image.fetchPriority = priority >= 3 ? "high" : "auto";
|
| 3573 |
}
|
| 3574 |
-
if (force)
|
|
|
|
|
|
|
|
|
|
| 3575 |
return shell._backgroundRender;
|
| 3576 |
}
|
| 3577 |
const task =
|
|
@@ -3598,12 +3630,131 @@ function renderPdfInBackground(shell, force = false, priority = pdfPagePriority(
|
|
| 3598 |
});
|
| 3599 |
return task;
|
| 3600 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3601 |
function renderPdfManifestShell(shell, force = false, priority = false) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3602 |
if (!shell) return Promise.reject(new Error("PDF page shell missing"));
|
| 3603 |
if (shell._renderPromise) return shell._renderPromise;
|
| 3604 |
if (!force && shell.dataset.renderState === "rendered") return Promise.resolve();
|
| 3605 |
shell.dataset.renderState = "rendering";
|
| 3606 |
const renderController = new AbortController();
|
|
|
|
| 3607 |
shell._renderCancel = () => renderController.abort();
|
| 3608 |
shell._renderStarted = false;
|
| 3609 |
priority = normalizePdfPriority(priority || pdfPagePriority(shell));
|
|
@@ -3611,7 +3762,14 @@ function renderPdfManifestShell(shell, force = false, priority = false) {
|
|
| 3611 |
const task = (async () => {
|
| 3612 |
let acquired = false;
|
| 3613 |
try {
|
| 3614 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3615 |
acquired = true;
|
| 3616 |
shell._renderStarted = true;
|
| 3617 |
assertReaderActive();
|
|
@@ -3661,7 +3819,8 @@ function renderPdfManifestShell(shell, force = false, priority = false) {
|
|
| 3661 |
if (image.complete && image.naturalWidth) finish();
|
| 3662 |
});
|
| 3663 |
assertReaderActive();
|
| 3664 |
-
|
|
|
|
| 3665 |
if (priority >= 2 && ocrManifestUrl && !navigator.connection?.saveData)
|
| 3666 |
loadText ||= renderPdfOcrText(shell);
|
| 3667 |
loadText?.catch(() => {});
|
|
@@ -3677,14 +3836,17 @@ function renderPdfManifestShell(shell, force = false, priority = false) {
|
|
| 3677 |
} catch (error) {
|
| 3678 |
shell.querySelector("img")?.remove();
|
| 3679 |
const pageState = shell.querySelector(".reader-page-state");
|
| 3680 |
-
|
| 3681 |
pageState.hidden = false;
|
| 3682 |
pageState.textContent = "้กต้ขๅ ่ฝฝๅคฑ่ดฅ๏ผๆญฃๅจ้่ฏโฆ";
|
| 3683 |
}
|
| 3684 |
-
shell.dataset.renderState = "idle";
|
| 3685 |
throw error;
|
| 3686 |
} finally {
|
| 3687 |
-
if (acquired)
|
|
|
|
|
|
|
|
|
|
| 3688 |
}
|
| 3689 |
})().finally(() => {
|
| 3690 |
if (shell._renderPromise === task) delete shell._renderPromise;
|
|
@@ -3696,13 +3858,15 @@ function renderPdfManifestShell(shell, force = false, priority = false) {
|
|
| 3696 |
return task;
|
| 3697 |
}
|
| 3698 |
function cancelSpeculativePdfRenders(protectedShell) {
|
| 3699 |
-
for (const shell of content.querySelectorAll('.reader-page
|
|
|
|
| 3700 |
if (
|
| 3701 |
shell === protectedShell ||
|
| 3702 |
isPdfPageVisible(shell)
|
| 3703 |
)
|
| 3704 |
continue;
|
| 3705 |
shell._renderCancel?.();
|
|
|
|
| 3706 |
}
|
| 3707 |
}
|
| 3708 |
function renderPdfShell(shell, force = false, priority = false) {
|
|
@@ -3934,7 +4098,8 @@ function releasePdfTextSlot() {
|
|
| 3934 |
}
|
| 3935 |
function trimPdfCanvases(protectedShell) {
|
| 3936 |
const limit = matchMedia("(max-width: 700px)").matches ? 7 : 11;
|
| 3937 |
-
const rendered = [...content.querySelectorAll('.reader-page[data-render-state="rendered"]')]
|
|
|
|
| 3938 |
if (rendered.length <= limit) return;
|
| 3939 |
rendered.sort((a, b) => {
|
| 3940 |
const aVisible =
|
|
@@ -4740,6 +4905,8 @@ function disposeFormatResources(mode) {
|
|
| 4740 |
}
|
| 4741 |
if (["pdf", "pdf-pages", "image-pages"].includes(mode)) {
|
| 4742 |
pdfDocument = null;
|
|
|
|
|
|
|
| 4743 |
pdfPageManifest = null;
|
| 4744 |
pdfOcrManifest = null;
|
| 4745 |
pdfOcrManifestPromise = null;
|
|
@@ -4992,7 +5159,7 @@ async function resolveReaderSource() {
|
|
| 4992 |
)
|
| 4993 |
extension = "pdf-pages";
|
| 4994 |
capability = readerRuntime.negotiate(VoiceOfMLReader.capability(extension));
|
| 4995 |
-
if (capability.mode !== "pdf") releasePdfWorker?.();
|
| 4996 |
readerRuntime.update("source", {
|
| 4997 |
url: sourceUrl,
|
| 4998 |
contentUrl,
|
|
@@ -5157,12 +5324,12 @@ function loadPdfTaskWithTimeout(pdfjs, options, url) {
|
|
| 5157 |
);
|
| 5158 |
});
|
| 5159 |
}
|
| 5160 |
-
function loadPdfWithTimeout(pdfjs, options) {
|
| 5161 |
-
return retryReaderProxy(() => loadPdfTaskWithTimeout(pdfjs, options,
|
| 5162 |
assertReaderActive();
|
| 5163 |
if (error && error.name === "AbortError") throw error;
|
| 5164 |
if (retryableReaderProxyError(error)) throw error;
|
| 5165 |
-
return loadPdfTaskWithTimeout(pdfjs, options,
|
| 5166 |
});
|
| 5167 |
}
|
| 5168 |
function preloadPdfEngine() {
|
|
@@ -5171,7 +5338,7 @@ function preloadPdfEngine() {
|
|
| 5171 |
}
|
| 5172 |
async function preparePdfWorker(pdfjs) {
|
| 5173 |
assertReaderActive();
|
| 5174 |
-
if (capability.mode !== "pdf") return pdfjs;
|
| 5175 |
pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;
|
| 5176 |
const worker = new pdfjs.PDFWorker();
|
| 5177 |
pdfWorker = worker;
|
|
@@ -5248,7 +5415,7 @@ async function loadPdfEngine() {
|
|
| 5248 |
}
|
| 5249 |
}
|
| 5250 |
}
|
| 5251 |
-
function loadPdfDocument() {
|
| 5252 |
return preloadPdfEngine().then((pdfjs) => {
|
| 5253 |
assertReaderActive();
|
| 5254 |
if (!pdfFetchPolicy) {
|
|
@@ -5271,7 +5438,7 @@ function loadPdfDocument() {
|
|
| 5271 |
standardFontDataUrl: PDFJS_STANDARD_FONT_URL,
|
| 5272 |
withCredentials: false
|
| 5273 |
});
|
| 5274 |
-
return loadPdfWithTimeout(pdfjs, options);
|
| 5275 |
});
|
| 5276 |
}
|
| 5277 |
function loadTextDocument() {
|
|
@@ -5974,7 +6141,7 @@ document
|
|
| 5974 |
const fullSearchButton = document.querySelector("#full-search-toggle");
|
| 5975 |
fullSearchButton.textContent = "ๅ
จๆๆ็ดข";
|
| 5976 |
fullSearchButton.setAttribute("aria-label", "ๅ
จๆๆ็ดข");
|
| 5977 |
-
fullSearchButton.hidden = !capability.features.search || (capability.mode === "pdf-pages" && !ocrManifestUrl);
|
| 5978 |
const fullSearchInput = fullSearchView.querySelector("#full-search-input"),
|
| 5979 |
fullSearchStatus = fullSearchView.querySelector("#full-search-status"),
|
| 5980 |
fullSearchResultsNode = fullSearchView.querySelector("#full-search-results"),
|
|
@@ -6946,8 +7113,10 @@ async function runFullSearch() {
|
|
| 6946 |
}
|
| 6947 |
fullSearchStatus.textContent = "ๆญฃๅจๆ็ดขๆญฃๆโฆ";
|
| 6948 |
try {
|
| 6949 |
-
if (capability.mode === "pdf" && !ocrManifestUrl)
|
|
|
|
| 6950 |
await fullSearchPdfMatches(query, generation);
|
|
|
|
| 6951 |
else if (["pdf", "pdf-pages"].includes(capability.mode))
|
| 6952 |
publishSearchResults(generation, await searchConcentratedPdf(query, generation));
|
| 6953 |
else if (capability.mode === "foliate")
|
|
@@ -7127,7 +7296,7 @@ function syncCapabilityControls() {
|
|
| 7127 |
document.querySelector(".page-controls").hidden = !capability.features.pagination;
|
| 7128 |
document.querySelector(".zoom-controls").hidden = !capability.features.zoom;
|
| 7129 |
mediaTab.hidden = !capability.features.media;
|
| 7130 |
-
fullSearchButton.hidden = !capability.features.search || (capability.mode === "pdf-pages" && !ocrManifestUrl);
|
| 7131 |
bookmarkRibbon.hidden = !capability.features.bookmarks;
|
| 7132 |
readingProgressSummary.querySelector(".reader-progress-bookmark").hidden =
|
| 7133 |
!capability.features.bookmarks;
|
|
|
|
| 53 |
}
|
| 54 |
readerRuntime.track(stopReaderWork);
|
| 55 |
trackReaderResource(() => window.__VOICE_READER_RESOLVE__?.dispose());
|
| 56 |
+
function awaitReader(promise, extraSignal = null) {
|
| 57 |
return new Promise((resolve, reject) => {
|
| 58 |
+
const signals = extraSignal ? [readerAbortController.signal, extraSignal] : [readerAbortController.signal],
|
| 59 |
abort = () => reject(readerAbortError());
|
| 60 |
Promise.resolve(promise)
|
| 61 |
.then(resolve, reject)
|
| 62 |
+
.finally(() => signals.forEach(signal => signal.removeEventListener("abort", abort)));
|
| 63 |
+
if (signals.some(signal => signal.aborted)) abort();
|
| 64 |
+
else signals.forEach(signal => signal.addEventListener("abort", abort, { once: true }));
|
| 65 |
});
|
| 66 |
}
|
| 67 |
function waitForReader(delay = 0, animationFrame = false) {
|
|
|
|
| 191 |
let pdfFirstPagePreload = null;
|
| 192 |
let pdfFirstPagePreloadPage = 1;
|
| 193 |
let pdfEnginePreload = null;
|
| 194 |
+
let pdfHybridUrl = "";
|
| 195 |
+
let pdfHybridDocumentPromise = null;
|
| 196 |
+
let pdfHybridPreviewLoads = 0;
|
| 197 |
let pdfWorker = null;
|
| 198 |
let releasePdfWorker = null;
|
| 199 |
if (localReaderData) {
|
|
|
|
| 819 |
let zoomChangedByUser = false;
|
| 820 |
function setZoom(percent, persist = true) {
|
| 821 |
const anchor = foliateScrollAnchors.capture();
|
| 822 |
+
const pdfAnchor = pdfHybridUrl ? pageAtMarker() : null;
|
| 823 |
+
const pdfBounds = pdfAnchor?.getBoundingClientRect();
|
| 824 |
+
const pdfOffset = pdfBounds ? (viewport.getBoundingClientRect().top - pdfBounds.top) / Math.max(1, pdfBounds.height) : 0;
|
| 825 |
const normalized = VoiceOfMLReader.clampNumber(percent, 25, 400, 100);
|
| 826 |
const horizontalCenter = viewport.scrollWidth
|
| 827 |
? (viewport.scrollLeft + viewport.clientWidth / 2) / viewport.scrollWidth
|
|
|
|
| 830 |
content.style.setProperty("--reader-zoom", String(documentState.zoom));
|
| 831 |
zoomInput.value = String(normalized);
|
| 832 |
pdfShellWindow?.resize();
|
| 833 |
+
if (pdfAnchor?.isConnected) {
|
| 834 |
+
const bounds = pdfAnchor.getBoundingClientRect();
|
| 835 |
+
viewport.scrollTop += bounds.top - viewport.getBoundingClientRect().top + pdfOffset * bounds.height;
|
| 836 |
+
}
|
| 837 |
if (htmlFrame && htmlFrame.contentDocument)
|
| 838 |
htmlFrame.contentDocument.documentElement.style.zoom = String(documentState.zoom);
|
| 839 |
if (pdfDocument) rerenderVisiblePdfPages();
|
|
|
|
| 2750 |
if (record && pdfManifestPrefetchActive.has(record)) record.image.fetchPriority = "high";
|
| 2751 |
}
|
| 2752 |
function schedulePdfManifestPrefetch(page) {
|
| 2753 |
+
if (pdfHybridUrl) return;
|
| 2754 |
if (!["pdf-pages", "image-pages"].includes(capability.mode) || !pdfPageManifest) return;
|
| 2755 |
const origin = Math.max(1, Math.min(documentState.pageCount + 1, page + 1));
|
| 2756 |
if (pdfManifestPrefetchOrigin === origin && pdfManifestPrefetchNext) {
|
|
|
|
| 2929 |
return task;
|
| 2930 |
}
|
| 2931 |
function trimPdfManifestImages(protectedShell) {
|
| 2932 |
+
const images = [...content.querySelectorAll('.reader-page[data-render-state="rendered"]')]
|
| 2933 |
+
.filter((shell) => shell.querySelector("img"));
|
| 2934 |
if (images.length <= 25) return;
|
| 2935 |
images.sort(
|
| 2936 |
(a, b) =>
|
|
|
|
| 3194 |
if (bounds.width && bounds.height) ratios.set(page, bounds.height / bounds.width);
|
| 3195 |
shell._textEpoch = (shell._textEpoch || 0) + 1;
|
| 3196 |
shell._renderCancel?.();
|
| 3197 |
+
shell._hybridCancel?.();
|
| 3198 |
unobserve(shell);
|
| 3199 |
pdfManifestShells[page] = undefined;
|
| 3200 |
}
|
|
|
|
| 3274 |
const totalPages = manifest.page_count;
|
| 3275 |
if (!source) throw new Error("PDF_MANIFEST_INVALID");
|
| 3276 |
pdfPageManifest = { ...source, pageCount: totalPages };
|
| 3277 |
+
pdfHybridUrl = pdfPrimarySource();
|
| 3278 |
+
if (pdfHybridUrl) {
|
| 3279 |
+
pdfHybridDocumentPromise = loadPdfDocument(pdfHybridUrl).then((pdf) => {
|
| 3280 |
+
assertReaderActive();
|
| 3281 |
+
if (pdf.numPages !== totalPages) throw new Error("PDF_PRIMARY_PAGE_COUNT_MISMATCH");
|
| 3282 |
+
pdfDocument = pdf;
|
| 3283 |
+
clearPdfManifestPrefetches();
|
| 3284 |
+
syncCapabilityControls();
|
| 3285 |
+
return pdf;
|
| 3286 |
+
});
|
| 3287 |
+
pdfHybridDocumentPromise.catch((error) => {
|
| 3288 |
+
if (error?.name !== "AbortError" && !readerLifecycle.disposed)
|
| 3289 |
+
console.warn("Primary PDF unavailable; page stream retained", error);
|
| 3290 |
+
});
|
| 3291 |
+
}
|
| 3292 |
updateDocumentState({ pageCount: totalPages });
|
| 3293 |
pageInput.max = String(totalPages);
|
| 3294 |
document.querySelector("#page-total").textContent = `/ ${totalPages}`;
|
|
|
|
| 3356 |
const shell = document.createElement("section");
|
| 3357 |
shell.className = "reader-page";
|
| 3358 |
shell.dataset.page = String(page);
|
| 3359 |
+
if (pdfHybridUrl) shell.dataset.pdfHybrid = "1";
|
| 3360 |
shell.style.aspectRatio = "1 / 1.414";
|
| 3361 |
pdfManifestShells[page] = shell;
|
| 3362 |
shell.tabIndex = 0;
|
|
|
|
| 3600 |
const image = shell.querySelector("img");
|
| 3601 |
if (image) image.fetchPriority = priority >= 3 ? "high" : "auto";
|
| 3602 |
}
|
| 3603 |
+
if (force) {
|
| 3604 |
+
shell.dataset.pendingRerender = "1";
|
| 3605 |
+
if (pdfHybridUrl) shell.dataset.pendingHybridRerender = "1";
|
| 3606 |
+
}
|
| 3607 |
return shell._backgroundRender;
|
| 3608 |
}
|
| 3609 |
const task =
|
|
|
|
| 3630 |
});
|
| 3631 |
return task;
|
| 3632 |
}
|
| 3633 |
+
function pdfPrimarySource() {
|
| 3634 |
+
if (capability.mode !== "pdf-pages") return "";
|
| 3635 |
+
const candidate = normalizeSourceUrl(params.get("pdf_document") || resolvedReaderData?.pdf_document ||
|
| 3636 |
+
(resolvedReaderData?.original_extension === "pdf" || /\.pdf(?:$|[?#])/i.test(downloadUrl)
|
| 3637 |
+
? downloadUrl : ""));
|
| 3638 |
+
try {
|
| 3639 |
+
const parsed = new URL(candidate, location.href);
|
| 3640 |
+
const path = parsed.searchParams.get("path") || parsed.pathname;
|
| 3641 |
+
return validSource(parsed.href) && /\.pdf$/i.test(path) ? parsed.href : "";
|
| 3642 |
+
} catch (_) { return ""; }
|
| 3643 |
+
}
|
| 3644 |
function renderPdfManifestShell(shell, force = false, priority = false) {
|
| 3645 |
+
if (!pdfHybridUrl) return renderPdfImageShell(shell, force, priority);
|
| 3646 |
+
if (!force && shell.querySelector("canvas.ready")) return Promise.resolve();
|
| 3647 |
+
if (shell._hybridRenderPromise) {
|
| 3648 |
+
if (force) shell.dataset.pendingHybridRerender = "1";
|
| 3649 |
+
return shell._hybridReadyPromise;
|
| 3650 |
+
}
|
| 3651 |
+
const controller = new AbortController();
|
| 3652 |
+
shell._hybridCancel = () => { controller.abort(); shell._renderCancel?.(); };
|
| 3653 |
+
const pdfTask = renderHybridPdfCanvas(shell, controller.signal, priority);
|
| 3654 |
+
const previewTask = (async () => {
|
| 3655 |
+
if (pdfDocument || shell.dataset.pdfPresented === "1") await waitForReader(250);
|
| 3656 |
+
if (controller.signal.aborted || !shell.isConnected) throw readerAbortError();
|
| 3657 |
+
if (shell.querySelector("canvas.ready") || shell.dataset.pdfPresented === "1") return pdfTask;
|
| 3658 |
+
if (!normalizePdfPriority(priority) && pdfDocument) return pdfTask;
|
| 3659 |
+
const preview = await renderPdfImageShell(shell, false, priority);
|
| 3660 |
+
if (controller.signal.aborted) throw readerAbortError();
|
| 3661 |
+
return preview;
|
| 3662 |
+
})();
|
| 3663 |
+
const ready = Promise.any([pdfTask, previewTask]).catch((error) => {
|
| 3664 |
+
if (controller.signal.aborted || readerAbortController.signal.aborted) throw readerAbortError();
|
| 3665 |
+
throw error.errors?.[1] || error.errors?.[0] || error;
|
| 3666 |
+
});
|
| 3667 |
+
shell._hybridReadyPromise = ready;
|
| 3668 |
+
const complete = Promise.allSettled([pdfTask, previewTask]).finally(() => {
|
| 3669 |
+
if (shell._hybridRenderPromise === complete) {
|
| 3670 |
+
delete shell._hybridRenderPromise;
|
| 3671 |
+
delete shell._hybridReadyPromise;
|
| 3672 |
+
delete shell._hybridCancel;
|
| 3673 |
+
if (shell.dataset.pendingHybridRerender && shell.isConnected && !readerLifecycle.disposed) {
|
| 3674 |
+
delete shell.dataset.pendingHybridRerender;
|
| 3675 |
+
renderPdfInBackground(shell, true);
|
| 3676 |
+
}
|
| 3677 |
+
}
|
| 3678 |
+
});
|
| 3679 |
+
shell._hybridRenderPromise = complete;
|
| 3680 |
+
return ready;
|
| 3681 |
+
}
|
| 3682 |
+
async function renderHybridPdfCanvas(shell, signal, priority) {
|
| 3683 |
+
let acquired = false, canvas = null, rendering = null;
|
| 3684 |
+
const untrack = trackReaderResource(() => { rendering?.cancel?.(); shell._hybridCancel?.(); });
|
| 3685 |
+
const cancel = () => rendering?.cancel?.();
|
| 3686 |
+
signal.addEventListener("abort", cancel, { once: true });
|
| 3687 |
+
try {
|
| 3688 |
+
const pdf = await awaitReader(pdfHybridDocumentPromise, signal);
|
| 3689 |
+
do {
|
| 3690 |
+
const generation = readerRuntime.currentGeneration("pdf");
|
| 3691 |
+
if (signal.aborted || !shell.isConnected) throw readerAbortError();
|
| 3692 |
+
const page = await awaitReader(pdf.getPage(Number(shell.dataset.page)), signal);
|
| 3693 |
+
if (signal.aborted || !shell.isConnected) throw readerAbortError();
|
| 3694 |
+
if (!acquired) {
|
| 3695 |
+
await acquirePdfRenderSlot(priority, shell, signal);
|
| 3696 |
+
acquired = true;
|
| 3697 |
+
}
|
| 3698 |
+
const base = page.getViewport({ scale: 1 });
|
| 3699 |
+
const view = page.getViewport({ scale: Math.min(3, Math.max(0.5, shell.clientWidth / base.width)) });
|
| 3700 |
+
const outputScale = Math.min(2, Math.max(1, Number(window.devicePixelRatio) || 1));
|
| 3701 |
+
canvas = document.createElement("canvas");
|
| 3702 |
+
canvas.setAttribute("aria-hidden", "true");
|
| 3703 |
+
canvas.width = Math.ceil(view.width * outputScale);
|
| 3704 |
+
canvas.height = Math.ceil(view.height * outputScale);
|
| 3705 |
+
rendering = page.render({ canvasContext: canvas.getContext("2d"), viewport: view,
|
| 3706 |
+
transform: outputScale === 1 ? null : [outputScale, 0, 0, outputScale, 0, 0] });
|
| 3707 |
+
await awaitReader(rendering.promise, signal);
|
| 3708 |
+
rendering = null;
|
| 3709 |
+
while (pdfSelectionIntersects(shell) && !signal.aborted) await waitForReader(100);
|
| 3710 |
+
if (signal.aborted || !shell.isConnected) throw readerAbortError();
|
| 3711 |
+
if (!isReaderGenerationCurrent("pdf", generation)) {
|
| 3712 |
+
canvas.width = canvas.height = 0;
|
| 3713 |
+
continue;
|
| 3714 |
+
}
|
| 3715 |
+
const anchor = content.querySelector(`.reader-page[data-page="${documentState.page}"]`);
|
| 3716 |
+
const oldTop = anchor?.getBoundingClientRect().top;
|
| 3717 |
+
const oldHeight = anchor?.getBoundingClientRect().height || 1;
|
| 3718 |
+
const fraction = anchor ? Math.max(0, (viewport.getBoundingClientRect().top - oldTop) / oldHeight) : 0;
|
| 3719 |
+
const previous = shell.querySelector("canvas");
|
| 3720 |
+
canvas.classList.add("ready");
|
| 3721 |
+
if (previous) { previous.replaceWith(canvas); previous.width = previous.height = 0; }
|
| 3722 |
+
else shell.prepend(canvas);
|
| 3723 |
+
shell.style.aspectRatio = `${base.width} / ${base.height}`;
|
| 3724 |
+
shell._renderCancel?.();
|
| 3725 |
+
shell.querySelector("img")?.remove();
|
| 3726 |
+
const pageState = shell.querySelector(".reader-page-state");
|
| 3727 |
+
if (pageState) pageState.hidden = true;
|
| 3728 |
+
shell.dataset.pdfPresented = "1";
|
| 3729 |
+
delete shell.dataset.pendingHybridRerender;
|
| 3730 |
+
shell.dataset.renderState = "rendered";
|
| 3731 |
+
shell.dataset.renderUsedAt = String(Date.now());
|
| 3732 |
+
if (anchor) {
|
| 3733 |
+
const current = anchor.getBoundingClientRect();
|
| 3734 |
+
viewport.scrollTop += current.top - oldTop + fraction * (current.height - oldHeight);
|
| 3735 |
+
}
|
| 3736 |
+
pdfShellWindow?.remember(shell);
|
| 3737 |
+
trimPdfCanvases(shell);
|
| 3738 |
+
(ocrManifestUrl ? renderPdfOcrText(shell) : renderPdfText(page, shell, signal)).catch(() => {});
|
| 3739 |
+
scheduleMarkerSync();
|
| 3740 |
+
canvas = null;
|
| 3741 |
+
return;
|
| 3742 |
+
} while (true);
|
| 3743 |
+
} finally {
|
| 3744 |
+
rendering?.cancel?.();
|
| 3745 |
+
if (canvas) canvas.width = canvas.height = 0;
|
| 3746 |
+
if (acquired) releasePdfRenderSlot();
|
| 3747 |
+
signal.removeEventListener("abort", cancel);
|
| 3748 |
+
untrack();
|
| 3749 |
+
}
|
| 3750 |
+
}
|
| 3751 |
+
function renderPdfImageShell(shell, force = false, priority = false) {
|
| 3752 |
if (!shell) return Promise.reject(new Error("PDF page shell missing"));
|
| 3753 |
if (shell._renderPromise) return shell._renderPromise;
|
| 3754 |
if (!force && shell.dataset.renderState === "rendered") return Promise.resolve();
|
| 3755 |
shell.dataset.renderState = "rendering";
|
| 3756 |
const renderController = new AbortController();
|
| 3757 |
+
const hybridPreview = !!pdfHybridUrl;
|
| 3758 |
shell._renderCancel = () => renderController.abort();
|
| 3759 |
shell._renderStarted = false;
|
| 3760 |
priority = normalizePdfPriority(priority || pdfPagePriority(shell));
|
|
|
|
| 3762 |
const task = (async () => {
|
| 3763 |
let acquired = false;
|
| 3764 |
try {
|
| 3765 |
+
if (hybridPreview) {
|
| 3766 |
+
while (pdfHybridPreviewLoads >= 2) {
|
| 3767 |
+
await waitForReader(25);
|
| 3768 |
+
if (renderController.signal.aborted) throw readerAbortError();
|
| 3769 |
+
}
|
| 3770 |
+
if (renderController.signal.aborted) throw readerAbortError();
|
| 3771 |
+
pdfHybridPreviewLoads++;
|
| 3772 |
+
} else await acquirePdfRenderSlot(priority, shell, renderController.signal);
|
| 3773 |
acquired = true;
|
| 3774 |
shell._renderStarted = true;
|
| 3775 |
assertReaderActive();
|
|
|
|
| 3819 |
if (image.complete && image.naturalWidth) finish();
|
| 3820 |
});
|
| 3821 |
assertReaderActive();
|
| 3822 |
+
if (shell.dataset.pdfPresented === "1") return;
|
| 3823 |
+
shell.style.aspectRatio = `${image.naturalWidth || 1} / ${image.naturalHeight || 1}`;
|
| 3824 |
if (priority >= 2 && ocrManifestUrl && !navigator.connection?.saveData)
|
| 3825 |
loadText ||= renderPdfOcrText(shell);
|
| 3826 |
loadText?.catch(() => {});
|
|
|
|
| 3836 |
} catch (error) {
|
| 3837 |
shell.querySelector("img")?.remove();
|
| 3838 |
const pageState = shell.querySelector(".reader-page-state");
|
| 3839 |
+
if (pageState && shell.dataset.pdfPresented !== "1") {
|
| 3840 |
pageState.hidden = false;
|
| 3841 |
pageState.textContent = "้กต้ขๅ ่ฝฝๅคฑ่ดฅ๏ผๆญฃๅจ้่ฏโฆ";
|
| 3842 |
}
|
| 3843 |
+
if (shell.dataset.pdfPresented !== "1") shell.dataset.renderState = "idle";
|
| 3844 |
throw error;
|
| 3845 |
} finally {
|
| 3846 |
+
if (acquired) {
|
| 3847 |
+
if (hybridPreview) pdfHybridPreviewLoads--;
|
| 3848 |
+
else releasePdfRenderSlot();
|
| 3849 |
+
}
|
| 3850 |
}
|
| 3851 |
})().finally(() => {
|
| 3852 |
if (shell._renderPromise === task) delete shell._renderPromise;
|
|
|
|
| 3858 |
return task;
|
| 3859 |
}
|
| 3860 |
function cancelSpeculativePdfRenders(protectedShell) {
|
| 3861 |
+
for (const shell of content.querySelectorAll('.reader-page')) {
|
| 3862 |
+
if (!shell._hybridRenderPromise && shell.dataset.renderState !== "rendering") continue;
|
| 3863 |
if (
|
| 3864 |
shell === protectedShell ||
|
| 3865 |
isPdfPageVisible(shell)
|
| 3866 |
)
|
| 3867 |
continue;
|
| 3868 |
shell._renderCancel?.();
|
| 3869 |
+
shell._hybridCancel?.();
|
| 3870 |
}
|
| 3871 |
}
|
| 3872 |
function renderPdfShell(shell, force = false, priority = false) {
|
|
|
|
| 4098 |
}
|
| 4099 |
function trimPdfCanvases(protectedShell) {
|
| 4100 |
const limit = matchMedia("(max-width: 700px)").matches ? 7 : 11;
|
| 4101 |
+
const rendered = [...content.querySelectorAll('.reader-page[data-render-state="rendered"]')]
|
| 4102 |
+
.filter((shell) => shell.querySelector("canvas.ready"));
|
| 4103 |
if (rendered.length <= limit) return;
|
| 4104 |
rendered.sort((a, b) => {
|
| 4105 |
const aVisible =
|
|
|
|
| 4905 |
}
|
| 4906 |
if (["pdf", "pdf-pages", "image-pages"].includes(mode)) {
|
| 4907 |
pdfDocument = null;
|
| 4908 |
+
pdfHybridUrl = "";
|
| 4909 |
+
pdfHybridDocumentPromise = null;
|
| 4910 |
pdfPageManifest = null;
|
| 4911 |
pdfOcrManifest = null;
|
| 4912 |
pdfOcrManifestPromise = null;
|
|
|
|
| 5159 |
)
|
| 5160 |
extension = "pdf-pages";
|
| 5161 |
capability = readerRuntime.negotiate(VoiceOfMLReader.capability(extension));
|
| 5162 |
+
if (capability.mode !== "pdf" && !pdfPrimarySource()) releasePdfWorker?.();
|
| 5163 |
readerRuntime.update("source", {
|
| 5164 |
url: sourceUrl,
|
| 5165 |
contentUrl,
|
|
|
|
| 5324 |
);
|
| 5325 |
});
|
| 5326 |
}
|
| 5327 |
+
function loadPdfWithTimeout(pdfjs, options, originalUrl = sourceUrl, proxyUrl = contentUrl) {
|
| 5328 |
+
return retryReaderProxy(() => loadPdfTaskWithTimeout(pdfjs, options, proxyUrl)).catch((error) => {
|
| 5329 |
assertReaderActive();
|
| 5330 |
if (error && error.name === "AbortError") throw error;
|
| 5331 |
if (retryableReaderProxyError(error)) throw error;
|
| 5332 |
+
return loadPdfTaskWithTimeout(pdfjs, options, originalUrl);
|
| 5333 |
});
|
| 5334 |
}
|
| 5335 |
function preloadPdfEngine() {
|
|
|
|
| 5338 |
}
|
| 5339 |
async function preparePdfWorker(pdfjs) {
|
| 5340 |
assertReaderActive();
|
| 5341 |
+
if (capability.mode !== "pdf" && !pdfPrimarySource()) return pdfjs;
|
| 5342 |
pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;
|
| 5343 |
const worker = new pdfjs.PDFWorker();
|
| 5344 |
pdfWorker = worker;
|
|
|
|
| 5415 |
}
|
| 5416 |
}
|
| 5417 |
}
|
| 5418 |
+
function loadPdfDocument(target = sourceUrl) {
|
| 5419 |
return preloadPdfEngine().then((pdfjs) => {
|
| 5420 |
assertReaderActive();
|
| 5421 |
if (!pdfFetchPolicy) {
|
|
|
|
| 5438 |
standardFontDataUrl: PDFJS_STANDARD_FONT_URL,
|
| 5439 |
withCredentials: false
|
| 5440 |
});
|
| 5441 |
+
return loadPdfWithTimeout(pdfjs, options, target, readerContentUrl(target));
|
| 5442 |
});
|
| 5443 |
}
|
| 5444 |
function loadTextDocument() {
|
|
|
|
| 6141 |
const fullSearchButton = document.querySelector("#full-search-toggle");
|
| 6142 |
fullSearchButton.textContent = "ๅ
จๆๆ็ดข";
|
| 6143 |
fullSearchButton.setAttribute("aria-label", "ๅ
จๆๆ็ดข");
|
| 6144 |
+
fullSearchButton.hidden = !capability.features.search || (capability.mode === "pdf-pages" && !ocrManifestUrl && !pdfHybridUrl);
|
| 6145 |
const fullSearchInput = fullSearchView.querySelector("#full-search-input"),
|
| 6146 |
fullSearchStatus = fullSearchView.querySelector("#full-search-status"),
|
| 6147 |
fullSearchResultsNode = fullSearchView.querySelector("#full-search-results"),
|
|
|
|
| 7113 |
}
|
| 7114 |
fullSearchStatus.textContent = "ๆญฃๅจๆ็ดขๆญฃๆโฆ";
|
| 7115 |
try {
|
| 7116 |
+
if ((capability.mode === "pdf" || pdfHybridUrl) && !ocrManifestUrl) {
|
| 7117 |
+
if (pdfHybridUrl) await pdfHybridDocumentPromise;
|
| 7118 |
await fullSearchPdfMatches(query, generation);
|
| 7119 |
+
}
|
| 7120 |
else if (["pdf", "pdf-pages"].includes(capability.mode))
|
| 7121 |
publishSearchResults(generation, await searchConcentratedPdf(query, generation));
|
| 7122 |
else if (capability.mode === "foliate")
|
|
|
|
| 7296 |
document.querySelector(".page-controls").hidden = !capability.features.pagination;
|
| 7297 |
document.querySelector(".zoom-controls").hidden = !capability.features.zoom;
|
| 7298 |
mediaTab.hidden = !capability.features.media;
|
| 7299 |
+
fullSearchButton.hidden = !capability.features.search || (capability.mode === "pdf-pages" && !ocrManifestUrl && !pdfHybridUrl);
|
| 7300 |
bookmarkRibbon.hidden = !capability.features.bookmarks;
|
| 7301 |
readingProgressSummary.querySelector(".reader-progress-bookmark").hidden =
|
| 7302 |
!capability.features.bookmarks;
|
tests/test_api_contract.py
CHANGED
|
@@ -44,6 +44,23 @@ class ApiContractTests(unittest.TestCase):
|
|
| 44 |
self.assertIn('"page_size":1', payload)
|
| 45 |
self.assertIn('"results"', payload)
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
def test_unknown_repo_endpoints_are_404(self):
|
| 48 |
self.assertEqual(asyncio.run(app.api_search_repo("Missing", app.SearchRequest())).status_code, 404)
|
| 49 |
self.assertEqual(app.api_folders("Missing").status_code, 404)
|
|
|
|
| 44 |
self.assertIn('"page_size":1', payload)
|
| 45 |
self.assertIn('"results"', payload)
|
| 46 |
|
| 47 |
+
def test_encoded_search_cache_reuses_body_and_invalidates_asset_revision(self):
|
| 48 |
+
app.api_response_cache.clear()
|
| 49 |
+
request = app.SearchRequest(q="readme", page_size=1)
|
| 50 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value={"v":1,"f":{}})), \
|
| 51 |
+
mock.patch.object(app, "reader_assets_revision", "first"):
|
| 52 |
+
first = asyncio.run(app.api_search(request))
|
| 53 |
+
with mock.patch.object(app, "add_reader_assets", side_effect=AssertionError("repeat enrichment")):
|
| 54 |
+
second = asyncio.run(app.api_search(request))
|
| 55 |
+
self.assertIs(first.body, second.body)
|
| 56 |
+
enriched = {**json.loads(first.body), "updated":True}
|
| 57 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value={"v":1,"f":{}})), \
|
| 58 |
+
mock.patch.object(app, "reader_assets_revision", "second"), \
|
| 59 |
+
mock.patch.object(app, "add_reader_assets", return_value=enriched):
|
| 60 |
+
updated = asyncio.run(app.api_search(request))
|
| 61 |
+
self.assertTrue(json.loads(updated.body)["updated"])
|
| 62 |
+
self.assertNotIn("readme", updated.headers["server-timing"])
|
| 63 |
+
|
| 64 |
def test_unknown_repo_endpoints_are_404(self):
|
| 65 |
self.assertEqual(asyncio.run(app.api_search_repo("Missing", app.SearchRequest())).status_code, 404)
|
| 66 |
self.assertEqual(app.api_folders("Missing").status_code, 404)
|
tests/test_cache_and_malformed.py
CHANGED
|
@@ -4,6 +4,7 @@ import copy
|
|
| 4 |
import gzip
|
| 5 |
import tempfile
|
| 6 |
import unittest
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
IMPORT_ERROR = None
|
|
@@ -38,16 +39,18 @@ class CacheAndMalformedTests(unittest.TestCase):
|
|
| 38 |
|
| 39 |
def test_cache_eviction_removes_oldest_when_over_500(self):
|
| 40 |
app.api_response_cache.clear()
|
|
|
|
| 41 |
for i in range(500):
|
| 42 |
-
app.api_response_cache[i] = (i, i)
|
| 43 |
app.cached_payload(500, lambda: 500)
|
| 44 |
self.assertNotIn(0, app.api_response_cache)
|
| 45 |
self.assertIn(500, app.api_response_cache)
|
| 46 |
|
| 47 |
def test_cache_eviction_retains_newer_entries(self):
|
| 48 |
app.api_response_cache.clear()
|
|
|
|
| 49 |
for i in range(500):
|
| 50 |
-
app.api_response_cache[i] = (i, i)
|
| 51 |
app.cached_payload("new", lambda: "value")
|
| 52 |
self.assertEqual(app.api_response_cache[499][1], 499)
|
| 53 |
|
|
@@ -57,6 +60,37 @@ class CacheAndMalformedTests(unittest.TestCase):
|
|
| 57 |
app.cached_payload(("search", "x", "size"), lambda: "size")
|
| 58 |
self.assertEqual(len(app.api_response_cache), 2)
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
def test_generation_invalidates_folder_and_initial_payload_caches(self):
|
| 61 |
old_generation = app._data_generation
|
| 62 |
old_tree = app.folder_tree_data
|
|
|
|
| 4 |
import gzip
|
| 5 |
import tempfile
|
| 6 |
import unittest
|
| 7 |
+
from unittest.mock import patch
|
| 8 |
from pathlib import Path
|
| 9 |
|
| 10 |
IMPORT_ERROR = None
|
|
|
|
| 39 |
|
| 40 |
def test_cache_eviction_removes_oldest_when_over_500(self):
|
| 41 |
app.api_response_cache.clear()
|
| 42 |
+
now = app.time.monotonic()
|
| 43 |
for i in range(500):
|
| 44 |
+
app.api_response_cache[i] = (now - (500 - i) / 1000, i)
|
| 45 |
app.cached_payload(500, lambda: 500)
|
| 46 |
self.assertNotIn(0, app.api_response_cache)
|
| 47 |
self.assertIn(500, app.api_response_cache)
|
| 48 |
|
| 49 |
def test_cache_eviction_retains_newer_entries(self):
|
| 50 |
app.api_response_cache.clear()
|
| 51 |
+
now = app.time.monotonic()
|
| 52 |
for i in range(500):
|
| 53 |
+
app.api_response_cache[i] = (now - (500 - i) / 1000, i)
|
| 54 |
app.cached_payload("new", lambda: "value")
|
| 55 |
self.assertEqual(app.api_response_cache[499][1], 499)
|
| 56 |
|
|
|
|
| 60 |
app.cached_payload(("search", "x", "size"), lambda: "size")
|
| 61 |
self.assertEqual(len(app.api_response_cache), 2)
|
| 62 |
|
| 63 |
+
def test_encoded_response_cache_reuses_exact_body_and_preserves_headers(self):
|
| 64 |
+
app.api_response_cache.clear()
|
| 65 |
+
value = {"text": "\u6587\u5316", "records": [{"name": "book", "size": 0}]}
|
| 66 |
+
expected = app.JSONResponse(value).body
|
| 67 |
+
first = app.cached_json_response("response", lambda: value, {"Cache-Control":"public, max-age=300"})
|
| 68 |
+
with patch.object(app, "JSONResponse", side_effect=AssertionError("duplicate serialization")):
|
| 69 |
+
second = app.cached_json_response("response", lambda: value)
|
| 70 |
+
self.assertEqual(first.body, expected)
|
| 71 |
+
self.assertIs(first.body, second.body)
|
| 72 |
+
self.assertEqual(first.headers["cache-control"], "public, max-age=300")
|
| 73 |
+
self.assertEqual(second.headers["content-type"], "application/json")
|
| 74 |
+
entry = next(iter(app.api_response_cache.values()))
|
| 75 |
+
self.assertEqual(entry[2], len(expected) + len(str(next(iter(app.api_response_cache))).encode("utf-8")))
|
| 76 |
+
|
| 77 |
+
def test_cache_byte_budget_lru_expiry_and_oversized_bypass(self):
|
| 78 |
+
store = {}
|
| 79 |
+
with patch.object(app, "RESPONSE_CACHE_BYTES_MAX", 80), patch.object(app, "RESPONSE_CACHE_ENTRY_BYTES_MAX", 50), patch.object(app.time, "monotonic", return_value=10):
|
| 80 |
+
for key in ("a", "b", "c"):
|
| 81 |
+
app._cached(store, key, lambda: "x" * 20, 100, 500)
|
| 82 |
+
app._cached(store, "a", lambda: "wrong", 100, 500)
|
| 83 |
+
app._cached(store, "d", lambda: "x" * 20, 100, 500)
|
| 84 |
+
self.assertNotIn("b", store)
|
| 85 |
+
self.assertIn("a", store)
|
| 86 |
+
self.assertLessEqual(sum(entry[2] for entry in store.values()), 80)
|
| 87 |
+
live = app._cached(store, "huge", lambda: "y" * 100, 100, 500)
|
| 88 |
+
self.assertEqual(live, "y" * 100)
|
| 89 |
+
self.assertNotIn("huge", store)
|
| 90 |
+
with patch.object(app.time, "monotonic", return_value=110):
|
| 91 |
+
app._cached(store, "fresh", lambda: "value", 100, 500)
|
| 92 |
+
self.assertEqual(list(store), ["fresh"])
|
| 93 |
+
|
| 94 |
def test_generation_invalidates_folder_and_initial_payload_caches(self):
|
| 95 |
old_generation = app._data_generation
|
| 96 |
old_tree = app.folder_tree_data
|
tests/test_native_search_indexes.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional compiled parser equivalence; no build or corpus scan on import."""
|
| 2 |
+
import random
|
| 3 |
+
import unittest
|
| 4 |
+
from unittest.mock import patch
|
| 5 |
+
|
| 6 |
+
import search_indexes
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def varint(value):
|
| 10 |
+
encoded = bytearray()
|
| 11 |
+
while value >= 128:
|
| 12 |
+
encoded.append((value & 127) | 128)
|
| 13 |
+
value >>= 7
|
| 14 |
+
encoded.append(value)
|
| 15 |
+
return bytes(encoded)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@unittest.skipUnless(search_indexes._native_read_entries, "build optional native posting decoder explicitly")
|
| 19 |
+
class NativeSearchIndexTests(unittest.TestCase):
|
| 20 |
+
def test_native_entries_match_python_for_multibyte_duplicates_and_corruption(self):
|
| 21 |
+
rng = random.Random(731)
|
| 22 |
+
bodies = []
|
| 23 |
+
for _ in range(100):
|
| 24 |
+
ids = sorted(rng.randrange(100000) for _ in range(rng.randrange(40)))
|
| 25 |
+
if ids:
|
| 26 |
+
ids.insert(0, ids[0])
|
| 27 |
+
previous = 0
|
| 28 |
+
body = b""
|
| 29 |
+
for index in ids:
|
| 30 |
+
body += varint(index - previous)
|
| 31 |
+
previous = index
|
| 32 |
+
key = "\u6587\u5316".encode()
|
| 33 |
+
encoded = varint(len(key)) + key + varint(len(set(ids))) + varint(len(body)) + body
|
| 34 |
+
bodies.extend([encoded, encoded[:-1], encoded + b"\0", encoded[:-1] + b"\x80"])
|
| 35 |
+
bodies.extend([b"", b"\x01\xff\0\0", b"\x01a\x01\x01\x80",
|
| 36 |
+
b"\x01a\x01\x02" + varint(100000), b"\x01a\x02\x02\0\0"])
|
| 37 |
+
native = search_indexes._native_read_entries
|
| 38 |
+
for materialize in (False, True):
|
| 39 |
+
for body in bodies:
|
| 40 |
+
with self.subTest(materialize=materialize, body=body):
|
| 41 |
+
try:
|
| 42 |
+
expected = {key: decoded if materialize else location
|
| 43 |
+
for key, location, decoded in search_indexes._read_posting_entries(body, 0, 1, 100000, materialize)}
|
| 44 |
+
except (ValueError, UnicodeError):
|
| 45 |
+
with self.assertRaises((ValueError, UnicodeError)):
|
| 46 |
+
native(body, 0, 1, 100000, materialize)
|
| 47 |
+
else:
|
| 48 |
+
self.assertEqual(native(body, 0, 1, 100000, materialize), expected)
|
| 49 |
+
|
| 50 |
+
def test_empty_trailing_bounds_and_wide_varint_fallback(self):
|
| 51 |
+
native = search_indexes._native_read_entries
|
| 52 |
+
self.assertEqual(native(b"", 0, 0, 0, False), {})
|
| 53 |
+
for args in ((b"x", 0, 0, 1, False), (b"", -1, 0, 1, False), (b"", 1, 0, 1, False)):
|
| 54 |
+
with self.assertRaises(ValueError):
|
| 55 |
+
native(*args)
|
| 56 |
+
# An overlong encoding of zero remains valid under the Python contract.
|
| 57 |
+
body = b"\x01a\x01\x0b" + b"\x80" * 10 + b"\x00"
|
| 58 |
+
with patch.object(search_indexes, "_native_read_entries", native):
|
| 59 |
+
self.assertEqual(search_indexes._load_posting_entries(body, 0, 1, 1, True), {"a":{0}})
|
| 60 |
+
|
| 61 |
+
def test_partial_native_failure_cannot_publish_entries(self):
|
| 62 |
+
body = b"\x01a\x01\x01\x00" + b"\x01b\x01\x01\x80"
|
| 63 |
+
with self.assertRaises(ValueError):
|
| 64 |
+
search_indexes._native_read_entries(body, 0, 2, 10, True)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
unittest.main()
|
tests/test_paging_recovery.py
CHANGED
|
@@ -60,6 +60,33 @@ class PagingRecoveryTests(unittest.TestCase):
|
|
| 60 |
def tearDown(self):
|
| 61 |
self.context.close()
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
def test_truncated_nonempty_page_is_rejected_and_retry_preserves_all_ids(self):
|
| 64 |
self.reach_bottom()
|
| 65 |
self.expire_pending('short')
|
|
|
|
| 60 |
def tearDown(self):
|
| 61 |
self.context.close()
|
| 62 |
|
| 63 |
+
def test_updated_generation_relocates_without_mixing_ordinary_pages(self):
|
| 64 |
+
self.page.evaluate(r'''() => {
|
| 65 |
+
const previous = window.fetch;
|
| 66 |
+
window.currentGeneration = 'A';
|
| 67 |
+
window.fetch = (input, options) => {
|
| 68 |
+
const body = JSON.parse(options?.body || '{}');
|
| 69 |
+
if (body.q !== 'paging-generation') return previous(input, options);
|
| 70 |
+
const generation = currentGeneration;
|
| 71 |
+
if (generation === 'A' && body.page > 1) return new Promise(() => {});
|
| 72 |
+
const all = Array.from({length:301}, (_, i) => ({Repo:'VoiceOfML/Test',
|
| 73 |
+
File: 'paging-' + (generation === 'B' ? i - 1 : i), Extension:'txt', Folder:[], Size:1}));
|
| 74 |
+
const anchor_index = body.anchor_id === undefined ? undefined : all.findIndex(r => getResultStableId(r) === body.anchor_id);
|
| 75 |
+
return Promise.resolve(new Response(JSON.stringify({generation, total:301, page:body.page,
|
| 76 |
+
page_size:body.page_size, anchor_index,
|
| 77 |
+
results:all.slice((body.page-1)*body.page_size,body.page*body.page_size)})));
|
| 78 |
+
};
|
| 79 |
+
STATE.query = 'paging-generation'; doSearch(false, true);
|
| 80 |
+
}''')
|
| 81 |
+
self.page.wait_for_function("STATE._loadedPage === 1 && !STATE.isLoading && searchPageMetadata.get(STATE.results[0])?.generation === 'A'")
|
| 82 |
+
self.page.evaluate("currentGeneration='B'; cancelSearchPrefetch(); STATE.page=2; doSearch(true)")
|
| 83 |
+
self.page.wait_for_function("!positionRestore && resultWindow?.generation === 'B' && !STATE.isLoading")
|
| 84 |
+
names = self.page.evaluate('STATE.results.filter(Boolean).map(r => r.File)')
|
| 85 |
+
self.assertGreaterEqual(len(names), 200)
|
| 86 |
+
self.assertEqual(names, ['paging-' + str(i) for i in range(-1, len(names) - 1)])
|
| 87 |
+
self.assertEqual(self.page.evaluate('STATE.total'), 301)
|
| 88 |
+
self.assertEqual(self.errors, [])
|
| 89 |
+
|
| 90 |
def test_truncated_nonempty_page_is_rejected_and_retry_preserves_all_ids(self):
|
| 91 |
self.reach_bottom()
|
| 92 |
self.expire_pending('short')
|
tests/test_reader_architecture.js
CHANGED
|
@@ -96,7 +96,7 @@ assertCode(reader, 'await formatAdapters.active.restore(entry, generation)')
|
|
| 96 |
assert.match(reader, /const restorationPromise = loadReaderRestoration\(\)/)
|
| 97 |
assert.match(reader, /await formatAdapters\.active\.render\(prepared\)[\s\S]*?const restored = await awaitReader\(restorationPromise\)/)
|
| 98 |
assert.doesNotMatch(reader, /Promise\.all\(\[loadReaderRestoration\(\)/)
|
| 99 |
-
assert.strictEqual((reader.match(/function loadPdfDocument\(
|
| 100 |
for (const renderer of ['renderImageDocument', 'renderMedia']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\s*\\(`,'g')) || []).length, 1)
|
| 101 |
for (const renderer of ['renderTextDocument', 'renderMarkdownDocument']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\(`,'g')) || []).length, 1)
|
| 102 |
for (const loader of ['loadTextDocument', 'loadMarkdownDocument', 'loadHtmlDocument', 'loadDocxDocument']) assert.strictEqual((reader.match(new RegExp(`function ${loader}\\(`,'g')) || []).length, 1)
|
|
|
|
| 96 |
assert.match(reader, /const restorationPromise = loadReaderRestoration\(\)/)
|
| 97 |
assert.match(reader, /await formatAdapters\.active\.render\(prepared\)[\s\S]*?const restored = await awaitReader\(restorationPromise\)/)
|
| 98 |
assert.doesNotMatch(reader, /Promise\.all\(\[loadReaderRestoration\(\)/)
|
| 99 |
+
assert.strictEqual((reader.match(/function loadPdfDocument\(/g) || []).length, 1)
|
| 100 |
for (const renderer of ['renderImageDocument', 'renderMedia']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\s*\\(`,'g')) || []).length, 1)
|
| 101 |
for (const renderer of ['renderTextDocument', 'renderMarkdownDocument']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\(`,'g')) || []).length, 1)
|
| 102 |
for (const loader of ['loadTextDocument', 'loadMarkdownDocument', 'loadHtmlDocument', 'loadDocxDocument']) assert.strictEqual((reader.match(new RegExp(`function ${loader}\\(`,'g')) || []).length, 1)
|
tests/test_reader_backend.py
CHANGED
|
@@ -203,6 +203,27 @@ class ReaderArchiveValidationTests(unittest.TestCase):
|
|
| 203 |
self.assertEqual(decoded["f"], {})
|
| 204 |
|
| 205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
@unittest.skipIf(app is None, f"backend dependencies unavailable: {IMPORT_ERROR}")
|
| 207 |
class ReaderBackendTests(unittest.IsolatedAsyncioTestCase):
|
| 208 |
async def asyncSetUp(self):
|
|
@@ -348,6 +369,101 @@ class ReaderBackendTests(unittest.IsolatedAsyncioTestCase):
|
|
| 348 |
self.assertEqual(response.media_type, "audio/flac")
|
| 349 |
self.assertEqual(response.body, b"flac")
|
| 350 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
async def content(self, upstream, method="GET"):
|
| 352 |
self.session(upstream)
|
| 353 |
return await app.api_reader_content(SimpleNamespace(method=method, headers={}), SOURCE, None)
|
|
@@ -651,6 +767,21 @@ class ReaderBackendTests(unittest.IsolatedAsyncioTestCase):
|
|
| 651 |
self.assertEqual(response.body, bucket_body)
|
| 652 |
self.assertEqual(read.call_args.args[0], chapter_path)
|
| 653 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 654 |
async def test_bucket_content_rejects_arbitrary_relative_and_ambiguous_paths(self):
|
| 655 |
for url in (
|
| 656 |
"https://[broken", "/api/other?path=x", "//evil.test/api/reader-bucket-resource?path=x",
|
|
|
|
| 203 |
self.assertEqual(decoded["f"], {})
|
| 204 |
|
| 205 |
|
| 206 |
+
def test_pdf_primary_document_survives_decoder_and_metadata_projection(self):
|
| 207 |
+
path = "derived/test/" + "c" * 32 + "/document.pdf"
|
| 208 |
+
entry = {"s": 2, "m": "p", "p": BUCKET_PATH, "b": "vomebook/pdf-pages-v2",
|
| 209 |
+
"pd": path, "pdb": "vomebook/pdf-pages-v2"}
|
| 210 |
+
payload = gzip.compress(json.dumps({"v": 1, "f": {"book": entry}}).encode())
|
| 211 |
+
self.assertEqual(app.decode_reader_assets(payload)["f"]["book"], entry)
|
| 212 |
+
record = {"Repo": "VoiceOfML/Test", "File": "converted", "Extension": "caj", "Folder": []}
|
| 213 |
+
resolved = app.reader_resolved_record(record, entry)
|
| 214 |
+
self.assertEqual(resolved["extension"], "pdf-pages")
|
| 215 |
+
self.assertEqual(resolved["pdf_document"],
|
| 216 |
+
"https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + path)
|
| 217 |
+
enriched = app.add_reader_assets({"results": [record]},
|
| 218 |
+
{"f": {app.build_reader_asset_key(record): entry}})["results"][0]
|
| 219 |
+
self.assertEqual(enriched["ReaderPdfDocument"], resolved["pdf_document"])
|
| 220 |
+
for invalid in ({**entry, "pdb": "vomebook/pdf-pages"},
|
| 221 |
+
{**entry, "pdb": []},
|
| 222 |
+
{**entry, "pd": "../document.pdf"}, {**entry, "pd": BUCKET_PATH}):
|
| 223 |
+
raw = gzip.compress(json.dumps({"v": 1, "f": {"book": invalid}}).encode())
|
| 224 |
+
self.assertEqual(app.decode_reader_assets(raw)["f"], {})
|
| 225 |
+
|
| 226 |
+
|
| 227 |
@unittest.skipIf(app is None, f"backend dependencies unavailable: {IMPORT_ERROR}")
|
| 228 |
class ReaderBackendTests(unittest.IsolatedAsyncioTestCase):
|
| 229 |
async def asyncSetUp(self):
|
|
|
|
| 369 |
self.assertEqual(response.media_type, "audio/flac")
|
| 370 |
self.assertEqual(response.body, b"flac")
|
| 371 |
|
| 372 |
+
async def test_bucket_image_disconnect_stops_stream_and_releases_slot(self):
|
| 373 |
+
path = "pages/image/bmp/" + "a" * 64 + "/pages/page-000001.webp"
|
| 374 |
+
upstream = FakeResponse(chunks=(b"image",))
|
| 375 |
+
self.session(upstream)
|
| 376 |
+
with patch.object(app, "get_reader_bucket_resource", AsyncMock()) as buffered:
|
| 377 |
+
response = await app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers={}))
|
| 378 |
+
buffered.assert_not_awaited()
|
| 379 |
+
started = asyncio.Event()
|
| 380 |
+
|
| 381 |
+
async def send(message):
|
| 382 |
+
started.set()
|
| 383 |
+
await asyncio.Event().wait()
|
| 384 |
+
|
| 385 |
+
async def receive():
|
| 386 |
+
await started.wait()
|
| 387 |
+
return {"type": "http.disconnect"}
|
| 388 |
+
|
| 389 |
+
await asyncio.wait_for(response({"type": "http", "asgi": {"spec_version": "2.0"}}, receive, send), 1)
|
| 390 |
+
self.assertTrue(upstream.released)
|
| 391 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 1)
|
| 392 |
+
|
| 393 |
+
async def test_uncached_bucket_bodies_stream_without_filesystem_worker(self):
|
| 394 |
+
prefix = 'a' * 64
|
| 395 |
+
paths = [f'documents/text/txt/{prefix}/document.txt',
|
| 396 |
+
f'documents/web/html/{prefix}/document.html',
|
| 397 |
+
f'documents/office/docx/{prefix}/document.docx',
|
| 398 |
+
f'chapters/ebook/epub/{prefix}/'+'b'*16+'/chapters/chapter-0001.xhtml',
|
| 399 |
+
f'media/swf/native/{prefix}/document.swf']
|
| 400 |
+
for path in paths:
|
| 401 |
+
with self.subTest(path=path):
|
| 402 |
+
upstream = FakeResponse(chunks=(b'body',))
|
| 403 |
+
self.session(upstream)
|
| 404 |
+
with patch.object(app, 'get_reader_bucket_resource', AsyncMock()) as buffered:
|
| 405 |
+
response = await app.api_reader_bucket_resource(path, SimpleNamespace(method='GET', headers={}))
|
| 406 |
+
buffered.assert_not_awaited()
|
| 407 |
+
self.assertEqual(b''.join([chunk async for chunk in response.body_iterator]), b'body')
|
| 408 |
+
self.assertTrue(upstream.released)
|
| 409 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 1)
|
| 410 |
+
|
| 411 |
+
async def test_disconnect_while_waiting_for_headers_releases_transport_slot(self):
|
| 412 |
+
self.session()
|
| 413 |
+
disconnected = asyncio.Event()
|
| 414 |
+
started = asyncio.Event()
|
| 415 |
+
cancelled = asyncio.Event()
|
| 416 |
+
|
| 417 |
+
async def open_upstream(*args, **kwargs):
|
| 418 |
+
started.set()
|
| 419 |
+
try:
|
| 420 |
+
await asyncio.Event().wait()
|
| 421 |
+
finally:
|
| 422 |
+
cancelled.set()
|
| 423 |
+
|
| 424 |
+
request = SimpleNamespace(method="GET", headers={},
|
| 425 |
+
is_disconnected=AsyncMock(side_effect=lambda: disconnected.is_set()))
|
| 426 |
+
with patch.object(app, "open_download_response", side_effect=open_upstream):
|
| 427 |
+
task = asyncio.create_task(app.stream_reader_document(request, SOURCE))
|
| 428 |
+
await asyncio.wait_for(started.wait(), 1)
|
| 429 |
+
disconnected.set()
|
| 430 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 431 |
+
await asyncio.wait_for(task, 1)
|
| 432 |
+
self.assertTrue(cancelled.is_set())
|
| 433 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 1)
|
| 434 |
+
|
| 435 |
+
async def test_disconnect_while_queued_does_not_start_upstream(self):
|
| 436 |
+
await app.app.state.upstream_semaphore.acquire()
|
| 437 |
+
request = SimpleNamespace(method="GET", headers={}, is_disconnected=AsyncMock(return_value=True))
|
| 438 |
+
with patch.object(app, "open_download_response", AsyncMock()) as opened:
|
| 439 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 440 |
+
await asyncio.wait_for(app.stream_reader_document(request, SOURCE), 1)
|
| 441 |
+
opened.assert_not_awaited()
|
| 442 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 0)
|
| 443 |
+
app.app.state.upstream_semaphore.release()
|
| 444 |
+
|
| 445 |
+
async def test_cached_range_finishes_when_disconnect_probe_swallows_cancellation(self):
|
| 446 |
+
app.app.state.reader_range_cache = app.OrderedDict()
|
| 447 |
+
app.app.state.reader_range_cache_bytes = 3
|
| 448 |
+
key = (SOURCE, 'bytes=0-2', app.READER_DOCUMENT_MAX_BYTES, None)
|
| 449 |
+
app.app.state.reader_range_cache[key] = (time.monotonic(), b'pdf', {
|
| 450 |
+
'Content-Type':'application/pdf', 'Content-Length':'3', 'Content-Range':'bytes 0-2/3'})
|
| 451 |
+
|
| 452 |
+
async def probe():
|
| 453 |
+
try:
|
| 454 |
+
await asyncio.Event().wait()
|
| 455 |
+
except asyncio.CancelledError:
|
| 456 |
+
# Starlette's Request probe owns a cancellation scope.
|
| 457 |
+
return False
|
| 458 |
+
|
| 459 |
+
request = SimpleNamespace(method='GET', headers={'Range':'bytes=0-2'}, is_disconnected=probe)
|
| 460 |
+
with patch.object(app, 'open_download_response', AsyncMock()) as opened:
|
| 461 |
+
response = await asyncio.wait_for(app.stream_reader_document(request, SOURCE), .5)
|
| 462 |
+
self.assertEqual(response.status_code, 206)
|
| 463 |
+
self.assertEqual(response.body, b'pdf')
|
| 464 |
+
self.assertEqual(response.headers['cache-control'], 'no-store')
|
| 465 |
+
opened.assert_not_awaited()
|
| 466 |
+
|
| 467 |
async def content(self, upstream, method="GET"):
|
| 468 |
self.session(upstream)
|
| 469 |
return await app.api_reader_content(SimpleNamespace(method=method, headers={}), SOURCE, None)
|
|
|
|
| 767 |
self.assertEqual(response.body, bucket_body)
|
| 768 |
self.assertEqual(read.call_args.args[0], chapter_path)
|
| 769 |
|
| 770 |
+
async def test_cold_resolve_waits_for_conversion_and_empty_failure_is_not_cacheable(self):
|
| 771 |
+
with patch.object(app, "reader_assets_cache", {"v": 1, "f": {}}):
|
| 772 |
+
await app.api_reader_resolve("0ym7e7wbcxau0")
|
| 773 |
+
app.get_reader_assets.assert_awaited_with(wait=True)
|
| 774 |
+
self.assets['f'][app.build_reader_asset_key(self.record)] = {
|
| 775 |
+
's':2, 'm':'p', 'p':'documents/pdf/ps/'+'a'*64+'/document.pdf',
|
| 776 |
+
'b':'vomebook/reader-assets-v2'}
|
| 777 |
+
with patch.object(app, "reader_assets_cache", self.assets):
|
| 778 |
+
response = await app.api_reader_resolve("0ym7e7wbcxau0")
|
| 779 |
+
app.get_reader_assets.assert_awaited_with(wait=False)
|
| 780 |
+
self.assertEqual(json.loads(response.body)['extension'], 'pdf')
|
| 781 |
+
self.assets['f'].clear()
|
| 782 |
+
response = await app.api_reader_resolve("0ym7e7wbcxau0")
|
| 783 |
+
self.assertEqual(response.headers['cache-control'], 'no-store')
|
| 784 |
+
|
| 785 |
async def test_bucket_content_rejects_arbitrary_relative_and_ambiguous_paths(self):
|
| 786 |
for url in (
|
| 787 |
"https://[broken", "/api/other?path=x", "//evil.test/api/reader-bucket-resource?path=x",
|
tests/test_reader_index_warming.py
CHANGED
|
@@ -14,6 +14,7 @@ class ReaderIndexWarmingTests(unittest.IsolatedAsyncioTestCase):
|
|
| 14 |
def setUp(self):
|
| 15 |
self.saved_records = copy.deepcopy(app.records)
|
| 16 |
self.saved_ready = app._reader_indexes_ready
|
|
|
|
| 17 |
self.saved_indices = (
|
| 18 |
app.reader_record_indices,
|
| 19 |
app.repo_reader_record_indices,
|
|
@@ -31,26 +32,63 @@ class ReaderIndexWarmingTests(unittest.IsolatedAsyncioTestCase):
|
|
| 31 |
def tearDown(self):
|
| 32 |
app.records = self.saved_records
|
| 33 |
app._reader_indexes_ready = self.saved_ready
|
|
|
|
| 34 |
(app.reader_record_indices, app.repo_reader_record_indices,
|
| 35 |
app.reader_record_key_indices, app.reader_source_id_indices) = self.saved_indices
|
| 36 |
app.app.state.reader_index_build_task = self.saved_task
|
| 37 |
|
| 38 |
async def test_concurrent_reader_requests_share_one_build(self):
|
| 39 |
calls = 0
|
| 40 |
-
original = app.
|
| 41 |
|
| 42 |
def build_once():
|
| 43 |
nonlocal calls
|
| 44 |
calls += 1
|
| 45 |
-
original()
|
| 46 |
|
| 47 |
-
with mock.patch.object(app, "
|
| 48 |
await asyncio.gather(app.ensure_reader_indexes_async(), app.ensure_reader_indexes_async())
|
| 49 |
|
| 50 |
self.assertEqual(calls, 1)
|
| 51 |
self.assertTrue(app._reader_indexes_ready)
|
| 52 |
self.assertEqual(list(app.reader_record_indices), [0])
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
if __name__ == "__main__":
|
| 56 |
unittest.main()
|
|
|
|
| 14 |
def setUp(self):
|
| 15 |
self.saved_records = copy.deepcopy(app.records)
|
| 16 |
self.saved_ready = app._reader_indexes_ready
|
| 17 |
+
self.saved_build = app._reader_index_build
|
| 18 |
self.saved_indices = (
|
| 19 |
app.reader_record_indices,
|
| 20 |
app.repo_reader_record_indices,
|
|
|
|
| 32 |
def tearDown(self):
|
| 33 |
app.records = self.saved_records
|
| 34 |
app._reader_indexes_ready = self.saved_ready
|
| 35 |
+
app._reader_index_build = self.saved_build
|
| 36 |
(app.reader_record_indices, app.repo_reader_record_indices,
|
| 37 |
app.reader_record_key_indices, app.reader_source_id_indices) = self.saved_indices
|
| 38 |
app.app.state.reader_index_build_task = self.saved_task
|
| 39 |
|
| 40 |
async def test_concurrent_reader_requests_share_one_build(self):
|
| 41 |
calls = 0
|
| 42 |
+
original = app._advance_reader_indexes
|
| 43 |
|
| 44 |
def build_once():
|
| 45 |
nonlocal calls
|
| 46 |
calls += 1
|
| 47 |
+
return original()
|
| 48 |
|
| 49 |
+
with mock.patch.object(app, "_advance_reader_indexes", side_effect=build_once):
|
| 50 |
await asyncio.gather(app.ensure_reader_indexes_async(), app.ensure_reader_indexes_async())
|
| 51 |
|
| 52 |
self.assertEqual(calls, 1)
|
| 53 |
self.assertTrue(app._reader_indexes_ready)
|
| 54 |
self.assertEqual(list(app.reader_record_indices), [0])
|
| 55 |
|
| 56 |
+
async def test_partial_reader_build_yields_to_search_and_publishes_only_complete_indexes(self):
|
| 57 |
+
from search_execution import SearchExecutor
|
| 58 |
+
app.records *= 700
|
| 59 |
+
app.build_indexes(build_words=False, build_reader=False)
|
| 60 |
+
seen = []
|
| 61 |
+
original = app._advance_reader_indexes
|
| 62 |
+
loop = asyncio.get_running_loop()
|
| 63 |
+
foreground = []
|
| 64 |
+
async with SearchExecutor() as executor:
|
| 65 |
+
app.app.state.search_executor = executor
|
| 66 |
+
def advance():
|
| 67 |
+
result = original(limit=10, budget=float("inf"))
|
| 68 |
+
if not seen:
|
| 69 |
+
loop.call_soon_threadsafe(lambda: foreground.append(asyncio.create_task(
|
| 70 |
+
executor.run(lambda: seen.append((app._reader_indexes_ready, app._reader_index_build["next"]))))))
|
| 71 |
+
return result
|
| 72 |
+
try:
|
| 73 |
+
with mock.patch.object(app, "_advance_reader_indexes", side_effect=advance):
|
| 74 |
+
await app.ensure_reader_indexes_async()
|
| 75 |
+
await asyncio.gather(*foreground)
|
| 76 |
+
finally:
|
| 77 |
+
del app.app.state.search_executor
|
| 78 |
+
self.assertTrue(seen)
|
| 79 |
+
self.assertEqual(seen[0], (False, 10))
|
| 80 |
+
self.assertEqual(list(app.reader_record_indices), list(range(700)))
|
| 81 |
+
self.assertIsNone(app._reader_index_build)
|
| 82 |
+
|
| 83 |
+
async def test_rebuild_discards_partial_old_corpus(self):
|
| 84 |
+
app.records *= 10
|
| 85 |
+
self.assertFalse(app._advance_reader_indexes(limit=1))
|
| 86 |
+
self.assertEqual(app.reader_source_id_indices, {})
|
| 87 |
+
app.records = [{"Repo":"Repo/B", "File":"new", "Extension":"txt", "Folder":[]}]
|
| 88 |
+
app.build_indexes(build_words=False, build_reader=False)
|
| 89 |
+
await app.ensure_reader_indexes_async()
|
| 90 |
+
self.assertEqual(list(app.reader_record_key_indices), [app.build_reader_asset_key(app.records[0])])
|
| 91 |
+
|
| 92 |
|
| 93 |
if __name__ == "__main__":
|
| 94 |
unittest.main()
|
tests/test_reader_pdf_hybrid.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline hybrid handoff acceptance; may target either checked-out Reader."""
|
| 2 |
+
import contextlib
|
| 3 |
+
import functools
|
| 4 |
+
import http.server
|
| 5 |
+
import io
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import threading
|
| 10 |
+
import unittest
|
| 11 |
+
from urllib.parse import parse_qs, urlencode, urlparse
|
| 12 |
+
|
| 13 |
+
from PIL import Image
|
| 14 |
+
from playwright.sync_api import sync_playwright
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
ROOT = Path(os.environ.get("READER_HYBRID_ROOT", Path(__file__).resolve().parents[1]))
|
| 18 |
+
PAGES = ROOT.name == "github-Search"
|
| 19 |
+
BASE_PATH = "/search" if PAGES else ""
|
| 20 |
+
PDF = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/hybrid.pdf"
|
| 21 |
+
PATH = "objects/aa/" + "a" * 64 + "/" + "b" * 16 + "/page-manifest.json"
|
| 22 |
+
ENGINE = """
|
| 23 |
+
export const GlobalWorkerOptions = {};
|
| 24 |
+
export class PDFWorker { promise = Promise.resolve(); destroy() { window.__workerClosed = true; } }
|
| 25 |
+
export function getDocument(options) {
|
| 26 |
+
window.__documentOptions = {url: options.url, chunk: options.rangeChunkSize,
|
| 27 |
+
stream: options.disableStream, auto: options.disableAutoFetch};
|
| 28 |
+
let finish;
|
| 29 |
+
const promise = new Promise(resolve => { finish = resolve; });
|
| 30 |
+
const pdf = { numPages: window.__wrongCount ? 79 : 80, getOutline: async () => null,
|
| 31 |
+
getPage: async number => ({
|
| 32 |
+
getViewport: ({scale}) => ({width: 600*scale, height: 800*scale}),
|
| 33 |
+
getTextContent: async () => ({items: [{str:'hybrid searchable page '+number,
|
| 34 |
+
transform:[12,0,0,12,20,40], width:120, height:12}], styles: {}}),
|
| 35 |
+
render: ({canvasContext: ctx}) => {
|
| 36 |
+
window.__renders.push(number);
|
| 37 |
+
let resolve, reject;
|
| 38 |
+
const promise = new Promise((yes, no) => {resolve=yes; reject=no;});
|
| 39 |
+
const done = () => {ctx.fillStyle='#1c8b68'; ctx.fillRect(0,0,6000,8000); resolve();};
|
| 40 |
+
if (window.__holdPages.includes(number)) window.__releasePages[number] = done;
|
| 41 |
+
else done();
|
| 42 |
+
return {promise, cancel: () => reject(Object.assign(Error('cancelled'), {name:'AbortError'}))};
|
| 43 |
+
}
|
| 44 |
+
})};
|
| 45 |
+
window.__releaseDocument = () => finish(pdf);
|
| 46 |
+
return {promise, destroy: async () => {window.__documentClosed = true;}};
|
| 47 |
+
}
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class HybridPdfTests(unittest.TestCase):
|
| 52 |
+
@classmethod
|
| 53 |
+
def setUpClass(cls):
|
| 54 |
+
stack = contextlib.ExitStack()
|
| 55 |
+
cls.addClassCleanup(stack.close)
|
| 56 |
+
class Handler(http.server.SimpleHTTPRequestHandler):
|
| 57 |
+
def do_GET(self):
|
| 58 |
+
if self.path.startswith("/search/"):
|
| 59 |
+
self.path = self.path[len("/search"):]
|
| 60 |
+
return super().do_GET()
|
| 61 |
+
def guess_type(self, path):
|
| 62 |
+
return "text/javascript" if path.endswith((".js", ".mjs")) else super().guess_type(path)
|
| 63 |
+
def log_message(self, *_args):
|
| 64 |
+
pass
|
| 65 |
+
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Handler, directory=str(ROOT)))
|
| 66 |
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
| 67 |
+
thread.start()
|
| 68 |
+
cls.addClassCleanup(lambda: (server.shutdown(), server.server_close(), thread.join(3)))
|
| 69 |
+
cls.origin = f"http://127.0.0.1:{server.server_port}"
|
| 70 |
+
playwright = stack.enter_context(sync_playwright())
|
| 71 |
+
cls.browser = playwright.chromium.launch(headless=True, args=["--no-sandbox"])
|
| 72 |
+
cls.addClassCleanup(cls.browser.close)
|
| 73 |
+
output = io.BytesIO()
|
| 74 |
+
Image.new("RGB", (600, 800), "white").save(output, "WEBP")
|
| 75 |
+
cls.image = output.getvalue()
|
| 76 |
+
|
| 77 |
+
def setUp(self):
|
| 78 |
+
self.context = self.browser.new_context(service_workers="block")
|
| 79 |
+
self.addCleanup(self.context.close)
|
| 80 |
+
self.page = self.context.new_page()
|
| 81 |
+
self.images, self.errors = [], []
|
| 82 |
+
self.page_count = 80
|
| 83 |
+
self.page.on("pageerror", lambda error: self.errors.append(str(error)))
|
| 84 |
+
self.page.add_init_script("window.__renders=[];window.__holdPages=[];window.__releasePages={};")
|
| 85 |
+
self.page.route("**/static/vendor/pdf.min.*.mjs*", lambda route: route.fulfill(
|
| 86 |
+
content_type="text/javascript", body=ENGINE))
|
| 87 |
+
self.page.route("**/api/reader-bucket-resource?**", self.asset)
|
| 88 |
+
|
| 89 |
+
def asset(self, route):
|
| 90 |
+
path = parse_qs(urlparse(route.request.url).query)["path"][0]
|
| 91 |
+
if path.endswith("page-manifest.json"):
|
| 92 |
+
route.fulfill(content_type="application/json", body=json.dumps(
|
| 93 |
+
{"version": 2, "kind": "pdf-pages", "page_count": self.page_count}))
|
| 94 |
+
else:
|
| 95 |
+
self.images.append(int(path.split("page-")[-1].split(".")[0]))
|
| 96 |
+
route.fulfill(content_type="image/webp", body=self.image)
|
| 97 |
+
|
| 98 |
+
def open(self, page=1):
|
| 99 |
+
source = ("https://voiceofml-search.hf.space" if PAGES else self.origin) + "/api/reader-bucket-resource?" + urlencode({"path": PATH})
|
| 100 |
+
if page != 1:
|
| 101 |
+
script = (ROOT / "static/reader-store.js").read_text() + "\n" + (
|
| 102 |
+
"window.VoiceOfMLReaderStore=Object.freeze({...window.VoiceOfMLReaderStore,"
|
| 103 |
+
"get:async url=>({schema:3,url,page:" + str(page) + ",pageCount:80,pageOffset:0})});")
|
| 104 |
+
self.page.route("**/static/reader-store.js*", lambda route: route.fulfill(
|
| 105 |
+
content_type="text/javascript", body=script))
|
| 106 |
+
self.page.goto(self.origin + BASE_PATH + "/static/reader.html?" + urlencode(
|
| 107 |
+
{"url": source, "ext": "pdf-pages", "pdf_document": PDF}), wait_until="domcontentloaded")
|
| 108 |
+
self.page.wait_for_function("() => typeof window.__releaseDocument === 'function'")
|
| 109 |
+
self.page.locator(f'.reader-page[data-page="{page}"] img.ready').wait_for()
|
| 110 |
+
return self.page.locator(f'.reader-page[data-page="{page}"]')
|
| 111 |
+
|
| 112 |
+
def jump(self, number):
|
| 113 |
+
self.page.locator("#page-number").fill(str(number))
|
| 114 |
+
self.page.locator("#page-number").press("Enter")
|
| 115 |
+
|
| 116 |
+
def test_first_stream_fast_pdf_later_pages_skip_images_and_zoom_keeps_canvas(self):
|
| 117 |
+
shell = self.open()
|
| 118 |
+
shell.evaluate("s => {window.__firstShell=s; window.__beforeTop=s.getBoundingClientRect().top;}")
|
| 119 |
+
self.page.evaluate("window.__releaseDocument()")
|
| 120 |
+
shell.locator("canvas.ready").wait_for()
|
| 121 |
+
self.assertEqual(shell.locator("img").count(), 0)
|
| 122 |
+
self.assertTrue(shell.evaluate("s => s === window.__firstShell"))
|
| 123 |
+
self.assertLess(abs(shell.evaluate("s => s.getBoundingClientRect().top-window.__beforeTop")), 3)
|
| 124 |
+
self.images.clear()
|
| 125 |
+
self.jump(60)
|
| 126 |
+
target = self.page.locator('.reader-page[data-page="60"]')
|
| 127 |
+
target.locator("canvas.ready").wait_for()
|
| 128 |
+
self.page.wait_for_timeout(350)
|
| 129 |
+
self.assertNotIn(60, self.images)
|
| 130 |
+
self.assertEqual(self.page.evaluate("window.__documentOptions.chunk"), 262144)
|
| 131 |
+
self.assertTrue(self.page.evaluate("window.__documentOptions.stream && window.__documentOptions.auto"))
|
| 132 |
+
target.evaluate("s => {window.__oldCanvas=s.querySelector('canvas');}")
|
| 133 |
+
self.page.locator("#zoom-in").click()
|
| 134 |
+
self.page.wait_for_function("() => document.querySelector('[data-page=\"60\"] canvas.ready') !== window.__oldCanvas")
|
| 135 |
+
self.assertNotIn(60, self.images)
|
| 136 |
+
self.assertEqual(self.errors, [])
|
| 137 |
+
|
| 138 |
+
def test_late_page_stream_backfills_slow_pdf_then_handoffs_on_mobile(self):
|
| 139 |
+
self.page.set_viewport_size({"width": 390, "height": 844})
|
| 140 |
+
self.open()
|
| 141 |
+
self.page.evaluate("window.__releaseDocument()")
|
| 142 |
+
self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for()
|
| 143 |
+
self.page.evaluate("window.__holdPages=[60]")
|
| 144 |
+
self.jump(60)
|
| 145 |
+
shell = self.page.locator('.reader-page[data-page="60"]')
|
| 146 |
+
shell.locator("img.ready").wait_for()
|
| 147 |
+
self.assertIn(60, self.images)
|
| 148 |
+
self.assertEqual(shell.locator("canvas.ready").count(), 0)
|
| 149 |
+
self.page.evaluate("window.__releasePages[60]()")
|
| 150 |
+
shell.locator("canvas.ready").wait_for()
|
| 151 |
+
self.assertEqual(shell.locator("img").count(), 0)
|
| 152 |
+
pixels = shell.locator("canvas").evaluate("c=>Array.from(c.getContext('2d').getImageData(10,10,1,1).data)")
|
| 153 |
+
self.assertGreater(pixels[1], 100)
|
| 154 |
+
self.assertEqual(self.errors, [])
|
| 155 |
+
|
| 156 |
+
def test_wrong_pdf_page_count_retains_stream(self):
|
| 157 |
+
self.page.add_init_script("window.__wrongCount=true")
|
| 158 |
+
shell = self.open()
|
| 159 |
+
self.page.evaluate("window.__releaseDocument()")
|
| 160 |
+
self.page.wait_for_timeout(300)
|
| 161 |
+
self.assertEqual(shell.locator("img.ready").count(), 1)
|
| 162 |
+
self.assertEqual(shell.locator("canvas.ready").count(), 0)
|
| 163 |
+
self.assertEqual(self.page.locator(".reader-error").count(), 0)
|
| 164 |
+
self.assertEqual(self.errors, [])
|
| 165 |
+
|
| 166 |
+
def test_disposal_cancels_pending_pdf_without_late_canvas(self):
|
| 167 |
+
shell = self.open()
|
| 168 |
+
self.page.evaluate("window.dispatchEvent(new Event('pagehide'))")
|
| 169 |
+
self.page.evaluate("window.__releaseDocument()")
|
| 170 |
+
self.page.wait_for_timeout(350)
|
| 171 |
+
self.assertEqual(shell.locator("canvas.ready").count(), 0)
|
| 172 |
+
self.assertTrue(self.page.evaluate("window.__documentClosed"))
|
| 173 |
+
self.assertEqual(self.errors, [])
|
| 174 |
+
|
| 175 |
+
def test_history_opens_deep_page_stream_directly_and_preserves_position(self):
|
| 176 |
+
shell = self.open(page=60)
|
| 177 |
+
self.assertEqual(self.images[0], 60)
|
| 178 |
+
self.assertEqual(self.page.locator("#page-number").input_value(), "60")
|
| 179 |
+
top = shell.evaluate("s=>s.getBoundingClientRect().top")
|
| 180 |
+
self.page.evaluate("window.__releaseDocument()")
|
| 181 |
+
shell.locator("canvas.ready").wait_for()
|
| 182 |
+
self.assertLess(abs(shell.evaluate("s=>s.getBoundingClientRect().top") - top), 3)
|
| 183 |
+
self.assertEqual(self.page.locator("#page-number").input_value(), "60")
|
| 184 |
+
self.assertEqual(self.errors, [])
|
| 185 |
+
|
| 186 |
+
def test_failed_image_does_not_fail_readable_pdf(self):
|
| 187 |
+
original = self.asset
|
| 188 |
+
self.page.unroute("**/api/reader-bucket-resource?**")
|
| 189 |
+
def asset(route):
|
| 190 |
+
if "page-manifest" in route.request.url:
|
| 191 |
+
return original(route)
|
| 192 |
+
self.page.evaluate("window.__releaseDocument?.()")
|
| 193 |
+
route.fulfill(status=404, body="missing preview")
|
| 194 |
+
self.page.route("**/api/reader-bucket-resource?**", asset)
|
| 195 |
+
source = ("https://voiceofml-search.hf.space" if PAGES else self.origin) + "/api/reader-bucket-resource?" + urlencode({"path": PATH})
|
| 196 |
+
self.page.goto(self.origin + BASE_PATH + "/static/reader.html?" + urlencode(
|
| 197 |
+
{"url": source, "ext": "pdf-pages", "pdf_document": PDF}), wait_until="domcontentloaded")
|
| 198 |
+
self.page.wait_for_function("() => typeof window.__releaseDocument === 'function'")
|
| 199 |
+
self.page.evaluate("window.__releaseDocument()")
|
| 200 |
+
self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for()
|
| 201 |
+
self.assertEqual(self.page.locator(".reader-error").count(), 0)
|
| 202 |
+
self.assertEqual(self.errors, [])
|
| 203 |
+
|
| 204 |
+
def test_real_pdf_engine_replaces_stream_without_second_adapter(self):
|
| 205 |
+
from tests.test_reader_performance import minimal_pdf
|
| 206 |
+
self.page_count = 1
|
| 207 |
+
self.page.unroute("**/static/vendor/pdf.min.*.mjs*")
|
| 208 |
+
pending = []
|
| 209 |
+
self.page.route("**/api/reader-content?**", lambda route: pending.append(route))
|
| 210 |
+
source = ("https://voiceofml-search.hf.space" if PAGES else self.origin) + "/api/reader-bucket-resource?" + urlencode({"path": PATH})
|
| 211 |
+
with self.page.expect_request("**/api/reader-content?**"):
|
| 212 |
+
self.page.goto(self.origin + BASE_PATH + "/static/reader.html?" + urlencode(
|
| 213 |
+
{"url": source, "ext": "pdf-pages", "pdf_document": PDF}), wait_until="domcontentloaded")
|
| 214 |
+
shell = self.page.locator('.reader-page[data-page="1"]')
|
| 215 |
+
shell.locator("img.ready").wait_for()
|
| 216 |
+
self.page.wait_for_function("() => document.querySelector('[data-page=\"1\"] img.ready') !== null")
|
| 217 |
+
self.assertTrue(pending)
|
| 218 |
+
pending[0].fulfill(content_type="application/pdf", body=minimal_pdf())
|
| 219 |
+
shell.locator("canvas.ready").wait_for()
|
| 220 |
+
self.assertEqual(shell.locator("img").count(), 0)
|
| 221 |
+
self.assertEqual(len(self.page.workers), 1)
|
| 222 |
+
self.assertGreater(shell.locator("canvas").evaluate("c=>c.toDataURL().length"), 1000)
|
| 223 |
+
self.assertEqual(self.errors, [])
|
| 224 |
+
|
| 225 |
+
def test_navigation_cancels_obsolete_held_render(self):
|
| 226 |
+
self.open()
|
| 227 |
+
self.page.evaluate("window.__releaseDocument()")
|
| 228 |
+
self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for()
|
| 229 |
+
self.page.evaluate("window.__holdPages=[60]")
|
| 230 |
+
self.jump(60)
|
| 231 |
+
self.page.locator('.reader-page[data-page="60"] img.ready').wait_for()
|
| 232 |
+
self.jump(75)
|
| 233 |
+
self.page.locator('.reader-page[data-page="75"] canvas.ready').wait_for()
|
| 234 |
+
self.page.evaluate("window.__releasePages[60]()")
|
| 235 |
+
self.page.wait_for_timeout(300)
|
| 236 |
+
self.assertEqual(self.page.locator('[data-page="60"] canvas.ready').count(), 0)
|
| 237 |
+
self.assertEqual(self.page.locator("#page-number").input_value(), "75")
|
| 238 |
+
self.assertEqual(self.errors, [])
|
| 239 |
+
|
| 240 |
+
def test_active_selection_defers_swap_without_destroying_text_nodes(self):
|
| 241 |
+
shell = self.open()
|
| 242 |
+
shell.evaluate("""s=>{
|
| 243 |
+
const layer=s.querySelector('.reader-pdf-text');
|
| 244 |
+
const span=document.createElement('span'); span.textContent='selected text';
|
| 245 |
+
span.className='reader-pdf-text-run'; layer.append(span); s.dataset.textReady='1';
|
| 246 |
+
const range=document.createRange(); range.selectNodeContents(span);
|
| 247 |
+
getSelection().removeAllRanges(); getSelection().addRange(range);
|
| 248 |
+
}""")
|
| 249 |
+
self.page.evaluate("window.__releaseDocument()")
|
| 250 |
+
self.page.wait_for_function("() => window.__renders.includes(1)")
|
| 251 |
+
self.page.wait_for_timeout(150)
|
| 252 |
+
self.assertEqual(shell.locator("canvas.ready").count(), 0)
|
| 253 |
+
self.assertEqual(self.page.evaluate("getSelection().toString()"), "selected text")
|
| 254 |
+
self.page.evaluate("getSelection().removeAllRanges()")
|
| 255 |
+
shell.locator("canvas.ready").wait_for()
|
| 256 |
+
self.assertEqual(shell.locator(".reader-pdf-text").inner_text(), "selected text")
|
| 257 |
+
self.assertEqual(self.errors, [])
|
| 258 |
+
|
| 259 |
+
def test_hybrid_without_ocr_searches_complete_native_pdf_text(self):
|
| 260 |
+
self.open()
|
| 261 |
+
self.page.evaluate("window.__releaseDocument()")
|
| 262 |
+
self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for()
|
| 263 |
+
self.page.locator("#history").click()
|
| 264 |
+
self.page.locator("#full-search-toggle").click()
|
| 265 |
+
self.page.locator("#full-search-input").fill("searchable")
|
| 266 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '80 ไธช็ปๆ'")
|
| 267 |
+
self.assertEqual(self.errors, [])
|
| 268 |
+
|
| 269 |
+
def test_zoom_immediately_after_fast_handoff_is_not_lost(self):
|
| 270 |
+
self.open()
|
| 271 |
+
self.page.evaluate("window.__releaseDocument()")
|
| 272 |
+
self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for()
|
| 273 |
+
self.jump(60)
|
| 274 |
+
canvas = self.page.locator('[data-page="60"] canvas.ready')
|
| 275 |
+
canvas.wait_for()
|
| 276 |
+
canvas.evaluate("c=>{window.__immediateCanvas=c;}")
|
| 277 |
+
self.page.locator("#zoom-in").click()
|
| 278 |
+
self.page.wait_for_function("() => {const c=document.querySelector('[data-page=\"60\"] canvas.ready'); return c && c !== window.__immediateCanvas;}")
|
| 279 |
+
self.assertNotIn(60, self.images)
|
| 280 |
+
self.assertEqual(self.errors, [])
|
tests/test_search.py
CHANGED
|
@@ -54,6 +54,31 @@ class SearchContractTests(unittest.TestCase):
|
|
| 54 |
self.assertEqual(result["total"], 2)
|
| 55 |
self.assertEqual({item["File"] for item in result["results"]}, {"ๆๅ้ฉๅฝ่ตๆ", "ๆๅ่ตๆ"})
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
def test_search_folders_false_excludes_folder_only_match(self):
|
| 58 |
result = app.search("้ฉๅฝ", search_folders=False)
|
| 59 |
self.assertEqual({item["File"] for item in result["results"]}, {"ๆๅ้ฉๅฝ่ตๆ", "้ฉๅฝ่ตๆ"})
|
|
|
|
| 54 |
self.assertEqual(result["total"], 2)
|
| 55 |
self.assertEqual({item["File"] for item in result["results"]}, {"ๆๅ้ฉๅฝ่ตๆ", "ๆๅ่ตๆ"})
|
| 56 |
|
| 57 |
+
def test_query_postings_are_scoped_once_per_token_without_mutating_published_sets(self):
|
| 58 |
+
expected = app._search_order_uncached("ๆๅ ้ฉๅฝ", search_folders=False)
|
| 59 |
+
previous = deepcopy(app.word_index)
|
| 60 |
+
with mock.patch.object(app, "scoped_word_postings", wraps=app.scoped_word_postings) as scoped:
|
| 61 |
+
self.assertEqual(app._search_order_uncached("ๆๅ ้ฉๅฝ", search_folders=False), expected)
|
| 62 |
+
tokens = [call.args[0] for call in scoped.call_args_list]
|
| 63 |
+
self.assertEqual(len(tokens), len(set(tokens)))
|
| 64 |
+
self.assertEqual(app.word_index, previous)
|
| 65 |
+
|
| 66 |
+
def test_ngram_intersection_starts_with_rarest_and_skips_repeated_or_missing_grams(self):
|
| 67 |
+
app.ngram_postings = {2: {"ab": {0, 1, 2}, "bc": {1}, "cd": {1, 2}}}
|
| 68 |
+
original = app.resolve_postings
|
| 69 |
+
with mock.patch.object(app, "resolve_postings", wraps=original) as decode:
|
| 70 |
+
self.assertEqual(app.literal_candidates("abcd"), {1})
|
| 71 |
+
self.assertEqual(decode.call_args_list[0].args[0], {1})
|
| 72 |
+
with mock.patch.object(app, "resolve_postings", wraps=original) as decode:
|
| 73 |
+
self.assertEqual(app.literal_candidates("abcd", ["Repo/C"]), set())
|
| 74 |
+
self.assertEqual(decode.call_count, 1)
|
| 75 |
+
with mock.patch.object(app, "resolve_postings", side_effect=AssertionError("unneeded decode")):
|
| 76 |
+
self.assertEqual(app.literal_candidates("abcdx"), set())
|
| 77 |
+
app.ngram_postings = {2: {"aa": {0, 1}}}
|
| 78 |
+
with mock.patch.object(app, "resolve_postings", wraps=original) as decode:
|
| 79 |
+
self.assertEqual(app.literal_candidates("aaaaa"), {0, 1})
|
| 80 |
+
self.assertEqual(decode.call_count, 1)
|
| 81 |
+
|
| 82 |
def test_search_folders_false_excludes_folder_only_match(self):
|
| 83 |
result = app.search("้ฉๅฝ", search_folders=False)
|
| 84 |
self.assertEqual({item["File"] for item in result["results"]}, {"ๆๅ้ฉๅฝ่ตๆ", "้ฉๅฝ่ตๆ"})
|
tests/test_search_execution.py
CHANGED
|
@@ -5,6 +5,40 @@ from search_execution import SearchBusy, SearchExecutor
|
|
| 5 |
|
| 6 |
|
| 7 |
class SearchExecutionTests(unittest.IsolatedAsyncioTestCase):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
async def test_slow_search_does_not_block_http_ping_and_busy_requests_retry(self):
|
| 9 |
import app
|
| 10 |
import httpx
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
class SearchExecutionTests(unittest.IsolatedAsyncioTestCase):
|
| 8 |
+
async def test_cancelling_background_wait_keeps_foreground_ownership(self):
|
| 9 |
+
started, release = threading.Event(), threading.Event()
|
| 10 |
+
seen = []
|
| 11 |
+
async with SearchExecutor() as executor:
|
| 12 |
+
active = asyncio.create_task(executor.run(lambda: (started.set(), release.wait(2), seen.append("active"))))
|
| 13 |
+
try:
|
| 14 |
+
self.assertTrue(await asyncio.to_thread(started.wait, 1))
|
| 15 |
+
background = asyncio.create_task(executor.run(lambda: seen.append("cancelled"), background=True))
|
| 16 |
+
await asyncio.sleep(0)
|
| 17 |
+
background.cancel()
|
| 18 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 19 |
+
await background
|
| 20 |
+
self.assertFalse(active.done())
|
| 21 |
+
finally:
|
| 22 |
+
release.set()
|
| 23 |
+
await active
|
| 24 |
+
self.assertEqual(seen, ["active"])
|
| 25 |
+
|
| 26 |
+
async def test_background_jobs_wait_for_admitted_foreground_jobs(self):
|
| 27 |
+
started, release = threading.Event(), threading.Event()
|
| 28 |
+
seen = []
|
| 29 |
+
async with SearchExecutor() as executor:
|
| 30 |
+
active = asyncio.create_task(executor.run(lambda: (started.set(), release.wait(2))))
|
| 31 |
+
try:
|
| 32 |
+
self.assertTrue(await asyncio.to_thread(started.wait, 1))
|
| 33 |
+
background = asyncio.create_task(executor.run(lambda: seen.append("background"), background=True))
|
| 34 |
+
await asyncio.sleep(0)
|
| 35 |
+
foreground = asyncio.create_task(executor.run(lambda: seen.append("foreground")))
|
| 36 |
+
await asyncio.sleep(.01)
|
| 37 |
+
finally:
|
| 38 |
+
release.set()
|
| 39 |
+
await asyncio.gather(active, foreground, background)
|
| 40 |
+
self.assertEqual(seen, ["foreground", "background"])
|
| 41 |
+
|
| 42 |
async def test_slow_search_does_not_block_http_ping_and_busy_requests_retry(self):
|
| 43 |
import app
|
| 44 |
import httpx
|