vomebook commited on
Commit ·
eeb144a
1
Parent(s): 3cfe96e
Organize backend and search implementations by feature layers
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- backend/app.py+26-26
- backend/cache_core.py+7-30
- backend/data_formats.py+17-110
- backend/download/application/__init__.pyAdded+1
- backend/download/application/warming.pyAdded+42
- backend/download/http/routes.py+1-1
- backend/download_warm.py+9-42
- backend/folder_contents.py+12-84
- backend/folder_tree.py+9-69
- backend/proxy_streams.py+11-287
- backend/reader/archive/domain/content.py+1-1
- backend/reader/archive/domain/validation.pyAdded+156
- backend/reader/catalog/application/indexes.py+2-2
- backend/reader/catalog/domain/__init__.pyAdded+1
- backend/reader/catalog/domain/assets.pyAdded+154
- backend/reader/catalog/domain/index.pyAdded+54
- backend/reader/catalog/infrastructure/__init__.pyAdded+1
- backend/reader/catalog/infrastructure/v3.pyAdded+161
- backend/reader/document/application/ranges.py+1-1
- backend/reader/document/domain/policy.py+1-1
- backend/reader/document/domain/range_cache.pyAdded+67
- backend/reader/document/http/transport.py+2-2
- backend/reader/query/application/ocr.py+1-1
- backend/reader/query/domain/ocr.pyAdded+165
- backend/reader_archive.py+12-156
- backend/reader_assets.py+11-152
- backend/reader_index.py+10-54
- backend/reader_ocr.py+13-165
- backend/reader_range_cache.py+12-67
- backend/reader_v3_catalog.py+18-161
- backend/record_metadata.py+23-185
- backend/runtime/application/lifecycle.py+2-2
- backend/search/application/bootstrap.pyAdded+31
- backend/search/corpus/application/preparation.py+2-2
- backend/search/corpus/domain/folder_contents.pyAdded+84
- backend/search/corpus/domain/folder_tree.pyAdded+69
- backend/search/corpus/domain/formats.pyAdded+110
- backend/search/corpus/domain/records.pyAdded+185
- backend/search/corpus/domain/words.pyAdded+65
- backend/search/corpus/infrastructure/__init__.pyAdded+1
- backend/search/corpus/infrastructure/indexes.pyAdded+205
- backend/search/corpus/infrastructure/selection.pyAdded+290
- backend/search/domain/browse.pyAdded+47
- backend/search/domain/candidates.pyAdded+72
- backend/search/domain/filters.pyAdded+134
- backend/search/domain/matching.pyAdded+179
- backend/search/domain/ordering.py+2-2
- backend/search/domain/term_candidates.pyAdded+129
- backend/search/http/body_limit.pyAdded+64
- backend/search/http/responses.py+1-1
30 unmodified lines313233343536377 unmodified lines45464748495051525354555657585960616211 unmodified lines74757677787980818283848586878889909192939411 unmodified lines10610710810911011111218 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541 unmodified line15615715815916016116230 unmodified linesfrom fastapi.middleware.gzip import GZipMiddlewarefrom starlette.types import Scopefrom contextlib import asynccontextmanagerfrom backend.cache_core import cached as _bounded_cachefrom backend.catalog.application.metadata import (CatalogMetadata, RepoSummary as RepoSummary, load_sidebar_payload as load_sidebar_payload,)7 unmodified linesDownloadDependencies, DownloadState, download as _download, download_check as _download_check,download_with_disconnect as _download_with_disconnect,)from backend.download_warm import (warm_download_connection as _warm_download_connection,schedule_download_connection_warm as _schedule_download_connection_warm)from backend.folder_tree import build_folder_tree as _build_folder_treefrom backend.folder_contents import get_folder_contents as _get_folder_contentsfrom backend.search_bootstrap import build_initial_payload as _build_initial_payload, trim_initial_results as _trim_initial_resultsfrom backend.search_candidates import literal_candidates as _literal_candidates, wildcard_literal_candidates as _wildcard_literal_candidatesfrom backend.search_browse import browse_order as _browse_orderfrom backend.search_term_candidates import term_candidates as _search_term_candidatesfrom backend.search_projection import public_record as _public_record, trim_results as _trim_resultsfrom backend.reader_identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE,canonical_reader_source_url as canonical_reader_source_url, reader_short_id as reader_short_id)from backend.reader_index import ReaderIndexBuild, advance_build, new_buildfrom backend.reader.catalog.application.indexes import (IndexDependencies, IndexPublication, IndexRuntime, IndexState, ReaderIndexes,)11 unmodified linesQueryStream, reader_resolve as _query_resolve, reader_content as _query_content,reader_ocr_search as _query_ocr_search,)from backend.reader_ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text,parse_reader_ocr_book as _parse_reader_ocr_book, search_reader_ocr_pages as search_reader_ocr_pages)from backend.search_filters import (apply_filters as _apply_filters,apply_mixed_folder_filters as _apply_mixed_folder_filters,mixed_folder_index_candidates as _mixed_folder_index_candidates, score_record as _score_record)from backend.search_words import (build_vocab_by_len as _build_vocab_by_len, build_word_index as _build_word_index,matches_file_query as _matches_file_query, matches_file_token as _matches_file_token,records_digest as _records_digest, tokenize as _tokenize)from backend.search_matching import (compile_exact_matcher as compile_exact_matcher,split_exact_terms as split_exact_terms, edit_distance as edit_distance,could_be_fuzzy as could_be_fuzzy, is_fuzzy_match as is_fuzzy_match)from backend.proxy_streams import (OwnedStreamingResponse as OwnedStreamingResponse, SharedRangeFlight as SharedRangeFlight, UpstreamLease,)from backend.reader_range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange,requested_range_bounds as _requested_range_bounds)from backend.reader.document.domain.policy import (RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry, RangeFlightKey as RangeFlightKey,11 unmodified linesfrom backend.runtime.application.lifecycle import (LifecycleDependencies, LifecycleState, lifespan as _application_lifespan,)from backend.search_execution import SearchBusy as SearchBusy, SearchExecutor, check_search_cancelledfrom backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnectfrom backend.search.application.cached import (CacheDependencies, search_cached as _search_cached, order_key as _order_key,18 unmodified linesfrom backend.search.corpus.domain.metadata import (MetadataMaps, populate_metadata, name_order, size_order, pack_postings,)from backend.search_transport import SearchBodyLimitMiddlewarefrom backend.search_indexes import (NGRAM_MAGIC as NGRAM_MAGIC, WORD_INDEX_MAGIC as WORD_INDEX_MAGIC,WORD_INDEX_TOKENIZER as WORD_INDEX_TOKENIZER, Posting, PostingIndex,decode_postings as decode_postings, decode_varint as decode_varint,load_ngram_index, load_word_index, resolve_postings,)from backend.reader_assets import (READER_ASSET_FILENAMES as READER_ASSET_FILENAMES, READER_BUCKET_PATH_RE, decode_reader_assets,)from backend.reader_v3_catalog import decode_in_thread, load_reading_catalog, merge_sidecar as merge_v3_sidecarfrom backend.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shellfrom backend.data_formats import (decode_browser_entry as decode_browser_entry, decode_folder_browser_data as decode_folder_browser_data,decode_folder_tree_data as decode_folder_tree_data, decode_search_payload as decode_search_payload,decode_tree_node as decode_tree_node,)from backend.record_metadata import (READER_ASSET_MODES as READER_ASSET_MODES,add_reader_assets, build_browser_file_name as build_browser_file_name, build_reader_asset_key,build_record_link, build_record_path_url, build_record_relative_path,1 unmodified linereader_asset_url as reader_asset_url, reader_extension_for_asset as reader_extension_for_asset,reader_resolved_record,)from backend.upstream_http import (ALLOWED_DOWNLOAD_HOSTS as ALLOWED_DOWNLOAD_HOSTS,ALLOWED_DOWNLOAD_HOST_SUFFIXES as ALLOWED_DOWNLOAD_HOST_SUFFIXES, MAX_REDIRECTS as MAX_REDIRECTS,READER_ASSET_PATH_RE as READER_ASSET_PATH_RE, VOICEOFML_READER_SOURCE_RE as VOICEOFML_READER_SOURCE_RE,30 unmodified lines313233343536377 unmodified lines45464748495051525354555657585960616211 unmodified lines74757677787980818283848586878889909192939411 unmodified lines10610710810911011111218 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541 unmodified line15615715815916016116230 unmodified linesfrom fastapi.middleware.gzip import GZipMiddlewarefrom starlette.types import Scopefrom contextlib import asynccontextmanagerfrom backend.shared.cache.core import cached as _bounded_cachefrom backend.catalog.application.metadata import (CatalogMetadata, RepoSummary as RepoSummary, load_sidebar_payload as load_sidebar_payload,)7 unmodified linesDownloadDependencies, DownloadState, download as _download, download_check as _download_check,download_with_disconnect as _download_with_disconnect,)from backend.download.application.warming import (warm_download_connection as _warm_download_connection,schedule_download_connection_warm as _schedule_download_connection_warm)from backend.search.corpus.domain.folder_tree import build_folder_tree as _build_folder_treefrom backend.search.corpus.domain.folder_contents import get_folder_contents as _get_folder_contentsfrom backend.search.application.bootstrap import build_initial_payload as _build_initial_payload, trim_initial_results as _trim_initial_resultsfrom backend.search.domain.candidates import literal_candidates as _literal_candidates, wildcard_literal_candidates as _wildcard_literal_candidatesfrom backend.search.domain.browse import browse_order as _browse_orderfrom backend.search.domain.term_candidates import term_candidates as _search_term_candidatesfrom backend.search.domain.projection import public_record as _public_record, trim_results as _trim_resultsfrom backend.reader.query.domain.identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE,canonical_reader_source_url as canonical_reader_source_url, reader_short_id as reader_short_id)from backend.reader.catalog.domain.index import ReaderIndexBuild, advance_build, new_buildfrom backend.reader.catalog.application.indexes import (IndexDependencies, IndexPublication, IndexRuntime, IndexState, ReaderIndexes,)11 unmodified linesQueryStream, reader_resolve as _query_resolve, reader_content as _query_content,reader_ocr_search as _query_ocr_search,)from backend.reader.query.domain.ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text,parse_reader_ocr_book as _parse_reader_ocr_book, search_reader_ocr_pages as search_reader_ocr_pages)from backend.search.domain.filters import (apply_filters as _apply_filters,apply_mixed_folder_filters as _apply_mixed_folder_filters,mixed_folder_index_candidates as _mixed_folder_index_candidates, score_record as _score_record)from backend.search.corpus.domain.words import (build_vocab_by_len as _build_vocab_by_len, build_word_index as _build_word_index,matches_file_query as _matches_file_query, matches_file_token as _matches_file_token,records_digest as _records_digest, tokenize as _tokenize)from backend.search.domain.matching import (compile_exact_matcher as compile_exact_matcher,split_exact_terms as split_exact_terms, edit_distance as edit_distance,could_be_fuzzy as could_be_fuzzy, is_fuzzy_match as is_fuzzy_match)from backend.shared.transport.streams import (OwnedStreamingResponse as OwnedStreamingResponse, SharedRangeFlight as SharedRangeFlight, UpstreamLease,)from backend.reader.document.domain.range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange,requested_range_bounds as _requested_range_bounds)from backend.reader.document.domain.policy import (RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry, RangeFlightKey as RangeFlightKey,11 unmodified linesfrom backend.runtime.application.lifecycle import (LifecycleDependencies, LifecycleState, lifespan as _application_lifespan,)from backend.search.infrastructure.executor import SearchBusy as SearchBusy, SearchExecutor, check_search_cancelledfrom backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnectfrom backend.search.application.cached import (CacheDependencies, search_cached as _search_cached, order_key as _order_key,18 unmodified linesfrom backend.search.corpus.domain.metadata import (MetadataMaps, populate_metadata, name_order, size_order, pack_postings,)from backend.search.http.body_limit import SearchBodyLimitMiddlewarefrom backend.search.corpus.infrastructure.indexes import (NGRAM_MAGIC as NGRAM_MAGIC, WORD_INDEX_MAGIC as WORD_INDEX_MAGIC,WORD_INDEX_TOKENIZER as WORD_INDEX_TOKENIZER, Posting, PostingIndex,decode_postings as decode_postings, decode_varint as decode_varint,load_ngram_index, load_word_index, resolve_postings,)from backend.reader.catalog.domain.assets import (READER_ASSET_FILENAMES as READER_ASSET_FILENAMES, READER_BUCKET_PATH_RE, decode_reader_assets,)from backend.reader.catalog.infrastructure.v3 import decode_in_thread, load_reading_catalog, merge_sidecar as merge_v3_sidecarfrom backend.site.application.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shellfrom backend.search.corpus.domain.formats import (decode_browser_entry as decode_browser_entry, decode_folder_browser_data as decode_folder_browser_data,decode_folder_tree_data as decode_folder_tree_data, decode_search_payload as decode_search_payload,decode_tree_node as decode_tree_node,)from backend.search.corpus.domain.records import (READER_ASSET_MODES as READER_ASSET_MODES,add_reader_assets, build_browser_file_name as build_browser_file_name, build_reader_asset_key,build_record_link, build_record_path_url, build_record_relative_path,1 unmodified linereader_asset_url as reader_asset_url, reader_extension_for_asset as reader_extension_for_asset,reader_resolved_record,)from backend.shared.transport.upstream import (ALLOWED_DOWNLOAD_HOSTS as ALLOWED_DOWNLOAD_HOSTS,ALLOWED_DOWNLOAD_HOST_SUFFIXES as ALLOWED_DOWNLOAD_HOST_SUFFIXES, MAX_REDIRECTS as MAX_REDIRECTS,READER_ASSET_PATH_RE as READER_ASSET_PATH_RE, VOICEOFML_READER_SOURCE_RE as VOICEOFML_READER_SOURCE_RE,
12345678910111213141516171819202122232425262728293031"""Bounded insertion-ordered response cache shared by API and search."""from collections.abc import Callable, Hashableimport jsonimport timedef cached(store: dict[Hashable, tuple[float, object] | tuple[float, object, int]], key: Hashable,builder: Callable[[], object], ttl: float, limit: int, *,max_entry_bytes: int, max_total_bytes: int) -> object:now = time.monotonic()cached = store.get(key)if cached and now - cached[0] < ttl:store[key] = store.pop(key)return cached[1]value = builder()store.pop(key, None)for old_key, entry in list(store.items()):if now - entry[0] >= ttl:del store[old_key]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"))if size > max_entry_bytes:return valuetotal = sum(entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8")) for entry in store.values())while store and (len(store) >= limit or total + size > max_total_bytes):oldest_key = next(iter(store))entry = store.pop(oldest_key)total -= entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8"))if size <= max_total_bytes:store[key] = (now, value, size)return value12345678"""Compatibility import for backend.shared.cache.core."""import sysfrom backend.shared.cache import core as _implementationfrom backend.shared.cache.core import (cached as cached,)sys.modules[__name__] = _implementation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""Decode the current compact corpus and directory formats without runtime state."""from typing import TypedDict, castclass CompactCorpus(TypedDict, total=False):rp: list[str]fd: list[list[str]]rc: list[object]class CompactTreeNode(TypedDict, total=False):n: strc: intdf: boolch: list["CompactTreeNode"]class CompactFolder(TypedDict, total=False):n: strc: intclass CompactFile(TypedDict, total=False):n: stre: strt: bools: int | strclass CompactBrowserEntry(TypedDict, total=False):d: list[CompactFolder]f: list[CompactFile]def decode_search_payload(data: object) -> list[dict[str, object]]:if not isinstance(data, dict):return []compact = cast(CompactCorpus, data)repos = compact.get("rp", []) or []folders = compact.get("fd", []) or []records: list[dict[str, object]] = []for raw_item in compact.get("rc", []) or []:if not isinstance(raw_item, list):continueitem = cast(list[object], raw_item)if len(item) < 6:continuerepo = repos[item[0]] if isinstance(item[0], int) and 0 <= item[0] < len(repos) else ""folder = folders[item[3]] if isinstance(item[3], int) and 0 <= item[3] < len(folders) else []records.append({"Repo": repo,"File": item[1],"Extension": item[2],"Folder": folder,"Size": item[4],"HasTxt": bool(item[5]),})return recordsdef decode_tree_node(node: CompactTreeNode, parent_path: str = "", is_root: bool = False) -> dict[str, object]:name = node.get("n", "")path = "" if is_root else (f"{parent_path}/{name}" if parent_path else name)children = [decode_tree_node(child, path, False) for child in node.get("ch", [])]decoded: dict[str, object] = {"name": name,"path": path,"count": node.get("c", 0),"hasDirectFiles": node.get("df", False),"hasChildren": len(children) > 0,"showSelfToggle": bool(path and node.get("df", False) and len(children) > 0),"children": children,}if is_root:decoded["isRoot"] = Truereturn decodeddef decode_folder_tree_data(data: dict[str, list[CompactTreeNode]] | None) -> dict[str, list[dict[str, object]]]:return {repo: [decode_tree_node(node, "", True) for node in nodes]for repo, nodes in (data or {}).items()}def decode_browser_entry(entry: CompactBrowserEntry, current_path: str = "") -> dict[str, object]:return {"folders": [{"name": item.get("n", ""),"path": f"{current_path}/{item.get('n', '')}" if current_path else item.get("n", ""),"count": item.get("c", 0),}for item in entry.get("d", [])],"files": [{"name": item.get("n", ""),"ext": item.get("e", ""),"hasTxt": item.get("t", False),"size": item.get("s", ""),}for item in entry.get("f", [])],"current_path": current_path,}def decode_folder_browser_data(data: dict[str, dict[str, CompactBrowserEntry]] | None) -> dict[str, dict[str, dict[str, object]]]:return {repo: {path: decode_browser_entry(entry, path) for path, entry in (browser or {}).items()}for repo, browser in (data or {}).items()}1234567891011121314151617"""Compatibility import for backend.search.corpus.domain.formats."""import sysfrom backend.search.corpus.domain import formats as _implementationfrom backend.search.corpus.domain.formats import (CompactBrowserEntry as CompactBrowserEntry,CompactCorpus as CompactCorpus,CompactFile as CompactFile,CompactFolder as CompactFolder,CompactTreeNode as CompactTreeNode,decode_browser_entry as decode_browser_entry,decode_folder_browser_data as decode_folder_browser_data,decode_folder_tree_data as decode_folder_tree_data,decode_search_payload as decode_search_payload,decode_tree_node as decode_tree_node,)sys.modules[__name__] = _implementation
1"""download application package."""123456789101112131415161718192021222324252627282930313233343536373839404142"""Bounded, owned speculative connection warmup for the download pool."""from __future__ import annotations
import asynciofrom collections.abc import Callable, Coroutinefrom typing import Anyfrom fastapi import FastAPIimport aiohttp
async def warm_download_connection(app: FastAPI): # Use the download pool, but never queue speculative work behind real transfers. semaphore = app.state.upstream_semaphore if semaphore.locked(): return try: async with semaphore: async with app.state.http_session.head( "https://huggingface.co/robots.txt", allow_redirects=False, timeout=aiohttp.ClientTimeout(total=4, connect=3, sock_read=3), ): pass except (aiohttp.ClientError, asyncio.TimeoutError): # A failed warmup must not affect ping or the later download attempt. pass
def schedule_download_connection_warm(app: FastAPI, *, now: Callable[[], float], interval: Callable[[], int], warm: Callable[[FastAPI], Coroutine[Any, Any, None]]) -> None: state = app.state if not getattr(state, "download_warm_enabled", False): return task = state.download_warm_task current_time = now() if task is not None and not task.done(): return if current_time - state.download_warm_at < interval(): return state.download_warm_at = current_time state.download_warm_task = asyncio.create_task(warm(app))9 unmodified lines101112131415169 unmodified linesfrom fastapi import Requestfrom fastapi.responses import JSONResponse, Responsefrom backend.proxy_streams import OwnedStreamingResponse, UpstreamLeaseclass DownloadState(Protocol):9 unmodified lines101112131415169 unmodified linesfrom fastapi import Requestfrom fastapi.responses import JSONResponse, Responsefrom backend.shared.transport.streams import OwnedStreamingResponse, UpstreamLeaseclass DownloadState(Protocol):
123456789101112131415161718192021222324252627282930313233343536373839404142"""Bounded, owned speculative connection warmup for the download pool."""from __future__ import annotationsimport asynciofrom collections.abc import Callable, Coroutinefrom typing import Anyfrom fastapi import FastAPIimport aiohttpasync def warm_download_connection(app: FastAPI):# Use the download pool, but never queue speculative work behind real transfers.semaphore = app.state.upstream_semaphoreif semaphore.locked():returntry:async with semaphore:async with app.state.http_session.head("https://huggingface.co/robots.txt",allow_redirects=False,timeout=aiohttp.ClientTimeout(total=4, connect=3, sock_read=3),):passexcept (aiohttp.ClientError, asyncio.TimeoutError):# A failed warmup must not affect ping or the later download attempt.passdef schedule_download_connection_warm(app: FastAPI, *, now: Callable[[], float],interval: Callable[[], int],warm: Callable[[FastAPI], Coroutine[Any, Any, None]]) -> None:state = app.stateif not getattr(state, "download_warm_enabled", False):returntask = state.download_warm_taskcurrent_time = now()if task is not None and not task.done():returnif current_time - state.download_warm_at < interval():returnstate.download_warm_at = current_timestate.download_warm_task = asyncio.create_task(warm(app))123456789"""Compatibility import for backend.download.application.warming."""import sysfrom backend.download.application import warming as _implementationfrom backend.download.application.warming import (schedule_download_connection_warm as schedule_download_connection_warm,warm_download_connection as warm_download_connection,)sys.modules[__name__] = _implementation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Directory browser lookup against a caller-owned search index snapshot."""from __future__ import annotationsfrom collections.abc import Callable, Mapping, Sequencefrom typing import castSearchRecord = dict[str, object]BrowserEntries = Mapping[str, Mapping[str, SearchRecord]]FolderIndex = Mapping[str, Mapping[str, Sequence[int]]]RepoIndices = Mapping[str, Sequence[int]]def get_folder_contents(repo: str, path: str, *,get_browser: Callable[[], BrowserEntries],get_folder_index: Callable[[], FolderIndex],get_repo_indices: Callable[[], RepoIndices],get_records: Callable[[], Sequence[SearchRecord]],enrich_browser_entry: Callable[[str, str, SearchRecord], SearchRecord],build_record_link: Callable[[SearchRecord], str],build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord:"""Prefer precomputed entries, otherwise count and project the indexed subtree."""if repo in get_browser():repo_browser = get_browser().get(repo, {}) or {}if path in repo_browser:return enrich_browser_entry(repo, path, repo_browser[path])if path == "" and "" in repo_browser:return enrich_browser_entry(repo, path, repo_browser[""])return _from_index(repo, path, get_folder_index, get_repo_indices, get_records,build_record_link, build_record_path_url)def _from_index(repo: str, path: str, get_folder_index: Callable[[], FolderIndex],get_repo_indices: Callable[[], RepoIndices], get_records: Callable[[], Sequence[SearchRecord]],build_record_link: Callable[[SearchRecord], str],build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord:path_parts = [p for p in path.strip("/").split("/") if p]path_depth = len(path_parts)repo_folders = get_folder_index().get(repo)candidate_indices = (repo_folders.get("/".join(path_parts), [])if repo_folders is not None else get_repo_indices().get(repo, []))def is_under(rec_folders: list[str], prefix: list[str]) -> bool:return rec_folders[:len(prefix)] == prefixmatching = [get_records()[i] for i in candidate_indicesif is_under(cast(list[str], get_records()[i].get("Folder", []) or []), path_parts)]result_folders = _subfolder_results(matching, path_parts, path_depth)direct_files = _direct_file_results(matching, path_depth, build_record_link, build_record_path_url)return {"folders": result_folders, "files": direct_files, "current_path": path}def _subfolder_results(matching: Sequence[SearchRecord], path_parts: list[str],path_depth: int) -> list[SearchRecord]:subfolder_names: set[str] = set()subfolder_counts: dict[str, int] = {}for rec in matching:folders = cast(list[str], rec.get("Folder", []) or [])if len(folders) > path_depth:name = folders[path_depth]subfolder_names.add(name)subfolder_counts[name] = subfolder_counts.get(name, 0) + 1result_folders: list[SearchRecord] = []for fname in sorted(subfolder_names):full_path = "/".join(path_parts + [fname]) if path_parts else fnameresult_folders.append({"name": fname, "path": full_path, "count": subfolder_counts.get(fname, 0)})return result_foldersdef _direct_file_results(matching: Sequence[SearchRecord], path_depth: int,build_record_link: Callable[[SearchRecord], str],build_record_path_url: Callable[[SearchRecord], str]) -> list[SearchRecord]:direct_files: list[SearchRecord] = []for rec in matching:folders = cast(list[str], rec.get("Folder", []) or [])if len(folders) == path_depth:direct_files.append({"name": rec.get("File", ""),"ext": rec.get("Extension", ""),"link": rec.get("Link") or build_record_link(rec),"path": rec.get("Path") or build_record_path_url(rec),"hasTxt": rec.get("HasTxt", False),"size": rec.get("Size", ""),})direct_files.sort(key=lambda f: cast(str, f["name"]))return direct_files123456789101112"""Compatibility import for backend.search.corpus.domain.folder_contents."""import sysfrom backend.search.corpus.domain import folder_contents as _implementationfrom backend.search.corpus.domain.folder_contents import (BrowserEntries as BrowserEntries,FolderIndex as FolderIndex,RepoIndices as RepoIndices,SearchRecord as SearchRecord,get_folder_contents as get_folder_contents,)sys.modules[__name__] = _implementation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""Build search filter trees from a caller-owned index snapshot."""from __future__ import annotationsfrom collections.abc import Mapping, Sequencefrom typing import NotRequired, TypedDict, castclass FolderTreeNode(TypedDict):name: strpath: strchildren: list[FolderTreeNode]count: inthasDirectFiles: boolhasChildren: boolshowSelfToggle: boolisRoot: NotRequired[bool]def build_folder_tree(repo: str, folder_index: Mapping[str, Mapping[str, Sequence[int]]],repo_records_map: Mapping[str, Sequence[int]],records: Sequence[dict[str, object]]) -> list[FolderTreeNode]:"""Preserve corpus counts, stable child order and direct-file toggles."""if repo not in folder_index:return []repo_name_short = repo.split("/")[-1]tree_root: FolderTreeNode = {"name": repo_name_short,"path": "","children": [],"count": 0,"hasDirectFiles": False,"hasChildren": False,"showSelfToggle": False,"isRoot": True,}node_map: dict[str, FolderTreeNode] = {"": tree_root}for path, idx_list in folder_index[repo].items():if path == "":tree_root["count"] = len(idx_list)continueparts = path.split("/")for depth in range(1, len(parts) + 1):key = "/".join(parts[:depth])if key not in node_map:parent_key = "/".join(parts[:depth - 1]) if depth > 1 else ""parent = node_map[parent_key]node: FolderTreeNode = {"name": parts[depth - 1],"path": key,"children": [],"count": 0,"hasDirectFiles": False,"hasChildren": False,"showSelfToggle": False,}node_map[key] = nodeparent["children"].append(node)node_map[path]["count"] = len(idx_list)direct_file_dirs: set[str] = set()for idx in repo_records_map.get(repo, []):rec = records[idx]folders = cast(list[str], rec.get("Folder", []) or [])direct_file_dirs.add("/".join(folders))for path_key, node in node_map.items():node["hasDirectFiles"] = path_key in direct_file_dirsnode["children"].sort(key=lambda child: child["name"])node["hasChildren"] = len(node["children"]) > 0node["showSelfToggle"] = bool(path_key and node["hasDirectFiles"] and node["hasChildren"])return [tree_root]123456789"""Compatibility import for backend.search.corpus.domain.folder_tree."""import sysfrom backend.search.corpus.domain import folder_tree as _implementationfrom backend.search.corpus.domain.folder_tree import (FolderTreeNode as FolderTreeNode,build_folder_tree as build_folder_tree,)sys.modules[__name__] = _implementation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287"""Own upstream responses across the route-to-ASGI streaming handoff."""import asyncioimport inspectfrom collections.abc import AsyncIterator, Awaitable, Callable, Mappingfrom types import TracebackTypeimport aiohttpfrom fastapi.responses import StreamingResponsefrom starlette.background import BackgroundTaskfrom starlette.responses import ContentStream, Responsefrom starlette.types import Receive, Scope, Sendclass OwnedStreamingResponse(StreamingResponse):def __init__(self, content: ContentStream, *, cleanup: Callable[[], Awaitable[None] | None],status_code: int = 200, headers: Mapping[str, str] | None = None,media_type: str | None = None, background: BackgroundTask | None = None) -> None:super().__init__(content, status_code=status_code, headers=headers, media_type=media_type, background=background)self.cleanup = cleanupasync def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:try:await super().__call__(scope, receive, send)finally:# A disconnect may happen before the generator's first iteration.try:result = self.cleanup()if inspect.isawaitable(result):await resultfinally:close = getattr(self.body_iterator, "aclose", None)if close is not None:await close()class UpstreamLease:"""Own an upstream response and an optional, already-acquired pool slot."""def __init__(self, semaphore: asyncio.Semaphore | None = None) -> None:self.response: aiohttp.ClientResponse | None = Noneself.semaphore = semaphoreself.closed = Falseself.transferred = Falsedef close(self) -> None:if self.closed:returntry:if self.response is not None:self.response.release()self.response = Noneself.closed = Truefinally:if self.semaphore is not None:self.semaphore.release()self.semaphore = Nonedef __enter__(self) -> "UpstreamLease":return selfdef __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None,traceback: TracebackType | None) -> None:if not self.transferred:self.close()async def chunks(self, error_label: str) -> AsyncIterator[bytes]:try:response = self.responseif response is None:raise RuntimeError("upstream response unavailable")async for chunk in response.content.iter_chunked(65536):yield chunkexcept Exception as exc:print(f"{error_label}: {exc}")raisefinally:self.close()def streaming_response(self, content: ContentStream, *, status_code: int = 200,headers: Mapping[str, str] | None = None, media_type: str | None = None,background: BackgroundTask | None = None) -> OwnedStreamingResponse:response = OwnedStreamingResponse(content, cleanup=self.close, status_code=status_code,headers=headers, media_type=media_type, background=background)self.transferred = Truereturn responseclass SharedRangeFlight:"""Stream one bounded response to independently owned subscribers."""def __init__(self, create: Callable[[], Awaitable[Response]], limit: int,finished: Callable[["SharedRangeFlight"], None]) -> None:self.create = createself.limit = limitself.finished = finishedself.ready: asyncio.Future[bool] = asyncio.get_running_loop().create_future()self.ready.add_done_callback(lambda future: None if future.cancelled() else future.exception())self.changed = asyncio.Event()self.started = asyncio.Event()self.task: asyncio.Task[None] | None = Noneself.response: Response | None = Noneself.headers: dict[str, str] = {}self.chunks: list[bytes | memoryview] = []self.size = 0self.subscribers = 0self.shared = Falseself.done = Falseself.error: BaseException | None = Noneself.close_error: BaseException | None = Noneself._response_cleaned = Falseself._iterator_closed = Falsedef subscribe(self) -> "RangeSubscription":self.subscribers += 1if self.task is None:self.task = asyncio.create_task(self._run())self.task.add_done_callback(self._settled)return RangeSubscription(self)def _settled(self, task: asyncio.Task[None]) -> None:error = asyncio.CancelledError() if task.cancelled() else task.exception()if error is not None and self.error is None:self.error = errorif not self.done:self.done = Trueif not self.ready.done():self.ready.set_exception(self.error or RuntimeError("range flight stopped"))self.changed.set()if not self.subscribers:self.finished(self)async def _release_response(self) -> None:response = self.responseif response is None:returnerrors: list[BaseException] = []cleanup = getattr(response, "cleanup", None)try:if not self._response_cleaned:if cleanup:result = cleanup()if inspect.isawaitable(result):await resultself._response_cleaned = Trueexcept BaseException as exc:errors.append(exc)iterator = getattr(response, "body_iterator", None)try:if not self._iterator_closed:if iterator is not None:await iterator.aclose()self._iterator_closed = Trueexcept BaseException as exc:errors.append(exc)self.close_error = (errors[0] if len(errors) == 1 elseBaseExceptionGroup("Reader range response close failures", errors) if errors else None)if self.close_error is not None:raise self.close_errorself.response = Noneasync def _run(self) -> None:try:self.response = await self.create()try:length = int(self.response.headers.get("content-length", ""))except (TypeError, ValueError):length = -1if self.response.status_code != 206 or not 0 <= length <= self.limit:self.ready.set_result(False)returnself.shared = Trueself.headers = dict(self.response.headers)self.ready.set_result(True)# A transport may suppress cancellation and still return headers.# If all waiters left, no one can start this producer; release it.if not self.subscribers:returnawait self.started.wait()iterator = getattr(self.response, "body_iterator", None)if iterator is None:body = self.response.bodyif len(body) > length:raise ValueError("shared range body exceeds declared length")self.chunks.append(body)self.size = len(body)self.changed.set()else:async for chunk in iterator:if self.size + len(chunk) > length:raise ValueError("shared range body exceeds declared length")self.chunks.append(chunk)self.size += len(chunk)self.changed.set()if self.size < length:raise ValueError("shared range body shorter than declared length")except BaseException as error:self.error = errorif not self.ready.done():self.ready.set_exception(error)finally:try:if self.shared or self.error or not self.subscribers:await self._release_response()finally:self.done = Trueself.changed.set()if not self.subscribers:self.finished(self)def take_response(self) -> Response | None:response, self.response = self.response, Nonereturn responsedef unsubscribe(self) -> None:self.subscribers -= 1if self.subscribers:returnif not self.done:if self.task is not None:self.task.cancel()self.finished(self)elif self.response is not None:# An unclaimed declined response still owns its upstream lease.self.task = asyncio.create_task(self._close_declined())self.task.add_done_callback(self._settled)else:self.finished(self)async def _close_declined(self) -> None:try:await self._release_response()finally:self.finished(self)async def close(self) -> None:previous_error = self.close_errorif self.task and not self.task.done():self.task.cancel()if self.task:await asyncio.gather(self.task, return_exceptions=True)if self.close_error is not None and self.close_error is not previous_error:raise self.close_errorawait self._release_response()self.finished(self)class RangeSubscription:def __init__(self, flight: SharedRangeFlight) -> None:self.flight: SharedRangeFlight | None = flightself.closed = Falsedef close(self) -> None:if not self.closed:self.closed = Trueif self.flight is not None:self.flight.unsubscribe()async def release(self) -> None:flight = self.flightif flight is None:returnself.close()if not flight.subscribers and flight.task:await asyncio.gather(flight.task, return_exceptions=True)self.flight = Noneasync def stream(self) -> AsyncIterator[bytes | memoryview]:cursor = 0flight = self.flightif flight is None:returnflight.started.set()try:while not self.closed:while cursor < len(flight.chunks):chunk = flight.chunks[cursor]cursor += 1yield chunkif flight.done:if flight.error:raise flight.errorreturnflight.changed.clear()if cursor < len(flight.chunks) or flight.done:continueawait flight.changed.wait()finally:await self.release()1234567891011"""Compatibility import for backend.shared.transport.streams."""import sysfrom backend.shared.transport import streams as _implementationfrom backend.shared.transport.streams import (OwnedStreamingResponse as OwnedStreamingResponse,RangeSubscription as RangeSubscription,SharedRangeFlight as SharedRangeFlight,UpstreamLease as UpstreamLease,)sys.modules[__name__] = _implementation
5 unmodified lines67891011125 unmodified linesimport zipfileimport zlibfrom backend.reader_archive import (ReaderArchiveInvalidError as ReaderArchiveInvalidError,ReaderArchiveLimitError as ReaderArchiveLimitError,ReaderArchiveLimits as ReaderArchiveLimits,5 unmodified lines67891011125 unmodified linesimport zipfileimport zlibfrom backend.reader.archive.domain.validation import (ReaderArchiveInvalidError as ReaderArchiveInvalidError,ReaderArchiveLimitError as ReaderArchiveLimitError,ReaderArchiveLimits as ReaderArchiveLimits,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Bounded ZIP validation for reader archives with caller-owned limits."""from __future__ import annotations
import ioimport reimport zipfilefrom typing import Protocol, cast
class ReaderArchiveLimits(Protocol): """Limits are read on every use so callers may replace them at any time."""
@property def READER_RESOURCE_MAX_ARCHIVE_BYTES(self) -> int: ... @property def READER_ARCHIVE_MAX_ENTRIES(self) -> int: ... @property def READER_ARCHIVE_MAX_EXPANDED_BYTES(self) -> int: ... @property def READER_ARCHIVE_MAX_COMPRESSION_RATIO(self) -> int: ... @property def READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES(self) -> int: ... @property def READER_ARCHIVE_MAX_METADATA_BYTES(self) -> int: ... @property def READER_ARCHIVE_MEMBER_RE(self) -> re.Pattern[str]: ...
class ReaderArchiveLimitError(ValueError): pass
class ReaderArchiveInvalidError(ValueError): pass
class ReaderDocumentLimitError(ValueError): pass
def _plain_int(value: object) -> bool: return isinstance(value, int) and not isinstance(value, bool)
def _is_bytes(value: object) -> bool: return isinstance(value, bytes)
def _is_str(value: object) -> bool: return isinstance(value, str)
def validate_reader_archive(archive: bytes, limits: ReaderArchiveLimits) -> None: if len(archive) > limits.READER_RESOURCE_MAX_ARCHIVE_BYTES: raise ReaderArchiveLimitError("阅读文件过大") try: # Use the stdlib's EOCD/ZIP64 parser before ZipFile allocates its directory. # These bounded EOCD fields are stdlib internals missing from typeshed. zip_internal = cast(object, zipfile) end_record = getattr(zip_internal, "_EndRecData")(io.BytesIO(archive)) if not end_record: raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") central_directory_size = end_record[getattr(zip_internal, "_ECD_SIZE")] directory_offset = end_record[getattr(zip_internal, "_ECD_OFFSET")] entry_count = end_record[getattr(zip_internal, "_ECD_ENTRIES_TOTAL")] if (end_record[getattr(zip_internal, "_ECD_DISK_NUMBER")] != 0 or end_record[getattr(zip_internal, "_ECD_DISK_START")] != 0 or end_record[getattr(zip_internal, "_ECD_ENTRIES_THIS_DISK")] != entry_count or len(end_record[getattr(zip_internal, "_ECD_COMMENT")]) != end_record[getattr(zip_internal, "_ECD_COMMENT_SIZE")] or (end_record[getattr(zip_internal, "_ECD_SIGNATURE")] != getattr(zip_internal, "stringEndArchive64") and (central_directory_size == 0xffffffff or directory_offset == 0xffffffff))): raise ReaderArchiveInvalidError("阅读文件元数据无效") if central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES: raise ReaderArchiveLimitError("阅读文件元数据过大") if entry_count > limits.READER_ARCHIVE_MAX_ENTRIES: raise ReaderArchiveLimitError("阅读文件条目过多") if directory_offset + central_directory_size > len(archive): raise ReaderArchiveInvalidError("阅读文件元数据无效") with zipfile.ZipFile(io.BytesIO(archive)) as book_zip: infos = book_zip.infolist() if len(infos) > limits.READER_ARCHIVE_MAX_ENTRIES: raise ReaderArchiveLimitError("阅读文件条目过多")
if len(infos) != entry_count: raise ReaderArchiveInvalidError("阅读文件条目数无效") central_directory_offset = book_zip.start_dir archive_comment = book_zip.comment if ( not _plain_int(central_directory_size) or central_directory_size < 0 or central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES or not _plain_int(central_directory_offset) or central_directory_offset < 0 or central_directory_offset > len(archive) or central_directory_size > len(archive) - central_directory_offset or not _is_bytes(archive_comment) ): raise ReaderArchiveInvalidError("阅读文件元数据无效")
expanded = 0 compressed = 0 metadata_bytes = len(archive_comment) for info in infos: filename = info.orig_filename extra = info.extra comment = info.comment if not _is_str(filename) or not _is_bytes(extra) or not _is_bytes(comment): raise ReaderArchiveInvalidError("阅读文件元数据无效") name = filename.replace("\\", "/") name_parts = name.split("/") if (not name or name.startswith("/") or "\x00" in name or any(part in {".", ".."} for part in name_parts) or any(not part for part in name_parts[:-1]) or not limits.READER_ARCHIVE_MEMBER_RE.fullmatch(name)): raise ReaderArchiveInvalidError("阅读文件包含不安全路径") try: filename_bytes = len(filename.encode("utf-8", "surrogatepass")) except (UnicodeError, AttributeError) as exc: raise ReaderArchiveInvalidError("阅读文件元数据无效") from exc metadata_bytes += 46 + filename_bytes + len(extra) + len(comment) if metadata_bytes > limits.READER_ARCHIVE_MAX_METADATA_BYTES: raise ReaderArchiveLimitError("阅读文件元数据过大")
file_size = info.file_size compressed_size = info.compress_size header_offset = info.header_offset if ( not _plain_int(file_size) or file_size < 0 or not _plain_int(compressed_size) or compressed_size < 0 or compressed_size > len(archive) or not _plain_int(header_offset) or header_offset < 0 or header_offset >= len(archive) or header_offset >= central_directory_offset ): raise ReaderArchiveInvalidError("阅读文件条目无效") expanded += file_size compressed += compressed_size if expanded > limits.READER_ARCHIVE_MAX_EXPANDED_BYTES: raise ReaderArchiveLimitError("阅读文件展开后过大") if file_size and (compressed_size == 0 or file_size > compressed_size * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO): raise ReaderArchiveLimitError("阅读文件压缩比过高")
if compressed == 0: if expanded: raise ReaderArchiveLimitError("阅读文件压缩比过高") elif expanded > compressed * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO: raise ReaderArchiveLimitError("阅读文件压缩比过高") if compressed > len(archive): raise ReaderArchiveInvalidError("阅读文件条目无效") except (ReaderArchiveLimitError, ReaderArchiveInvalidError): raise except Exception as exc: raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") from exc6 unmodified lines78910111213146 unmodified linesfrom dataclasses import dataclassfrom typing import Protocolfrom backend.reader_index import ReaderIndexBuildfrom backend.search_execution import SearchBusy, SearchExecutorRecord = dict[str, object]6 unmodified lines78910111213146 unmodified linesfrom dataclasses import dataclassfrom typing import Protocolfrom backend.reader.catalog.domain.index import ReaderIndexBuildfrom backend.search.infrastructure.executor import SearchBusy, SearchExecutorRecord = dict[str, object]
1"""reader catalog domain package."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Pure validation and decoding for the Reader-Assets sidecar."""
import gzipimport ioimport jsonimport posixpathimport refrom typing import cast
from backend.shared.transport.upstream import READER_ASSET_PATH_RE as READER_ASSET_PATH_RE # re-exported for app/tests
READER_ASSET_FILENAMES = { "p": {"document.pdf", "linearized.pdf", "page-manifest.json"}, "e": {"document.epub", "book.epub", "document.mobi", "document.azw", "document.azw3", "document.fb2", "chapter-manifest.json"}, "d": {"document.docx"}, "h": {"document.html"}, "t": {"document.txt", "document.vcf", "document.ini"}, "k": {"document.md"}, "i": {"document.webp", "document.jpg", "document.jpeg", "document.png", "document.gif", "document.bmp", "page-manifest.json"}, "a": {"audio.mp3", "audio.wav", "audio.m4a", "audio.flac", "audio.mpga"}, "v": {"video.mp4", "video.mov"}, "f": {"document.swf"},}READER_BUCKET_PATH_RE = re.compile( r"^(?:documents/(?:text|web|spreadsheet|office|pdf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:document\.(?:txt|md|html|docx|pdf|vcf|ini))|" r"chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\.json|epub-search-index\.json\.gz|chapters/chapter-[0-9]{4}\.xhtml|resources/(?!\.{1,2}(?:/|$))[^/]+(?:/(?!\.{1,2}(?:/|$))[^/]+)*)|" r"media/(?:audio|video|swf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:audio\.[a-z0-9]+|video\.[a-z0-9]+|document\.swf)|" r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp|gif)/[0-9a-f]{64}/(?:document\.webp|page-manifest\.json|pages/page-[0-9]{6}\.webp)|" r"native/ebook/chm/[0-9a-f]{64}/document\.epub|" r"derived/[a-zA-Z0-9._-]+/[a-z0-9]{32}/(?:document\.pdf|page-manifest\.json|pages/page-[0-9]{6}\.webp|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))|" r"objects/(?P<djvu_prefix>[0-9a-f]{2})/(?P=djvu_prefix)[0-9a-f]{62}/[0-9a-f]{16}/document\.djvu|" r"objects/[0-9a-f]{2}/[0-9a-f]{64}/[0-9a-f]{16}/(?:reading-manifest\.json|page-map\.json\.gz|text-layer-manifest\.json|text-review-manifest\.json|text/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz|search-[0-9]{6}-[0-9]{6}\.json\.gz|partition-[0-9]{6}-[0-9]{6}-manifest\.json)|preview/(?:page-[0-9]{6}\.(?:png|webp|jpeg|svg|jxl)|partition-[0-9]{6}-[0-9]{6}-manifest\.json))|" r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl|png)|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)|document\.pdf))$")READER_EBOOK_BUCKET = "vomebook/reader-assets-v2"READER_ALLOWED_BUCKETS = {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}
def decode_reader_assets( raw: bytes, max_compressed_bytes: int = 5 * 1024 * 1024, max_decompressed_bytes: int = 50 * 1024 * 1024,) -> dict[str, object]: if len(raw) > max_compressed_bytes: raise ValueError("reader assets sidecar is too large") with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream: decoded = stream.read(max_decompressed_bytes + 1) if len(decoded) > max_decompressed_bytes: raise ValueError("reader assets sidecar expands beyond limit") payload: object = json.loads(decoded) payload_map = cast(dict[str, object], payload) if isinstance(payload, dict) else None files = payload_map.get("f") if payload_map is not None and payload_map.get("v") == 1 else None if not isinstance(files, dict): raise ValueError("invalid reader assets sidecar") file_map = cast(dict[object, object], files) clean: dict[str, dict[str, object]] = {} for key, raw_entry in file_map.items(): if not isinstance(key, str) or not isinstance(raw_entry, dict): continue entry = cast(dict[str, object], raw_entry) if entry.get("s") not in (2, 3, 4): continue if entry.get("s") == 2: path = entry.get("p") mode = entry.get("m") if not isinstance(path, str) or not isinstance(mode, str) or mode not in READER_ASSET_FILENAMES: continue if entry.get("b") not in READER_ALLOWED_BUCKETS: continue path_pattern = READER_BUCKET_PATH_RE image_page_path = bool(re.fullmatch(r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp)/[0-9a-f]{64}/pages/page-[0-9]{6}\.webp", path)) valid_filename = (posixpath.basename(path) in READER_ASSET_FILENAMES[mode] or (mode == "i" and image_page_path) or (mode == "p" and entry.get("b") == "vomebook/pdf-pages-v2" and path.endswith("/reading-manifest.json"))) if ( not path_pattern.fullmatch(path) or not valid_filename ): continue chapter_manifest = entry.get("c") fallback = entry.get("f") ocr_manifest = entry.get("o") chapter_bucket = entry.get("cb") bucket = entry.get("b") document_path, document_bucket = entry.get("pd"), entry.get("pdb") if (document_path is not None or document_bucket is not None) and ( mode != "p" or not path.endswith("/page-manifest.json") or not isinstance(document_bucket, str) or document_bucket not in READER_ALLOWED_BUCKETS or not isinstance(document_path, str) or not READER_BUCKET_PATH_RE.fullmatch(document_path) or not document_path.endswith("/document.pdf") ): continue if chapter_manifest is not None and ( mode not in {"e", "p"} or not isinstance(chapter_manifest, str) or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest) or not chapter_manifest.endswith("/chapter-manifest.json") ): continue if chapter_manifest is not None and chapter_bucket is None: continue if chapter_bucket is not None and ( chapter_bucket != READER_EBOOK_BUCKET or not isinstance(chapter_manifest, str) or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest) or not (chapter_manifest.startswith("ebook-chapters/") or (chapter_bucket == "vomebook/reader-assets-v2" and chapter_manifest.startswith("chapters/ebook/"))) ): continue fallback_is_chm = (bucket == READER_EBOOK_BUCKET and isinstance(fallback, str) and READER_BUCKET_PATH_RE.fullmatch(fallback) and fallback.endswith("/document.epub")) if fallback is not None and not fallback_is_chm: continue if ocr_manifest is not None and ( not isinstance(ocr_manifest, str) or not READER_BUCKET_PATH_RE.fullmatch(ocr_manifest) or not ocr_manifest.endswith("/ocr-manifest.json") ): continue if entry.get("b") is not None and entry.get("b") not in READER_ALLOWED_BUCKETS: continue if entry.get("ob") is not None and entry.get("ob") != "vomebook/pdf-pages-v2": continue if bucket == "vomebook/pdf-pages-v2": if mode == "p" and (not path.endswith(("/page-manifest.json", "/reading-manifest.json", "/document.pdf")) or not READER_BUCKET_PATH_RE.fullmatch(path)): continue clean[key] = { "s": 2, "m": mode, "p": path, **({"b": bucket} if bucket else {}), **({"pd": document_path, "pdb": document_bucket} if document_path else {}), **({"c": chapter_manifest} if chapter_manifest else {}), **({"cb": chapter_bucket} if chapter_bucket else {}), **({"f": fallback} if fallback else {}), **({"o": ocr_manifest} if ocr_manifest else {}), **({"ob": "vomebook/pdf-pages-v2"} if entry.get("ob") else {}), **({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {}), } else: ocr_manifest = entry.get("o") if (isinstance(ocr_manifest, str) and READER_BUCKET_PATH_RE.fullmatch(ocr_manifest) and ocr_manifest.endswith("/ocr-manifest.json")): clean[key] = {"s": 3, "m": "p", "o": ocr_manifest, "b": "vomebook/pdf-pages-v2", **({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {})} else: clean[key] = {"s": 4} return {"v": 1, "f": clean}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Incremental Reader index construction without publishing partial results."""
from collections.abc import Callablefrom typing import TypedDict, cast
class ReaderIndexBuild(TypedDict): generation: int records: list[dict[str, object]] next: int indices: list[int] repos: dict[str, list[int]] keys: dict[str, int] ids: dict[str, list[int]] legacy_ids: dict[str, list[int]]
def new_build(generation: int, records: list[dict[str, object]]) -> ReaderIndexBuild: return {"generation": generation, "records": records, "next": 0, "indices": [], "repos": {}, "keys": {}, "ids": {}, "legacy_ids": {}}
def advance_build(build: ReaderIndexBuild, limit: int, deadline: float, *, now: Callable[[], float], source_id: Callable[[str], str], asset_key: Callable[[dict[str, object]], str], record_link: Callable[[dict[str, object]], str], dataset_url: Callable[[str, str], str], reader_extensions: frozenset[str]) -> bool: """Advance at most one batch; callers own generation checks and publication.""" end = min(len(build["records"]), build["next"] + limit) while build["next"] < end: idx = build["next"] rec = build["records"][idx] repo = rec.get("Repo", "") build["keys"][asset_key(rec)] = idx current_url = cast(str, rec.get("Link") or record_link(rec)) build["ids"].setdefault(source_id(current_url), []).append(idx) # Old links omitted a repeated filename extension; index the historical # alias without changing the canonical identity or resolving collisions. name, ext, folders = rec.get("File", ""), rec.get("Extension", ""), rec.get("Folder", []) if (isinstance(repo, str) and repo.startswith("VoiceOfML/") and isinstance(name, str) and isinstance(ext, str) and ext and name.lower().endswith("." + ext.lower()) and isinstance(folders, list) and all(isinstance(part, str) for part in cast(list[object], folders))): legacy_path = "/".join([*cast(list[str], folders), name]) legacy_url = dataset_url(repo, legacy_path) if legacy_url != (rec.get("Link") or record_link(rec)): build["legacy_ids"].setdefault(source_id(legacy_url), []).append(idx) if rec.get("_ext_lower", "") in reader_extensions: build["indices"].append(idx) build["repos"].setdefault(cast(str, repo), []).append(idx) build["next"] += 1 if now() >= deadline: break return build["next"] >= len(build["records"])1"""reader catalog infrastructure package."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""Pinned v3 catalog projection, using only canonical bucket metadata URLs."""import asyncioimport hashlibimport jsonimport refrom typing import Callable, Literal, ParamSpec, TypeVar, cast, overload
import aiohttp
from backend.shared.transport.upstream import open_download_response, validate_fixed_source_redirect_url
BUCKET = "vomebook/reader-assets-v2"BASE = f"https://huggingface.co/buckets/{BUCKET}/resolve/"POINTER = "reader-index/v3/current.json"MAX_BYTES = 8 * 1024 * 1024
def sha(value: object) -> re.Match[str] | bool | None: return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value)
def catalog_path(generation: object) -> str: if not sha(generation): raise ValueError("invalid v3 catalog generation") return f"reader-index/v3/generations/{generation}/catalog.json"
def decode_catalog(pointer: dict[str, object], raw: bytes) -> dict[str, object]: from backend.reader.catalog.domain.assets import READER_BUCKET_PATH_RE if pointer.get("version") != 1 or pointer.get("kind") != "reader-reading-pointer": raise ValueError("invalid v3 pointer") generation = pointer.get("generation") ref = cast(dict[str, object], pointer.get("catalog", {})) if (ref.get("bucket") != BUCKET or ref.get("path") != catalog_path(generation) or ref.get("role") != "runtime" or type(ref.get("bytes")) is not int or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES or not sha(ref.get("sha256")) or len(raw) != ref["bytes"] or hashlib.sha256(raw).hexdigest() != ref["sha256"]): raise ValueError("v3 catalog resource mismatch") catalog = cast(dict[str, object], json.loads(raw)) body = {k: v for k, v in catalog.items() if k != "generation"} digest = hashlib.sha256(json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest() if (catalog.get("version") != 3 or catalog.get("kind") != "reader-reading-catalog" or catalog.get("generation") != generation or digest != generation or not isinstance(catalog.get("files"), dict)): raise ValueError("invalid v3 catalog identity") overrides: dict[str, dict[str, object]] = {} for key, raw_entry in cast(dict[object, object], catalog["files"]).items(): if not isinstance(key, str) or not key or not isinstance(raw_entry, dict): raise ValueError("invalid v3 source key") entry = cast(dict[str, object], raw_entry) resource = cast(dict[str, object], entry.get("resource", {})) source = entry.get("source_sha256") path = resource.get("path", "") if (not isinstance(source, str) or not sha(source) or not sha(entry.get("reading_generation")) or resource.get("bucket") != "vomebook/pdf-pages-v2" or resource.get("role") != "runtime" or not isinstance(path, str) or not READER_BUCKET_PATH_RE.fullmatch(path) or not path.startswith(f"objects/{source[:2]}/{source}/") or not path.endswith("/reading-manifest.json") or not sha(resource.get("sha256")) or type(resource.get("bytes")) is not int or cast(int, resource["bytes"]) < 1): raise ValueError("invalid v3 reading reference") overrides[key] = {"s": 2, "m": "p", "p": path, "b": resource["bucket"]} return {"generation": generation, "catalog_sha256": ref["sha256"], "files": overrides, "catalog": ref, **({"base_sidecar_ref": catalog["base_sidecar"]} if catalog.get("base_sidecar") else {})}
def validate_base_ref(ref: object) -> dict[str, object]: if not isinstance(ref, dict): raise ValueError("invalid unified base sidecar") ref = cast(dict[str, object], ref) if (ref.get("bucket") != BUCKET or ref.get("role") != "runtime" or not sha(ref.get("sha256")) or ref.get("path") != f"reader-index/snapshots/{ref['sha256']}/reader_assets.json.gz" or type(ref.get("bytes")) is not int or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES): raise ValueError("invalid unified base sidecar") return ref
_DecodeParams = ParamSpec("_DecodeParams")_DecodeResult = TypeVar("_DecodeResult")
async def decode_in_thread(func: Callable[_DecodeParams, _DecodeResult], *args: _DecodeParams.args, **kwargs: _DecodeParams.kwargs) -> _DecodeResult: # Keep the refresh owner alive until its worker exits even after cancellation. # Otherwise a subsequent refresh could start another large decode while the # abandoned worker still holds its inputs and intermediate objects. task = asyncio.create_task(asyncio.to_thread(func, *args, **kwargs)) try: return await asyncio.shield(task) except asyncio.CancelledError: while not task.done(): try: await asyncio.shield(task) except asyncio.CancelledError: continue except Exception: break if not task.cancelled(): task.exception() # Retrieve a worker failure without replacing cancellation. raise
async def load_reading_catalog(session: object) -> dict[str, object] | None: @overload async def fetch(path: str, *, missing: Literal[True]) -> bytes | None: ...
@overload async def fetch(path: str, *, missing: Literal[False] = False) -> bytes: ...
async def fetch(path: str, *, missing: bool = False) -> bytes | None: source_url = BASE + path # Validate every redirect hop against the fixed URL or signed storage; # metadata is mutable, so its signed targets are never reused. response = await open_download_response( session, source_url, aiohttp.ClientTimeout(total=20, connect=8, sock_read=10), request_headers={"Cache-Control": "no-cache"}, url_validator=lambda url: validate_fixed_source_redirect_url(url, source_url), cache_redirects=False, ) try: if missing and response.status == 404: return None if response.status != 200: raise RuntimeError(f"v3 metadata HTTP {response.status}") raw = bytearray() async for chunk in response.content.iter_chunked(64 * 1024): raw.extend(chunk) if len(raw) > MAX_BYTES: raise ValueError("v3 metadata exceeds limit") return bytes(raw) finally: response.release() raw = await fetch(POINTER, missing=True) if raw is None: return None pointer = cast(dict[str, object], json.loads(raw)) # Validate the exact fixed catalog path before starting another request. path = catalog_path(pointer.get("generation")) if cast(dict[str, object], pointer.get("catalog", {})).get("path") != path: raise ValueError("v3 pointer path mismatch") catalog = await fetch(path) result = await decode_in_thread(decode_catalog, pointer, catalog) if result.get("base_sidecar_ref"): ref = validate_base_ref(result["base_sidecar_ref"]) packed = await fetch(cast(str, ref["path"])) if len(packed) != ref["bytes"] or hashlib.sha256(packed).hexdigest() != ref["sha256"]: raise ValueError("unified base sidecar checksum mismatch") from backend.reader.catalog.domain.assets import decode_reader_assets result["base_sidecar"] = await decode_in_thread(decode_reader_assets, packed) return result
def merge_sidecar(base: dict[str, object], catalog: dict[str, object] | None) -> dict[str, object]: if not catalog: return base base = cast(dict[str, object], catalog.get("base_sidecar", base)) return {**base, "f": {**cast(dict[str, object], base["f"]), **cast(dict[str, object], catalog["files"])}, "v3": {"generation": catalog["generation"], "catalog_sha256": catalog["catalog_sha256"], "files": len(cast(dict[str, object], catalog["files"]))}}6 unmodified lines789101112136 unmodified linesfrom fastapi import Requestfrom fastapi.responses import Responsefrom backend.proxy_streams import OwnedStreamingResponse, SharedRangeFlightfrom backend.reader.document.domain.policy import RangeFlightKey, RangeKey, ReaderStreamOptions6 unmodified lines789101112136 unmodified linesfrom fastapi import Requestfrom fastapi.responses import Responsefrom backend.shared.transport.streams import OwnedStreamingResponse, SharedRangeFlightfrom backend.reader.document.domain.policy import RangeFlightKey, RangeKey, ReaderStreamOptions
1 unmodified line23456781 unmodified linefrom collections.abc import Callable, Hashable, Mappingfrom typing import TypedDictfrom backend.reader_range_cache import RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntryRangeFlightKey = tuple[RangeKey, Hashable, str | None]1 unmodified line23456781 unmodified linefrom collections.abc import Callable, Hashable, Mappingfrom typing import TypedDictfrom backend.reader.document.domain.range_cache import RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntryRangeFlightKey = tuple[RangeKey, Hashable, str | None]
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Safe exact-byte subrange reuse for the Reader proxy's bounded cache."""from __future__ import annotations
from collections import OrderedDictfrom collections.abc import Callablefrom typing import Protocolimport re
RangeKey = tuple[str, str, int | None, str | None]RangeCacheEntry = tuple[float, bytes, dict[str, str]]
class RangeCacheState(Protocol): reader_range_cache: OrderedDict[RangeKey, RangeCacheEntry] reader_range_cache_bytes: int
def requested_range_bounds(header: str | None, total: int) -> tuple[int, int] | None: """Resolve an ordinary single byte range; unknown/unsatisfiable forms return None.""" if header is None or total <= 0: return None match = re.fullmatch(r"bytes=([0-9]{0,20})-([0-9]{0,20})", header) if match is None: return None first, last = match.groups() if not first: if not last or int(last) == 0: return None return max(0, total - int(last)), total - 1 start = int(first) end = min(int(last), total - 1) if last else total - 1 if start > end: return None return start, end
def cached_subrange(range_key: RangeKey, get_state: Callable[[], RangeCacheState], get_limit: Callable[[], int], get_ttl: Callable[[], int], now: Callable[[], float]) -> tuple[bytes, dict[str, str]] | None: """Serve a verified contained range, evicting stale entries in LRU order.""" requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_key[1]) if requested is None: return None start, end = (int(value) for value in requested.groups()) if start > end or end - start + 1 > get_limit(): return None cache = get_state().reader_range_cache current_time = now() for key in reversed(list(cache)): cached_at, payload, headers = cache[key] if current_time - cached_at >= get_ttl(): cache.pop(key) get_state().reader_range_cache_bytes -= len(payload) continue if key[0] != range_key[0] or key[2:] != range_key[2:]: continue match = re.fullmatch(r"bytes ([0-9]+)-([0-9]+)/([0-9]+)", headers.get("Content-Range", "")) if match is None: continue cached_start, cached_end, total = (int(value) for value in match.groups()) final_end = min(end, total - 1) if cached_start <= start <= final_end <= cached_end and len(payload) == cached_end - cached_start + 1: cache.move_to_end(key) body = payload[start - cached_start:final_end - cached_start + 1] return body, {**headers, "Content-Range": f"bytes {start}-{final_end}/{total}", "Content-Length": str(len(body))} return None12 unmodified lines131415161718192012 unmodified linesfrom fastapi import Requestfrom fastapi.responses import JSONResponse, Responsefrom backend.proxy_streams import OwnedStreamingResponse, UpstreamLeasefrom backend.reader_range_cache import RangeCacheStatefrom backend.reader.document.domain.policy import RangeKey, RangeCacheEntry, ReaderStreamOptions12 unmodified lines131415161718192012 unmodified linesfrom fastapi import Requestfrom fastapi.responses import JSONResponse, Responsefrom backend.shared.transport.streams import OwnedStreamingResponse, UpstreamLeasefrom backend.reader.document.domain.range_cache import RangeCacheStatefrom backend.reader.document.domain.policy import RangeKey, RangeCacheEntry, ReaderStreamOptions
4 unmodified lines5678910114 unmodified linesfrom typing import Protocol, castfrom urllib.parse import ParseResult, parse_qsfrom backend.reader_ocr import OcrPage, OcrSearchHitJsonObject = dict[str, object]OcrSearch = Callable[[list[OcrPage], str, int, int], tuple[int, list[OcrSearchHit]]]4 unmodified lines5678910114 unmodified linesfrom typing import Protocol, castfrom urllib.parse import ParseResult, parse_qsfrom backend.reader.query.domain.ocr import OcrPage, OcrSearchHitJsonObject = dict[str, object]OcrSearch = Callable[[list[OcrPage], str, int, int], tuple[int, list[OcrSearchHit]]]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165"""Bounded PDF text-index validation and original-offset search."""from __future__ import annotations
from array import arrayimport gzipimport ioimport jsonimport refrom typing import NotRequired, TypedDict, cast
class OcrSpan(TypedDict): start: int end: int box: list[int | float]
class OcrPage(TypedDict): page: int text: str folded: str fold_map: NotRequired[array[int] | None] layout: dict[str, object] spans: list[OcrSpan]
class OcrSearchHit(TypedDict): page: int start: int length: int snippet: str snippet_start: int boxes: list[list[int | float]]
def fold_reader_ocr_text(text: str) -> tuple[str, array[int] | None]: """Map casefold-expanded code points back to the source text.""" folded = text.casefold() if len(folded) == len(text): return folded, None pieces: list[str] = [] fold_map: array[int] = array('I') for index, character in enumerate(text): piece = character.casefold() pieces.append(piece) fold_map.extend([index] * len(piece)) return "".join(pieces), fold_map
def parse_reader_ocr_book(raw: bytes, max_bytes: int) -> tuple[list[OcrPage], int]: """Decode and validate one v2 book index without exceeding its byte limit.""" with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream: decoded = stream.read(max_bytes + 1) if len(decoded) > max_bytes: raise ValueError("PDF OCR text index is too large") payload: object = json.loads(decoded) if not isinstance(payload, dict): raise ValueError("invalid PDF OCR text index") document = cast(dict[str, object], payload) raw_pages = document.get("pages") if not isinstance(raw_pages, list): raise ValueError("invalid PDF OCR text index") pages = cast(list[object], raw_pages) if (len(pages) > 200000 or document.get("version") != 2 or document.get("kind") != "pdf-book-text" or document.get("complete") is not True or document.get("offset_unit") != "unicode-codepoint" or document.get("page_count") != len(pages) or not re.fullmatch(r"[0-9a-f]{64}", str(document.get("source_sha256", "")))): raise ValueError("invalid PDF OCR text index") output: list[OcrPage] = [] total_bytes = 0 previous = 0 for raw_page in pages: if not isinstance(raw_page, dict): raise ValueError("invalid PDF OCR text page") item = cast(dict[str, object], raw_page) number, text = item.get("page"), item.get("text") if (not isinstance(number, int) or number < 1 or number <= previous or not isinstance(text, str)): raise ValueError("invalid PDF OCR text page") total_bytes += len(text.encode("utf-8")) if total_bytes > max_bytes: raise ValueError("PDF OCR text index is too large") layout, spans = item.get("layout"), item.get("text_spans") if (not isinstance(layout, dict) or cast(dict[str, object], layout).get("offset_unit") != "unicode-codepoint" or not isinstance(spans, list)): raise ValueError("invalid PDF text layout mapping") previous_span_end = 0 for raw_span in cast(list[object], spans): if not isinstance(raw_span, dict): raise ValueError("invalid PDF text span") span = cast(dict[str, object], raw_span) start, end, box = span.get("start"), span.get("end"), span.get("box") if (not isinstance(start, int) or not isinstance(end, int) or start < previous_span_end or end <= start or end > len(text) or not isinstance(box, list)): raise ValueError("invalid PDF text span") values = cast(list[object], box) if len(values) != 4 or any(not isinstance(value, (int, float)) or value < 0 or value > 1 for value in values): raise ValueError("invalid PDF text span") previous_span_end = end folded, fold_map = fold_reader_ocr_text(text) if fold_map is not None: total_bytes += len(fold_map) * fold_map.itemsize output.append({"page": number, "text": text, "folded": folded, "fold_map": fold_map, "layout": cast(dict[str, object], layout), "spans": cast(list[OcrSpan], spans)}) previous = number return output, total_bytes
def search_reader_ocr_pages( pages: list[OcrPage], needle: str, page: int, page_size: int) -> tuple[int, list[OcrSearchHit]]: """Count all non-overlapping matches; return one page in original offsets.""" offset = (page - 1) * page_size end_offset = offset + page_size folded_length = len(needle) total = 0 results: list[OcrSearchHit] = [] if not folded_length: return total, results # Once the requested page is full, only the remaining count is needed. # Exact built-ins keep custom string methods and unusual callers on the # existing per-match path, including their errors and side effects. count_safe = type(needle) is str and type(page) is int and type(page_size) is int and page_size > 0 for item in pages: text, folded = item["text"], item["folded"] if "fold_map" in item: fold_map = item["fold_map"] elif len(folded) == len(text): fold_map = None else: folded, fold_map = fold_reader_ocr_text(text) if count_safe and len(results) == page_size and type(folded) is str: total += folded.count(needle) continue start = 0 while True: found = folded.find(needle, start) if found < 0: break match_index = total total += 1 if offset <= match_index < end_offset: if fold_map is None: original_start, original_end = found, found + folded_length else: original_start = fold_map[found] original_end = fold_map[found + folded_length - 1] + 1 snippet_start = max(0, original_start - 72) snippet_end = min(len(text), original_end + 88) boxes = [span["box"] for span in item["spans"] if span["end"] > original_start and span["start"] < original_end] results.append({ "page": item["page"], "start": original_start, "length": original_end - original_start, "snippet": text[snippet_start:snippet_end], "snippet_start": original_start - snippet_start, "boxes": boxes, }) if count_safe and len(results) == page_size and type(folded) is str: total += folded.count(needle, found + folded_length) break start = found + folded_length return total, results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Bounded ZIP validation for reader archives with caller-owned limits."""from __future__ import annotationsimport ioimport reimport zipfilefrom typing import Protocol, castclass ReaderArchiveLimits(Protocol):"""Limits are read on every use so callers may replace them at any time."""@propertydef READER_RESOURCE_MAX_ARCHIVE_BYTES(self) -> int: ...@propertydef READER_ARCHIVE_MAX_ENTRIES(self) -> int: ...@propertydef READER_ARCHIVE_MAX_EXPANDED_BYTES(self) -> int: ...@propertydef READER_ARCHIVE_MAX_COMPRESSION_RATIO(self) -> int: ...@propertydef READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES(self) -> int: ...@propertydef READER_ARCHIVE_MAX_METADATA_BYTES(self) -> int: ...@propertydef READER_ARCHIVE_MEMBER_RE(self) -> re.Pattern[str]: ...class ReaderArchiveLimitError(ValueError):passclass ReaderArchiveInvalidError(ValueError):passclass ReaderDocumentLimitError(ValueError):passdef _plain_int(value: object) -> bool:return isinstance(value, int) and not isinstance(value, bool)def _is_bytes(value: object) -> bool:return isinstance(value, bytes)def _is_str(value: object) -> bool:return isinstance(value, str)def validate_reader_archive(archive: bytes, limits: ReaderArchiveLimits) -> None:if len(archive) > limits.READER_RESOURCE_MAX_ARCHIVE_BYTES:raise ReaderArchiveLimitError("阅读文件过大")try:# Use the stdlib's EOCD/ZIP64 parser before ZipFile allocates its directory.# These bounded EOCD fields are stdlib internals missing from typeshed.zip_internal = cast(object, zipfile)end_record = getattr(zip_internal, "_EndRecData")(io.BytesIO(archive))if not end_record:raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP")central_directory_size = end_record[getattr(zip_internal, "_ECD_SIZE")]directory_offset = end_record[getattr(zip_internal, "_ECD_OFFSET")]entry_count = end_record[getattr(zip_internal, "_ECD_ENTRIES_TOTAL")]if (end_record[getattr(zip_internal, "_ECD_DISK_NUMBER")] != 0or end_record[getattr(zip_internal, "_ECD_DISK_START")] != 0or end_record[getattr(zip_internal, "_ECD_ENTRIES_THIS_DISK")] != entry_countor len(end_record[getattr(zip_internal, "_ECD_COMMENT")]) != end_record[getattr(zip_internal, "_ECD_COMMENT_SIZE")]or (end_record[getattr(zip_internal, "_ECD_SIGNATURE")] != getattr(zip_internal, "stringEndArchive64")and (central_directory_size == 0xffffffff or directory_offset == 0xffffffff))):raise ReaderArchiveInvalidError("阅读文件元数据无效")if central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES:raise ReaderArchiveLimitError("阅读文件元数据过大")if entry_count > limits.READER_ARCHIVE_MAX_ENTRIES:raise ReaderArchiveLimitError("阅读文件条目过多")if directory_offset + central_directory_size > len(archive):raise ReaderArchiveInvalidError("阅读文件元数据无效")with zipfile.ZipFile(io.BytesIO(archive)) as book_zip:infos = book_zip.infolist()if len(infos) > limits.READER_ARCHIVE_MAX_ENTRIES:raise ReaderArchiveLimitError("阅读文件条目过多")if len(infos) != entry_count:raise ReaderArchiveInvalidError("阅读文件条目数无效")central_directory_offset = book_zip.start_dirarchive_comment = book_zip.commentif (not _plain_int(central_directory_size)or central_directory_size < 0or central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTESor not _plain_int(central_directory_offset)or central_directory_offset < 0or central_directory_offset > len(archive)or central_directory_size > len(archive) - central_directory_offsetor not _is_bytes(archive_comment)):raise ReaderArchiveInvalidError("阅读文件元数据无效")expanded = 0compressed = 0metadata_bytes = len(archive_comment)for info in infos:filename = info.orig_filenameextra = info.extracomment = info.commentif not _is_str(filename) or not _is_bytes(extra) or not _is_bytes(comment):raise ReaderArchiveInvalidError("阅读文件元数据无效")name = filename.replace("\\", "/")name_parts = name.split("/")if (not name or name.startswith("/") or "\x00" in nameor any(part in {".", ".."} for part in name_parts)or any(not part for part in name_parts[:-1])or not limits.READER_ARCHIVE_MEMBER_RE.fullmatch(name)):raise ReaderArchiveInvalidError("阅读文件包含不安全路径")try:filename_bytes = len(filename.encode("utf-8", "surrogatepass"))except (UnicodeError, AttributeError) as exc:raise ReaderArchiveInvalidError("阅读文件元数据无效") from excmetadata_bytes += 46 + filename_bytes + len(extra) + len(comment)if metadata_bytes > limits.READER_ARCHIVE_MAX_METADATA_BYTES:raise ReaderArchiveLimitError("阅读文件元数据过大")file_size = info.file_sizecompressed_size = info.compress_sizeheader_offset = info.header_offsetif (not _plain_int(file_size)or file_size < 0or not _plain_int(compressed_size)or compressed_size < 0or compressed_size > len(archive)or not _plain_int(header_offset)or header_offset < 0or header_offset >= len(archive)or header_offset >= central_directory_offset):raise ReaderArchiveInvalidError("阅读文件条目无效")expanded += file_sizecompressed += compressed_sizeif expanded > limits.READER_ARCHIVE_MAX_EXPANDED_BYTES:raise ReaderArchiveLimitError("阅读文件展开后过大")if file_size and (compressed_size == 0 or file_size > compressed_size * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO):raise ReaderArchiveLimitError("阅读文件压缩比过高")if compressed == 0:if expanded:raise ReaderArchiveLimitError("阅读文件压缩比过高")elif expanded > compressed * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO:raise ReaderArchiveLimitError("阅读文件压缩比过高")if compressed > len(archive):raise ReaderArchiveInvalidError("阅读文件条目无效")except (ReaderArchiveLimitError, ReaderArchiveInvalidError):raiseexcept Exception as exc:raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") from exc123456789101112"""Compatibility import for backend.reader.archive.domain.validation."""import sysfrom backend.reader.archive.domain import validation as _implementationfrom backend.reader.archive.domain.validation import (ReaderArchiveInvalidError as ReaderArchiveInvalidError,ReaderArchiveLimitError as ReaderArchiveLimitError,ReaderArchiveLimits as ReaderArchiveLimits,ReaderDocumentLimitError as ReaderDocumentLimitError,validate_reader_archive as validate_reader_archive,)sys.modules[__name__] = _implementation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Pure validation and decoding for the Reader-Assets sidecar."""import gzipimport ioimport jsonimport posixpathimport refrom typing import castfrom backend.upstream_http import READER_ASSET_PATH_RE as READER_ASSET_PATH_RE # re-exported for app/testsREADER_ASSET_FILENAMES = {"p": {"document.pdf", "linearized.pdf", "page-manifest.json"},"e": {"document.epub", "book.epub", "document.mobi", "document.azw", "document.azw3", "document.fb2", "chapter-manifest.json"},"d": {"document.docx"},"h": {"document.html"},"t": {"document.txt", "document.vcf", "document.ini"},"k": {"document.md"},"i": {"document.webp", "document.jpg", "document.jpeg", "document.png", "document.gif", "document.bmp", "page-manifest.json"},"a": {"audio.mp3", "audio.wav", "audio.m4a", "audio.flac", "audio.mpga"},"v": {"video.mp4", "video.mov"},"f": {"document.swf"},}READER_BUCKET_PATH_RE = re.compile(r"^(?:documents/(?:text|web|spreadsheet|office|pdf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:document\.(?:txt|md|html|docx|pdf|vcf|ini))|"r"chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\.json|epub-search-index\.json\.gz|chapters/chapter-[0-9]{4}\.xhtml|resources/(?!\.{1,2}(?:/|$))[^/]+(?:/(?!\.{1,2}(?:/|$))[^/]+)*)|"r"media/(?:audio|video|swf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:audio\.[a-z0-9]+|video\.[a-z0-9]+|document\.swf)|"r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp|gif)/[0-9a-f]{64}/(?:document\.webp|page-manifest\.json|pages/page-[0-9]{6}\.webp)|"r"native/ebook/chm/[0-9a-f]{64}/document\.epub|"r"derived/[a-zA-Z0-9._-]+/[a-z0-9]{32}/(?:document\.pdf|page-manifest\.json|pages/page-[0-9]{6}\.webp|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))|"r"objects/(?P<djvu_prefix>[0-9a-f]{2})/(?P=djvu_prefix)[0-9a-f]{62}/[0-9a-f]{16}/document\.djvu|"r"objects/[0-9a-f]{2}/[0-9a-f]{64}/[0-9a-f]{16}/(?:reading-manifest\.json|page-map\.json\.gz|text-layer-manifest\.json|text-review-manifest\.json|text/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz|search-[0-9]{6}-[0-9]{6}\.json\.gz|partition-[0-9]{6}-[0-9]{6}-manifest\.json)|preview/(?:page-[0-9]{6}\.(?:png|webp|jpeg|svg|jxl)|partition-[0-9]{6}-[0-9]{6}-manifest\.json))|"r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl|png)|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)|document\.pdf))$")READER_EBOOK_BUCKET = "vomebook/reader-assets-v2"READER_ALLOWED_BUCKETS = {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}def decode_reader_assets(raw: bytes,max_compressed_bytes: int = 5 * 1024 * 1024,max_decompressed_bytes: int = 50 * 1024 * 1024,) -> dict[str, object]:if len(raw) > max_compressed_bytes:raise ValueError("reader assets sidecar is too large")with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:decoded = stream.read(max_decompressed_bytes + 1)if len(decoded) > max_decompressed_bytes:raise ValueError("reader assets sidecar expands beyond limit")payload: object = json.loads(decoded)payload_map = cast(dict[str, object], payload) if isinstance(payload, dict) else Nonefiles = payload_map.get("f") if payload_map is not None and payload_map.get("v") == 1 else Noneif not isinstance(files, dict):raise ValueError("invalid reader assets sidecar")file_map = cast(dict[object, object], files)clean: dict[str, dict[str, object]] = {}for key, raw_entry in file_map.items():if not isinstance(key, str) or not isinstance(raw_entry, dict):continueentry = cast(dict[str, object], raw_entry)if entry.get("s") not in (2, 3, 4):continueif entry.get("s") == 2:path = entry.get("p")mode = entry.get("m")if not isinstance(path, str) or not isinstance(mode, str) or mode not in READER_ASSET_FILENAMES:continueif entry.get("b") not in READER_ALLOWED_BUCKETS:continuepath_pattern = READER_BUCKET_PATH_REimage_page_path = bool(re.fullmatch(r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp)/[0-9a-f]{64}/pages/page-[0-9]{6}\.webp", path))valid_filename = (posixpath.basename(path) in READER_ASSET_FILENAMES[mode]or (mode == "i" and image_page_path)or (mode == "p" and entry.get("b") == "vomebook/pdf-pages-v2"and path.endswith("/reading-manifest.json")))if (not path_pattern.fullmatch(path)or not valid_filename):continuechapter_manifest = entry.get("c")fallback = entry.get("f")ocr_manifest = entry.get("o")chapter_bucket = entry.get("cb")bucket = entry.get("b")document_path, document_bucket = entry.get("pd"), entry.get("pdb")if (document_path is not None or document_bucket is not None) and (mode != "p" or not path.endswith("/page-manifest.json")or not isinstance(document_bucket, str)or document_bucket not in READER_ALLOWED_BUCKETSor not isinstance(document_path, str)or not READER_BUCKET_PATH_RE.fullmatch(document_path)or not document_path.endswith("/document.pdf")):continueif chapter_manifest is not None and (mode not in {"e", "p"}or not isinstance(chapter_manifest, str)or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest)or not chapter_manifest.endswith("/chapter-manifest.json")):continueif chapter_manifest is not None and chapter_bucket is None:continueif chapter_bucket is not None and (chapter_bucket != READER_EBOOK_BUCKET or not isinstance(chapter_manifest, str)or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest)or not (chapter_manifest.startswith("ebook-chapters/")or (chapter_bucket == "vomebook/reader-assets-v2"and chapter_manifest.startswith("chapters/ebook/")))):continuefallback_is_chm = (bucket == READER_EBOOK_BUCKET and isinstance(fallback, str)and READER_BUCKET_PATH_RE.fullmatch(fallback)and fallback.endswith("/document.epub"))if fallback is not None and not fallback_is_chm:continueif ocr_manifest is not None and (not isinstance(ocr_manifest, str)or not READER_BUCKET_PATH_RE.fullmatch(ocr_manifest)or not ocr_manifest.endswith("/ocr-manifest.json")):continueif entry.get("b") is not None and entry.get("b") not in READER_ALLOWED_BUCKETS:continueif entry.get("ob") is not None and entry.get("ob") != "vomebook/pdf-pages-v2":continueif bucket == "vomebook/pdf-pages-v2":if mode == "p" and (not path.endswith(("/page-manifest.json", "/reading-manifest.json", "/document.pdf"))or not READER_BUCKET_PATH_RE.fullmatch(path)):continueclean[key] = {"s": 2,"m": mode,"p": path,**({"b": bucket} if bucket else {}),**({"pd": document_path, "pdb": document_bucket} if document_path else {}),**({"c": chapter_manifest} if chapter_manifest else {}),**({"cb": chapter_bucket} if chapter_bucket else {}),**({"f": fallback} if fallback else {}),**({"o": ocr_manifest} if ocr_manifest else {}),**({"ob": "vomebook/pdf-pages-v2"} if entry.get("ob") else {}),**({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {}),}else:ocr_manifest = entry.get("o")if (isinstance(ocr_manifest, str) and READER_BUCKET_PATH_RE.fullmatch(ocr_manifest)and ocr_manifest.endswith("/ocr-manifest.json")):clean[key] = {"s": 3, "m": "p", "o": ocr_manifest, "b": "vomebook/pdf-pages-v2",**({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {})}else:clean[key] = {"s": 4}return {"v": 1, "f": clean}12345678910111213"""Compatibility import for backend.reader.catalog.domain.assets."""import sysfrom backend.reader.catalog.domain import assets as _implementationfrom backend.reader.catalog.domain.assets import (READER_ALLOWED_BUCKETS as READER_ALLOWED_BUCKETS,READER_ASSET_FILENAMES as READER_ASSET_FILENAMES,READER_ASSET_PATH_RE as READER_ASSET_PATH_RE,READER_BUCKET_PATH_RE as READER_BUCKET_PATH_RE,READER_EBOOK_BUCKET as READER_EBOOK_BUCKET,decode_reader_assets as decode_reader_assets,)sys.modules[__name__] = _implementation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Incremental Reader index construction without publishing partial results."""from collections.abc import Callablefrom typing import TypedDict, castclass ReaderIndexBuild(TypedDict):generation: intrecords: list[dict[str, object]]next: intindices: list[int]repos: dict[str, list[int]]keys: dict[str, int]ids: dict[str, list[int]]legacy_ids: dict[str, list[int]]def new_build(generation: int, records: list[dict[str, object]]) -> ReaderIndexBuild:return {"generation": generation, "records": records, "next": 0,"indices": [], "repos": {}, "keys": {}, "ids": {}, "legacy_ids": {}}def advance_build(build: ReaderIndexBuild, limit: int, deadline: float, *,now: Callable[[], float], source_id: Callable[[str], str],asset_key: Callable[[dict[str, object]], str],record_link: Callable[[dict[str, object]], str],dataset_url: Callable[[str, str], str],reader_extensions: frozenset[str]) -> bool:"""Advance at most one batch; callers own generation checks and publication."""end = min(len(build["records"]), build["next"] + limit)while build["next"] < end:idx = build["next"]rec = build["records"][idx]repo = rec.get("Repo", "")build["keys"][asset_key(rec)] = idxcurrent_url = cast(str, rec.get("Link") or record_link(rec))build["ids"].setdefault(source_id(current_url), []).append(idx)# Old links omitted a repeated filename extension; index the historical# alias without changing the canonical identity or resolving collisions.name, ext, folders = rec.get("File", ""), rec.get("Extension", ""), rec.get("Folder", [])if (isinstance(repo, str) and repo.startswith("VoiceOfML/") and isinstance(name, str)and isinstance(ext, str) and ext and name.lower().endswith("." + ext.lower())and isinstance(folders, list) and all(isinstance(part, str) for part in cast(list[object], folders))):legacy_path = "/".join([*cast(list[str], folders), name])legacy_url = dataset_url(repo, legacy_path)if legacy_url != (rec.get("Link") or record_link(rec)):build["legacy_ids"].setdefault(source_id(legacy_url), []).append(idx)if rec.get("_ext_lower", "") in reader_extensions:build["indices"].append(idx)build["repos"].setdefault(cast(str, repo), []).append(idx)build["next"] += 1if now() >= deadline:breakreturn build["next"] >= len(build["records"])12345678910"""Compatibility import for backend.reader.catalog.domain.index."""import sysfrom backend.reader.catalog.domain import index as _implementationfrom backend.reader.catalog.domain.index import (ReaderIndexBuild as ReaderIndexBuild,advance_build as advance_build,new_build as new_build,)sys.modules[__name__] = _implementation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165"""Bounded PDF text-index validation and original-offset search."""from __future__ import annotationsfrom array import arrayimport gzipimport ioimport jsonimport refrom typing import NotRequired, TypedDict, castclass OcrSpan(TypedDict):start: intend: intbox: list[int | float]class OcrPage(TypedDict):page: inttext: strfolded: strfold_map: NotRequired[array[int] | None]layout: dict[str, object]spans: list[OcrSpan]class OcrSearchHit(TypedDict):page: intstart: intlength: intsnippet: strsnippet_start: intboxes: list[list[int | float]]def fold_reader_ocr_text(text: str) -> tuple[str, array[int] | None]:"""Map casefold-expanded code points back to the source text."""folded = text.casefold()if len(folded) == len(text):return folded, Nonepieces: list[str] = []fold_map: array[int] = array('I')for index, character in enumerate(text):piece = character.casefold()pieces.append(piece)fold_map.extend([index] * len(piece))return "".join(pieces), fold_mapdef parse_reader_ocr_book(raw: bytes, max_bytes: int) -> tuple[list[OcrPage], int]:"""Decode and validate one v2 book index without exceeding its byte limit."""with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:decoded = stream.read(max_bytes + 1)if len(decoded) > max_bytes:raise ValueError("PDF OCR text index is too large")payload: object = json.loads(decoded)if not isinstance(payload, dict):raise ValueError("invalid PDF OCR text index")document = cast(dict[str, object], payload)raw_pages = document.get("pages")if not isinstance(raw_pages, list):raise ValueError("invalid PDF OCR text index")pages = cast(list[object], raw_pages)if (len(pages) > 200000or document.get("version") != 2 or document.get("kind") != "pdf-book-text"or document.get("complete") is not Trueor document.get("offset_unit") != "unicode-codepoint"or document.get("page_count") != len(pages)or not re.fullmatch(r"[0-9a-f]{64}", str(document.get("source_sha256", "")))):raise ValueError("invalid PDF OCR text index")output: list[OcrPage] = []total_bytes = 0previous = 0for raw_page in pages:if not isinstance(raw_page, dict):raise ValueError("invalid PDF OCR text page")item = cast(dict[str, object], raw_page)number, text = item.get("page"), item.get("text")if (not isinstance(number, int) or number < 1 or number <= previousor not isinstance(text, str)):raise ValueError("invalid PDF OCR text page")total_bytes += len(text.encode("utf-8"))if total_bytes > max_bytes:raise ValueError("PDF OCR text index is too large")layout, spans = item.get("layout"), item.get("text_spans")if (not isinstance(layout, dict) or cast(dict[str, object], layout).get("offset_unit") != "unicode-codepoint"or not isinstance(spans, list)):raise ValueError("invalid PDF text layout mapping")previous_span_end = 0for raw_span in cast(list[object], spans):if not isinstance(raw_span, dict):raise ValueError("invalid PDF text span")span = cast(dict[str, object], raw_span)start, end, box = span.get("start"), span.get("end"), span.get("box")if (not isinstance(start, int) or not isinstance(end, int) or start < previous_span_endor end <= start or end > len(text) or not isinstance(box, list)):raise ValueError("invalid PDF text span")values = cast(list[object], box)if len(values) != 4 or any(not isinstance(value, (int, float)) or value < 0 or value > 1for value in values):raise ValueError("invalid PDF text span")previous_span_end = endfolded, fold_map = fold_reader_ocr_text(text)if fold_map is not None:total_bytes += len(fold_map) * fold_map.itemsizeoutput.append({"page": number, "text": text, "folded": folded, "fold_map": fold_map,"layout": cast(dict[str, object], layout), "spans": cast(list[OcrSpan], spans)})previous = numberreturn output, total_bytesdef search_reader_ocr_pages(pages: list[OcrPage], needle: str, page: int, page_size: int) -> tuple[int, list[OcrSearchHit]]:"""Count all non-overlapping matches; return one page in original offsets."""offset = (page - 1) * page_sizeend_offset = offset + page_sizefolded_length = len(needle)total = 0results: list[OcrSearchHit] = []if not folded_length:return total, results# Once the requested page is full, only the remaining count is needed.# Exact built-ins keep custom string methods and unusual callers on the# existing per-match path, including their errors and side effects.count_safe = type(needle) is str and type(page) is int and type(page_size) is int and page_size > 0for item in pages:text, folded = item["text"], item["folded"]if "fold_map" in item:fold_map = item["fold_map"]elif len(folded) == len(text):fold_map = Noneelse:folded, fold_map = fold_reader_ocr_text(text)if count_safe and len(results) == page_size and type(folded) is str:total += folded.count(needle)continuestart = 0while True:found = folded.find(needle, start)if found < 0:breakmatch_index = totaltotal += 1if offset <= match_index < end_offset:if fold_map is None:original_start, original_end = found, found + folded_lengthelse:original_start = fold_map[found]original_end = fold_map[found + folded_length - 1] + 1snippet_start = max(0, original_start - 72)snippet_end = min(len(text), original_end + 88)boxes = [span["box"] for span in item["spans"]if span["end"] > original_start and span["start"] < original_end]results.append({"page": item["page"], "start": original_start,"length": original_end - original_start,"snippet": text[snippet_start:snippet_end],"snippet_start": original_start - snippet_start, "boxes": boxes,})if count_safe and len(results) == page_size and type(folded) is str:total += folded.count(needle, found + folded_length)breakstart = found + folded_lengthreturn total, results12345678910111213"""Compatibility import for backend.reader.query.domain.ocr."""import sysfrom backend.reader.query.domain import ocr as _implementationfrom backend.reader.query.domain.ocr import (OcrPage as OcrPage,OcrSearchHit as OcrSearchHit,OcrSpan as OcrSpan,fold_reader_ocr_text as fold_reader_ocr_text,parse_reader_ocr_book as parse_reader_ocr_book,search_reader_ocr_pages as search_reader_ocr_pages,)sys.modules[__name__] = _implementation
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Safe exact-byte subrange reuse for the Reader proxy's bounded cache."""from __future__ import annotationsfrom collections import OrderedDictfrom collections.abc import Callablefrom typing import Protocolimport reRangeKey = tuple[str, str, int | None, str | None]RangeCacheEntry = tuple[float, bytes, dict[str, str]]class RangeCacheState(Protocol):reader_range_cache: OrderedDict[RangeKey, RangeCacheEntry]reader_range_cache_bytes: intdef requested_range_bounds(header: str | None, total: int) -> tuple[int, int] | None:"""Resolve an ordinary single byte range; unknown/unsatisfiable forms return None."""if header is None or total <= 0:return Nonematch = re.fullmatch(r"bytes=([0-9]{0,20})-([0-9]{0,20})", header)if match is None:return Nonefirst, last = match.groups()if not first:if not last or int(last) == 0:return Nonereturn max(0, total - int(last)), total - 1start = int(first)end = min(int(last), total - 1) if last else total - 1if start > end:return Nonereturn start, enddef cached_subrange(range_key: RangeKey, get_state: Callable[[], RangeCacheState],get_limit: Callable[[], int], get_ttl: Callable[[], int],now: Callable[[], float]) -> tuple[bytes, dict[str, str]] | None:"""Serve a verified contained range, evicting stale entries in LRU order."""requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_key[1])if requested is None:return Nonestart, end = (int(value) for value in requested.groups())if start > end or end - start + 1 > get_limit():return Nonecache = get_state().reader_range_cachecurrent_time = now()for key in reversed(list(cache)):cached_at, payload, headers = cache[key]if current_time - cached_at >= get_ttl():cache.pop(key)get_state().reader_range_cache_bytes -= len(payload)continueif key[0] != range_key[0] or key[2:] != range_key[2:]:continuematch = re.fullmatch(r"bytes ([0-9]+)-([0-9]+)/([0-9]+)", headers.get("Content-Range", ""))if match is None:continuecached_start, cached_end, total = (int(value) for value in match.groups())final_end = min(end, total - 1)if cached_start <= start <= final_end <= cached_end and len(payload) == cached_end - cached_start + 1:cache.move_to_end(key)body = payload[start - cached_start:final_end - cached_start + 1]return body, {**headers, "Content-Range": f"bytes {start}-{final_end}/{total}","Content-Length": str(len(body))}return None123456789101112"""Compatibility import for backend.reader.document.domain.range_cache."""import sysfrom backend.reader.document.domain import range_cache as _implementationfrom backend.reader.document.domain.range_cache import (RangeCacheEntry as RangeCacheEntry,RangeCacheState as RangeCacheState,RangeKey as RangeKey,cached_subrange as cached_subrange,requested_range_bounds as requested_range_bounds,)sys.modules[__name__] = _implementation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""Pinned v3 catalog projection, using only canonical bucket metadata URLs."""import asyncioimport hashlibimport jsonimport refrom typing import Callable, Literal, ParamSpec, TypeVar, cast, overloadimport aiohttpfrom backend.upstream_http import open_download_response, validate_fixed_source_redirect_urlBUCKET = "vomebook/reader-assets-v2"BASE = f"https://huggingface.co/buckets/{BUCKET}/resolve/"POINTER = "reader-index/v3/current.json"MAX_BYTES = 8 * 1024 * 1024def sha(value: object) -> re.Match[str] | bool | None:return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value)def catalog_path(generation: object) -> str:if not sha(generation):raise ValueError("invalid v3 catalog generation")return f"reader-index/v3/generations/{generation}/catalog.json"def decode_catalog(pointer: dict[str, object], raw: bytes) -> dict[str, object]:from backend.reader_assets import READER_BUCKET_PATH_REif pointer.get("version") != 1 or pointer.get("kind") != "reader-reading-pointer":raise ValueError("invalid v3 pointer")generation = pointer.get("generation")ref = cast(dict[str, object], pointer.get("catalog", {}))if (ref.get("bucket") != BUCKET or ref.get("path") != catalog_path(generation)or ref.get("role") != "runtime" or type(ref.get("bytes")) is not intor not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES or not sha(ref.get("sha256"))or len(raw) != ref["bytes"] or hashlib.sha256(raw).hexdigest() != ref["sha256"]):raise ValueError("v3 catalog resource mismatch")catalog = cast(dict[str, object], json.loads(raw))body = {k: v for k, v in catalog.items() if k != "generation"}digest = hashlib.sha256(json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"),allow_nan=False).encode()).hexdigest()if (catalog.get("version") != 3 or catalog.get("kind") != "reader-reading-catalog"or catalog.get("generation") != generation or digest != generationor not isinstance(catalog.get("files"), dict)):raise ValueError("invalid v3 catalog identity")overrides: dict[str, dict[str, object]] = {}for key, raw_entry in cast(dict[object, object], catalog["files"]).items():if not isinstance(key, str) or not key or not isinstance(raw_entry, dict):raise ValueError("invalid v3 source key")entry = cast(dict[str, object], raw_entry)resource = cast(dict[str, object], entry.get("resource", {}))source = entry.get("source_sha256")path = resource.get("path", "")if (not isinstance(source, str) or not sha(source) or not sha(entry.get("reading_generation"))or resource.get("bucket") != "vomebook/pdf-pages-v2" or resource.get("role") != "runtime"or not isinstance(path, str) or not READER_BUCKET_PATH_RE.fullmatch(path)or not path.startswith(f"objects/{source[:2]}/{source}/")or not path.endswith("/reading-manifest.json") or not sha(resource.get("sha256"))or type(resource.get("bytes")) is not int or cast(int, resource["bytes"]) < 1):raise ValueError("invalid v3 reading reference")overrides[key] = {"s": 2, "m": "p", "p": path, "b": resource["bucket"]}return {"generation": generation, "catalog_sha256": ref["sha256"],"files": overrides, "catalog": ref,**({"base_sidecar_ref": catalog["base_sidecar"]} if catalog.get("base_sidecar") else {})}def validate_base_ref(ref: object) -> dict[str, object]:if not isinstance(ref, dict):raise ValueError("invalid unified base sidecar")ref = cast(dict[str, object], ref)if (ref.get("bucket") != BUCKET or ref.get("role") != "runtime"or not sha(ref.get("sha256")) or ref.get("path") !=f"reader-index/snapshots/{ref['sha256']}/reader_assets.json.gz"or type(ref.get("bytes")) is not int or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES):raise ValueError("invalid unified base sidecar")return ref_DecodeParams = ParamSpec("_DecodeParams")_DecodeResult = TypeVar("_DecodeResult")async def decode_in_thread(func: Callable[_DecodeParams, _DecodeResult],*args: _DecodeParams.args, **kwargs: _DecodeParams.kwargs) -> _DecodeResult:# Keep the refresh owner alive until its worker exits even after cancellation.# Otherwise a subsequent refresh could start another large decode while the# abandoned worker still holds its inputs and intermediate objects.task = asyncio.create_task(asyncio.to_thread(func, *args, **kwargs))try:return await asyncio.shield(task)except asyncio.CancelledError:while not task.done():try:await asyncio.shield(task)except asyncio.CancelledError:continueexcept Exception:breakif not task.cancelled():task.exception() # Retrieve a worker failure without replacing cancellation.raiseasync def load_reading_catalog(session: object) -> dict[str, object] | None:@overloadasync def fetch(path: str, *, missing: Literal[True]) -> bytes | None: ...@overloadasync def fetch(path: str, *, missing: Literal[False] = False) -> bytes: ...async def fetch(path: str, *, missing: bool = False) -> bytes | None:source_url = BASE + path# Validate every redirect hop against the fixed URL or signed storage;# metadata is mutable, so its signed targets are never reused.response = await open_download_response(session, source_url, aiohttp.ClientTimeout(total=20, connect=8, sock_read=10),request_headers={"Cache-Control": "no-cache"},url_validator=lambda url: validate_fixed_source_redirect_url(url, source_url),cache_redirects=False,)try:if missing and response.status == 404:return Noneif response.status != 200:raise RuntimeError(f"v3 metadata HTTP {response.status}")raw = bytearray()async for chunk in response.content.iter_chunked(64 * 1024):raw.extend(chunk)if len(raw) > MAX_BYTES:raise ValueError("v3 metadata exceeds limit")return bytes(raw)finally:response.release()raw = await fetch(POINTER, missing=True)if raw is None:return Nonepointer = cast(dict[str, object], json.loads(raw))# Validate the exact fixed catalog path before starting another request.path = catalog_path(pointer.get("generation"))if cast(dict[str, object], pointer.get("catalog", {})).get("path") != path:raise ValueError("v3 pointer path mismatch")catalog = await fetch(path)result = await decode_in_thread(decode_catalog, pointer, catalog)if result.get("base_sidecar_ref"):ref = validate_base_ref(result["base_sidecar_ref"])packed = await fetch(cast(str, ref["path"]))if len(packed) != ref["bytes"] or hashlib.sha256(packed).hexdigest() != ref["sha256"]:raise ValueError("unified base sidecar checksum mismatch")from backend.reader_assets import decode_reader_assetsresult["base_sidecar"] = await decode_in_thread(decode_reader_assets, packed)return resultdef merge_sidecar(base: dict[str, object], catalog: dict[str, object] | None) -> dict[str, object]:if not catalog:return basebase = cast(dict[str, object], catalog.get("base_sidecar", base))return {**base, "f": {**cast(dict[str, object], base["f"]), **cast(dict[str, object], catalog["files"])},"v3": {"generation": catalog["generation"], "catalog_sha256": catalog["catalog_sha256"],"files": len(cast(dict[str, object], catalog["files"]))}}123456789101112131415161718"""Compatibility import for backend.reader.catalog.infrastructure.v3."""import sysfrom backend.reader.catalog.infrastructure import v3 as _implementationfrom backend.reader.catalog.infrastructure.v3 import (BASE as BASE,BUCKET as BUCKET,MAX_BYTES as MAX_BYTES,POINTER as POINTER,catalog_path as catalog_path,decode_catalog as decode_catalog,decode_in_thread as decode_in_thread,load_reading_catalog as load_reading_catalog,merge_sidecar as merge_sidecar,sha as sha,validate_base_ref as validate_base_ref,)sys.modules[__name__] = _implementation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"""Pure record paths and reader projections shared by search and reader APIs."""import posixpathimport refrom typing import castfrom urllib.parse import quoteREADER_ASSET_MODES = {"p": "pdf", "e": "epub", "d": "docx", "h": "html","t": "txt", "k": "md", "i": "webp", "a": "audio", "v": "video", "f": "swf",}READER_NATIVE_FOLIATE_EXTENSIONS = frozenset({"epub", "mobi", "azw", "azw3", "fb2"})def build_record_relative_path(rec: dict[str, object]) -> str:file_name = cast(str, rec.get("File", ""))extension = cast(str, rec.get("Extension", ""))full_name = f"{file_name}.{extension}" if extension else file_namefolders = cast(list[str], rec.get("Folder", []) or [])return posixpath.join(*folders, full_name) if folders else full_namedef build_reader_asset_key(rec: dict[str, object]) -> str:return f"{rec.get('Repo', '')}\0{build_record_relative_path(rec)}"def dataset_file_url(repo: str, relative_path: str, action: str = "resolve") -> str:return f"https://huggingface.co/datasets/{repo}/{action}/main/{quote(relative_path, safe='/')}"def dataset_file_urls(repo: str, relative_path: str) -> tuple[str, str]:"""Produce source and browser URLs using the same encoded path."""encoded = quote(relative_path, safe="/")prefix = f"https://huggingface.co/datasets/{repo}"return f"{prefix}/resolve/main/{encoded}", f"{prefix}/blob/main/{encoded}"def build_record_link(rec: dict[str, object]) -> str:return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec))def build_record_path_url(rec: dict[str, object]) -> str:return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec), "blob")def build_browser_file_name(file_item: dict[str, object]) -> str:name = str(file_item.get("name", "") or "file")ext = str(file_item.get("ext", "") or "")# Browser metadata stores the source record's stem and last extension in# separate fields; a repeated suffix in the stem is still significant.if not ext:return namereturn f"{name}.{ext}"def enrich_browser_entry(repo: str, path: str, entry: dict[str, object]) -> dict[str, object]:decoded = dict(entry or {})decoded["current_path"] = decoded.get("current_path", path)folders: list[dict[str, object]] = []for folder in cast(list[dict[str, object]], decoded.get("folders", []) or []):item = dict(folder)if "path" not in item:name = item.get("name", "")item["path"] = f"{path}/{name}" if path else namefolders.append(item)files: list[dict[str, object]] = []for file_item in cast(list[dict[str, object]], decoded.get("files", []) or []):item = dict(file_item)full_name = build_browser_file_name(item)rel_path = f"{path}/{full_name}" if path else full_nameif not item.get("link") and not item.get("path"):item["link"], item["path"] = dataset_file_urls(repo, rel_path)else:item["link"] = item.get("link") or dataset_file_url(repo, rel_path)item["path"] = item.get("path") or dataset_file_url(repo, rel_path, "blob")files.append(item)decoded["folders"] = foldersdecoded["files"] = filesreturn decodeddef reader_asset_url(asset: dict[str, object]) -> str:path = quote(str(asset.get("p") or ""), safe="/")return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + pathdef reader_extension_for_asset(asset: dict[str, object], original_extension: str = "") -> str:asset_path = str(asset.get("p") or "")if asset.get('c'):return 'epub-chapters'if asset_path.endswith(("page-manifest.json", "reading-manifest.json")):return "image-pages" if asset.get("m") == "i" else "pdf-pages"if asset.get("m") == "e":match = re.search(r"/(?:document|book)\.(epub|mobi|azw|azw3|fb2)$", asset_path, re.IGNORECASE)if match:return match.group(1).lower()extension = str(original_extension or "").lower().lstrip(".")return extension if extension in READER_NATIVE_FOLIATE_EXTENSIONS else "epub"mode = asset.get("m")return READER_ASSET_MODES.get(mode, "") if isinstance(mode, str) else ""def _reader_bucket_url(path: str) -> str:return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + quote(path, safe="/")def reader_asset_fields(asset: dict[str, object], original_extension: str) -> dict[str, str]:ocr_path = str(asset.get("o") or "")ocr_bucket = asset.get("b") == "vomebook/pdf-pages-v2" or asset.get("ob") == "vomebook/pdf-pages-v2"fields: dict[str, str] = {}if ocr_path.endswith("/ocr-manifest.json") and ocr_bucket:fields["ocr_manifest"] = _reader_bucket_url(ocr_path)fields["ocr_mode"] = str(asset.get("om") or "")if asset.get("s") == 3:return fieldsif asset.get("s") != 2 or asset.get("m") not in READER_ASSET_MODES or not asset.get("p"):return fieldsif str(original_extension).lower().lstrip('.') == 'djvu':# Existing OCR remains independent. Native DjVu reading starts at the# dataset source, never an older image stream, manifest or derivative.return fieldsif (asset.get('m') == 'p' and not asset.get('c') and str(asset['p']).endswith('/page-manifest.json')and str(original_extension).lower().lstrip('.') != 'djvu'):# Legacy page indexes no longer own PDF/converted-PDF reading. Keep# independent OCR metadata and prefer the validated PDF companion.if asset.get('pd') and asset.get('pdb') in {'vomebook/reader-assets-v2', 'vomebook/pdf-pages-v2'}:fields.update(url=_reader_bucket_url(cast(str, asset['pd'])), extension='pdf')return fieldsfields.update({"url": reader_asset_url(asset), "extension": reader_extension_for_asset(asset, original_extension)})if asset.get("pd") and asset.get("pdb") in {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}:fields["pdf_document"] = _reader_bucket_url(cast(str, asset["pd"]))if asset.get("c"):if asset.get("cb") == "vomebook/reader-assets-v2":fields["chapter_manifest"] = _reader_bucket_url(cast(str, asset["c"]))elif asset.get("cb") == "vomebook/pdf-pages-v2":fields["chapter_manifest"] = "/api/reader-bucket-resource?path=" + quote(cast(str, asset["c"]), safe="/")return fieldsdef enrich_reader_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]:result = dict(record)fields = reader_asset_fields(asset, cast(str, record.get("Extension", "")))direct_modes = {"pdf": ("pdf", "pdf"), "djvu": ("djvu", "pdf"), "vcf": ("vcf", "text"), "ini": ("ini", "text"),"tif": ("image", "image"), "tiff": ("image", "image"),}direct_extension = str(record.get("Extension") or "").lower().lstrip(".")if 'url' not in fields and direct_extension in direct_modes:# A PDF without a converted/page asset remains directly readable from# its immutable source dataset after the derived asset store changes.fields.update(url=cast(str, record.get("Link") or build_record_link(record)),extension=direct_modes[direct_extension][0])if fields:for source, target in (("url", "ReaderLink"), ("extension", "ReaderExtension"),("chapter_manifest", "ReaderChapterManifest"),("ocr_manifest", "ReaderOcrManifest"), ("ocr_mode", "ReaderOcrMode"),("pdf_document", "ReaderPdfDocument")):if source in fields:result[target] = fields[source]result["DownloadLink"] = record.get("Link") or build_record_link(record)return resultdef add_reader_assets(payload: dict[str, object], assets: dict[str, object]) -> dict[str, object]:files = cast(dict[str, dict[str, object]], assets.get("f", {}))return {**payload, "results": [enrich_reader_record(record, files.get(build_reader_asset_key(record), {}))for record in cast(list[dict[str, object]], payload.get("results", []))]}def reader_resolved_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]:source = record.get("Link") or build_record_link(record)extension = str(record.get("Extension") or "").lower().lstrip(".")repo = cast(str, record.get("Repo", "")).split("/")[-1]folders = [str(item) for item in cast(list[object], record.get("Folder", []))]return {"url": source, "download": source, "extension": extension,"original_extension": extension, "title": record.get("File") or record.get("Name") or "在线阅读",# Keep the exact indexed filename separate from the display title.# The stem may itself end in an extension, or include trailing spaces."filename": build_record_relative_path(record).rsplit("/", 1)[-1],"path": "/".join([repo, *folders]), "folder": "/".join(folders), "repo": repo,**reader_asset_fields(asset, extension),}1234567891011121314151617181920212223"""Compatibility import for backend.search.corpus.domain.records."""import sysfrom backend.search.corpus.domain import records as _implementationfrom backend.search.corpus.domain.records import (READER_ASSET_MODES as READER_ASSET_MODES,READER_NATIVE_FOLIATE_EXTENSIONS as READER_NATIVE_FOLIATE_EXTENSIONS,add_reader_assets as add_reader_assets,build_browser_file_name as build_browser_file_name,build_reader_asset_key as build_reader_asset_key,build_record_link as build_record_link,build_record_path_url as build_record_path_url,build_record_relative_path as build_record_relative_path,dataset_file_url as dataset_file_url,dataset_file_urls as dataset_file_urls,enrich_browser_entry as enrich_browser_entry,enrich_reader_record as enrich_reader_record,reader_asset_fields as reader_asset_fields,reader_asset_url as reader_asset_url,reader_extension_for_asset as reader_extension_for_asset,reader_resolved_record as reader_resolved_record,)sys.modules[__name__] = _implementation
8 unmodified lines9101112131415168 unmodified linesimport aiohttpfrom backend.reader.document.application.ranges import RangeFlightStatefrom backend.reader_range_cache import RangeCacheStatefrom backend.search_execution import SearchExecutorclass LifecycleState(RangeCacheState, RangeFlightState, Protocol):8 unmodified lines9101112131415168 unmodified linesimport aiohttpfrom backend.reader.document.application.ranges import RangeFlightStatefrom backend.reader.document.domain.range_cache import RangeCacheStatefrom backend.search.infrastructure.executor import SearchExecutorclass LifecycleState(RangeCacheState, RangeFlightState, Protocol):
12345678910111213141516171819202122232425262728293031"""Typed construction of initial search pages from caller-owned state."""from __future__ import annotations
from collections.abc import Callable, Iterable, Mapping, Sequence
SearchRecord = dict[str, object]
def trim_initial_results(raw: Iterable[SearchRecord]) -> list[SearchRecord]: return [{"Repo": record.get("Repo", ""), "File": record.get("File", ""), "Extension": record.get("Extension", ""), "Folder": record.get("Folder", []), "Size": record.get("Size", ""), "HasTxt": record.get("HasTxt", "")} for record in raw]
def build_initial_payload(repo: str | None, get_page_size: Callable[[], int], get_repos: Callable[[], Mapping[str, Sequence[int]]], get_records: Callable[[], Sequence[SearchRecord]], get_trim: Callable[[], Callable[[Sequence[SearchRecord]], list[SearchRecord]]], get_generation: Callable[[], Callable[[], str]]) -> dict[str, object]: """Preserve snapshot lookup, projection and generation evaluation order.""" if repo: indices = get_repos().get(repo, []) result_records = [get_records()[index] for index in indices[:get_page_size()]] mode = "repo" total = len(indices) else: result_records = get_records()[:get_page_size()] mode = "global" total = len(get_records()) return {"mode": mode, "repo": repo, "sort": "relevance", "page": 1, "page_size": get_page_size(), "total": total, "results": get_trim()(result_records), "generation": get_generation()()}7 unmodified lines891011121314157 unmodified linesfrom dataclasses import dataclassfrom pathlib import Pathfrom backend.data_formats import CompactTreeNode, CompactBrowserEntryfrom backend.search_indexes import PostingIndexfrom backend.search.corpus.domain.metadata import RecordTree = dict[str, list[Record]]7 unmodified lines891011121314157 unmodified linesfrom dataclasses import dataclassfrom pathlib import Pathfrom backend.search.corpus.domain.formats import CompactTreeNode, CompactBrowserEntryfrom backend.search.corpus.infrastructure.indexes import PostingIndexfrom backend.search.corpus.domain.metadata import RecordTree = dict[str, list[Record]]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Directory browser lookup against a caller-owned search index snapshot."""from __future__ import annotations
from collections.abc import Callable, Mapping, Sequencefrom typing import cast
SearchRecord = dict[str, object]BrowserEntries = Mapping[str, Mapping[str, SearchRecord]]FolderIndex = Mapping[str, Mapping[str, Sequence[int]]]RepoIndices = Mapping[str, Sequence[int]]
def get_folder_contents(repo: str, path: str, *, get_browser: Callable[[], BrowserEntries], get_folder_index: Callable[[], FolderIndex], get_repo_indices: Callable[[], RepoIndices], get_records: Callable[[], Sequence[SearchRecord]], enrich_browser_entry: Callable[[str, str, SearchRecord], SearchRecord], build_record_link: Callable[[SearchRecord], str], build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord: """Prefer precomputed entries, otherwise count and project the indexed subtree.""" if repo in get_browser(): repo_browser = get_browser().get(repo, {}) or {} if path in repo_browser: return enrich_browser_entry(repo, path, repo_browser[path]) if path == "" and "" in repo_browser: return enrich_browser_entry(repo, path, repo_browser[""]) return _from_index(repo, path, get_folder_index, get_repo_indices, get_records, build_record_link, build_record_path_url)
def _from_index(repo: str, path: str, get_folder_index: Callable[[], FolderIndex], get_repo_indices: Callable[[], RepoIndices], get_records: Callable[[], Sequence[SearchRecord]], build_record_link: Callable[[SearchRecord], str], build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord: path_parts = [p for p in path.strip("/").split("/") if p] path_depth = len(path_parts) repo_folders = get_folder_index().get(repo) candidate_indices = (repo_folders.get("/".join(path_parts), []) if repo_folders is not None else get_repo_indices().get(repo, []))
def is_under(rec_folders: list[str], prefix: list[str]) -> bool: return rec_folders[:len(prefix)] == prefix matching = [get_records()[i] for i in candidate_indices if is_under(cast(list[str], get_records()[i].get("Folder", []) or []), path_parts)] result_folders = _subfolder_results(matching, path_parts, path_depth) direct_files = _direct_file_results(matching, path_depth, build_record_link, build_record_path_url) return {"folders": result_folders, "files": direct_files, "current_path": path}
def _subfolder_results(matching: Sequence[SearchRecord], path_parts: list[str], path_depth: int) -> list[SearchRecord]: subfolder_names: set[str] = set() subfolder_counts: dict[str, int] = {} for rec in matching: folders = cast(list[str], rec.get("Folder", []) or []) if len(folders) > path_depth: name = folders[path_depth] subfolder_names.add(name) subfolder_counts[name] = subfolder_counts.get(name, 0) + 1 result_folders: list[SearchRecord] = [] for fname in sorted(subfolder_names): full_path = "/".join(path_parts + [fname]) if path_parts else fname result_folders.append({"name": fname, "path": full_path, "count": subfolder_counts.get(fname, 0)}) return result_folders
def _direct_file_results(matching: Sequence[SearchRecord], path_depth: int, build_record_link: Callable[[SearchRecord], str], build_record_path_url: Callable[[SearchRecord], str]) -> list[SearchRecord]: direct_files: list[SearchRecord] = [] for rec in matching: folders = cast(list[str], rec.get("Folder", []) or []) if len(folders) == path_depth: direct_files.append({ "name": rec.get("File", ""), "ext": rec.get("Extension", ""), "link": rec.get("Link") or build_record_link(rec), "path": rec.get("Path") or build_record_path_url(rec), "hasTxt": rec.get("HasTxt", False), "size": rec.get("Size", ""), }) direct_files.sort(key=lambda f: cast(str, f["name"])) return direct_files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""Build search filter trees from a caller-owned index snapshot."""from __future__ import annotations
from collections.abc import Mapping, Sequencefrom typing import NotRequired, TypedDict, cast
class FolderTreeNode(TypedDict): name: str path: str children: list[FolderTreeNode] count: int hasDirectFiles: bool hasChildren: bool showSelfToggle: bool isRoot: NotRequired[bool]
def build_folder_tree(repo: str, folder_index: Mapping[str, Mapping[str, Sequence[int]]], repo_records_map: Mapping[str, Sequence[int]], records: Sequence[dict[str, object]]) -> list[FolderTreeNode]: """Preserve corpus counts, stable child order and direct-file toggles.""" if repo not in folder_index: return [] repo_name_short = repo.split("/")[-1] tree_root: FolderTreeNode = { "name": repo_name_short, "path": "", "children": [], "count": 0, "hasDirectFiles": False, "hasChildren": False, "showSelfToggle": False, "isRoot": True, } node_map: dict[str, FolderTreeNode] = {"": tree_root} for path, idx_list in folder_index[repo].items(): if path == "": tree_root["count"] = len(idx_list) continue parts = path.split("/") for depth in range(1, len(parts) + 1): key = "/".join(parts[:depth]) if key not in node_map: parent_key = "/".join(parts[:depth - 1]) if depth > 1 else "" parent = node_map[parent_key] node: FolderTreeNode = { "name": parts[depth - 1], "path": key, "children": [], "count": 0, "hasDirectFiles": False, "hasChildren": False, "showSelfToggle": False, } node_map[key] = node parent["children"].append(node) node_map[path]["count"] = len(idx_list) direct_file_dirs: set[str] = set() for idx in repo_records_map.get(repo, []): rec = records[idx] folders = cast(list[str], rec.get("Folder", []) or []) direct_file_dirs.add("/".join(folders)) for path_key, node in node_map.items(): node["hasDirectFiles"] = path_key in direct_file_dirs node["children"].sort(key=lambda child: child["name"]) node["hasChildren"] = len(node["children"]) > 0 node["showSelfToggle"] = bool(path_key and node["hasDirectFiles"] and node["hasChildren"]) return [tree_root]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""Decode the current compact corpus and directory formats without runtime state."""
from typing import TypedDict, cast
class CompactCorpus(TypedDict, total=False): rp: list[str] fd: list[list[str]] rc: list[object]
class CompactTreeNode(TypedDict, total=False): n: str c: int df: bool ch: list["CompactTreeNode"]
class CompactFolder(TypedDict, total=False): n: str c: int
class CompactFile(TypedDict, total=False): n: str e: str t: bool s: int | str
class CompactBrowserEntry(TypedDict, total=False): d: list[CompactFolder] f: list[CompactFile]
def decode_search_payload(data: object) -> list[dict[str, object]]: if not isinstance(data, dict): return [] compact = cast(CompactCorpus, data) repos = compact.get("rp", []) or [] folders = compact.get("fd", []) or [] records: list[dict[str, object]] = [] for raw_item in compact.get("rc", []) or []: if not isinstance(raw_item, list): continue item = cast(list[object], raw_item) if len(item) < 6: continue repo = repos[item[0]] if isinstance(item[0], int) and 0 <= item[0] < len(repos) else "" folder = folders[item[3]] if isinstance(item[3], int) and 0 <= item[3] < len(folders) else [] records.append({ "Repo": repo, "File": item[1], "Extension": item[2], "Folder": folder, "Size": item[4], "HasTxt": bool(item[5]), }) return records
def decode_tree_node(node: CompactTreeNode, parent_path: str = "", is_root: bool = False) -> dict[str, object]: name = node.get("n", "") path = "" if is_root else (f"{parent_path}/{name}" if parent_path else name) children = [decode_tree_node(child, path, False) for child in node.get("ch", [])] decoded: dict[str, object] = { "name": name, "path": path, "count": node.get("c", 0), "hasDirectFiles": node.get("df", False), "hasChildren": len(children) > 0, "showSelfToggle": bool(path and node.get("df", False) and len(children) > 0), "children": children, } if is_root: decoded["isRoot"] = True return decoded
def decode_folder_tree_data(data: dict[str, list[CompactTreeNode]] | None) -> dict[str, list[dict[str, object]]]: return {repo: [decode_tree_node(node, "", True) for node in nodes] for repo, nodes in (data or {}).items()}
def decode_browser_entry(entry: CompactBrowserEntry, current_path: str = "") -> dict[str, object]: return { "folders": [ { "name": item.get("n", ""), "path": f"{current_path}/{item.get('n', '')}" if current_path else item.get("n", ""), "count": item.get("c", 0), } for item in entry.get("d", []) ], "files": [ { "name": item.get("n", ""), "ext": item.get("e", ""), "hasTxt": item.get("t", False), "size": item.get("s", ""), } for item in entry.get("f", []) ], "current_path": current_path, }
def decode_folder_browser_data(data: dict[str, dict[str, CompactBrowserEntry]] | None) -> dict[str, dict[str, dict[str, object]]]: return {repo: {path: decode_browser_entry(entry, path) for path, entry in (browser or {}).items()} for repo, browser in (data or {}).items()}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"""Pure record paths and reader projections shared by search and reader APIs."""import posixpathimport refrom typing import castfrom urllib.parse import quote
READER_ASSET_MODES = { "p": "pdf", "e": "epub", "d": "docx", "h": "html", "t": "txt", "k": "md", "i": "webp", "a": "audio", "v": "video", "f": "swf",}READER_NATIVE_FOLIATE_EXTENSIONS = frozenset({"epub", "mobi", "azw", "azw3", "fb2"})
def build_record_relative_path(rec: dict[str, object]) -> str: file_name = cast(str, rec.get("File", "")) extension = cast(str, rec.get("Extension", "")) full_name = f"{file_name}.{extension}" if extension else file_name folders = cast(list[str], rec.get("Folder", []) or []) return posixpath.join(*folders, full_name) if folders else full_name
def build_reader_asset_key(rec: dict[str, object]) -> str: return f"{rec.get('Repo', '')}\0{build_record_relative_path(rec)}"
def dataset_file_url(repo: str, relative_path: str, action: str = "resolve") -> str: return f"https://huggingface.co/datasets/{repo}/{action}/main/{quote(relative_path, safe='/')}"
def dataset_file_urls(repo: str, relative_path: str) -> tuple[str, str]: """Produce source and browser URLs using the same encoded path.""" encoded = quote(relative_path, safe="/") prefix = f"https://huggingface.co/datasets/{repo}" return f"{prefix}/resolve/main/{encoded}", f"{prefix}/blob/main/{encoded}"
def build_record_link(rec: dict[str, object]) -> str: return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec))
def build_record_path_url(rec: dict[str, object]) -> str: return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec), "blob")
def build_browser_file_name(file_item: dict[str, object]) -> str: name = str(file_item.get("name", "") or "file") ext = str(file_item.get("ext", "") or "") # Browser metadata stores the source record's stem and last extension in # separate fields; a repeated suffix in the stem is still significant. if not ext: return name return f"{name}.{ext}"
def enrich_browser_entry(repo: str, path: str, entry: dict[str, object]) -> dict[str, object]: decoded = dict(entry or {}) decoded["current_path"] = decoded.get("current_path", path) folders: list[dict[str, object]] = [] for folder in cast(list[dict[str, object]], decoded.get("folders", []) or []): item = dict(folder) if "path" not in item: name = item.get("name", "") item["path"] = f"{path}/{name}" if path else name folders.append(item) files: list[dict[str, object]] = [] for file_item in cast(list[dict[str, object]], decoded.get("files", []) or []): item = dict(file_item) full_name = build_browser_file_name(item) rel_path = f"{path}/{full_name}" if path else full_name if not item.get("link") and not item.get("path"): item["link"], item["path"] = dataset_file_urls(repo, rel_path) else: item["link"] = item.get("link") or dataset_file_url(repo, rel_path) item["path"] = item.get("path") or dataset_file_url(repo, rel_path, "blob") files.append(item) decoded["folders"] = folders decoded["files"] = files return decoded
def reader_asset_url(asset: dict[str, object]) -> str: path = quote(str(asset.get("p") or ""), safe="/") return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + path
def reader_extension_for_asset(asset: dict[str, object], original_extension: str = "") -> str: asset_path = str(asset.get("p") or "") if asset.get('c'): return 'epub-chapters' if asset_path.endswith(("page-manifest.json", "reading-manifest.json")): return "image-pages" if asset.get("m") == "i" else "pdf-pages" if asset.get("m") == "e": match = re.search(r"/(?:document|book)\.(epub|mobi|azw|azw3|fb2)$", asset_path, re.IGNORECASE) if match: return match.group(1).lower() extension = str(original_extension or "").lower().lstrip(".") return extension if extension in READER_NATIVE_FOLIATE_EXTENSIONS else "epub" mode = asset.get("m") return READER_ASSET_MODES.get(mode, "") if isinstance(mode, str) else ""
def _reader_bucket_url(path: str) -> str: return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + quote(path, safe="/")
def reader_asset_fields(asset: dict[str, object], original_extension: str) -> dict[str, str]: ocr_path = str(asset.get("o") or "") ocr_bucket = asset.get("b") == "vomebook/pdf-pages-v2" or asset.get("ob") == "vomebook/pdf-pages-v2" fields: dict[str, str] = {} if ocr_path.endswith("/ocr-manifest.json") and ocr_bucket: fields["ocr_manifest"] = _reader_bucket_url(ocr_path) fields["ocr_mode"] = str(asset.get("om") or "") if asset.get("s") == 3: return fields if asset.get("s") != 2 or asset.get("m") not in READER_ASSET_MODES or not asset.get("p"): return fields if str(original_extension).lower().lstrip('.') == 'djvu': # Existing OCR remains independent. Native DjVu reading starts at the # dataset source, never an older image stream, manifest or derivative. return fields if (asset.get('m') == 'p' and not asset.get('c') and str(asset['p']).endswith('/page-manifest.json') and str(original_extension).lower().lstrip('.') != 'djvu'): # Legacy page indexes no longer own PDF/converted-PDF reading. Keep # independent OCR metadata and prefer the validated PDF companion. if asset.get('pd') and asset.get('pdb') in {'vomebook/reader-assets-v2', 'vomebook/pdf-pages-v2'}: fields.update(url=_reader_bucket_url(cast(str, asset['pd'])), extension='pdf') return fields fields.update({"url": reader_asset_url(asset), "extension": reader_extension_for_asset(asset, original_extension)}) if asset.get("pd") and asset.get("pdb") in {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}: fields["pdf_document"] = _reader_bucket_url(cast(str, asset["pd"])) if asset.get("c"): if asset.get("cb") == "vomebook/reader-assets-v2": fields["chapter_manifest"] = _reader_bucket_url(cast(str, asset["c"])) elif asset.get("cb") == "vomebook/pdf-pages-v2": fields["chapter_manifest"] = "/api/reader-bucket-resource?path=" + quote(cast(str, asset["c"]), safe="/") return fields
def enrich_reader_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]: result = dict(record) fields = reader_asset_fields(asset, cast(str, record.get("Extension", ""))) direct_modes = { "pdf": ("pdf", "pdf"), "djvu": ("djvu", "pdf"), "vcf": ("vcf", "text"), "ini": ("ini", "text"), "tif": ("image", "image"), "tiff": ("image", "image"), } direct_extension = str(record.get("Extension") or "").lower().lstrip(".") if 'url' not in fields and direct_extension in direct_modes: # A PDF without a converted/page asset remains directly readable from # its immutable source dataset after the derived asset store changes. fields.update(url=cast(str, record.get("Link") or build_record_link(record)), extension=direct_modes[direct_extension][0]) if fields: for source, target in (("url", "ReaderLink"), ("extension", "ReaderExtension"), ("chapter_manifest", "ReaderChapterManifest"), ("ocr_manifest", "ReaderOcrManifest"), ("ocr_mode", "ReaderOcrMode"), ("pdf_document", "ReaderPdfDocument")): if source in fields: result[target] = fields[source] result["DownloadLink"] = record.get("Link") or build_record_link(record) return result
def add_reader_assets(payload: dict[str, object], assets: dict[str, object]) -> dict[str, object]: files = cast(dict[str, dict[str, object]], assets.get("f", {})) return {**payload, "results": [ enrich_reader_record(record, files.get(build_reader_asset_key(record), {})) for record in cast(list[dict[str, object]], payload.get("results", [])) ]}
def reader_resolved_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]: source = record.get("Link") or build_record_link(record) extension = str(record.get("Extension") or "").lower().lstrip(".") repo = cast(str, record.get("Repo", "")).split("/")[-1] folders = [str(item) for item in cast(list[object], record.get("Folder", []))] return { "url": source, "download": source, "extension": extension, "original_extension": extension, "title": record.get("File") or record.get("Name") or "在线阅读", # Keep the exact indexed filename separate from the display title. # The stem may itself end in an extension, or include trailing spaces. "filename": build_record_relative_path(record).rsplit("/", 1)[-1], "path": "/".join([repo, *folders]), "folder": "/".join(folders), "repo": repo, **reader_asset_fields(asset, extension), }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Pure search token matching and word-index construction."""from collections.abc import Callable, Iterable, Mapping, Sequenceimport hashlibimport refrom typing import cast
def records_digest(records: Sequence[Mapping[str, object]]) -> bytes: digest = hashlib.sha256() for record in records: for value in (record.get("_file_lower", ""), record.get("_repo_lower", ""), record.get("_folder_path_lower", "")): digest.update(cast(str, value).encode("utf-8")) digest.update(b"\0") return digest.digest()
def tokenize(text: str, segment: Callable[[str], list[str]]) -> list[str]: tokens: list[str] = [] text_lower = text.lower() tokens.extend(re.findall(r"[a-z0-9]+", text_lower)) chinese_text = re.sub(r"[a-z0-9\s]+", " ", text_lower) chinese_text = re.sub(r"[^\u4e00-\u9fff\u3400-\u4dbf\s]+", " ", chinese_text) chinese_tokens = segment(chinese_text) tokens.extend([token.strip() for token in chinese_tokens if token.strip()]) chinese_token_set = set(chinese_tokens) for ch in text_lower: if "\u4e00" <= ch <= "\u9fff" or "\u3400" <= ch <= "\u4dbf": if ch not in chinese_token_set: tokens.append(ch) # Stable token order keeps rebuilt vocabularies reproducible across hash seeds. return list(dict.fromkeys(tokens))
def matches_file_token(record: Mapping[str, object], token: str) -> bool: return (token in cast(str, record.get("_full_file_lower", record.get("_file_lower", ""))) or token in cast(str, record.get("_repo_lower", "")))
def matches_file_query(record: Mapping[str, object], tokens: Iterable[str], fuzzy_tokens: set[str], *, tokenize_text: Callable[[str], list[str]], file_match: Callable[[Mapping[str, object], str], bool], fuzzy_match: Callable[[str, str], bool]) -> bool: file_tokens = tokenize_text(cast(str, record.get("_full_file_lower", record.get("_file_lower", "")))) if fuzzy_tokens else [] return all(file_match(record, token) or ( token in fuzzy_tokens and any(fuzzy_match(token, word) for word in file_tokens) ) for token in tokens)
def build_vocab_by_len(words: Iterable[str], vocab: dict[int, list[str]]) -> None: for word in words: vocab.setdefault(len(word), []).append(word) # Generated postings are sorted by term; rebuilt indexes must traverse the # same vocabulary regardless of insertion order or Python hash seed. for bucket in vocab.values(): bucket.sort()
def build_word_index(records: Sequence[Mapping[str, object]], index: dict[str, set[int]], tokenize_text: Callable[[str], list[str]]) -> None: for idx, record in enumerate(records): file_name = cast(str, record.get("File", "")) folders = cast(list[str], record.get("Folder", [])) for token in tokenize_text(" ".join([file_name] + folders)): index.setdefault(token, set()).add(idx)1"""search corpus infrastructure package."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205"""Readers for the generated word and n-gram posting files.
The generated formats are deliberately small and self-describing. Keepingtheir parsing independent from the FastAPI application makes malformed inputhandling testable without importing application state."""
import gzipfrom collections.abc import Iteratorfrom pathlib import Pathfrom typing import Literal, overload
try: import _search_index_native as _native_indexexcept ImportError: _native_index = None
_native_read_entries = getattr(_native_index, "read_entries", None)_native_decode_postings = getattr(_native_index, "decode_postings", None)
NGRAM_MAGIC = b"VNG3"WORD_INDEX_MAGIC = b"VWI2"WORD_INDEX_TOKENIZER = "jieba-0.42.1-cjk-char-v1"
PostingLocation = tuple[int, int, int]Posting = set[int] | PostingLocationPostingIndex = dict[str, Posting]
def decode_varint(data: bytes, offset: int) -> tuple[int, int]: value = 0 shift = 0 while offset < len(data): byte = data[offset] offset += 1 value |= (byte & 0x7F) << shift if not byte & 0x80: return value, offset shift += 7 raise ValueError("truncated varint")
def decode_postings(data: bytes | memoryview, record_count: int | None = None) -> set[int]: # Non-byte, strided, or mutable-backed buffers retain Python iteration semantics. if (_native_decode_postings is not None and record_count is None and (type(data) is bytes or (type(data) is memoryview and data.readonly and type(data.obj) is bytes and data.format == "B" and data.ndim == 1 and data.c_contiguous))): try: return _native_decode_postings(data) except OverflowError: # Python integers support valid varints and cumulative IDs wider than 64 bits. pass return _decode_postings_python(data, record_count)
def _decode_postings_python(data: bytes | memoryview, record_count: int | None = None) -> set[int]: record_ids: set[int] = set() previous = 0 value = shift = 0 for byte in data: value |= (byte & 0x7F) << shift if byte & 0x80: shift += 7 continue previous += value if record_count is not None and previous >= record_count: raise ValueError("posting record id out of range") record_ids.add(previous) value = shift = 0 if shift: raise ValueError("truncated varint") return record_ids
def _bounded_slice(data: bytes, offset: int, length: int) -> tuple[int, int]: end = offset + length if length < 0 or end < offset or end > len(data): raise ValueError("truncated postings") return offset, end
def _validate_postings(data: bytes, start: int, end: int, record_count: int) -> int: """Count distinct monotonic IDs without allocating a temporary posting set.""" previous = 0 last = -1 count = 0 value = shift = 0 for offset in range(start, end): byte = data[offset] value |= (byte & 0x7F) << shift if byte & 0x80: shift += 7 continue previous += value if previous >= record_count: raise ValueError("posting record id out of range") if previous != last: count += 1 last = previous value = shift = 0 if shift: raise ValueError("truncated varint") return count
def _read_posting_entries(data: bytes, offset: int, count: int, record_count: int, materialize: bool = True) -> Iterator[tuple[str, PostingLocation, set[int] | None]]: """Yield validated entries while leaving storage policy to each loader.""" for _ in range(count): key_length, offset = decode_varint(data, offset) key_start, offset = _bounded_slice(data, offset, key_length) key = data[key_start:offset].decode("utf-8") posting_count, offset = decode_varint(data, offset) posting_length, offset = decode_varint(data, offset) posting_start, offset = _bounded_slice(data, offset, posting_length) decoded = decode_postings(memoryview(data)[posting_start:offset], record_count) if materialize else None actual_count = len(decoded) if decoded is not None else _validate_postings(data, posting_start, offset, record_count) if actual_count != posting_count: raise ValueError("posting count mismatch") yield key, (posting_start, offset, posting_count), decoded if offset != len(data): raise ValueError("trailing postings")
def _load_posting_entries(data: bytes, offset: int, count: int, record_count: int, materialize: bool) -> PostingIndex: if _native_read_entries is not None: try: return _native_read_entries(data, offset, count, record_count, materialize) except OverflowError: # Retain arbitrary-width varint behavior for unusual valid inputs. pass if materialize: entries: PostingIndex = {} for key, _, decoded in _read_posting_entries(data, offset, count, record_count, True): if decoded is None: raise RuntimeError("materialized posting missing") entries[key] = decoded return entries return {key: location for key, location, _ in _read_posting_entries(data, offset, count, record_count, False)}
def load_ngram_index( path: Path, width: int, record_count: int, expected_digest: bytes,) -> tuple[PostingIndex, bytes]: try: data = gzip.decompress(path.read_bytes()) if not data.startswith(NGRAM_MAGIC) or len(data) < 37 or data[4] != width: return {}, b"" if data[5:37] != expected_digest: return {}, b"" offset = 37 stored_record_count, offset = decode_varint(data, offset) count, offset = decode_varint(data, offset) if stored_record_count != record_count: return {}, b"" postings = _load_posting_entries(data, offset, count, record_count, False) return postings, data except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError): return {}, b""
@overloaddef load_word_index(path: Path, record_count: int, expected_digest: bytes, materialize: Literal[False]) -> tuple[PostingIndex, bytes]: ...
@overloaddef load_word_index(path: Path, record_count: int, expected_digest: bytes, materialize: Literal[True] = True) -> PostingIndex: ...
def load_word_index(path: Path, record_count: int, expected_digest: bytes, materialize: bool = True) -> PostingIndex | tuple[PostingIndex, bytes]: try: data = gzip.decompress(path.read_bytes()) if not data.startswith(WORD_INDEX_MAGIC): return {} if materialize else ({}, b"") offset = len(WORD_INDEX_MAGIC) tokenizer_length, offset = decode_varint(data, offset) tokenizer_start, offset = _bounded_slice(data, offset, tokenizer_length) tokenizer = data[tokenizer_start:offset].decode("utf-8") digest_start, offset = _bounded_slice(data, offset, 32) if tokenizer != WORD_INDEX_TOKENIZER or data[digest_start:offset] != expected_digest: return {} if materialize else ({}, b"") stored_record_count, offset = decode_varint(data, offset) count, offset = decode_varint(data, offset) if stored_record_count != record_count: return {} if materialize else ({}, b"") entries = _load_posting_entries(data, offset, count, record_count, materialize) return entries if materialize else (entries, data) except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError): return {} if materialize else ({}, b"")
def resolve_postings(value: Posting | frozenset[int] | bytes | memoryview, buffer: bytes) -> set[int]: if isinstance(value, tuple): start, end, _ = value return decode_postings(memoryview(buffer)[start:end]) return set(value) if isinstance(value, (set, frozenset)) else decode_postings(value)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290"""Select a verified, immutable local search-data generation before startup.
The caller supplies the build-materialized directory. Selection is opt-in andall-or-nothing: hashes, lengths, path containment and gzip/JSON structure arechecked before any application paths are changed. This module never writes abucket pointer or downloads data and does not replace a running process's data."""from __future__ import annotations
import gzipimport hashlibimport jsonimport refrom dataclasses import dataclassfrom pathlib import Pathfrom typing import castfrom urllib.parse import quote
from backend.search.corpus.infrastructure.indexes import load_ngram_index, load_word_index
SHA = re.compile(r"[0-9a-f]{64}\Z")MANDATORY = frozenset({"search_data.json.gz", "folder_tree.json.gz", "folder_browser.json.gz", "search_words.bin.gz", "search_ngrams_2.bin.gz", "search_ngrams_3.bin.gz", "initial/global.json", "initial/manifest.json", "sidebar/global.json", "sidebar/manifest.json"})MAX_FILE = 32 * 1024 * 1024MAX_EXPANDED = 256 * 1024 * 1024MAX_FILES = 1024
def as_mapping(value: object, label: str) -> dict[str, object]: if not isinstance(value, dict): raise ValueError(f"{label} must be an object") mapping = cast(dict[object, object], value) if any(not isinstance(key, str) for key in mapping): raise ValueError(f"{label} keys must be strings") return cast(dict[str, object], mapping)
def as_list(value: object, label: str) -> list[object]: if not isinstance(value, list): raise ValueError(f"{label} must be an array") return cast(list[object], value)
def canonical(value: object) -> bytes: return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n").encode("utf-8")
def read_compressed_mapping(path: Path, label: str) -> dict[str, object]: """Bound expanded generated JSON before interpreting any directory data.""" try: with gzip.open(path, "rb") as stream: raw = stream.read(MAX_EXPANDED + 1) except (OSError, EOFError) as error: raise ValueError(f"invalid compressed {label}") from error if len(raw) > MAX_EXPANDED: raise ValueError(f"expanded {label} exceeds limit") try: return as_mapping(json.loads(raw), label) except (UnicodeDecodeError, json.JSONDecodeError) as error: raise ValueError(f"invalid {label} JSON") from error
def read_json_mapping(path: Path, label: str) -> dict[str, object]: try: return as_mapping(json.loads(path.read_bytes()), label) except (UnicodeDecodeError, json.JSONDecodeError) as error: raise ValueError(f"invalid {label} JSON") from error
def append_bootstrap_record(global_prefix: list[dict[str, object]], repo_prefix: list[dict[str, object]], record: dict[str, object]) -> None: """Keep bounded prefixes; avoid retaining every decoded corpus record.""" if len(global_prefix) < 500: global_prefix.append(record) if len(repo_prefix) < 500: repo_prefix.append(record)
def validate_directory_data(root: Path, repos: list[str]) -> dict[str, dict[str, object]]: tree = read_compressed_mapping(root / "folder_tree.json.gz", "Space folder tree") browser = read_compressed_mapping(root / "folder_browser.json.gz", "Space folder browser") if set(tree) != set(repos) or set(browser) != set(repos): raise ValueError("Space directory repositories mismatch") roots: dict[str, dict[str, object]] = {} for repo in repos: nodes = as_list(tree[repo], "Space folder roots") pending = list(nodes) while pending: node = as_mapping(pending.pop(), "Space folder node") if not isinstance(node.get("n"), str) or type(node.get("c")) is not int or cast(int, node["c"]) < 0: raise ValueError("invalid Space folder node") if not isinstance(node.get("df"), bool): raise ValueError("invalid Space folder node") pending.extend(as_list(node.get("ch"), "Space folder children")) paths = as_mapping(browser[repo], "Space folder browser paths") if "" not in paths: raise ValueError("Space folder browser root missing") for path, value in paths.items(): entry = as_mapping(value, "Space folder browser entry") for folder in as_list(entry.get("d"), "Space folder browser folders"): item = as_mapping(folder, "Space folder browser folder") if not isinstance(item.get("n"), str) or type(item.get("c")) is not int or cast(int, item["c"]) < 0: raise ValueError("invalid Space folder browser folder") for file in as_list(entry.get("f"), "Space folder browser files"): item = as_mapping(file, "Space folder browser file") if (not isinstance(item.get("n"), str) or not isinstance(item.get("e"), str) or not isinstance(item.get("t"), bool) or not isinstance(item.get("s"), (int, str)) or isinstance(item.get("s"), bool)): raise ValueError("invalid Space folder browser file") if path == "": roots[repo] = entry return roots
def safe_name(name: object) -> bool: if (not isinstance(name, str) or not name or name.startswith("/") or "\\" in name or any(part in {"", ".", ".."} for part in name.split("/")) or any(ord(char) < 32 or ord(char) == 127 for char in name)): return False return name in MANDATORY or bool(re.fullmatch(r"(?:initial|sidebar)/repos/[^/]+\.json", name))
@dataclass(frozen=True)class SelectedGeneration: generation: str directory: Path file_count: int record_count: int
def inspect_generation(directory: Path, generation: str) -> SelectedGeneration: """Verify every advertised Space member and return the immutable selection.""" if not SHA.fullmatch(generation): raise ValueError("invalid search generation identity") if directory.is_symlink() or not directory.is_dir(): raise ValueError("generation directory must be an ordinary directory") root = directory.resolve() report_file = root / "generation-manifest.json" if report_file.is_symlink() or not report_file.is_file() or report_file.stat().st_size > 1024 * 1024: raise ValueError("missing or oversized local generation manifest") raw_manifest = report_file.read_bytes() manifest = as_mapping(json.loads(raw_manifest), "search generation manifest") if (manifest.get("version") != 1 or manifest.get("kind") != "search-snapshot-local" or manifest.get("generation") != generation or manifest.get("object_layout") != "objects/sha256/<first-two>/<sha256>"): raise ValueError("invalid search generation manifest") excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"} identity = {key: value for key, value in manifest.items() if key not in excluded} if hashlib.sha256(canonical(identity)).hexdigest() != generation: raise ValueError("search manifest identity mismatch") objects = as_mapping(manifest.get("objects"), "generation objects") files = as_mapping(manifest.get("files"), "generation files") entries = as_mapping(objects.get("space"), "Space objects") original = as_mapping(files.get("space"), "Space files") if set(entries) != set(original): raise ValueError("Space manifest member mismatch") actual: set[str] = set() for path in root.rglob("*"): if path.is_symlink(): raise ValueError("symlinks are forbidden in generation files") if path.is_file() and path != report_file: actual.add(path.relative_to(root).as_posix()) elif not path.is_dir() and path != report_file: raise ValueError("generation contains a non-file object") if actual != set(entries): raise ValueError("Space generation contains missing or unlisted files") if not MANDATORY <= set(entries) or len(entries) > MAX_FILES: raise ValueError("Space generation is incomplete") for name, item in entries.items(): if not safe_name(name): raise ValueError("invalid Space member") metadata = as_mapping(item, "Space member metadata") original_metadata = as_mapping(original[name], "original Space member metadata") digest, size = metadata.get("sha256"), metadata.get("bytes") if (not isinstance(digest, str) or not SHA.fullmatch(digest) or type(size) is not int or not 1 <= size <= MAX_FILE or original_metadata != {"sha256": digest, "bytes": size} or metadata.get("object") != f"objects/sha256/{digest[:2]}/{digest}"): raise ValueError("Space member identity mismatch") path = root.joinpath(*name.split("/")) if not path.is_file() or root not in path.resolve().parents or path.stat().st_size != size: raise ValueError("Space member missing or wrong size") if hashlib.sha256(path.read_bytes()).hexdigest() != digest: raise ValueError("Space member digest mismatch") corpus_path = root / "search_data.json.gz" with gzip.open(corpus_path, "rb") as stream: decoded = stream.read(MAX_EXPANDED + 1) if len(decoded) > MAX_EXPANDED: raise ValueError("expanded search corpus exceeds limit") corpus = as_mapping(json.loads(decoded), "Space corpus") rows = as_list(corpus.get("rc"), "Space corpus records") if corpus.get("v") != 2 or len(rows) != manifest.get("record_count") or not rows: raise ValueError("Space corpus record count mismatch") # Index files are not allowed to silently degrade into an empty/rebuilt # index when the selected generation is loaded by the actual application. repos = as_list(corpus.get("rp"), "Space corpus repositories") folders = as_list(corpus.get("fd"), "Space corpus folders") if (not repos or any(not isinstance(repo, str) or not re.fullmatch(r"VoiceOfML/[A-Za-z0-9._-]+", repo) for repo in repos)): raise ValueError("invalid Space corpus repository dictionary") repo_names = cast(list[str], repos) if len(set(repo_names)) != len(repo_names) or len({repo.split("/")[-1] for repo in repo_names}) != len(repo_names): raise ValueError("duplicate Space corpus repository") folder_names: list[list[str]] = [] for value in folders: folder = as_list(value, "Space corpus folder") if any(not isinstance(part, str) for part in folder): raise ValueError("invalid Space corpus folder") folder_names.append(cast(list[str], folder)) digest_builder = hashlib.sha256() # Bootstrap pages contain at most 500 rows; retain only those prefixes and # counts rather than materializing another complete Python corpus. repo_prefixes: dict[str, list[dict[str, object]]] = {repo: [] for repo in repo_names} repo_counts = dict.fromkeys(repo_names, 0) global_prefix: list[dict[str, object]] = [] for row in rows: item = as_list(row, "Space corpus record") if (len(item) != 6 or type(item[0]) is not int or not 0 <= item[0] < len(repo_names) or not isinstance(item[1], str) or not isinstance(item[2], str) or type(item[3]) is not int or not 0 <= item[3] < len(folder_names) or type(item[5]) is not int or item[5] not in (0, 1)): raise ValueError("invalid Space corpus record") if not isinstance(item[4], (int, str)) or isinstance(item[4], bool): raise ValueError("invalid Space corpus record size") repo = repo_names[item[0]] repo_counts[repo] += 1 if len(global_prefix) < 500 or len(repo_prefixes[repo]) < 500: record: dict[str, object] = {"Repo": repo, "File": item[1], "Extension": item[2], "Folder": folder_names[item[3]], "Size": item[4], "HasTxt": bool(item[5])} append_bootstrap_record(global_prefix, repo_prefixes[repo], record) for text in (item[1], repo_names[item[0]], "/".join(folder_names[item[3]])): digest_builder.update(text.lower().encode("utf-8")) digest_builder.update(b"\0") browser_roots = validate_directory_data(root, repo_names) digest = digest_builder.digest() words, _ = load_word_index(root / "search_words.bin.gz", len(rows), digest, materialize=False) if not words: raise ValueError("Space word index is missing, invalid or empty") for width in (2, 3): grams, _ = load_ngram_index(root / f"search_ngrams_{width}.bin.gz", width, len(rows), digest) if not grams: raise ValueError(f"Space {width}-gram index is missing, invalid or empty") for family in ("initial", "sidebar"): listing = read_json_mapping(root / family / "manifest.json", "Space bootstrap manifest") urls = as_list(listing.get("urls"), "Space bootstrap URLs") if not urls: raise ValueError("invalid Space bootstrap manifest") prefix = f"/data/{family}/" listed: set[str] = set() for url in urls: if not isinstance(url, str) or not url.startswith(prefix): raise ValueError("invalid Space bootstrap URL") name = f"{family}/" + url[len(prefix):] if not safe_name(name) or name not in entries or name in listed or name.endswith("/manifest.json"): raise ValueError("missing or duplicated Space bootstrap member") listed.add(name) expected = {name for name in entries if name == f"{family}/global.json" or name.startswith(f"{family}/repos/")} wanted = {f"{family}/global.json"} | { f"{family}/repos/{quote(repo.split('/')[-1], safe='')}.json" for repo in repo_names} if listed != expected or listed != wanted: raise ValueError("Space bootstrap manifest does not cover its members") for repo in [None, *repo_names]: name = "initial/global.json" if repo is None else f"initial/repos/{quote(repo.split('/')[-1], safe='')}.json" payload = read_json_mapping(root / name, "Space initial payload") expected_records = global_prefix if repo is None else repo_prefixes[repo] expected_total = len(rows) if repo is None else repo_counts[repo] page_size = payload.get("page_size") if (payload.get("version") != 2 or payload.get("mode") != ("global" if repo is None else "repo") or payload.get("repo") != repo or payload.get("sort") != "relevance" or payload.get("page") != 1 or type(page_size) is not int or not 1 <= page_size <= 500 or payload.get("total") != expected_total or payload.get("results") != expected_records[:page_size]): raise ValueError("Space initial payload does not match corpus") sidebar = read_json_mapping(root / "sidebar/global.json", "Space sidebar payload") repo_summaries = as_list(sidebar.get("repos"), "Space sidebar repositories") expected_summaries = [{"name": repo, "count": repo_counts[repo]} for repo in sorted(repo_names)] if repo_summaries != expected_summaries: raise ValueError("Space sidebar repositories do not match corpus") for repo in repo_names: name = f"sidebar/repos/{quote(repo.split('/')[-1], safe='')}.json" payload = read_json_mapping(root / name, "Space sidebar repository") root_entry = browser_roots[repo] if (payload.get("repo") != repo or payload.get("path") != "" or payload.get("folders") != root_entry.get("d") or payload.get("files") != root_entry.get("f")): raise ValueError("invalid Space sidebar repository") return SelectedGeneration(generation=generation, directory=root, file_count=len(entries), record_count=len(rows))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Plan empty-query browsing against caller-owned search indexes."""from __future__ import annotations
from collections.abc import Callable, Sequence
Size = int | float | NonePaths = Sequence[str] | NoneRecordFilter = Callable[[Sequence[int], Paths, Paths, Paths, Size, Size, str], list[int]]MixedRecordFilter = Callable[[Sequence[int], Paths, Paths, Size, Size], list[int]]MixedFilter = Callable[[Sequence[int], Paths, Paths], Sequence[int]]MixedCandidates = Callable[[Paths, Paths, Paths], list[int] | None]
def browse_order(repos: Paths, extensions: Paths, folders: Paths, min_size: Size, max_size: Size, folder_match_mode: str, folder_selfs: Paths, folder_subtrees: Paths, sort: str, *, get_precomputed: Callable[[Paths, str], Sequence[int]], get_mixed_candidates: MixedCandidates, get_initial: Callable[[Paths], Sequence[int]], filter_mixed: MixedFilter, filter_records: RecordFilter, filter_mixed_records: MixedRecordFilter, key_name: Callable[[int], str], key_size: Callable[[int], tuple[int | float, str]]) -> Sequence[int]: """Preserve precomputed order identity or filter a bounded corpus snapshot.""" has_filters = (extensions or folders or min_size is not None or max_size is not None or folder_match_mode == "mixed") if not has_filters and (not repos or len(repos) == 1): return get_precomputed(repos, sort) filtered = _filtered_order(repos, extensions, folders, min_size, max_size, folder_match_mode, folder_selfs, folder_subtrees, get_mixed_candidates, get_initial, filter_mixed, filter_records, filter_mixed_records) if sort == "name": filtered.sort(key=key_name) elif sort == "size": filtered.sort(key=key_size) return filtered
def _filtered_order(repos: Paths, extensions: Paths, folders: Paths, min_size: Size, max_size: Size, folder_match_mode: str, folder_selfs: Paths, folder_subtrees: Paths, get_mixed_candidates: MixedCandidates, get_initial: Callable[[Paths], Sequence[int]], filter_mixed: MixedFilter, filter_records: RecordFilter, filter_mixed_records: MixedRecordFilter) -> list[int]: if folder_match_mode == "mixed": indices = get_mixed_candidates(repos, folder_selfs, folder_subtrees) if indices is None: indices = get_initial(repos) mixed = filter_mixed(indices, folder_selfs, folder_subtrees) return filter_mixed_records(mixed, repos, extensions, min_size, max_size) indices = get_initial(repos) return filter_records(indices, repos, extensions, folders, min_size, max_size, folder_match_mode)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Typed literal n-gram candidate selection over caller-owned search state."""from __future__ import annotations
from collections.abc import Callable, Iterable, Mapping, Sequenceimport refrom backend.search.corpus.infrastructure.indexes import Posting, PostingIndex
PostingResolver = Callable[[Posting, bytes], set[int]]
def wildcard_literal_candidates(query: str, repos: Iterable[str] | None, get_candidates: Callable[[str, Iterable[str] | None], set[int] | None], get_scope: Callable[[Iterable[str] | None], Sequence[int]]) -> list[int]: """Bound wildcard search by a safe mandatory CJK, digit or ASCII run.
Python IGNORECASE additionally equates i, k and s to non-ASCII characters; those letters are deliberately excluded. The selected safe run is guaranteed by any match, while the wildcard matcher still verifies every candidate. """ chunks = re.findall(r"[\u3400-\u4DBF\u4E00-\u9FFF0-9a-hjl-rt-zA-HJL-RT-Z]{2,}", query) # Prefer an available non-ASCII run even when a longer format suffix is # present: common extensions can otherwise expand tens of thousands of IDs. native = [chunk for chunk in chunks if any(ord(char) > 127 for char in chunk)] selected = native or chunks candidates = get_candidates(max(selected, key=len).lower(), repos) if selected else None return sorted(get_scope(repos) if candidates is None else candidates)
def literal_candidates(query: str, repos: Iterable[str] | None, get_postings: Callable[[], Mapping[int, PostingIndex]], get_buffers: Callable[[], Mapping[int, bytes]], get_repos: Callable[[], Mapping[str, Sequence[int]]], get_records: Callable[[], Sequence[dict[str, object]]], get_resolver: Callable[[], PostingResolver]) -> set[int] | None: """Return an exact posting intersection, or None when no index is usable.
Index records, repository lists and published postings remain caller-owned. The first decoded posting is owned by the resolver and may be narrowed in place exactly as before; no state is cached or published by this helper. """ width = 3 if len(query) >= 3 and get_postings().get(3) else 2 postings = get_postings().get(width) if not postings or len(query) < width: return None entries: list[Posting] = [] for gram in dict.fromkeys(query[index:index + width] for index in range(len(query) - width + 1)): encoded = postings.get(gram) if encoded is None: return set() entries.append(encoded) entries.sort(key=lambda entry: entry[2] if isinstance(entry, tuple) else len(entry)) candidates: set[int] | None = None repo_scope = set(repos) if repos else None for encoded in entries: matches = get_resolver()(encoded, get_buffers().get(width, b"")) if candidates is None: candidates = matches if repo_scope is not None: if len(candidates) <= 2048 and sum( len(get_repos().get(repo, ())) for repo in repo_scope) > len(candidates) * 8: candidates = {idx for idx in candidates if 0 <= idx < len(get_records()) and get_records()[idx].get("Repo", "") in repo_scope} else: allowed: set[int] = set() for repo in repo_scope: allowed.update(get_repos().get(repo, [])) candidates.intersection_update(allowed) else: candidates.intersection_update(matches) if not candidates: return set() return candidates or set()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""Typed search record filters over a caller-owned corpus snapshot."""from __future__ import annotations
from collections.abc import Iterable, Mapping, Sequencefrom typing import cast
SearchRecord = dict[str, object]FolderIndex = Mapping[str, Mapping[str, Sequence[int]]]RepoIndex = Mapping[str, Sequence[int]]
def score_record(record: SearchRecord, query_tokens: Iterable[str], search_folders: bool = True) -> int: score = 0 file_name = cast(str, record.get("_file_lower", "")) repo = cast(str, record.get("_repo_lower", "")) folder_text = cast(str, record.get("_folder_text", "")) for token in query_tokens: if token in file_name: score += 3 if search_folders and token in folder_text: score += 2 if token in repo: score += 1 return score
def apply_filters(records: Sequence[SearchRecord], indices: Iterable[int], repos: Sequence[str] | None = None, extensions: Sequence[str] | None = None, folders: Sequence[str] | None = None, min_size: int | float | None = None, max_size: int | float | None = None, folder_match_mode: str = "prefix") -> list[int]: repos_set = set(repos) if repos else None extensions_lower = {extension.lower() for extension in extensions} if extensions else None folder_set = {folder.strip("/") for folder in folders} if folders else None if folder_match_mode != "exact" and folder_set and "" in folder_set: # Unlike the Worker, an empty API prefix includes the complete scope. folder_set = None folder_prefix = next(iter(folder_set)) + "/" if folder_set and len(folder_set) == 1 and folder_match_mode != "exact" else None result: list[int] = [] for idx in indices: record = records[idx] if repos_set and record.get("Repo") not in repos_set: continue if extensions_lower and record.get("_ext_lower", "") not in extensions_lower: continue rec_path = "" if folder_set: rec_path = (cast(str, record["_folder_path"]) if "_folder_path" in record else "/".join(cast(list[str], record.get("Folder", []) or []))) matched = rec_path in folder_set if not matched and folder_match_mode != "exact": if folder_prefix is not None: matched = rec_path.startswith(folder_prefix) else: end = rec_path.rfind("/") while end > 0: if rec_path[:end] in folder_set: matched = True break end = rec_path.rfind("/", 0, end) if not matched: continue size = record.get("Size") if size and isinstance(size, (int, float)) and size > 0: if min_size is not None and size < min_size: continue if max_size is not None and size > max_size: continue result.append(idx) return result
def apply_mixed_folder_filters(records: Sequence[SearchRecord], indices: Sequence[int], self_folders: Sequence[str] | None = None, subtree_folders: Sequence[str] | None = None) -> Sequence[int]: self_set = {str(path).strip("/") for path in (self_folders or [])} subtree_set = {str(path).strip("/") for path in (subtree_folders or []) if str(path).strip("/")} if not self_set and not subtree_set: return indices result: list[int] = [] for idx in indices: rec_folders = cast(list[str], records[idx].get("Folder", []) or []) rec_path = "/".join(rec_folders) if rec_path in self_set: result.append(idx) continue if not subtree_set: continue if rec_path in subtree_set: result.append(idx) continue matched = False prefix = "" for depth, part in enumerate(rec_folders): # A slash may itself be part of a folder component; only actual # component boundaries are eligible subtree matches. prefix = part if depth == 0 else prefix + "/" + part if prefix in subtree_set: matched = True break if matched: result.append(idx) return result
def mixed_folder_index_candidates(records: Sequence[SearchRecord], folder_index: FolderIndex, repo_records_map: RepoIndex, repos: Sequence[str] | None, self_folders: Sequence[str] | None = None, subtree_folders: Sequence[str] | None = None) -> list[int] | None: """Return a bounded corpus-ordered superset, or None to retain a full scan.""" if len(self_folders or ()) + len(subtree_folders or ()) > 64: return None paths = {str(path).strip("/") for path in (self_folders or [])} paths.update(str(path).strip("/") for path in (subtree_folders or []) if str(path).strip("/")) if not paths: return None selected_repos = sorted(set(repos)) if repos else list(repo_records_map) scope_size = sum(len(repo_records_map.get(repo, ())) for repo in selected_repos) if repos else len(records) # Broad selections fall back rather than allocating an unbounded set. limit = min(32768, max(64, scope_size // 2)) postings: list[Sequence[int]] = [] estimated = 0 for repo in selected_repos: folders = folder_index.get(repo, {}) for path in paths: indices = folders.get(path, ()) estimated += len(indices) if estimated > limit: return None if indices: postings.append(indices) candidates: set[int] = set() for indices in postings: candidates.update(indices) return sorted(candidates)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179"""Bounded exact, wildcard and fuzzy search matching."""from collections.abc import Callableimport re
def compile_exact_matcher(query: str) -> Callable[[str], bool]: if "*" not in query and "?" not in query: lower = query.lower() return lambda text: lower in text.lower() if not query.strip("*"): # An unanchored sequence of stars matches the empty substring. return lambda _text: True if "*" in query and "?" in query and not query.strip("*?"): # Stars may match nothing; each question consumes a non-LF code point. required = query.count("?")
def matches_question_run(text: str) -> bool: start = 0 while start < len(text): end = text.find("\n", start) if end < 0: end = len(text) if end - start >= required: return True start = max(start, end) + 1 return False
return matches_question_run if "*" not in query: # Escaped fixed-width literals and dots need no variable-length regex # repetition, retaining IGNORECASE and dot's LF behavior. fixed = re.compile("".join("." if char == "?" else re.escape(char) for char in query), re.IGNORECASE) if len(query) < 128 or not any(char != "?" for char in query): return lambda text: fixed.search(text) is not None literals = [re.compile(re.escape(char), re.IGNORECASE) for char in dict.fromkeys(query) if char != "?"] return lambda text: ((len(text) <= 4096 or all(literal.search(text) for literal in literals)) and fixed.search(text) is not None) # In substring matching, stars at either boundary can match zero chars. # Keep Unicode IGNORECASE behavior, unlike the literal .lower() branch. core = query.strip("*") if core and "*" not in core and "?" not in core: literal = re.compile(re.escape(core), re.IGNORECASE) return lambda text: literal.search(text) is not None if "*" in core and "?" not in core and "\n" not in core: # A leftmost match for each mandatory chunk leaves the most room for # later chunks. Wildcard dots cannot cross LF in Python's regex rules. chunks = [re.compile(re.escape(part), re.IGNORECASE) for part in re.split(r"\*+", core)]
def matches_chunks(text: str) -> bool: for line in text.split("\n"): position = 0 for chunk in chunks: match = chunk.search(line, position) if match is None: break position = match.end() else: return True return False
return matches_chunks # A leading/trailing wildcard run followed/preceded by a fixed literal # has only one variable-width part. Strip its boundary stars: they can # always match zero characters in an unanchored search. The remaining # questions have fixed width and therefore cannot backtrack exponentially. core_parts = core.split("*") nonempty_parts = [part for part in core_parts if part] if len(nonempty_parts) == 2: first, last = nonempty_parts first_questions = first and not first.strip("?") and "?" not in last last_questions = last and not last.strip("?") and "?" not in first if first_questions or last_questions: fixed = first + last expression = re.compile("".join("." if char == "?" else re.escape(char) for char in fixed), re.IGNORECASE) if len(fixed) >= 128: literals = [re.compile(re.escape(char), re.IGNORECASE) for char in dict.fromkeys(fixed) if char != "?"] return lambda text: ((len(text) <= 4096 or all(literal.search(text) for literal in literals)) and expression.search(text) is not None) return lambda text: expression.search(text) is not None # Bitset NFA: each bit is a pattern position. Collapse adjacent stars so # epsilon closure needs one shift. No input can cause regex backtracking. pattern = re.sub(r"\*+", "*", query) stars = questions = 0 literal_bits: dict[str, int] = {} for index, char in enumerate(pattern): bit = 1 << index if char == "*": stars |= bit elif char == "?": questions |= bit else: literal_bits[char] = literal_bits.get(char, 0) | bit # Single-character regexes retain Python IGNORECASE's Unicode semantics. literals = [(re.compile(re.escape(char), re.IGNORECASE), bits) for char, bits in literal_bits.items()] masks: dict[str, int] = {} end = 1 << len(pattern) start = 1 | ((1 & stars) << 1)
def matches(text: str) -> bool: # Every literal is mandatory; C-level scans reject unrelated fields early. if any(regex.search(text) is None for regex, _ in literals): return False active = start for char in text: mask = masks.get(char) if mask is None: mask = sum(bits for regex, bits in literals if regex.fullmatch(char)) if len(masks) >= 512: masks.clear() masks[char] = mask wildcard = char != "\n" active = ((active & (mask | (questions if wildcard else 0))) << 1) | ( active & stars if wildcard else 0) | 1 active |= (active & stars) << 1 if active & end: return True return False return matches
def matches_exact_query(text: str, query: str) -> bool: return compile_exact_matcher(query)(text)
def split_exact_terms(query: str) -> list[str]: """Whitespace separates literal terms; each term must match independently.""" return [term for term in query.split() if term]
def edit_distance(s1: str, s2: str, max_dist: int = 2) -> int: if abs(len(s1) - len(s2)) > max_dist: return 999 prev = list(range(len(s2) + 1)) for i, c1 in enumerate(s1): curr = [i + 1] for j, c2 in enumerate(s2): cost = 0 if c1 == c2 else 1 curr.append(min(prev[j + 1] + 1, curr[j] + 1, prev[j] + cost)) if min(curr) > max_dist: return 999 prev = curr return prev[-1]
def could_be_fuzzy(tok: str, word: str, max_dist: int = 2) -> bool: if abs(len(tok) - len(word)) > max_dist: return False if len(tok) < 4: return True counts: dict[str, int] = {} for ch in tok: counts[ch] = counts.get(ch, 0) + 1 diff = 0 for ch in word: if counts.get(ch, 0) > 0: counts[ch] -= 1 else: diff += 1 if diff > 2 * max_dist: return False for remaining in counts.values(): diff += remaining if diff > 2 * max_dist: return False return True
def fuzzy_distance_budget(token: str) -> int: """Short tokens cannot tolerate the same edit radius as longer words.""" if len(token) <= 1: return 0 return 1 if len(token) <= 3 else 2
def is_fuzzy_match(token: str, word: str) -> bool: limit = fuzzy_distance_budget(token) return could_be_fuzzy(token, word, limit) and edit_distance(token, word, max_dist=limit) <= limit9 unmodified lines10111213141516179 unmodified linesfrom dataclasses import dataclassfrom typing import Protocol, TypedDict, castfrom backend.search_browse import MixedCandidates, MixedFilter, MixedRecordFilter, RecordFilter as BrowseRecordFilterfrom backend.search_indexes import PostingRecord = dict[str, object]Paths = Sequence[str] | None9 unmodified lines10111213141516179 unmodified linesfrom dataclasses import dataclassfrom typing import Protocol, TypedDict, castfrom backend.search.domain.browse import MixedCandidates, MixedFilter, MixedRecordFilter, RecordFilter as BrowseRecordFilterfrom backend.search.corpus.infrastructure.indexes import PostingRecord = dict[str, object]Paths = Sequence[str] | None
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""Word and fuzzy candidate selection for a single search term."""from __future__ import annotations
from collections.abc import Callable, Mapping, Sequencefrom typing import cast
from backend.search.infrastructure.executor import check_search_cancelled
SearchRecord = dict[str, object]
def term_candidates(term: str, query_token_count: int, posting_cache: dict[str, set[int]], search_folders: bool, *, tokenize: Callable[[str], list[str]], scoped_word_postings: Callable[[str, bool], set[int]], get_word_index: Callable[[], Mapping[str, object]], get_records: Callable[[], Sequence[SearchRecord]], get_vocab: Callable[[], Mapping[int, list[str]]], is_fuzzy_match: Callable[[str, str], bool]) -> tuple[set[int], set[str]]: """Intersect term postings without truncating before record filters.""" query_tokens = tokenize(term) return candidates_for_tokens(query_tokens, query_token_count, posting_cache, search_folders, tokenize=tokenize, scoped_word_postings=scoped_word_postings, get_word_index=get_word_index, get_records=get_records, get_vocab=get_vocab, is_fuzzy_match=is_fuzzy_match)
def candidates_for_tokens(query_tokens: Sequence[str], query_token_count: int, posting_cache: dict[str, set[int]], search_folders: bool, *, tokenize: Callable[[str], list[str]], scoped_word_postings: Callable[[str, bool], set[int]], get_word_index: Callable[[], Mapping[str, object]], get_records: Callable[[], Sequence[SearchRecord]], get_vocab: Callable[[], Mapping[int, list[str]]], is_fuzzy_match: Callable[[str, str], bool]) -> tuple[set[int], set[str]]: """Resolve already-tokenized input without repeating tokenization.""" # Candidate caps before repository and record filtering can lose valid hits. fuzzy_candidate_limit = None fuzzy_tokens: set[str] = set()
def query_postings(token: str) -> set[int]: if token not in posting_cache: posting_cache[token] = scoped_word_postings(token, search_folders) return posting_cache[token]
exact_constraint = _exact_constraint(query_tokens, get_word_index, query_postings) token_candidates: list[set[int]] = [] for tok in query_tokens: check_search_cancelled() candidates: set[int] = query_postings(tok) if tok in get_word_index() else set() if not candidates: fuzzy_tokens.add(tok) candidates = _fuzzy_candidates(tok, exact_constraint, fuzzy_candidate_limit, search_folders, get_records, get_vocab, tokenize, is_fuzzy_match, query_postings) if not candidates: return set(), fuzzy_tokens token_candidates.append(candidates) return _intersect_candidates(token_candidates), fuzzy_tokens
def _exact_constraint(query_tokens: Sequence[str], get_word_index: Callable[[], Mapping[str, object]], query_postings: Callable[[str], set[int]]) -> set[int] | None: exact_constraint: set[int] | None = None for tok in query_tokens: if tok not in get_word_index(): continue postings = query_postings(tok) if not postings: continue exact_constraint = set(postings) if exact_constraint is None else exact_constraint.intersection(postings) return exact_constraint
def _intersect_candidates(token_candidates: list[set[int]]) -> set[int]: if not token_candidates: return set() token_candidates.sort(key=len) matched = set(token_candidates[0]) for candidates in token_candidates[1:]: matched.intersection_update(candidates) if not matched: break return matched
def _fuzzy_candidates(tok: str, exact_constraint: set[int] | None, limit: int | None, search_folders: bool, get_records: Callable[[], Sequence[SearchRecord]], get_vocab: Callable[[], Mapping[int, list[str]]], tokenize: Callable[[str], list[str]], is_fuzzy_match: Callable[[str, str], bool], query_postings: Callable[[str], set[int]]) -> set[int]: if exact_constraint is not None: return _fuzzy_record_candidates(tok, exact_constraint, limit, search_folders, get_records, tokenize, is_fuzzy_match) return _fuzzy_vocabulary_candidates(tok, limit, get_vocab, is_fuzzy_match, query_postings)
def _fuzzy_record_candidates(tok: str, exact_constraint: set[int], limit: int | None, search_folders: bool, get_records: Callable[[], Sequence[SearchRecord]], tokenize: Callable[[str], list[str]], is_fuzzy_match: Callable[[str, str], bool]) -> set[int]: candidates: set[int] = set() for offset, idx in enumerate(sorted(exact_constraint)): if offset % 256 == 0: check_search_cancelled() rec = get_records()[idx] record_tokens = tokenize(" ".join([cast(str, rec.get("File", "")), *(cast(list[str], rec.get("Folder", []) or []) if search_folders else [])])) if any(is_fuzzy_match(tok, word) for word in record_tokens): candidates.add(idx) if limit is not None and len(candidates) >= limit: break return candidates
def _fuzzy_vocabulary_candidates(tok: str, limit: int | None, get_vocab: Callable[[], Mapping[int, list[str]]], is_fuzzy_match: Callable[[str, str], bool], query_postings: Callable[[str], set[int]]) -> set[int]: candidates: set[int] = set() tok_len = len(tok) for delta in (-2, -1, 0, 1, 2): for offset, vocab_word in enumerate(get_vocab().get(tok_len + delta, [])): if offset % 256 == 0: check_search_cancelled() if is_fuzzy_match(tok, vocab_word): candidates.update(query_postings(vocab_word)) if limit is not None and len(candidates) >= limit: break if limit is not None and len(candidates) >= limit: break return candidates12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Bound search uploads before JSON parsing; leave application failures untouched."""import asyncio
from starlette.responses import Responsefrom starlette.types import ASGIApp, Message, Receive, Scope, Send
SEARCH_BODY_MAX_BYTES = 8 * 1024 * 1024SEARCH_BODY_TIMEOUT_SECONDS = 15.0
class SearchBodyLimitMiddleware: def __init__(self, app: ASGIApp) -> None: self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: path = scope.get("path", "") if (scope["type"] != "http" or scope["method"] != "POST" or not (path == "/api/search" or path.startswith("/api/search/"))): await self.app(scope, receive, send) return # Count actual wire bytes, including chunked uploads and misleading # Content-Length. A bytearray also bounds overhead from tiny chunks. body = bytearray() status = None chunk = b"" message: Message = {} deadline = asyncio.timeout(SEARCH_BODY_TIMEOUT_SECONDS) try: async with deadline: while True: message = await receive() if message["type"] == "http.disconnect": status = 204 break chunk = message.get("body", b"") if len(body) + len(chunk) > SEARCH_BODY_MAX_BYTES: status = 413 break body.extend(chunk) if not message.get("more_body", False): break # receive may complete synchronously for buffered messages. await asyncio.sleep(0) except TimeoutError: if not deadline.expired(): raise status = 408 del message, chunk if status is not None: body.clear() await Response(status_code=status, headers={"Cache-Control": "no-store"})(scope, receive, send) return buffered: bytes | None = bytes(body) body.clear()
async def replay() -> Message: nonlocal buffered if buffered is not None: payload, buffered = buffered, None return {"type": "http.request", "body": payload, "more_body": False} return await receive()
# The upload deadline ends before validation, routing or response send. await self.app(scope, replay, send)13 unmodified lines1415161718192013 unmodified linesNormalizeSearchList, SearchFunction, SearchParameters, normalize_search_parameters,)from backend.search.http.schemas import SearchRequestfrom backend.search_execution import SearchBusyJsonObject = dict[str, object]13 unmodified lines1415161718192013 unmodified linesNormalizeSearchList, SearchFunction, SearchParameters, normalize_search_parameters,)from backend.search.http.schemas import SearchRequestfrom backend.search.infrastructure.executor import SearchBusyJsonObject = dict[str, object]
backend/app.py+26-26
backend/cache_core.py+7-30
backend/data_formats.py+17-110
backend/download/application/__init__.pyAdded+1
backend/download/application/warming.pyAdded+42
backend/download/http/routes.py+1-1
backend/download_warm.py+9-42
backend/folder_contents.py+12-84
backend/folder_tree.py+9-69
backend/proxy_streams.py+11-287
backend/reader/archive/domain/content.py+1-1
backend/reader/archive/domain/validation.pyAdded+156
backend/reader/catalog/application/indexes.py+2-2
backend/reader/catalog/domain/__init__.pyAdded+1
backend/reader/catalog/domain/assets.pyAdded+154
backend/reader/catalog/domain/index.pyAdded+54
backend/reader/catalog/infrastructure/__init__.pyAdded+1
backend/reader/catalog/infrastructure/v3.pyAdded+161
backend/reader/document/application/ranges.py+1-1
backend/reader/document/domain/policy.py+1-1
backend/reader/document/domain/range_cache.pyAdded+67
backend/reader/document/http/transport.py+2-2
backend/reader/query/application/ocr.py+1-1
backend/reader/query/domain/ocr.pyAdded+165
backend/reader_archive.py+12-156
backend/reader_assets.py+11-152
backend/reader_index.py+10-54
backend/reader_ocr.py+13-165
backend/reader_range_cache.py+12-67
backend/reader_v3_catalog.py+18-161
backend/record_metadata.py+23-185
backend/runtime/application/lifecycle.py+2-2
backend/search/application/bootstrap.pyAdded+31
backend/search/corpus/application/preparation.py+2-2
backend/search/corpus/domain/folder_contents.pyAdded+84
backend/search/corpus/domain/folder_tree.pyAdded+69
backend/search/corpus/domain/formats.pyAdded+110
backend/search/corpus/domain/records.pyAdded+185
backend/search/corpus/domain/words.pyAdded+65
backend/search/corpus/infrastructure/__init__.pyAdded+1
backend/search/corpus/infrastructure/indexes.pyAdded+205
backend/search/corpus/infrastructure/selection.pyAdded+290
backend/search/domain/browse.pyAdded+47
backend/search/domain/candidates.pyAdded+72
backend/search/domain/filters.pyAdded+134
backend/search/domain/matching.pyAdded+179
backend/search/domain/ordering.py+2-2
backend/search/domain/term_candidates.pyAdded+129
backend/search/http/body_limit.pyAdded+64
backend/search/http/responses.py+1-1