"""FastAPI application, routes and process-owned search state."""
import asyncio
import gzip
import hashlib
import json
import random
import re
import sys
import time
import functools
import threading
import weakref
from collections import OrderedDict
from collections.abc import AsyncGenerator, Awaitable, Callable, Hashable, Iterable, Mapping, MutableSequence
from array import array
from uuid import uuid4
import io
import zipfile
import zlib
from pathlib import Path
from typing import Annotated, BinaryIO, Literal, Optional, Protocol, Sequence, TypedDict, TypeVar, cast
from urllib.parse import unquote, quote, urlparse, parse_qs
import aiohttp
from huggingface_hub import HfFileSystem
import jieba
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from starlette.types import Scope
from pydantic import BaseModel, Field
from contextlib import asynccontextmanager
from backend.cache_core import cached as _bounded_cache
from backend.folder_tree import build_folder_tree as _build_folder_tree
from backend.folder_contents import get_folder_contents as _get_folder_contents
from backend.search_bootstrap import build_initial_payload as _build_initial_payload, trim_initial_results as _trim_initial_results
from backend.search_candidates import literal_candidates as _literal_candidates, wildcard_literal_candidates as _wildcard_literal_candidates
from backend.search_projection import public_record as _public_record, trim_results as _trim_results
from 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_build
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, SharedRangeFlight, UpstreamLease
from backend.search_execution import SearchBusy, SearchExecutor
from 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 load_reading_catalog, merge_sidecar as merge_v3_sidecar
from backend.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shell
from backend.data_formats import (
decode_browser_entry as decode_browser_entry, decode_folder_browser_data, decode_folder_tree_data,
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,
dataset_file_url, enrich_browser_entry, enrich_reader_record,
reader_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,
decode_url_path, is_allowed_download_host as is_allowed_download_host,
normalize_download_url as normalize_download_url, open_download_response,
source_url_scope as source_url_scope,
validate_download_url as validate_download_url, validate_path_safety, validate_reader_redirect_url,
validate_fixed_source_redirect_url, validate_reader_source_url,
validate_voiceofml_redirect_url, validate_voiceofml_source_url,
)
MAX_ARCHIVE_NAME_LENGTH = 240
DATA_PATH = Path("data/search_data.json.gz")
NGRAM_PATHS = {2: Path("data/search_ngrams_2.bin.gz"), 3: Path("data/search_ngrams_3.bin.gz")}
WORD_INDEX_PATH = Path("data/search_words.bin.gz")
FOLDER_TREE_PATH = Path("data/folder_tree.json.gz")
FOLDER_BROWSER_PATH = Path("data/folder_browser.json.gz")
READER_ASSETS_URL = "https://huggingface.co/buckets/vomebook/reader-assets-v2/resolve/reader-index/reader_assets.json.gz"
READER_ASSETS_CACHE_TTL_SECONDS = 300
READER_ASSETS_MAX_COMPRESSED_BYTES = 5 * 1024 * 1024
READER_ASSETS_MAX_DECOMPRESSED_BYTES = 50 * 1024 * 1024
READER_ASSET_ROUTING_CONTRACT_VERSION = "reader-buckets-v2-pdf-primary-only-v1"
# Decoded corpus records share the heterogeneous mapping used by the typed helpers.
SearchRecord = dict[str, object]
JsonObject = dict[str, object]
# Index postings are built as lists and published as packed arrays.
IndexPostings = MutableSequence[int]
CacheKey = tuple[int, str, str]
# (target URL, Range header, byte limit, media type) and its cached 206 body.
RangeKey = tuple[str, str, int | None, str | None]
RangeCacheEntry = tuple[float, bytes, dict[str, str]]
RangeFlightKey = tuple[RangeKey, Hashable, str | None]
_T = TypeVar("_T")
class RepoSummary(TypedDict):
name: str
count: int
class ReaderJoinCache(TypedDict):
all: dict[int, JsonObject]
repos: dict[str, dict[int, JsonObject]]
class IndexedRecord(TypedDict, total=False):
"""Typed view of a corpus record after build_indexes adds its derived fields."""
Repo: str
File: str
Extension: str
Folder: list[str]
_file_lower: str
_folder_path_lower: str
_repo_lower: str
records: list[SearchRecord] = []
folder_tree_data: dict[str, list[JsonObject]] = {}
folder_browser_data: dict[str, dict[str, JsonObject]] = {}
word_index: Mapping[str, Posting] = {}
word_index_buffer = b""
folder_index: dict[str, dict[str, IndexPostings]] = {}
extension_counts: dict[str, int] = {}
repo_counts: dict[str, int] = {}
repo_list: list[RepoSummary] = []
extension_list: list[str] = []
repo_extension_counts: dict[str, dict[str, int]] = {}
vocab_by_len: dict[int, list[str]] = {}
repo_records_map: dict[str, IndexPostings] = {}
sorted_by_name: Sequence[int] = []
sorted_by_size: Sequence[int] = []
repo_sorted_by_name: dict[str, IndexPostings] = {}
repo_sorted_by_size: dict[str, IndexPostings] = {}
READER_EXTENSIONS = frozenset({"pdf", "djvu", "caj", "kdh", "epub", "mobi", "azw", "azw3", "fb2", "fbz", "html", "htm", "txt", "md", "markdown", "vcf", "ini", "jpg", "jpeg", "png", "gif", "bmp", "tif", "tiff", "webp", "mp3", "mp4", "wav", "m4a", "flac", "mov", "mpga", "wma", "ape", "amr"})
reader_record_indices: Sequence[int] = []
repo_reader_record_indices: dict[str, Sequence[int]] = {}
reader_record_key_indices: dict[str, int] = {}
reader_source_id_indices: dict[str, list[int]] = {}
reader_legacy_source_id_indices: dict[str, list[int]] = {}
_reader_indexes_ready = False
_reader_indexes_lock = threading.Lock()
_reader_index_build: ReaderIndexBuild | None = None
READER_INDEX_BATCH_RECORDS = 256
READER_INDEX_BATCH_SECONDS = .008
READER_INDEX_WARM_DELAY_SECONDS = 5
READER_INDEX_IDLE_SECONDS = 5
initial_payload_global: JsonObject | None = None
initial_payload_by_repo: dict[str, JsonObject] = {}
API_CACHE_TTL_SECONDS = 120
RESPONSE_CACHE_BYTES_MAX = 16 * 1024 * 1024
RESPONSE_CACHE_ENTRY_BYTES_MAX = 2 * 1024 * 1024
_api_response_cache_lock = threading.Lock()
api_response_cache: dict[Hashable, tuple[float, object] | tuple[float, object, int]] = {}
_data_generation = 0
SEARCH_CACHE_TTL_SECONDS = 120
_search_cache: dict[Hashable, tuple[float, object] | tuple[float, object, int]] = {}
_search_instance = uuid4().hex
# Bump when matching, filtering, ordering or public record semantics change.
SEARCH_SEMANTICS_VERSION = "hf-search-v5"
_search_generation: str | None = None
_search_logged_generation: int | None = None
SearchOrderKey = tuple[Hashable, ...]
# array[int] is not subscriptable at runtime on Python 3.11, so keep these annotations lazy.
_search_order_cache: "OrderedDict[SearchOrderKey, tuple[float, array[int]]]" = OrderedDict()
SEARCH_ORDER_CACHE_MAX = 32
SEARCH_ORDER_CACHE_BYTES_MAX = 16 * 1024 * 1024
SEARCH_ORDER_CACHE_TTL_SECONDS = 600
_search_anchor_cache: "OrderedDict[int, tuple[weakref.ref[array[int]], OrderedDict[str, int]]]" = OrderedDict()
SEARCH_ANCHOR_ORDER_MAX = 8
SEARCH_ANCHOR_PER_ORDER_MAX = 8
SEARCH_ANCHOR_KEY_MAX = 4096
METADATA_CACHE_HEADERS = {
"Cache-Control": "public, max-age=300, stale-while-revalidate=1800",
}
ngram_postings: dict[int, PostingIndex] = {}
ngram_posting_buffers: dict[int, bytes] = {}
injected_html_cache: dict[str | None, str] = {}
last_user_request_at = time.monotonic()
reader_assets_cache: JsonObject = {"v": 1, "f": {}}
reader_assets_cache_at = 0.0
reader_assets_revision = hashlib.sha256(b'{"v":1,"f":{}}').hexdigest()
reader_join_cache_key: CacheKey | None = None
reader_join_cache: ReaderJoinCache = {"all": {}, "repos": {}}
reader_pool_cache_key: CacheKey | None = None
reader_pool_cache: "dict[str | None, array[int]]" = {}
def _cached(store: dict[Hashable, tuple[float, object] | tuple[float, object, int]], key: Hashable,
builder: Callable[[], object], ttl: float, limit: int) -> object:
return _bounded_cache(store, key, builder, ttl, limit, max_entry_bytes=RESPONSE_CACHE_ENTRY_BYTES_MAX,
max_total_bytes=RESPONSE_CACHE_BYTES_MAX)
def cached_payload(key: Hashable, builder: Callable[[], object]) -> object:
with _api_response_cache_lock:
return _cached(api_response_cache, key, builder, API_CACHE_TTL_SECONDS, 500)
def cached_json_response(key: Hashable, builder: Callable[[], object], headers: dict[str, str] | None = None) -> Response:
# Encode once, measure the actual body and reuse it within the existing budget.
body = cached_payload(("json", key), lambda: JSONResponse(builder()).body)
return Response(cast(bytes, body), media_type="application/json", headers=headers)
async def get_reader_assets(*, wait: bool = True) -> JsonObject:
if reader_assets_cache_at != 0 and time.monotonic() - reader_assets_cache_at < READER_ASSETS_CACHE_TTL_SECONDS:
return reader_assets_cache
task = getattr(app.state, "reader_assets_task", None)
if task is None or task.done():
task = asyncio.create_task(refresh_reader_assets())
app.state.reader_assets_task = task
# Search can enrich with the last snapshot while an owned refresh runs.
return await asyncio.shield(task) if wait else reader_assets_cache
async def _load_reader_asset_base(session: object) -> tuple[bytes, JsonObject]:
"""Read the fixed mutable base sidecar; never publish a partial response."""
source_url = f"{READER_ASSETS_URL}?v={int(time.time())}"
response = await open_download_response(
session, source_url, aiohttp.ClientTimeout(total=20, connect=8, sock_read=10),
url_validator=lambda target: validate_fixed_source_redirect_url(target, source_url),
cache_redirects=False,
)
try:
if response.status == 404:
raise RuntimeError("reader assets bucket and legacy sources unavailable")
if response.status != 200:
raise RuntimeError(f"reader assets HTTP {response.status}")
chunks = bytearray()
async for chunk in response.content.iter_chunked(64 * 1024):
chunks.extend(chunk)
if len(chunks) > READER_ASSETS_MAX_COMPRESSED_BYTES:
raise ValueError("reader assets response is too large")
raw = bytes(chunks)
return raw, await asyncio.to_thread(decode_reader_assets, raw)
finally:
response.release()
async def refresh_reader_assets() -> JsonObject:
global reader_assets_cache, reader_assets_cache_at, reader_assets_revision
now = time.monotonic()
if reader_assets_cache_at != 0 and now - reader_assets_cache_at < READER_ASSETS_CACHE_TTL_SECONDS:
return reader_assets_cache
async with app.state.reader_assets_lock:
now = time.monotonic()
if reader_assets_cache_at != 0 and now - reader_assets_cache_at < READER_ASSETS_CACHE_TTL_SECONDS:
return reader_assets_cache
base_task = asyncio.create_task(_load_reader_asset_base(app.state.http_session))
v3_task = asyncio.create_task(load_reading_catalog(app.state.http_session))
try:
# These two fixed, validated metadata reads are independent. The
# existing all-or-nothing publication and v3 pinning remain below.
(raw, decoded), v3_catalog = await asyncio.gather(base_task, v3_task)
if v3_catalog is None and reader_assets_cache.get("v3"):
raise ValueError("previously published v3 pointer disappeared")
decoded = merge_v3_sidecar(decoded, v3_catalog)
reader_assets_cache = decoded
revision_body = raw + json.dumps(decoded["v3"], sort_keys=True).encode() if v3_catalog else raw
reader_assets_revision = hashlib.sha256(revision_body).hexdigest()
reader_assets_cache_at = time.monotonic()
except Exception as exc:
print(f"reader assets refresh failed: {exc}")
# Retain last-known assets, but retry failures after a short backoff.
reader_assets_cache_at = time.monotonic() - READER_ASSETS_CACHE_TTL_SECONDS + 5
finally:
for task in (base_task, v3_task):
if not task.done():
task.cancel()
await asyncio.gather(base_task, v3_task, return_exceptions=True)
return reader_assets_cache
def records_digest() -> bytes:
return _records_digest(records)
def word_postings(token: str) -> set[int]:
value = word_index.get(token)
return resolve_postings(value, word_index_buffer) if value is not None else set()
def word_posting_count(token: str) -> int:
value = word_index.get(token)
if value is None:
return 0
if isinstance(value, tuple):
return value[2]
return len(value)
def _candidate_postings() -> dict[int, PostingIndex]:
return ngram_postings
def _candidate_buffers() -> dict[int, bytes]:
return ngram_posting_buffers
def _candidate_repos() -> dict[str, IndexPostings]:
return repo_records_map
def _candidate_records() -> list[SearchRecord]:
return records
def _candidate_resolver() -> Callable[[Posting, bytes], set[int]]:
return resolve_postings
def literal_candidates(query: str, repos: Iterable[str] | None = None) -> set[int] | None:
return _literal_candidates(query, repos, _candidate_postings, _candidate_buffers,
_candidate_repos, _candidate_records, _candidate_resolver)
INITIAL_PAGE_SIZE = 100
SIDEBAR_DATA_PATH = Path("data/sidebar")
RECORD_KEY_MAP = {
"r": "Repo",
"f": "File",
"e": "Extension",
"d": "Folder",
"s": "Size",
"t": "HasTxt",
}
TREE_KEY_MAP = {
"n": "name",
"c": "count",
"df": "hasDirectFiles",
"ch": "children",
}
BROWSER_ENTRY_KEY_MAP = {
"d": "folders",
"f": "files",
}
BROWSER_FOLDER_ITEM_KEY_MAP = {
"n": "name",
"c": "count",
}
BROWSER_FILE_ITEM_KEY_MAP = {
"n": "name",
"e": "ext",
"t": "hasTxt",
"s": "size",
}
READER_SHORT_ID_RE = re.compile(r"^[0-9a-z]{13}$")
# Only lowercase escapes, encoded unreserved ASCII and malformed percent signs
# require normalization. Canonical reserved/UTF-8 escapes can pass through.
def sanitize_archive_name(value: object) -> str:
name = str(value or "file").replace("\\", "/").rsplit("/", 1)[-1]
name = "".join(ch for ch in name if ord(ch) >= 32 and ch != "\x7f").strip()
if not name or name in (".", ".."):
name = "file"
return name[:MAX_ARCHIVE_NAME_LENGTH]
def tokenize(text: str) -> list[str]:
return _tokenize(text, jieba.lcut)
def matches_exact_query(text: str, query: str) -> bool:
return compile_exact_matcher(query)(text)
def matches_file_token(record: Mapping[str, object], token: str) -> bool:
return _matches_file_token(record, token)
def scoped_word_postings(token: str, search_folders: bool) -> set[int]:
postings = word_postings(token)
if search_folders:
return postings
return {index for index in postings if matches_file_token(records[index], token)}
def matches_file_query(record: dict[str, object], tokens: Iterable[str], fuzzy_tokens: set[str]) -> bool:
return _matches_file_query(record, tokens, fuzzy_tokens, tokenize_text=tokenize,
file_match=matches_file_token, fuzzy_match=is_fuzzy_match)
def build_word_index():
global word_index, word_index_buffer, vocab_by_len
index: dict[str, set[int]] = {}
word_index = index
word_index_buffer = b""
_build_word_index(records, index, tokenize)
vocab_by_len = {}
_build_vocab_by_len(word_index, vocab_by_len)
def build_vocab_by_len():
global vocab_by_len
vocab_by_len = {}
_build_vocab_by_len(word_index, vocab_by_len)
def _advance_reader_indexes(limit: int = READER_INDEX_BATCH_RECORDS, budget: float = READER_INDEX_BATCH_SECONDS) -> bool:
global reader_record_indices, repo_reader_record_indices
global reader_record_key_indices, reader_source_id_indices, reader_legacy_source_id_indices, _reader_indexes_ready
global _reader_index_build
with _reader_indexes_lock:
if _reader_indexes_ready:
return True
if _reader_index_build is None or _reader_index_build["generation"] != _data_generation:
_reader_index_build = new_build(_data_generation, records)
build = _reader_index_build
deadline = time.perf_counter() + budget
if not advance_build(build, limit, deadline, now=time.perf_counter,
source_id=reader_short_id, asset_key=build_reader_asset_key,
record_link=build_record_link, dataset_url=dataset_file_url,
reader_extensions=READER_EXTENSIONS):
return False
if build["generation"] != _data_generation or build["records"] is not records:
_reader_index_build = None
return False
reader_record_indices = array('I', build["indices"])
repo_reader_record_indices = {key: array('I', indices) for key, indices in build["repos"].items()}
reader_record_key_indices = build["keys"]
reader_source_id_indices = build["ids"]
reader_legacy_source_id_indices = build["legacy_ids"]
_reader_indexes_ready = True
_reader_index_build = None
return True
def _build_reader_indexes():
while not _advance_reader_indexes(len(records), float("inf")):
pass
def ensure_reader_indexes():
global _reader_indexes_ready
if _reader_indexes_ready:
return
_build_reader_indexes()
async def ensure_reader_indexes_async():
"""Join the shared background build, or start one for an early Reader request."""
if _reader_indexes_ready:
return
task = getattr(app.state, "reader_index_build_task", None)
if task is None or task.done():
async def build():
while not _reader_indexes_ready:
executor = getattr(app.state, "search_executor", None)
if executor is None:
await asyncio.to_thread(_advance_reader_indexes)
else:
try:
await executor.run(_advance_reader_indexes, background=True)
except SearchBusy:
await asyncio.sleep(.02)
continue
await asyncio.sleep(0)
task = asyncio.create_task(build())
app.state.reader_index_build_task = task
await asyncio.shield(task)
async def warm_reader_indexes():
"""Prepare Reader routing during a quiet period without delaying startup."""
await asyncio.sleep(READER_INDEX_WARM_DELAY_SECONDS)
while not _reader_indexes_ready:
while time.monotonic() - last_user_request_at < READER_INDEX_IDLE_SECONDS:
await asyncio.sleep(READER_INDEX_IDLE_SECONDS)
try:
await ensure_reader_indexes_async()
except SearchBusy:
await asyncio.sleep(READER_INDEX_IDLE_SECONDS)
def build_indexes(build_words: bool = True, build_reader: bool = True):
global _reader_index_build
global reader_source_id_indices, reader_legacy_source_id_indices, _search_generation
global _data_generation, word_index, word_index_buffer, folder_index, extension_counts, repo_counts, repo_list, extension_list, repo_extension_counts, repo_records_map, sorted_by_name, sorted_by_size, repo_sorted_by_name, repo_sorted_by_size, reader_record_indices, repo_reader_record_indices, reader_record_key_indices, _reader_indexes_ready
_data_generation += 1
_search_generation = None
_search_order_cache.clear()
_search_anchor_cache.clear()
_search_cache.clear()
word_index = {}
word_index_buffer = b""
folder_index = {}
extension_counts = {}
repo_extension_counts = {}
repo_counts = {}
repo_records_map = {}
repo_sorted_by_name = {}
repo_sorted_by_size = {}
reader_record_indices = []
repo_reader_record_indices = {}
reader_record_key_indices = {}
reader_source_id_indices = {}
reader_legacy_source_id_indices = {}
_reader_indexes_ready = False
_reader_index_build = None
for idx, rec in enumerate(records):
repo = cast(str, rec.get("Repo", ""))
repo_counts[repo] = repo_counts.get(repo, 0) + 1
ext = cast(str, rec.get("Extension") or "").lower()
if ext:
extension_counts[ext] = extension_counts.get(ext, 0) + 1
repo_ext = repo_extension_counts.setdefault(repo, {})
repo_ext[ext] = repo_ext.get(ext, 0) + 1
file_name = cast(str, rec.get("File", ""))
folders = cast(list[str], rec.get("Folder", []))
if repo not in folder_index:
folder_index[repo] = {}
for depth in range(len(folders) + 1):
folder_path = "/".join(folders[:depth]) if depth > 0 else ""
folder_index[repo].setdefault(folder_path, []).append(idx)
repo_records_map.setdefault(repo, []).append(idx)
folders_lower = [f.lower() for f in (folders or [])]
rec["_file_lower"] = file_name.lower()
rec["_folders_lower"] = folders_lower
rec["_folder_text"] = " ".join(folders_lower)
rec["_folder_path_lower"] = "/".join(folders_lower)
rec["_folder_path"] = "/".join(folders)
rec["_ext_lower"] = ext
rec["_repo_lower"] = repo.lower()
repo_list = sorted(
[RepoSummary(name=r, count=c) for r, c in repo_counts.items()],
key=lambda x: x["name"],
)
if build_words:
build_word_index()
else:
word_index = {}
global vocab_by_len
vocab_by_len = {}
extension_list = sorted(extension_counts.keys())
all_indices = list(range(len(records)))
sorted_by_name = sorted(all_indices, key=lambda i: cast(str, records[i].get("File") or "").lower())
sorted_by_size = sorted(all_indices, key=lambda i: (
-_record_size(records[i]),
cast(str, records[i].get("File") or "").lower(),
))
for repo, repo_indices in repo_records_map.items():
repo_sorted_by_name[repo] = sorted(repo_indices, key=lambda i: cast(str, records[i].get("File") or "").lower())
repo_sorted_by_size[repo] = sorted(repo_indices, key=lambda i: (
-_record_size(records[i]),
cast(str, records[i].get("File") or "").lower(),
))
# These complete, ordered postings are read-only after publication.
# Packed IDs avoid retaining a Python pointer (and often an int) per slot.
sorted_by_name = array('I', sorted_by_name)
sorted_by_size = array('I', sorted_by_size)
for mapping in (repo_records_map, repo_sorted_by_name, repo_sorted_by_size,
*folder_index.values()):
for key, indices in mapping.items():
mapping[key] = array('I', indices)
if build_reader:
_build_reader_indexes()
def search_data_generation(raw: bytes, index_paths: Iterable[Path]) -> str:
digest = hashlib.sha256()
digest.update(SEARCH_SEMANTICS_VERSION.encode())
digest.update(str(sys.version_info[:3]).encode())
digest.update(jieba.__version__.encode())
digest.update(hashlib.sha256(raw).digest())
for path in index_paths:
# Index content matters too; file timestamps and process IDs do not.
digest.update(path.name.encode())
digest.update(hashlib.sha256(path.read_bytes()).digest() if path.exists() else b"missing")
return "api:" + digest.hexdigest()
def load_data():
global records, folder_tree_data, folder_browser_data, ngram_postings, ngram_posting_buffers, word_index, word_index_buffer, _search_generation
start = time.perf_counter()
stage_start = start
timings = {}
if DATA_PATH.exists():
raw = gzip.decompress(DATA_PATH.read_bytes())
records = decode_search_payload(json.loads(raw.decode("utf-8")))
else:
print("⚠ 数据文件不存在")
records = []
return
if FOLDER_TREE_PATH.exists():
folder_tree_data = decode_folder_tree_data(json.loads(gzip.decompress(FOLDER_TREE_PATH.read_bytes()).decode("utf-8")))
else:
folder_tree_data = {}
if FOLDER_BROWSER_PATH.exists():
folder_browser_data = decode_folder_browser_data(json.loads(gzip.decompress(FOLDER_BROWSER_PATH.read_bytes()).decode("utf-8")))
else:
folder_browser_data = {}
timings["data_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
print(f"📖 已加载 {len(records)} 条记录 ({time.perf_counter() - start:.2f}s)")
stage_start = time.perf_counter()
# Reader ID/pool indexes are built on first Reader use; normal search does
# not need to scan every record to prepare them during cold startup.
build_indexes(build_words=False, build_reader=False)
digest = records_digest()
timings["metadata_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
stage_start = time.perf_counter()
word_index, word_index_buffer = load_word_index(WORD_INDEX_PATH, len(records), digest, materialize=False)
word_index_source = "generated" if word_index else "rebuilt"
if word_index:
build_vocab_by_len()
else:
word_index_buffer = b""
build_word_index()
timings["words_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
stage_start = time.perf_counter()
loaded_ngrams = {
width: load_ngram_index(path, width, len(records), digest)
for width, path in NGRAM_PATHS.items()
}
ngram_postings = {width: loaded[0] for width, loaded in loaded_ngrams.items()}
ngram_posting_buffers = {width: loaded[1] for width, loaded in loaded_ngrams.items()}
timings["ngrams_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
stage_start = time.perf_counter()
_search_generation = search_data_generation(raw, [WORD_INDEX_PATH, *NGRAM_PATHS.values()])
timings["fingerprint_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
print(f"🧭 已加载词索引: {len(word_index)}")
print(f"🔎 已加载 ngram 索引: 2={len(ngram_postings[2])}, 3={len(ngram_postings[3])}")
build_initial_payloads()
precompute_injected_html()
del raw
stage_start = time.perf_counter()
# A generated postings file avoids corpus tokenization, but query tokenization
# still needs jieba's dictionary. Prepare it before accepting the first query,
# after releasing the decoded source and finishing index-loading temporaries.
jieba.initialize()
timings["tokenizer_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
timings["total_ms"] = round((time.perf_counter() - start) * 1000, 2)
print("search_performance " + json.dumps({"stage": "startup", "word_index": word_index_source, **timings}))
def score_record(rec_idx: int, query_tokens: Iterable[str], search_folders: bool = True) -> int:
return _score_record(records[rec_idx], query_tokens, search_folders)
def apply_filters(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]:
return _apply_filters(records, indices, repos, extensions, folders, min_size, max_size, folder_match_mode)
def public_record(record: SearchRecord) -> SearchRecord:
return _public_record(record, lambda item: build_record_link(item), lambda item: build_record_path_url(item))
def trim_results(raw: Iterable[SearchRecord]) -> list[SearchRecord]:
return _trim_results(raw, lambda record: public_record(record))
def sort_key_name(idx: int) -> str:
return cast(str, records[idx].get("File") or "").lower()
def _record_size(record: SearchRecord) -> int | float:
size = record.get("Size")
return size if isinstance(size, (int, float)) else 0
def sort_key_size(idx: int) -> tuple[int | float, str]:
return (
-_record_size(records[idx]),
cast(str, records[idx].get("File") or "").lower(),
)
def paginate_indices(indices: Sequence[int], page: int, page_size: int) -> tuple[int, list[SearchRecord]]:
total = len(indices)
start = (page - 1) * page_size
return total, [records[i] for i in indices[start:start + page_size]]
def canonical_repos(repos: Iterable[str] | None) -> list[str] | None:
"""Repository filters are sets: request order and repetition never matter."""
return sorted(set(repos)) if repos else None
def get_initial_indices(repos: Iterable[str] | None = None) -> Sequence[int]:
if repos:
repos = canonical_repos(repos) or []
indices: list[int] = []
for repo in repos:
indices.extend(repo_records_map.get(repo, []))
if len(repos) > 1:
# Corpus order, matching the sorted literal n-gram candidate path.
indices.sort()
return indices
return range(len(records))
def _term_literal_candidates(term: str, repos: Iterable[str] | None = None) -> Sequence[int]:
"""Candidates whose searched fields contain the literal term (corpus order)."""
if not term:
return []
candidates = literal_candidates(term.lower(), repos)
if candidates is None:
return get_initial_indices(repos)
return sorted(candidates)
def _term_matches_literal(rec: SearchRecord, term: str, search_folders: bool) -> bool:
lowered = term.lower()
indexed = cast(IndexedRecord, rec)
return (
lowered in indexed.get("_file_lower", "")
or lowered in indexed.get("_repo_lower", "")
or (search_folders and lowered in indexed.get("_folder_path_lower", ""))
)
def _term_is_plain(term: str) -> bool:
"""True when a term contains only letters/digits/CJK (no literal punctuation)."""
return all(char.isalnum() or char.isspace() for char in term)
def _term_candidates(term: str, query_token_count: int, posting_cache: dict[str, set[int]], search_folders: bool = True) -> tuple[set[int], set[str]]:
"""Existing jieba/fuzzy candidate semantics for one ordinary query term."""
query_tokens = tokenize(term)
fuzzy_candidate_limit = 200 if query_token_count == 1 else 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=search_folders)
return posting_cache[token]
exact_constraint: set[int] | None = None
for tok in query_tokens:
if tok not in 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)
token_candidates: list[set[int]] = []
for tok in query_tokens:
candidates: set[int] = query_postings(tok) if tok in word_index else set()
if not candidates:
fuzzy_tokens.add(tok)
fuzzy_candidates: set[int] = set()
if exact_constraint is not None:
for idx in sorted(exact_constraint):
rec = 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):
fuzzy_candidates.add(idx)
if fuzzy_candidate_limit is not None and len(fuzzy_candidates) >= fuzzy_candidate_limit:
break
else:
tok_len = len(tok)
for delta in (-2, -1, 0, 1, 2):
for vocab_word in vocab_by_len.get(tok_len + delta, []):
if is_fuzzy_match(tok, vocab_word):
fuzzy_candidates.update(query_postings(vocab_word))
if fuzzy_candidate_limit is not None and len(fuzzy_candidates) >= fuzzy_candidate_limit:
break
if fuzzy_candidate_limit is not None and len(fuzzy_candidates) >= fuzzy_candidate_limit:
break
candidates = fuzzy_candidates
if not candidates:
return set(), fuzzy_tokens
token_candidates.append(candidates)
if not token_candidates:
return set(), fuzzy_tokens
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, fuzzy_tokens
def search_generation() -> str:
return _search_generation or f"api:{_search_instance}:{_data_generation}"
def build_response(results: list[SearchRecord], total: int, page: int, page_size: int) -> JsonObject:
return {
"results": trim_results(results),
"total": total,
"page": page,
"page_size": page_size,
"generation": search_generation(),
}
def trim_initial_results(raw: Sequence[SearchRecord]) -> list[SearchRecord]:
return _trim_initial_results(raw)
def _bootstrap_page_size() -> int:
return INITIAL_PAGE_SIZE
def _bootstrap_trim() -> Callable[[Sequence[SearchRecord]], list[SearchRecord]]:
return trim_initial_results
def _bootstrap_generation() -> Callable[[], str]:
return search_generation
def build_initial_payload(repo: str | None = None) -> JsonObject:
return _build_initial_payload(repo, _bootstrap_page_size, _candidate_repos, _candidate_records,
_bootstrap_trim, _bootstrap_generation)
def build_initial_payloads() -> None:
global initial_payload_global, initial_payload_by_repo
initial_payload_global = build_initial_payload(None)
initial_payload_by_repo = {
repo: build_initial_payload(repo)
for repo in repo_records_map
}
def precompute_injected_html() -> None:
global injected_html_cache, seo_catalog_cache
try:
# Corpus decoding supplies the SEO fields; startup still owns the
# legacy heterogeneous record mapping used by the search engine.
seo_catalog_cache = build_seo_catalog(cast(list[CatalogRecord], records), project="hf", corpus_identity=search_generation())
except ValueError:
# SEO failure must not replace search data or publish a partial catalog.
seo_catalog_cache = None
print("seo_catalog=unavailable reason=source_contract", flush=True)
index_path = Path("static/index.html")
if not index_path.exists():
injected_html_cache = {}
return
html = index_path.read_text(encoding="utf-8")
injected_html_cache = {None: inject_initial_payload(html, None)}
for repo in repo_records_map:
injected_html_cache[repo] = inject_initial_payload(html, repo.split("/")[-1])
def load_sidebar_payload(path: Path) -> object:
if not path.exists() or not path.is_file():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return None
def build_global_bootstrap() -> JsonObject:
sidebar: object = load_sidebar_payload(SIDEBAR_DATA_PATH / "global.json") or {}
return {
"generation": search_generation(),
"repos": repo_list,
"extensions": [{"name": name, "count": extension_counts[name]} for name in sorted(extension_counts)],
"sidebar": sidebar,
}
def inject_initial_payload(html: str, repo_short: str | None = None) -> str:
repo = f"VoiceOfML/{repo_short}" if repo_short else None
html = enrich_search_shell(html, repo, repo_counts.get(repo) if repo else None)
payload = initial_payload_by_repo.get(repo) if repo else initial_payload_global
if not payload:
return html
script = (
'"
)
app_script = re.search(r'', html)
if app_script:
return html[:app_script.start()] + script + "\n" + app_script.group(0) + html[app_script.end():]
return html.replace("