Enforce strict backend types and speech planner checks
Browse filesFiles changed (11)
- .dockerignore+2
- Dockerfile+4
- app.py+263-153
- ocr_release.py+167-52
- pyrightconfig.json+1-1
- static/tts-client.js+35-4
- tests/test_ocr_release.py+32
- tests/test_speech_plan.cjsAdded+27
- tests/test_speech_static.pyAdded+40
- tests/test_static_checks.py+7-1
- tests/test_typed_contracts.py+20
12 unmodified lines13141516171812 unmodified lines!tests/test_static_checks.py!tests/test_coverage_gate.py!tests/test_service_worker.cjs!tests/test_search.py!tests/test_prepare_fulltext_index.py!tests/test_ocr_release.py12 unmodified lines131415161718192012 unmodified lines!tests/test_static_checks.py!tests/test_coverage_gate.py!tests/test_service_worker.cjs!tests/test_speech_static.py!tests/test_speech_plan.cjs!tests/test_search.py!tests/test_prepare_fulltext_index.py!tests/test_ocr_release.py
17 unmodified lines1819202122232425261 unmodified line28293031323317 unmodified linesCOPY --from=static-check-node /check/node_modules/ /check/node_modules/COPY --from=static-check-node /check/jsconfig.service-worker.json ./COPY --from=static-check-node /check/static/sw.js static/sw.jsCOPY pyrightconfig.json app.py build_fulltext_db.py prepare_fulltext_index.py ocr_release.py ./COPY Dockerfile .coveragerc ./COPY tests/__init__.py tests/test_static_checks.py tests/test_coverage_gate.py tests/test_service_worker.cjs tests/RUN node node_modules/pyright/index.js --project pyrightconfig.jsonRUN mkdir -p data/initial data/sidebar static/iconsRUN printf '{"urls":[]}' > data/initial/manifest.json \1 unmodified lineCOPY tests/test_search.py tests/test_prepare_fulltext_index.py tests/test_ocr_release.py tests/test_integration.py tests/test_typed_contracts.py tests/support.py tests/RUN python -B -m unittest tests.test_static_checks tests.test_coverage_gate -v \&& node tests/test_service_worker.cjs \&& python -m coverage run -m unittest -q tests.test_search.TokenizationTests tests.test_prepare_fulltext_index tests.test_ocr_release tests.test_integration.FulltextIntegrationTests tests.test_typed_contracts tests.test_coverage_gate \&& python -m coverage report --fail-under=6517 unmodified lines18192021222324252627281 unmodified line303132333435363717 unmodified linesCOPY --from=static-check-node /check/node_modules/ /check/node_modules/COPY --from=static-check-node /check/jsconfig.service-worker.json ./COPY --from=static-check-node /check/static/sw.js static/sw.jsCOPY static/tts-client.js static/tts-client.jsCOPY pyrightconfig.json app.py build_fulltext_db.py prepare_fulltext_index.py ocr_release.py ./COPY Dockerfile .coveragerc ./COPY tests/__init__.py tests/test_static_checks.py tests/test_coverage_gate.py tests/test_service_worker.cjs tests/COPY tests/test_speech_static.py tests/test_speech_plan.cjs tests/RUN node node_modules/pyright/index.js --project pyrightconfig.jsonRUN mkdir -p data/initial data/sidebar static/iconsRUN printf '{"urls":[]}' > data/initial/manifest.json \1 unmodified lineCOPY tests/test_search.py tests/test_prepare_fulltext_index.py tests/test_ocr_release.py tests/test_integration.py tests/test_typed_contracts.py tests/support.py tests/RUN python -B -m unittest tests.test_static_checks tests.test_coverage_gate -v \&& node tests/test_service_worker.cjs \&& python -B -m unittest tests.test_speech_static -v \&& node tests/test_speech_plan.cjs \&& python -m coverage run -m unittest -q tests.test_search.TokenizationTests tests.test_prepare_fulltext_index tests.test_ocr_release tests.test_integration.FulltextIntegrationTests tests.test_typed_contracts tests.test_coverage_gate \&& python -m coverage report --fail-under=65
15 unmodified lines16171819202122231 unmodified line25262728293011 unmodified lines42434445464748495051525354555657585960616263646566676869707172737415 unmodified lines909192939495969798991001011021031041058 unmodified lines11411511611711811912026 unmodified lines1471481491501511521534 unmodified lines15815916016116216316412 unmodified lines1771781791801811821831 unmodified line1851861871881891901916 unmodified lines19819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722828 unmodified lines25725825926026126226358 unmodified lines32232332432532632732816 unmodified lines34534634734834935035113 unmodified lines36536636736836937037137237337437537637737837924 unmodified lines40440540640740840941029 unmodified lines44044144244344444544658 unmodified lines50550650750850951051151251325 unmodified lines53954054154254354454554654754 unmodified lines60260360460560660760860961061161261361461526 unmodified lines6426436446456466476485 unmodified lines6546556566576586596602 unmodified lines6636646656666676686696 unmodified lines67667767867968068168268368468517 unmodified lines70370470570670770870971071171271371427 unmodified lines7427437447457467477486 unmodified lines7557567577587597607616 unmodified lines7687697707717727737747757767777787797807814 unmodified lines7867877887897907917927935 unmodified lines79980080180280380480522 unmodified lines82882983083183283383416 unmodified lines85185285385485585685785885986086186216 unmodified lines87988088188288388488513 unmodified lines8999009019029039049059069079089099109119129139149159169172 unmodified lines9209219229239249259267 unmodified lines9349359369379389399409411 unmodified line9439449459469479489495 unmodified lines9559569579589599609619629639649659661 unmodified line96896997097197297397497597697797897998098198298390 unmodified lines107410751076107710781079108010811082108310841085108612 unmodified lines1099110011011102110311041105110612 unmodified lines11191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431 unmodified line11451146114711481149115011511152115311541155115635 unmodified lines119211931194119511961197119813 unmodified lines1212121312141215121612171218121912201221122212231224122512261 unmodified line122812291230123112321233123410 unmodified lines12451246124712481249125012514 unmodified lines1256125712581259126012611262126312641265126612677 unmodified lines1275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712985 unmodified lines130413051306130713081309131013111312131313141315131620 unmodified lines1337133813391340134113421343134413451346134715 unmodified lines136313641365136613671368136913705 unmodified lines1376137713781379138013811382138313841385138613871388138928 unmodified lines141814191420142114221423142428 unmodified lines14531454145514561457145814594 unmodified lines14641465146614671468146914703 unmodified lines147414751476147714781479148015 unmodified lines14961497149814991500150115026 unmodified lines15091510151115121513151439 unmodified lines15541555155615571558155915601 unmodified line156215631564156515661567156831 unmodified lines1600160116021603160416059 unmodified lines161516161617161816191620162136 unmodified lines1658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016812 unmodified lines168416851686168716881689169016911692169316941695169616971698169917001701170217032 unmodified lines17061707170817091710171117127 unmodified lines17201721172217231724172517267 unmodified lines173417351736173717381739174017411742174317441745174677 unmodified lines182418251826182718281829183018311 unmodified line183318341835183618371838183948 unmodified lines188818891890189118921893189418 unmodified lines19131914191519161917191819197 unmodified lines1927192819291930193119321933120 unmodified lines20542055205620572058205920602 unmodified lines206320642065206620672068206946 unmodified lines211621172118211921202121212265 unmodified lines2188218921902191219221932194219521962197219821 unmodified lines222022212222222322242225222661 unmodified lines228822892290229122922293229415 unmodified linesimport unicodedatafrom functools import lru_cachefrom contextlib import asynccontextmanager, contextmanagerfrom pathlib import Pathfrom typing import Literal, Optionalfrom urllib.parse import parse_qs, quote, unquote, urlencodefrom fastapi import FastAPI, Query, Requestfrom fastapi.middleware.cors import CORSMiddleware1 unmodified linefrom fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Responsefrom fastapi.staticfiles import StaticFilesfrom starlette.background import BackgroundTaskfrom pydantic import BaseModel, Fieldimport ocr_releaseBASE_DIR = Path(__file__).resolve().parent11 unmodified linesFULLTEXT_DIR = BASE_DIR / "data/fulltext"INDEX_BUILD_STATUS_PATH = FULLTEXT_DIR / "build-status.json"BUCKET_INDEX_STATUS_PATH = FULLTEXT_DIR / "bucket-index-status.json"records: list[dict] = []name_order: list[int] = []size_order: list[int] = []source_name_order: dict[str, list[int]] = {}source_size_order: dict[str, list[int]] = {}record_map: dict[str, dict] = {}record_map_index: dict[str, int] = {}source_doc_number_index: dict[str, dict[int, int]] = {}newspaper_text_path_index: dict[tuple[str, str], str] = {}sources: list[dict] = []source_counts: dict[str, int] = {}# Public OCR repositories are logical sources backed by the one physical OCR# database. Keep the mapping explicit so full-text readiness and doc-number# lookup still use the database's own source key.source_physical_map: dict[str, str] = {}physical_source_counts: dict[str, int] = {}ocr_public_browser: dict[str, dict[str, dict]] = {}folder_tree_data: dict[str, list[dict]] = {}folder_browser_data: dict[str, dict[str, dict]] = {}source_records_map: dict[str, list[int]] = {}extension_counts: dict[str, int] = {}source_extension_counts: dict[str, dict[str, int]] = {}# Posting lists are read-only after build; array("I") keeps 4 bytes per record# id instead of a hash-set entry plus a Python int object.word_index: dict[str, array] = {}latin_all_index: dict[str, array] = {}latin_file_index: dict[str, array] = {}latin_vocabulary_all: set[str] = set()TOKEN_RE = re.compile(r"[a-z0-9]+|[\u4e00-\u9fff\u3400-\u4dbf]+")LATIN_RE = re.compile(r"[a-z0-9]+")15 unmodified linesMETADATA_MATCH_CACHE_MAX_TOTAL_IDS = 250000PREVIEW_CACHE_MAX_ENTRIES = 64PREVIEW_CACHE_MAX_ENTRY_BYTES = 2 * 1024 * 1024api_response_cache: dict[tuple, tuple[float, object]] = {}api_response_cache_lock = threading.Lock()search_response_cache: dict[tuple, tuple[float, object]] = {}search_response_cache_lock = threading.Lock()metadata_match_cache: dict[tuple, frozenset[int]] = {}metadata_match_cache_lock = threading.Lock()metadata_match_cache_generation = 0preview_text_cache: dict[str, str] = {}preview_text_cache_lock = threading.Lock()cache_key_locks: dict[tuple, threading.Lock] = {}cache_key_locks_guard = threading.Lock()ZIP_TOKEN_TTL_SECONDS = 600ZIP_TOKEN_MAX_ENTRIES = 328 unmodified lines)FULLTEXT_REFRESH_INTERVAL_SECONDS = max(1, int(os.environ.get("CCRD_FULLTEXT_REFRESH_INTERVAL_SECONDS", "5")))fulltext_refresh_stop = threading.Event()active_ocr_release = Noneocr_reader_urls: dict[str, str] = {}def clear_metadata_match_cache() -> None:26 unmodified linesreturn list(dict.fromkeys(TOKEN_RE.findall(normalize_text(text))))def index_tokens(text: str) -> set[str]:tokens = set()for part in query_terms(text):if re.fullmatch(r"[\u4e00-\u9fff\u3400-\u4dbf]+", part):tokens.update(part)4 unmodified lines@lru_cache(maxsize=4096)def query_tokens(text: str) -> list[str]:tokens = []for part in query_terms(text):if re.fullmatch(r"[\u4e00-\u9fff\u3400-\u4dbf]+", part) and len(part) > 1:tokens.extend(part[index:index + 2] for index in range(len(part) - 1))12 unmodified lines@lru_cache(maxsize=4096)def wildcard_required_tokens(text: str) -> list[str]:tokens = []for fixed_part in re.split(r"[*?]+", normalize_text(text)):for term in TOKEN_RE.findall(fixed_part):if re.fullmatch(r"[\u4e00-\u9fff\u3400-\u4dbf]+", term):1 unmodified linereturn list(dict.fromkeys(tokens))def decode_doc_numbers(payload: bytes, candidates: set[int] | None = None) -> set[int]:results = set()number = shift = previous = 0for byte in payload:number |= (byte & 0x7F) << shift6 unmodified linesnumber = shift = 0return resultsclass FulltextDatabases:def __init__(self, directory: Path, in_memory: bool = False, refresh: bool = True, extra_paths=(), disk_sources=None):self.directory = directoryself.extra_paths = tuple(extra_paths)self.in_memory = in_memoryself.disk_sources = FULLTEXT_DISK_SOURCES if disk_sources is None else frozenset(disk_sources)self.lock = threading.RLock()self.refresh_lock = threading.Lock()self.connections = {}self.has_doc_counts = {}self.tokenizer_versions = {}self.has_content_fts = {}self.has_snippet_anchors = {}self.has_sqlite_texts = {}self.hybrid_texts_ready = {}self.document_counts = {}self.fts_counts = {}self.file_signatures = {}self.connection_readers = {}self.retired_connections = set()self.closed = Falseself.generation = 0self.match_cache = {}self.match_inflight = {}if refresh:self.refresh()28 unmodified linescontinueself._install_candidate(path.stem, signature, candidate)def _open_candidate(self, path: Path) -> dict:uri = f"file:{path.resolve()}?mode=ro&immutable=1"source_connection = sqlite3.connect(uri, uri=True, check_same_thread=False)connection = source_connection58 unmodified lines"fts_count": fts_count,}def _install_candidate(self, source: str, signature: tuple[int, int, int], candidate: dict) -> None:connection = candidate["connection"]old_connection = self.connections.get(source)self.connections[source] = connection16 unmodified linesold_connection.close()@contextmanagerdef _lease_source(self, source: str):with self.lock:connection = self.connections.get(source)if connection is None or self.closed:13 unmodified linesfinally:if lease is None:returnwith self.lock:remaining = self.connection_readers.get(connection, 1) - 1if remaining:self.connection_readers[connection] = remainingelse:self.connection_readers.pop(connection, None)if connection in self.retired_connections:self.retired_connections.remove(connection)connection.close()def close(self) -> None:with self.refresh_lock:24 unmodified linesconnection, state = leasereturn self._cached_source_search(source, connection, query, exact, state)def _cached_source_search(self, source, connection, query, exact, state) -> set[int]:key = (source, connection, query, exact)event = Nonewhile True:29 unmodified linesself.match_inflight.pop(key)event.set()def _search_source_connection(self, connection: sqlite3.Connection, query: str, exact: bool, state: dict) -> set[int]:version = state["tokenizer_version"]has_content_fts = state["has_content_fts"]has_doc_counts = state["has_doc_counts"]58 unmodified linesif len(rows) != len(token_hashes):return set()posting_rows = [(docs, doc_count) for _token_hash, docs, doc_count in rows]posting_rows.sort(key=lambda item: item[1])else:posting_rows = []for token_hash in token_hashes:row = connection.execute("SELECT docs FROM postings WHERE token_hash = ?", (token_hash,)).fetchone()if row is None:25 unmodified linesif len(rows) != len(token_hashes):return set()posting_rows = [(docs, doc_count) for _token_hash, docs, doc_count in rows]posting_rows.sort(key=lambda item: item[1])else:posting_rows = []for token_hash in token_hashes:row = connection.execute("SELECT docs FROM postings WHERE token_hash = ?", (token_hash,)).fetchone()if row is None:54 unmodified linesreturn matcheddef summaries(self, doc_ids: list[str]) -> dict[str, str]:grouped = {}for doc_id in doc_ids:grouped.setdefault(doc_id.split(":", 1)[0], []).append(doc_id)with self.lock:missing = any(source not in self.connections for source in grouped)if missing:self.refresh()summaries = {}for source, source_doc_ids in grouped.items():with self._lease_source(source) as lease:if lease is None:26 unmodified linesrow = connection.execute(f"SELECT {field} FROM texts WHERE doc_id=?", (doc_id,)).fetchone()return (bool(row) if exists_only else row[0]) if row else Nonedef matched_snippets(self, doc_ids: list[str], query: str, exact: bool = False, timings=None) -> dict[str, dict]:normalized_query = normalize_text(query.strip())# A fixed wildcard fragment can occur long before the actual match.# Let the original-text snippet endpoint locate the verified span.5 unmodified linesneedle = next(iter(query_tokens(query)), "")if not needle:return {}grouped = {}for doc_id in doc_ids:source, _, number = doc_id.partition(":")if number.isdigit():2 unmodified linesmissing = any(source not in self.connections for source in grouped)if missing:self.refresh()snippets = {}for source, source_docs in grouped.items():with self._lease_source(source) as lease:if lease is None:6 unmodified lines)return snippetsdef _matched_snippets_source(self, snippets, connection, state, source_docs, needle, query, exact, timings) -> None:doc_id_by_number = {number: doc_id for doc_id, number in source_docs}numbers = list(doc_id_by_number)anchored_numbers = set()# Exact snippets retain the established literal path. Normal snippets can seek# directly to a token anchor without scanning FTS content with instr().if not exact and state["has_snippet_anchors"]:17 unmodified lines[needle, token_hash, *batch],).fetchall()if timings is not None:timings["snippet_anchor_sql"] = timings.get("snippet_anchor_sql", 0) + (time.perf_counter() - anchor_started) * 1000for number, char_offset, text in rows:payload_started = time.perf_counter()payload = build_normalized_snippet_payload(text or "", query)if timings is not None:timings["snippet_payload"] = timings.get("snippet_payload", 0) + (time.perf_counter() - payload_started) * 1000if not payload["highlights"]:continueextracted_start = max(int(char_offset) - 219, 1)27 unmodified lines[needle, *batch, needle],).fetchall()if timings is not None:timings["snippet_fallback_sql"] = timings.get("snippet_fallback_sql", 0) + (time.perf_counter() - fallback_started) * 1000for number, match_position, text in rows:payload_started = time.perf_counter()extracted_start = max(int(match_position or 0) - 220, 1)6 unmodified linesif not payload["highlights"]:payload = build_snippet_payload(text or "", needle, exact=True)if timings is not None:timings["snippet_payload"] = timings.get("snippet_payload", 0) + (time.perf_counter() - payload_started) * 1000if payload["snippet"] and extracted_start > 1 and not payload["snippet"].startswith("..."):payload["snippet"] = "..." + payload["snippet"]if payload["snippet"] and len(text or "") > 440 + len(needle) and not payload["snippet"].endswith("..."):6 unmodified linesdef tokenize(text: str) -> list[str]:return query_terms(text)def compile_exact_query(query: str) -> tuple[str, re.Pattern | None]:normalized_query = normalize_text(query)if has_wildcard_query(normalized_query):expression = re.escape(normalized_query).replace(r"\*", ".*?").replace(r"\?", ".")return normalized_query, re.compile(expression, re.DOTALL)return normalized_query, Nonedef matches_normalized_exact_query(text: str, normalized_query: str, pattern: re.Pattern | None = None) -> bool:return pattern.search(text) is not None if pattern is not None else normalized_query in textdef matches_exact_query(text: str, query: str) -> bool:4 unmodified linesreturn "*" in query or "?" in querydef normalized_text_map(text: str) -> tuple[str, list[tuple[int, int]]]:normalized = []offsets = []for index, character in enumerate(text):value = normalize_text(character)normalized.append(value)5 unmodified linesnormalized_query = normalize_text(query.strip())if not normalized_text or not normalized_query or not offsets:return []normalized_spans = []if exact:if has_wildcard_query(normalized_query):pattern = re.escape(normalized_query).replace(r"\*", ".*?").replace(r"\?", ".")22 unmodified linesif start < end and end <= len(offsets)]def build_snippet_payload(text: str, query: str, window: int = 110, exact: bool = False) -> dict:query = (query or "").strip()if not text or not query:return {"snippet": "", "highlights": []}16 unmodified lines))return {"snippet": snippet, "highlights": [value for value in highlights if value]}def build_normalized_snippet_payload(text: str, query: str, window: int = 110) -> dict:"""Build a normal-search snippet when text already came from normalized content_fts."""query = (query or "").strip()if not text or not query:return {"snippet": "", "highlights": []}spans = []for token in query_tokens(query):token = normalize_text(token)index = text.find(token)16 unmodified lines))return {"snippet": snippet, "highlights": [value for value in highlights if value]}def build_normalized_exact_snippet_payload(text: str, query: str, window: int = 110) -> dict:needle = normalize_text(query.strip())index = text.find(needle)if index == -1:13 unmodified linesdef load_json_gz(path: Path):return json.loads(gzip.decompress(path.read_bytes()).decode("utf-8"))def public_source_slug(rec: dict) -> str:return rec.get("public_source") or rec["source"]def public_source_name(rec: dict) -> str:return rec.get("public_source_name") or rec["source_name"]def public_record_dirs(rec: dict) -> list[str]:return rec.get("public_dirs", rec.get("display_dirs", []))def public_record_path(rec: dict) -> str:return rec.get("public_rel_path") or rec["display_rel_path"]def _find_tree_node(nodes: list[dict], target: str) -> dict | None:for node in nodes:if node.get("path") == target:return node2 unmodified linesreturn foundreturn Nonedef _rebase_tree_node(node: dict, prefix: str) -> dict:path = node.get("path", "")if path == prefix:relative = ""7 unmodified lines"children": [_rebase_tree_node(child, prefix) for child in node.get("children", [])],}def _rebase_ocr_browser(browser: dict, prefix: str) -> dict:result = {}for full_path, entry in browser.items():if full_path == prefix:relative = ""1 unmodified linerelative = full_path[len(prefix) + 1:]else:continuefolders = []for folder in entry.get("folders", []):folder_path = folder.get("path", "")if folder_path == prefix:5 unmodified linesfolders.append({**folder, "path": folder_relative})result[relative] = {"folders": folders,"files": [dict(file) for file in entry.get("files", [])],}result.setdefault("", {"folders": [], "files": []})return resultdef build_ocr_public_layout(extra: dict, base_slugs: set[str]) -> dict:"""Expose each OCR origin repository as its own logical source.The OCR release keeps one physical database and ``OCR:<n>`` document IDs.1 unmodified linerelease contract, full-text index, TXT URLs and downloads stay unchanged."""records = extra.get("records") or []groups: dict[tuple[str, str], list[dict]] = {}for rec in records:dirs = rec.get("display_dirs") or []if len(dirs) < 2 or not dirs[0] or not dirs[1]:raise ValueError("OCR record lacks owner/repository hierarchy")groups.setdefault((dirs[0], dirs[1]), []).append(rec)tree = extra.get("tree") or []browser = extra.get("browser") or {}used = set(base_slugs)public_sources, trees, browsers, physical_map = [], {}, {}, {}for owner, repo in sorted(groups, key=lambda item: (item[1], item[0])):group = groups[(owner, repo)]slug = repo90 unmodified linesposting.append(idx)name_order = sorted(range(len(records)),key=lambda idx: (records[idx]["_rank_path_key"], records[idx]["doc_id"]),)size_order = sorted(range(len(records)),key=lambda idx: (-(records[idx].get("size") or 0),records[idx]["_rank_path_key"],records[idx]["doc_id"],),)12 unmodified lines(uppercase escapes, decode escaped unreserved ASCII, never decode ``%2F`` ordouble-decode ``%25``), then FNV-1a 64-bit as base36 padded to 13 chars."""def replace_path(match):def replace_token(token_match):token = token_match.group()if len(token) == 3:char = chr(int(token[1:], 16))12 unmodified linesreturn (output or "0").rjust(13, "0")def ocr_reader_url(export: dict) -> str:"""Deep link to the existing HF Search Reader in its converted image mode.``?id=`` resolves the Reader record, which selects ``pdf-pages`` (theconverted page stream) instead of opening the raw PDF with ``?url=``."""repo = export.get("origin_repo") or ""path = export.get("origin_rel_path") or ""if not repo.startswith("VoiceOfML/") or not path:return ""source = f"https://huggingface.co/datasets/{repo}/resolve/main/" + quote(path, safe="/")readable = export.get("readable_rel_path") or pathtitle = readable.rsplit("/", 1)[-1]if "." in title:title = title.rsplit(".", 1)[0]return f"{HF_SEARCH_READER}?{urlencode({'id': reader_source_id(source), 'title': title, 'ext': 'pdf-pages'})}"def intern_shared_strings(records: list[dict]) -> None:"""Share repeated structural strings across records.JSON decoding creates a separate string object for every occurrence. Source1 unmodified linethousands of records, so interning them removes that duplication withoutchanging any value or comparison."""fields = ("source", "source_name", "storage_root", "extension", "text_storage")for rec in records:for key in fields:value = rec.get(key)if type(value) is str:rec[key] = sys.intern(value)dirs = rec.get("display_dirs")if type(dirs) is list:for index, value in enumerate(dirs):35 unmodified linesocr_public_browser = {}layout = Noneif extra:records = [*records, *extra["records"]]layout = build_ocr_public_layout(extra, {item["slug"] for item in base_sources})sources = [*sources, *layout["sources"]]physical_source_counts["OCR"] = len(extra["records"])13 unmodified linesfor export in extra.get("exports", []):url = ocr_reader_url(export)if url:ocr_reader_urls[export["doc_id"]] = urlintern_shared_strings(records)build_indexes()print(f"loaded {len(records)} txt records in {time.time() - start:.2f}s")def score_record(idx: int, query_tokens: list[str], search_paths: bool = True) -> int:score = 0file_text = records[idx]["_file_search_text"]path_text = records[idx]["_path_search_text"]for token in query_tokens:if token in file_text:score += 31 unmodified linescore += 2return scoredef relevance_page(indices, query_tokens: list[str], search_paths: bool, start: int, page_size: int) -> list[int]:limit = start + page_sizeif limit <= 0:return []10 unmodified linesif len(candidates) == len(indices) and len(potential) >= limit:# Only maximum-score hits can make unseen candidates irrelevant.maximum = (5 if search_paths else 3) * len(query_tokens)highest = []for idx in name_order:if idx in potential and score_record(idx, query_tokens, search_paths) == maximum:highest.append(idx)4 unmodified linesscores = {idx: score_record(idx, query_tokens, search_paths) for idx in indices}if len(scores) == len(indices):# Scores are small integers; the global name order supplies exact ties.buckets = {}for idx in name_order:score = scores.get(idx)if score is not None:buckets.setdefault(score, []).append(idx)selected = []for score in sorted(buckets, reverse=True):bucket = buckets[score]if start >= len(bucket):7 unmodified linesranked = heapq.nsmallest(limit,indices,key=lambda idx: (-score_record(idx, query_tokens, search_paths), records[idx]["_rank_path_key"], records[idx]["doc_id"]),)return ranked[start:limit]def ordered_page(indices, ordering: list[int], start: int, page_size: int) -> list[int]:candidates = set(indices)if not candidates or page_size <= 0 or start >= len(candidates):return []if len(candidates) <= page_size:if ordering is name_order:ranked = sorted(candidates, key=lambda idx: (records[idx]["_rank_path_key"], records[idx]["doc_id"]))return ranked[start:start + page_size]if ordering is size_order:ranked = sorted(candidates, key=lambda idx: (-(records[idx].get("size") or 0), records[idx]["_rank_path_key"], records[idx]["doc_id"],))return ranked[start:start + page_size]selected = []matched = 0for idx in ordering:if idx not in candidates:5 unmodified linesmatched += 1return selecteddef apply_filters(indices: list[int], sources_filter=None, folders=None, min_size=None, max_size=None):if not has_filters(sources_filter, folders, min_size, max_size):return list(indices)selected_sources = set(sources_filter) if sources_filter is not None else Noneselected_folders = set(folders or [])single_folder = next(iter(selected_folders)) if len(selected_folders) == 1 else Noneresult = []for idx in indices:rec = records[idx]if selected_sources is not None and public_source_slug(rec) not in selected_sources:20 unmodified linesresult.append(idx)return resultdef has_filters(sources_filter=None, folders=None, min_size=None, max_size=None) -> bool:return bool(sources_filter is not None or folders or min_size is not None or max_size is not None)def empty_query_order(sources_filter=None, folders=None, min_size=None, max_size=None, sort="relevance") -> list[int] | range | None:if folders or min_size is not None or max_size is not None:return Noneif sources_filter is None:15 unmodified linesreturn source_records_map.get(source, [])return Nonedef trim_record(rec: dict) -> dict:item = {"doc_id": rec["doc_id"],"Source": public_source_slug(rec),"SourceName": public_source_name(rec),5 unmodified lines"HasTxt": True,}if rec.get("source") == "OCR":item.update({"TextUrl": "/txt/OCR/" + quote(rec["display_rel_path"], safe="/"),"TextQuality": rec.get("text_quality", "unreviewed"),"TextGeneration": rec.get("text_generation")})elif uses_sqlite_text(rec):item["TextUrl"] = "/txt/" + rec["source"] + "/" + quote(rec["storage_rel_path"], safe="/")return itemdef add_summaries(items: list[dict], query: str = "", matched_snippets: bool = False, content_indices: set[int] | None = None, exact: bool = False, timings=None) -> list[dict]:if fulltext_databases is None or not items:return itemssummaries_started = time.perf_counter()28 unmodified linesreturn candidatesdef metadata_prefilter(terms: list[str], search_paths: bool) -> set[int] | None:postings = []for term in terms:if LATIN_RE.fullmatch(term):indices = latin_substring_candidates(term, search_paths)28 unmodified linesif has_wildcard_query(q):candidate_set = Nonefor token in wildcard_required_tokens(normalized_query):token_indices = word_index.get(token, set())candidate_set = set(token_indices) if candidate_set is None else candidate_set.intersection(token_indices)if not candidate_set:return set()4 unmodified linescandidates = metadata_prefilter(terms, search_paths) or set()return {idx for idx in candidatesif matches_normalized_exact_query(records[idx][field], normalized_query, pattern)}terms = query_terms(q)if not terms:3 unmodified linescandidates = range(len(records))return {idx for idx in candidatesif all(term in records[idx][field] for term in terms)}15 unmodified linesmetadata_match_cache.pop(next(iter(metadata_match_cache)), None)return resultdef search(q="", sources_filter=None, folders=None, min_size=None, max_size=None, page=1, page_size=100, sort="relevance", exact=False, search_paths=True, timings=None):started = time.perf_counter()q = q.strip()start = (page - 1) * page_size6 unmodified linestimings["decorate"] = (time.perf_counter() - summaries_started) * 1000timings["engine"] = (time.perf_counter() - started) * 1000return {"results": result_items, "total": len(preordered), "page": page, "page_size": page_size}if not q:indices = list(range(len(records)))filter_started = time.perf_counter()39 unmodified linestimings["engine"] = (time.perf_counter() - started) * 1000return {"results": result_items, "total": total, "page": page, "page_size": page_size}def fulltext_search(q="", sources_filter=None, folders=None, min_size=None, max_size=None, page=1, page_size=100, sort="relevance", exact=False, search_paths=True, timings=None):started = time.perf_counter()q = q.strip()if not q or fulltext_databases is None:1 unmodified linesource_slugs = sources_filter if sources_filter is not None else list(source_counts)if not source_slugs:return {"results": [], "total": 0, "page": max(1, page), "page_size": page_size}content_indices = set()sqlite_started = time.perf_counter()physical_slugs = list(dict.fromkeys(source_physical_map.get(slug, slug) for slug in source_slugs))for physical_slug in physical_slugs:31 unmodified linesselected = ordered_page(filtered, size_order, (page - 1) * page_size, page_size)if timings is not None:timings["sort"] = (time.perf_counter() - sort_started) * 1000total = len(filtered)summaries_started = time.perf_counter()result_items = add_summaries(9 unmodified linestimings["engine"] = (time.perf_counter() - started) * 1000return {"results": result_items, "total": total, "page": page, "page_size": page_size}def get_doc_storage_path(doc: dict) -> Path:if doc.get("source") == "OCR" and active_ocr_release is not None:return active_ocr_release["text_paths"][doc["doc_id"]]return BASE_DIR / doc["storage_root"] / doc["storage_rel_path"]36 unmodified linesreturn textdef uses_sqlite_text(rec: dict) -> bool:return rec.get("source") in NEWSPAPER_SOURCES and rec.get("text_storage") == "sqlite"def document_text_exists(rec: dict) -> bool:if uses_sqlite_text(rec):return fulltext_databases is not None and fulltext_databases.stored_text(rec["doc_id"], exists_only=True) is Truereturn get_doc_storage_path(rec).exists()def read_document_text(rec: dict, *, preview: bool = False) -> str:if uses_sqlite_text(rec):body = fulltext_databases.stored_text(rec["doc_id"]) if fulltext_databases is not None else Noneif not isinstance(body, str):raise FileNotFoundError(rec["doc_id"])payload = body.encode("utf-8")if (len(payload) != rec.get("size") or not re.fullmatch(r"[0-9a-f]{64}", rec.get("text_sha256", ""))or hashlib.sha256(payload).hexdigest() != rec["text_sha256"]):raise ValueError("stored newspaper TXT differs from the pinned metadata")return bodypath = get_doc_storage_path(rec)2 unmodified linesreturn read_preview_text(rec["doc_id"], path) if preview else read_source_text(path)def text_not_found(rec: dict):if uses_sqlite_text(rec):return JSONResponse({"error": "text index unavailable", "indexing": True}, status_code=503)return JSONResponse({"error": f"missing file: {get_doc_storage_path(rec).name}"}, status_code=404)def get_folder_contents(source_slug: str, path: str) -> dict:source_browser = folder_browser_data.get(source_slug, {})if path in source_browser:entry = dict(source_browser[path])entry["current_path"] = pathreturn entryreturn {"folders": [], "files": [], "current_path": path}def _cached_payload(cache, lock, key: tuple, builder, ttl: int, max_entries: int, timings=None):cache_started = time.perf_counter()now = time.monotonic()with lock:2 unmodified linesif timings is not None:timings["cache"] = "hit"timings["cache_lookup"] = (time.perf_counter() - cache_started) * 1000return cached[1]if timings is not None:timings["cache"] = "miss"timings["cache_lookup"] = (time.perf_counter() - cache_started) * 10007 unmodified lineswith lock:cached = cache.get(key)if cached and now - cached[0] < ttl:return cached[1]value = builder()inserted_at = time.monotonic()with lock:7 unmodified linesif cache_key_locks.get(key) is key_lock:cache_key_locks.pop(key, None)def cached_payload(key: tuple, builder, timings=None):return _cached_payload(api_response_cache, api_response_cache_lock, key, builder,API_CACHE_TTL_SECONDS, API_CACHE_MAX_ENTRIES, timings,)def cached_search_payload(key: tuple, builder, timings=None):return _cached_payload(search_response_cache, search_response_cache_lock, key, builder,SEARCH_CACHE_TTL_SECONDS, SEARCH_CACHE_MAX_ENTRIES, timings,77 unmodified linesreturn Nonereturn item[1]def zip_entries(doc_ids: list[str]) -> list[tuple[str, Path | dict]]:entries = []for doc_id in dict.fromkeys(doc_ids):rec = record_map.get(doc_id)if not rec:1 unmodified lineif uses_sqlite_text(rec):# Fetch one article at ZIP-write time rather than retaining up to# 500 bodies in memory. Non-newspaper entry behavior is unchanged.file_path = recelse:file_path = get_doc_storage_path(rec)if not file_path.exists():48 unmodified linesbackground=BackgroundTask(archive_path.unlink, missing_ok=True),)def run_search(body: SearchRequest, sources_filter=None, timings=None, exact=None):selected_sources = sources_filter if sources_filter is not None else body.sources# `exact` lets the HTTP layer run punctuation queries as normal search while# the request object, response shape, UI toggle and URL stay unchanged.18 unmodified linesbody.search_paths,body.fulltext,)def build_payload():result = (fulltext_search(body.q, selected_sources, body.folders, body.min_size, body.max_size,7 unmodified linestimings,))payload = dict(result)requested_sources = set(selected_sources or source_counts)payload["indexing"] = bool(body.fulltext and not requested_sources.issubset(ready_fulltext_sources()))payload["index_generation"] = fulltext_generation120 unmodified lines@app.get("/txt/{source_slug}/{readable_path:path}")def readable_newspaper_txt(source_slug: str, readable_path: str):doc_id = newspaper_text_path_index.get((source_slug, readable_path))rec = record_map.get(doc_id)if rec is None or not uses_sqlite_text(rec):return PlainTextResponse("text not found", status_code=404)try:2 unmodified linesreturn text_not_found(rec)return Response(body, media_type="text/plain; charset=utf-8", headers={"Content-Disposition": "inline; filename*=UTF-8''" + quote(rec["display_name"] + ".txt", safe=""),"Content-Encoding": "identity", "ETag": '"' + rec["text_sha256"] + '"',})46 unmodified linesreturn text_not_found(rec)return Response(body, media_type="text/plain; charset=utf-8", headers={"Content-Disposition": "attachment; filename*=UTF-8''" + quote(rec["display_name"] + ".txt", safe=""),"Content-Encoding": "identity", "ETag": '"' + rec["text_sha256"] + '"',})file_path = get_doc_storage_path(rec)if not file_path.exists():65 unmodified linesclass OcrMetadataFiles(StaticFiles):def __init__(self, kind):self.kind = kindsuper().__init__(directory=str(BASE_DIR / "data" / kind))async def get_response(self, path, scope):if active_ocr_release:source = Noneif path == "global.json":21 unmodified linesapp.mount("/data/initial", OcrMetadataFiles("initial"), name="initial-data")app.mount("/data/sidebar", OcrMetadataFiles("sidebar"), name="sidebar-data")@lru_cache(maxsize=1)def _manifest_payload() -> dict:return json.loads((BASE_DIR / "static/manifest.json").read_text(encoding="utf-8"))@app.get("/manifest.json")61 unmodified linesinitial_payload = initial_payload_for_path(rest_of_path)sidebar_payload = sidebar_payload_for_path(rest_of_path)global_sidebar_payload = sidebar_payload_for_path("")scripts = []if initial_payload:initial_payload = initial_payload.replace("</", "<\\/")scripts.append(f'<script id="initial-search-data" type="application/json">{initial_payload}</script>')15 unmodified lines1617181920212223241 unmodified line2627282930313211 unmodified lines44454647484950515253545556575859606162636465666768697071727374757677787980818215 unmodified lines98991001011021031041051061071081091101111121138 unmodified lines12212312412512612712826 unmodified lines1551561571581591601614 unmodified lines16616716816917017117212 unmodified lines1851861871881891901911 unmodified line1931941951961971981996 unmodified lines20620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326428 unmodified lines29329429529629729829958 unmodified lines35835936036136236336416 unmodified lines38138238338438538638738813 unmodified lines40240340440540640740840941041141241341441541641724 unmodified lines44244344444544644744844929 unmodified lines47948048148248348448558 unmodified lines54454554654754854955055155225 unmodified lines57857958058158258358458558654 unmodified lines64164264364464564664764864965065165265365426 unmodified lines6816826836846856866876885 unmodified lines6946956966976986997002 unmodified lines7037047057067077087096 unmodified lines71671771871972072172272372472572672717 unmodified lines74574674774874975075175275375475575627 unmodified lines7847857867877887897906 unmodified lines7977987998008018028036 unmodified lines8108118128138148158168178188198208218228234 unmodified lines8288298308318328338348355 unmodified lines84184284384484584684722 unmodified lines87087187287387487587616 unmodified lines89389489589689789889990090190290390416 unmodified lines92192292392492592692713 unmodified lines9419429439449459469479489499509519529539549559569579589592 unmodified lines9629639649659669679687 unmodified lines9769779789799809819829831 unmodified line9859869879889899909915 unmodified lines99799899910001001100210031004100510061007100810091010101110121013101410151 unmodified line1017101810191020102110221023102410251026102710281029103010311032103310341035103690 unmodified lines112711281129113011311132113311341135113611371138113912 unmodified lines1152115311541155115611571158115912 unmodified lines117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001 unmodified line120212031204120512061207120812091210121112121213121435 unmodified lines125012511252125312541255125613 unmodified lines1270127112721273127412751276127712781279128012811282128312841 unmodified line128612871288128912901291129210 unmodified lines13031304130513061307130813094 unmodified lines1314131513161317131813191320132113221323132413257 unmodified lines1333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513565 unmodified lines13621363136413651366136713681369137013711372137313741375137620 unmodified lines1397139813991400140114021403140414051406140714081409141015 unmodified lines142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014515 unmodified lines145714581459146014611462146314641465146614671468146914701471147228 unmodified lines150115021503150415051506150728 unmodified lines15361537153815391540154115424 unmodified lines15471548154915501551155215533 unmodified lines155715581559156015611562156315 unmodified lines157915801581158215831584158515861587158815891590159115921593159415956 unmodified lines160216031604160516061607160839 unmodified lines16481649165016511652165316541655165616571 unmodified line165916601661166216631664166531 unmodified lines169716981699170017011702170317049 unmodified lines171417151716171717181719172036 unmodified lines1757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917802 unmodified lines1783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118122 unmodified lines18151816181718181819182018217 unmodified lines18291830183118321833183418357 unmodified lines184318441845184618471848184918501851185218531854185577 unmodified lines193319341935193619371938193919401 unmodified line194219431944194519461947194848 unmodified lines1997199819992000200120022003200418 unmodified lines20232024202520262027202820297 unmodified lines2037203820392040204120422043120 unmodified lines21642165216621672168216921702 unmodified lines217321742175217621772178217946 unmodified lines222622272228222922302231223265 unmodified lines2298229923002301230223032304230523062307230821 unmodified lines233023312332233323342335233661 unmodified lines239823992400240124022403240415 unmodified linesimport unicodedatafrom functools import lru_cachefrom contextlib import asynccontextmanager, contextmanagerfrom collections.abc import Callable, Iterable, Sequencefrom pathlib import Pathfrom typing import Generator, Literal, NotRequired, Optional, TypedDict, TypeVar, castfrom urllib.parse import parse_qs, quote, unquote, urlencodefrom fastapi import FastAPI, Query, Requestfrom fastapi.middleware.cors import CORSMiddleware1 unmodified linefrom fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Responsefrom fastapi.staticfiles import StaticFilesfrom starlette.background import BackgroundTaskfrom starlette.types import Scopefrom pydantic import BaseModel, Fieldimport ocr_releaseBASE_DIR = Path(__file__).resolve().parent11 unmodified linesFULLTEXT_DIR = BASE_DIR / "data/fulltext"INDEX_BUILD_STATUS_PATH = FULLTEXT_DIR / "build-status.json"BUCKET_INDEX_STATUS_PATH = FULLTEXT_DIR / "bucket-index-status.json"records: list[ocr_release.PublicRecord] = []name_order: list[int] = []size_order: list[int] = []source_name_order: dict[str, list[int]] = {}source_size_order: dict[str, list[int]] = {}record_map: dict[str, ocr_release.PublicRecord] = {}record_map_index: dict[str, int] = {}source_doc_number_index: dict[str, dict[int, int]] = {}newspaper_text_path_index: dict[tuple[str, str], str] = {}class SourceInfo(TypedDict):slug: strname: strcount: intsources: list[SourceInfo] = []source_counts: dict[str, int] = {}# Public OCR repositories are logical sources backed by the one physical OCR# database. Keep the mapping explicit so full-text readiness and doc-number# lookup still use the database's own source key.source_physical_map: dict[str, str] = {}physical_source_counts: dict[str, int] = {}ocr_public_browser: dict[str, dict[str, ocr_release.BrowserEntry]] = {}folder_tree_data: dict[str, list[ocr_release.DirectoryNode]] = {}folder_browser_data: dict[str, dict[str, ocr_release.BrowserEntry]] = {}source_records_map: dict[str, list[int]] = {}extension_counts: dict[str, int] = {}source_extension_counts: dict[str, dict[str, int]] = {}# Posting lists are read-only after build; array("I") keeps 4 bytes per record# id instead of a hash-set entry plus a Python int object.word_index: dict[str, array[int]] = {}latin_all_index: dict[str, array[int]] = {}latin_file_index: dict[str, array[int]] = {}latin_vocabulary_all: set[str] = set()TOKEN_RE = re.compile(r"[a-z0-9]+|[\u4e00-\u9fff\u3400-\u4dbf]+")LATIN_RE = re.compile(r"[a-z0-9]+")15 unmodified linesMETADATA_MATCH_CACHE_MAX_TOTAL_IDS = 250000PREVIEW_CACHE_MAX_ENTRIES = 64PREVIEW_CACHE_MAX_ENTRY_BYTES = 2 * 1024 * 1024api_response_cache: dict[tuple[object, ...], tuple[float, object]] = {}api_response_cache_lock = threading.Lock()search_response_cache: dict[tuple[object, ...], tuple[float, object]] = {}search_response_cache_lock = threading.Lock()metadata_match_cache: dict[tuple[object, ...], frozenset[int]] = {}metadata_match_cache_lock = threading.Lock()metadata_match_cache_generation = 0preview_text_cache: dict[str, str] = {}preview_text_cache_lock = threading.Lock()cache_key_locks: dict[tuple[object, ...], threading.Lock] = {}cache_key_locks_guard = threading.Lock()ZIP_TOKEN_TTL_SECONDS = 600ZIP_TOKEN_MAX_ENTRIES = 328 unmodified lines)FULLTEXT_REFRESH_INTERVAL_SECONDS = max(1, int(os.environ.get("CCRD_FULLTEXT_REFRESH_INTERVAL_SECONDS", "5")))fulltext_refresh_stop = threading.Event()active_ocr_release: ocr_release.Release | None = Noneocr_reader_urls: dict[str, str] = {}def clear_metadata_match_cache() -> None:26 unmodified linesreturn list(dict.fromkeys(TOKEN_RE.findall(normalize_text(text))))def index_tokens(text: str) -> set[str]:tokens: set[str] = set()for part in query_terms(text):if re.fullmatch(r"[\u4e00-\u9fff\u3400-\u4dbf]+", part):tokens.update(part)4 unmodified lines@lru_cache(maxsize=4096)def query_tokens(text: str) -> list[str]:tokens: list[str] = []for part in query_terms(text):if re.fullmatch(r"[\u4e00-\u9fff\u3400-\u4dbf]+", part) and len(part) > 1:tokens.extend(part[index:index + 2] for index in range(len(part) - 1))12 unmodified lines@lru_cache(maxsize=4096)def wildcard_required_tokens(text: str) -> list[str]:tokens: list[str] = []for fixed_part in re.split(r"[*?]+", normalize_text(text)):for term in TOKEN_RE.findall(fixed_part):if re.fullmatch(r"[\u4e00-\u9fff\u3400-\u4dbf]+", term):1 unmodified linereturn list(dict.fromkeys(tokens))def decode_doc_numbers(payload: bytes, candidates: set[int] | None = None) -> set[int]:results: set[int] = set()number = shift = previous = 0for byte in payload:number |= (byte & 0x7F) << shift6 unmodified linesnumber = shift = 0return resultsclass FulltextCandidate(TypedDict):connection: sqlite3.Connectionhas_doc_counts: booltokenizer_version: strhas_content_fts: boolhas_snippet_anchors: boolhas_sqlite_texts: boolhybrid_texts_ready: booldocument_count: intfts_count: intclass FulltextState(TypedDict):has_doc_counts: booltokenizer_version: str | Nonehas_content_fts: boolhas_snippet_anchors: boolhas_sqlite_texts: booldocument_count: intclass SnippetPayload(TypedDict):snippet: strhighlights: list[str]class FulltextDatabases:def __init__(self, directory: Path, in_memory: bool = False, refresh: bool = True,extra_paths: tuple[Path, ...] | list[Path] = (),disk_sources: set[str] | frozenset[str] | None = None):self.directory = directoryself.extra_paths = tuple(extra_paths)self.in_memory = in_memoryself.disk_sources = FULLTEXT_DISK_SOURCES if disk_sources is None else frozenset(disk_sources)self.lock = threading.RLock()self.refresh_lock = threading.Lock()self.connections: dict[str, sqlite3.Connection] = {}self.has_doc_counts: dict[str, bool] = {}self.tokenizer_versions: dict[str, str] = {}self.has_content_fts: dict[str, bool] = {}self.has_snippet_anchors: dict[str, bool] = {}self.has_sqlite_texts: dict[str, bool] = {}self.hybrid_texts_ready: dict[str, bool] = {}self.document_counts: dict[str, int] = {}self.fts_counts: dict[str, int] = {}self.file_signatures: dict[str, tuple[int, int, int]] = {}self.connection_readers: dict[sqlite3.Connection, int] = {}self.retired_connections: set[sqlite3.Connection] = set()self.closed = Falseself.generation = 0self.match_cache: dict[tuple[str, sqlite3.Connection, str, bool], tuple[float, frozenset[int]]] = {}self.match_inflight: dict[tuple[str, sqlite3.Connection, str, bool], threading.Event] = {}if refresh:self.refresh()28 unmodified linescontinueself._install_candidate(path.stem, signature, candidate)def _open_candidate(self, path: Path) -> FulltextCandidate:uri = f"file:{path.resolve()}?mode=ro&immutable=1"source_connection = sqlite3.connect(uri, uri=True, check_same_thread=False)connection = source_connection58 unmodified lines"fts_count": fts_count,}def _install_candidate(self, source: str, signature: tuple[int, int, int], candidate: FulltextCandidate) -> None:connection = candidate["connection"]old_connection = self.connections.get(source)self.connections[source] = connection16 unmodified linesold_connection.close()@contextmanagerdef _lease_source(self, source: str) -> Generator[tuple[sqlite3.Connection, FulltextState] | None, None, None]:lease: tuple[sqlite3.Connection, FulltextState] | Nonewith self.lock:connection = self.connections.get(source)if connection is None or self.closed:13 unmodified linesfinally:if lease is None:returnleased_connection = lease[0]with self.lock:remaining = self.connection_readers.get(leased_connection, 1) - 1if remaining:self.connection_readers[leased_connection] = remainingelse:self.connection_readers.pop(leased_connection, None)if leased_connection in self.retired_connections:self.retired_connections.remove(leased_connection)leased_connection.close()def close(self) -> None:with self.refresh_lock:24 unmodified linesconnection, state = leasereturn self._cached_source_search(source, connection, query, exact, state)def _cached_source_search(self, source: str, connection: sqlite3.Connection, query: str,exact: bool, state: FulltextState) -> set[int]:key = (source, connection, query, exact)event = Nonewhile True:29 unmodified linesself.match_inflight.pop(key)event.set()def _search_source_connection(self, connection: sqlite3.Connection, query: str, exact: bool, state: FulltextState) -> set[int]:version = state["tokenizer_version"]has_content_fts = state["has_content_fts"]has_doc_counts = state["has_doc_counts"]58 unmodified linesif len(rows) != len(token_hashes):return set()posting_rows = [(docs, doc_count) for _token_hash, docs, doc_count in rows]posting_rows.sort(key=lambda item: item[1] if item[1] is not None else 0)else:posting_rows: list[tuple[bytes, int | None]] = []for token_hash in token_hashes:row = connection.execute("SELECT docs FROM postings WHERE token_hash = ?", (token_hash,)).fetchone()if row is None:25 unmodified linesif len(rows) != len(token_hashes):return set()posting_rows = [(docs, doc_count) for _token_hash, docs, doc_count in rows]posting_rows.sort(key=lambda item: item[1] if item[1] is not None else 0)else:posting_rows: list[tuple[bytes, int | None]] = []for token_hash in token_hashes:row = connection.execute("SELECT docs FROM postings WHERE token_hash = ?", (token_hash,)).fetchone()if row is None:54 unmodified linesreturn matcheddef summaries(self, doc_ids: list[str]) -> dict[str, str]:grouped: dict[str, list[str]] = {}for doc_id in doc_ids:grouped.setdefault(doc_id.split(":", 1)[0], []).append(doc_id)with self.lock:missing = any(source not in self.connections for source in grouped)if missing:self.refresh()summaries: dict[str, str] = {}for source, source_doc_ids in grouped.items():with self._lease_source(source) as lease:if lease is None:26 unmodified linesrow = connection.execute(f"SELECT {field} FROM texts WHERE doc_id=?", (doc_id,)).fetchone()return (bool(row) if exists_only else row[0]) if row else Nonedef matched_snippets(self, doc_ids: list[str], query: str, exact: bool = False,timings: dict[str, float | str] | None = None) -> dict[str, SnippetPayload]:normalized_query = normalize_text(query.strip())# A fixed wildcard fragment can occur long before the actual match.# Let the original-text snippet endpoint locate the verified span.5 unmodified linesneedle = next(iter(query_tokens(query)), "")if not needle:return {}grouped: dict[str, list[tuple[str, int]]] = {}for doc_id in doc_ids:source, _, number = doc_id.partition(":")if number.isdigit():2 unmodified linesmissing = any(source not in self.connections for source in grouped)if missing:self.refresh()snippets: dict[str, SnippetPayload] = {}for source, source_docs in grouped.items():with self._lease_source(source) as lease:if lease is None:6 unmodified lines)return snippetsdef _matched_snippets_source(self, snippets: dict[str, SnippetPayload], connection: sqlite3.Connection,state: FulltextState, source_docs: list[tuple[str, int]],needle: str, query: str, exact: bool, timings: dict[str, float | str] | None) -> None:doc_id_by_number = {number: doc_id for doc_id, number in source_docs}numbers = list(doc_id_by_number)anchored_numbers: set[int] = set()# Exact snippets retain the established literal path. Normal snippets can seek# directly to a token anchor without scanning FTS content with instr().if not exact and state["has_snippet_anchors"]:17 unmodified lines[needle, token_hash, *batch],).fetchall()if timings is not None:timings["snippet_anchor_sql"] = float(timings.get("snippet_anchor_sql", 0)) + (time.perf_counter() - anchor_started) * 1000for number, char_offset, text in rows:payload_started = time.perf_counter()payload = build_normalized_snippet_payload(text or "", query)if timings is not None:timings["snippet_payload"] = float(timings.get("snippet_payload", 0)) + (time.perf_counter() - payload_started) * 1000if not payload["highlights"]:continueextracted_start = max(int(char_offset) - 219, 1)27 unmodified lines[needle, *batch, needle],).fetchall()if timings is not None:timings["snippet_fallback_sql"] = float(timings.get("snippet_fallback_sql", 0)) + (time.perf_counter() - fallback_started) * 1000for number, match_position, text in rows:payload_started = time.perf_counter()extracted_start = max(int(match_position or 0) - 220, 1)6 unmodified linesif not payload["highlights"]:payload = build_snippet_payload(text or "", needle, exact=True)if timings is not None:timings["snippet_payload"] = float(timings.get("snippet_payload", 0)) + (time.perf_counter() - payload_started) * 1000if payload["snippet"] and extracted_start > 1 and not payload["snippet"].startswith("..."):payload["snippet"] = "..." + payload["snippet"]if payload["snippet"] and len(text or "") > 440 + len(needle) and not payload["snippet"].endswith("..."):6 unmodified linesdef tokenize(text: str) -> list[str]:return query_terms(text)def compile_exact_query(query: str) -> tuple[str, re.Pattern[str] | None]:normalized_query = normalize_text(query)if has_wildcard_query(normalized_query):expression = re.escape(normalized_query).replace(r"\*", ".*?").replace(r"\?", ".")return normalized_query, re.compile(expression, re.DOTALL)return normalized_query, Nonedef matches_normalized_exact_query(text: str, normalized_query: str, pattern: re.Pattern[str] | None = None) -> bool:return pattern.search(text) is not None if pattern is not None else normalized_query in textdef matches_exact_query(text: str, query: str) -> bool:4 unmodified linesreturn "*" in query or "?" in querydef normalized_text_map(text: str) -> tuple[str, list[tuple[int, int]]]:normalized: list[str] = []offsets: list[tuple[int, int]] = []for index, character in enumerate(text):value = normalize_text(character)normalized.append(value)5 unmodified linesnormalized_query = normalize_text(query.strip())if not normalized_text or not normalized_query or not offsets:return []normalized_spans: list[tuple[int, int]] = []if exact:if has_wildcard_query(normalized_query):pattern = re.escape(normalized_query).replace(r"\*", ".*?").replace(r"\?", ".")22 unmodified linesif start < end and end <= len(offsets)]def build_snippet_payload(text: str, query: str, window: int = 110, exact: bool = False) -> SnippetPayload:query = (query or "").strip()if not text or not query:return {"snippet": "", "highlights": []}16 unmodified lines))return {"snippet": snippet, "highlights": [value for value in highlights if value]}def build_normalized_snippet_payload(text: str, query: str, window: int = 110) -> SnippetPayload:"""Build a normal-search snippet when text already came from normalized content_fts."""query = (query or "").strip()if not text or not query:return {"snippet": "", "highlights": []}spans: list[tuple[int, int]] = []for token in query_tokens(query):token = normalize_text(token)index = text.find(token)16 unmodified lines))return {"snippet": snippet, "highlights": [value for value in highlights if value]}def build_normalized_exact_snippet_payload(text: str, query: str, window: int = 110) -> SnippetPayload:needle = normalize_text(query.strip())index = text.find(needle)if index == -1:13 unmodified linesdef load_json_gz(path: Path):return json.loads(gzip.decompress(path.read_bytes()).decode("utf-8"))def public_source_slug(rec: ocr_release.PublicRecord) -> str:return rec.get("public_source") or rec["source"]def public_source_name(rec: ocr_release.PublicRecord) -> str:return rec.get("public_source_name") or rec["source_name"]def public_record_dirs(rec: ocr_release.PublicRecord) -> list[str]:return rec.get("public_dirs", rec.get("display_dirs", []))def public_record_path(rec: ocr_release.PublicRecord) -> str:return rec.get("public_rel_path") or rec["display_rel_path"]def _find_tree_node(nodes: list[ocr_release.DirectoryNode], target: str) -> ocr_release.DirectoryNode | None:for node in nodes:if node.get("path") == target:return node2 unmodified linesreturn foundreturn Nonedef _rebase_tree_node(node: ocr_release.DirectoryNode, prefix: str) -> ocr_release.DirectoryNode:path = node.get("path", "")if path == prefix:relative = ""7 unmodified lines"children": [_rebase_tree_node(child, prefix) for child in node.get("children", [])],}def _rebase_ocr_browser(browser: dict[str, ocr_release.BrowserEntry], prefix: str) -> dict[str, ocr_release.BrowserEntry]:result: dict[str, ocr_release.BrowserEntry] = {}for full_path, entry in browser.items():if full_path == prefix:relative = ""1 unmodified linerelative = full_path[len(prefix) + 1:]else:continuefolders: list[ocr_release.DirectoryFolder] = []for folder in entry.get("folders", []):folder_path = folder.get("path", "")if folder_path == prefix:5 unmodified linesfolders.append({**folder, "path": folder_relative})result[relative] = {"folders": folders,"files": [file.copy() for file in entry.get("files", [])],}result.setdefault("", {"folders": [], "files": []})return resultclass OcrPublicLayout(TypedDict):sources: list[SourceInfo]trees: dict[str, list[ocr_release.DirectoryNode]]browsers: dict[str, dict[str, ocr_release.BrowserEntry]]physical_map: dict[str, str]def build_ocr_public_layout(extra: ocr_release.Release, base_slugs: set[str]) -> OcrPublicLayout:"""Expose each OCR origin repository as its own logical source.The OCR release keeps one physical database and ``OCR:<n>`` document IDs.1 unmodified linerelease contract, full-text index, TXT URLs and downloads stay unchanged."""records = extra.get("records") or []groups: dict[tuple[str, str], list[ocr_release.PublicRecord]] = {}for rec in records:public_rec = cast(ocr_release.PublicRecord, rec)dirs = rec.get("display_dirs") or []if len(dirs) < 2 or not dirs[0] or not dirs[1]:raise ValueError("OCR record lacks owner/repository hierarchy")groups.setdefault((dirs[0], dirs[1]), []).append(public_rec)tree = extra.get("tree") or []browser = extra.get("browser") or {}used = set(base_slugs)public_sources: list[SourceInfo] = []trees: dict[str, list[ocr_release.DirectoryNode]] = {}browsers: dict[str, dict[str, ocr_release.BrowserEntry]] = {}physical_map: dict[str, str] = {}for owner, repo in sorted(groups, key=lambda item: (item[1], item[0])):group = groups[(owner, repo)]slug = repo90 unmodified linesposting.append(idx)name_order = sorted(range(len(records)),key=lambda idx: (records[idx].get("_rank_path_key", ""), records[idx]["doc_id"]),)size_order = sorted(range(len(records)),key=lambda idx: (-(records[idx].get("size") or 0),records[idx].get("_rank_path_key", ""),records[idx]["doc_id"],),)12 unmodified lines(uppercase escapes, decode escaped unreserved ASCII, never decode ``%2F`` ordouble-decode ``%25``), then FNV-1a 64-bit as base36 padded to 13 chars."""def replace_path(match: re.Match[str]) -> str:def replace_token(token_match: re.Match[str]) -> str:token = token_match.group()if len(token) == 3:char = chr(int(token[1:], 16))12 unmodified linesreturn (output or "0").rjust(13, "0")def ocr_reader_url(export: dict[str, object]) -> str:"""Deep link to the existing HF Search Reader in its converted image mode.``?id=`` resolves the Reader record, which selects ``pdf-pages`` (theconverted page stream) instead of opening the raw PDF with ``?url=``."""repo = export.get("origin_repo")path = export.get("origin_rel_path")if not isinstance(repo, str) or not isinstance(path, str):return ""if not repo.startswith("VoiceOfML/") or not path:return ""source = f"https://huggingface.co/datasets/{repo}/resolve/main/" + quote(path, safe="/")readable = export.get("readable_rel_path")if not isinstance(readable, str) or not readable:readable = pathtitle = readable.rsplit("/", 1)[-1]if "." in title:title = title.rsplit(".", 1)[0]return f"{HF_SEARCH_READER}?{urlencode({'id': reader_source_id(source), 'title': title, 'ext': 'pdf-pages'})}"def intern_shared_strings(records: list[ocr_release.PublicRecord]) -> None:"""Share repeated structural strings across records.JSON decoding creates a separate string object for every occurrence. Source1 unmodified linethousands of records, so interning them removes that duplication withoutchanging any value or comparison."""for rec in records:rec["source"] = sys.intern(rec["source"])rec["source_name"] = sys.intern(rec["source_name"])rec["storage_root"] = sys.intern(rec["storage_root"])rec["extension"] = sys.intern(rec["extension"])if isinstance(text_storage := rec.get("text_storage"), str):rec["text_storage"] = sys.intern(text_storage)dirs = rec.get("display_dirs")if type(dirs) is list:for index, value in enumerate(dirs):35 unmodified linesocr_public_browser = {}layout = Noneif extra:records = [*records, *(cast(ocr_release.PublicRecord, rec) for rec in extra["records"])]layout = build_ocr_public_layout(extra, {item["slug"] for item in base_sources})sources = [*sources, *layout["sources"]]physical_source_counts["OCR"] = len(extra["records"])13 unmodified linesfor export in extra.get("exports", []):url = ocr_reader_url(export)if url:ocr_reader_urls[str(export["doc_id"])] = urlintern_shared_strings(records)build_indexes()print(f"loaded {len(records)} txt records in {time.time() - start:.2f}s")def score_record(idx: int, query_tokens: list[str], search_paths: bool = True) -> int:score = 0file_text = records[idx].get("_file_search_text", "")path_text = records[idx].get("_path_search_text", "")for token in query_tokens:if token in file_text:score += 31 unmodified linescore += 2return scoredef relevance_page(indices: Iterable[int], query_tokens: list[str], search_paths: bool, start: int, page_size: int) -> list[int]:limit = start + page_sizeif limit <= 0:return []10 unmodified linesif len(candidates) == len(indices) and len(potential) >= limit:# Only maximum-score hits can make unseen candidates irrelevant.maximum = (5 if search_paths else 3) * len(query_tokens)highest: list[int] = []for idx in name_order:if idx in potential and score_record(idx, query_tokens, search_paths) == maximum:highest.append(idx)4 unmodified linesscores = {idx: score_record(idx, query_tokens, search_paths) for idx in indices}if len(scores) == len(indices):# Scores are small integers; the global name order supplies exact ties.buckets: dict[int, list[int]] = {}for idx in name_order:score = scores.get(idx)if score is not None:buckets.setdefault(score, []).append(idx)selected: list[int] = []for score in sorted(buckets, reverse=True):bucket = buckets[score]if start >= len(bucket):7 unmodified linesranked = heapq.nsmallest(limit,indices,key=lambda idx: (-score_record(idx, query_tokens, search_paths), records[idx].get("_rank_path_key", ""), records[idx]["doc_id"]),)return ranked[start:limit]def ordered_page(indices: Iterable[int], ordering: list[int], start: int, page_size: int) -> list[int]:candidates = set(indices)if not candidates or page_size <= 0 or start >= len(candidates):return []if len(candidates) <= page_size:if ordering is name_order:ranked = sorted(candidates, key=lambda idx: (records[idx].get("_rank_path_key", ""), records[idx]["doc_id"]))return ranked[start:start + page_size]if ordering is size_order:ranked = sorted(candidates, key=lambda idx: (-(records[idx].get("size") or 0), records[idx].get("_rank_path_key", ""), records[idx]["doc_id"],))return ranked[start:start + page_size]selected: list[int] = []matched = 0for idx in ordering:if idx not in candidates:5 unmodified linesmatched += 1return selecteddef apply_filters(indices: Iterable[int], sources_filter: Sequence[str] | None = None,folders: Sequence[str] | None = None, min_size: int | None = None,max_size: int | None = None) -> list[int]:if not has_filters(sources_filter, folders, min_size, max_size):return list(indices)selected_sources = set(sources_filter) if sources_filter is not None else Noneselected_folders = set(folders or [])single_folder = next(iter(selected_folders)) if len(selected_folders) == 1 else Noneresult: list[int] = []for idx in indices:rec = records[idx]if selected_sources is not None and public_source_slug(rec) not in selected_sources:20 unmodified linesresult.append(idx)return resultdef has_filters(sources_filter: Sequence[str] | None = None, folders: Sequence[str] | None = None,min_size: int | None = None, max_size: int | None = None) -> bool:return bool(sources_filter is not None or folders or min_size is not None or max_size is not None)def empty_query_order(sources_filter: Sequence[str] | None = None, folders: Sequence[str] | None = None,min_size: int | None = None, max_size: int | None = None,sort: str = "relevance") -> list[int] | range | None:if folders or min_size is not None or max_size is not None:return Noneif sources_filter is None:15 unmodified linesreturn source_records_map.get(source, [])return Noneclass SearchResult(TypedDict):doc_id: strSource: strSourceName: strFile: strExtension: strFolder: list[str]DisplayPath: strSize: intHasTxt: boolTextUrl: NotRequired[str]TextQuality: NotRequired[str]TextGeneration: NotRequired[str | None]snippet: NotRequired[str]snippet_highlights: NotRequired[list[str]]snippet_complete: NotRequired[bool]def trim_record(rec: ocr_release.PublicRecord) -> SearchResult:item: SearchResult = {"doc_id": rec["doc_id"],"Source": public_source_slug(rec),"SourceName": public_source_name(rec),5 unmodified lines"HasTxt": True,}if rec.get("source") == "OCR":item["TextUrl"] = "/txt/OCR/" + quote(rec["display_rel_path"], safe="/")item["TextQuality"] = rec.get("text_quality", "unreviewed")item["TextGeneration"] = rec.get("text_generation")elif uses_sqlite_text(rec):item["TextUrl"] = "/txt/" + rec["source"] + "/" + quote(rec["storage_rel_path"], safe="/")return itemdef add_summaries(items: list[SearchResult], query: str = "", matched_snippets: bool = False,content_indices: set[int] | None = None, exact: bool = False,timings: dict[str, float | str] | None = None) -> list[SearchResult]:if fulltext_databases is None or not items:return itemssummaries_started = time.perf_counter()28 unmodified linesreturn candidatesdef metadata_prefilter(terms: list[str], search_paths: bool) -> set[int] | None:postings: list[set[int] | array[int]] = []for term in terms:if LATIN_RE.fullmatch(term):indices = latin_substring_candidates(term, search_paths)28 unmodified linesif has_wildcard_query(q):candidate_set = Nonefor token in wildcard_required_tokens(normalized_query):token_indices: Iterable[int] = word_index.get(token, array("I"))candidate_set = set(token_indices) if candidate_set is None else candidate_set.intersection(token_indices)if not candidate_set:return set()4 unmodified linescandidates = metadata_prefilter(terms, search_paths) or set()return {idx for idx in candidatesif matches_normalized_exact_query(records[idx].get(field, ""), normalized_query, pattern)}terms = query_terms(q)if not terms:3 unmodified linescandidates = range(len(records))return {idx for idx in candidatesif all(term in records[idx].get(field, "") for term in terms)}15 unmodified linesmetadata_match_cache.pop(next(iter(metadata_match_cache)), None)return resultclass SearchPage(TypedDict):results: list[SearchResult]total: intpage: intpage_size: intdef search(q: str = "", sources_filter: list[str] | None = None, folders: list[str] | None = None,min_size: int | None = None, max_size: int | None = None, page: int = 1,page_size: int = 100, sort: str = "relevance", exact: bool = False,search_paths: bool = True, timings: dict[str, float | str] | None = None) -> SearchPage:started = time.perf_counter()q = q.strip()start = (page - 1) * page_size6 unmodified linestimings["decorate"] = (time.perf_counter() - summaries_started) * 1000timings["engine"] = (time.perf_counter() - started) * 1000return {"results": result_items, "total": len(preordered), "page": page, "page_size": page_size}paged_indices: list[int] = []if not q:indices = list(range(len(records)))filter_started = time.perf_counter()39 unmodified linestimings["engine"] = (time.perf_counter() - started) * 1000return {"results": result_items, "total": total, "page": page, "page_size": page_size}def fulltext_search(q: str = "", sources_filter: list[str] | None = None, folders: list[str] | None = None,min_size: int | None = None, max_size: int | None = None, page: int = 1,page_size: int = 100, sort: str = "relevance", exact: bool = False,search_paths: bool = True, timings: dict[str, float | str] | None = None) -> SearchPage:started = time.perf_counter()q = q.strip()if not q or fulltext_databases is None:1 unmodified linesource_slugs = sources_filter if sources_filter is not None else list(source_counts)if not source_slugs:return {"results": [], "total": 0, "page": max(1, page), "page_size": page_size}content_indices: set[int] = set()sqlite_started = time.perf_counter()physical_slugs = list(dict.fromkeys(source_physical_map.get(slug, slug) for slug in source_slugs))for physical_slug in physical_slugs:31 unmodified linesselected = ordered_page(filtered, size_order, (page - 1) * page_size, page_size)if timings is not None:timings["sort"] = (time.perf_counter() - sort_started) * 1000else:selected = filtered[(page - 1) * page_size:page * page_size]total = len(filtered)summaries_started = time.perf_counter()result_items = add_summaries(9 unmodified linestimings["engine"] = (time.perf_counter() - started) * 1000return {"results": result_items, "total": total, "page": page, "page_size": page_size}def get_doc_storage_path(doc: ocr_release.PublicRecord | ocr_release.OcrRecord) -> Path:if doc.get("source") == "OCR" and active_ocr_release is not None:return active_ocr_release["text_paths"][doc["doc_id"]]return BASE_DIR / doc["storage_root"] / doc["storage_rel_path"]36 unmodified linesreturn textdef uses_sqlite_text(rec: ocr_release.PublicRecord) -> bool:return rec.get("source") in NEWSPAPER_SOURCES and rec.get("text_storage") == "sqlite"def document_text_exists(rec: ocr_release.PublicRecord) -> bool:if uses_sqlite_text(rec):return fulltext_databases is not None and fulltext_databases.stored_text(rec["doc_id"], exists_only=True) is Truereturn get_doc_storage_path(rec).exists()def read_document_text(rec: ocr_release.PublicRecord, *, preview: bool = False) -> str:if uses_sqlite_text(rec):body = fulltext_databases.stored_text(rec["doc_id"]) if fulltext_databases is not None else Noneif not isinstance(body, str):raise FileNotFoundError(rec["doc_id"])payload = body.encode("utf-8")if (len(payload) != rec.get("size") or not re.fullmatch(r"[0-9a-f]{64}", rec.get("text_sha256", ""))or hashlib.sha256(payload).hexdigest() != rec.get("text_sha256")):raise ValueError("stored newspaper TXT differs from the pinned metadata")return bodypath = get_doc_storage_path(rec)2 unmodified linesreturn read_preview_text(rec["doc_id"], path) if preview else read_source_text(path)def text_not_found(rec: ocr_release.PublicRecord) -> JSONResponse:if uses_sqlite_text(rec):return JSONResponse({"error": "text index unavailable", "indexing": True}, status_code=503)return JSONResponse({"error": f"missing file: {get_doc_storage_path(rec).name}"}, status_code=404)class FolderContents(ocr_release.BrowserEntry):current_path: strdef get_folder_contents(source_slug: str, path: str) -> FolderContents:source_browser = folder_browser_data.get(source_slug, {})if path in source_browser:entry = dict(source_browser[path])entry["current_path"] = pathreturn cast(FolderContents, entry)return {"folders": [], "files": [], "current_path": path}CacheValue = TypeVar("CacheValue")TimingValues = dict[str, float | str]def _cached_payload(cache: dict[tuple[object, ...], tuple[float, object]], lock: threading.Lock,key: tuple[object, ...], builder: Callable[[], CacheValue], ttl: int, max_entries: int,timings: TimingValues | None = None) -> CacheValue:cache_started = time.perf_counter()now = time.monotonic()with lock:2 unmodified linesif timings is not None:timings["cache"] = "hit"timings["cache_lookup"] = (time.perf_counter() - cache_started) * 1000return cast(CacheValue, cached[1])if timings is not None:timings["cache"] = "miss"timings["cache_lookup"] = (time.perf_counter() - cache_started) * 10007 unmodified lineswith lock:cached = cache.get(key)if cached and now - cached[0] < ttl:return cast(CacheValue, cached[1])value = builder()inserted_at = time.monotonic()with lock:7 unmodified linesif cache_key_locks.get(key) is key_lock:cache_key_locks.pop(key, None)def cached_payload(key: tuple[object, ...], builder: Callable[[], CacheValue], timings: TimingValues | None = None) -> CacheValue:return _cached_payload(api_response_cache, api_response_cache_lock, key, builder,API_CACHE_TTL_SECONDS, API_CACHE_MAX_ENTRIES, timings,)def cached_search_payload(key: tuple[object, ...], builder: Callable[[], CacheValue], timings: TimingValues | None = None) -> CacheValue:return _cached_payload(search_response_cache, search_response_cache_lock, key, builder,SEARCH_CACHE_TTL_SECONDS, SEARCH_CACHE_MAX_ENTRIES, timings,77 unmodified linesreturn Nonereturn item[1]def zip_entries(doc_ids: list[str]) -> list[tuple[str, Path | ocr_release.PublicRecord]]:entries: list[tuple[str, Path | ocr_release.PublicRecord]] = []for doc_id in dict.fromkeys(doc_ids):rec = record_map.get(doc_id)if not rec:1 unmodified lineif uses_sqlite_text(rec):# Fetch one article at ZIP-write time rather than retaining up to# 500 bodies in memory. Non-newspaper entry behavior is unchanged.file_path: Path | ocr_release.PublicRecord = recelse:file_path = get_doc_storage_path(rec)if not file_path.exists():48 unmodified linesbackground=BackgroundTask(archive_path.unlink, missing_ok=True),)def run_search(body: SearchRequest, sources_filter: list[str] | None = None,timings: TimingValues | None = None, exact: bool | None = None) -> dict[str, object]:selected_sources = sources_filter if sources_filter is not None else body.sources# `exact` lets the HTTP layer run punctuation queries as normal search while# the request object, response shape, UI toggle and URL stay unchanged.18 unmodified linesbody.search_paths,body.fulltext,)def build_payload() -> dict[str, object]:result = (fulltext_search(body.q, selected_sources, body.folders, body.min_size, body.max_size,7 unmodified linestimings,))payload: dict[str, object] = dict(result)requested_sources = set(selected_sources or source_counts)payload["indexing"] = bool(body.fulltext and not requested_sources.issubset(ready_fulltext_sources()))payload["index_generation"] = fulltext_generation120 unmodified lines@app.get("/txt/{source_slug}/{readable_path:path}")def readable_newspaper_txt(source_slug: str, readable_path: str):doc_id = newspaper_text_path_index.get((source_slug, readable_path))rec = record_map.get(doc_id) if doc_id is not None else Noneif rec is None or not uses_sqlite_text(rec):return PlainTextResponse("text not found", status_code=404)try:2 unmodified linesreturn text_not_found(rec)return Response(body, media_type="text/plain; charset=utf-8", headers={"Content-Disposition": "inline; filename*=UTF-8''" + quote(rec["display_name"] + ".txt", safe=""),"Content-Encoding": "identity", "ETag": '"' + rec.get("text_sha256", "") + '"',})46 unmodified linesreturn text_not_found(rec)return Response(body, media_type="text/plain; charset=utf-8", headers={"Content-Disposition": "attachment; filename*=UTF-8''" + quote(rec["display_name"] + ".txt", safe=""),"Content-Encoding": "identity", "ETag": '"' + rec.get("text_sha256", "") + '"',})file_path = get_doc_storage_path(rec)if not file_path.exists():65 unmodified linesclass OcrMetadataFiles(StaticFiles):def __init__(self, kind: Literal["initial", "sidebar"]):self.kind = kindsuper().__init__(directory=str(BASE_DIR / "data" / kind))async def get_response(self, path: str, scope: Scope) -> Response:if active_ocr_release:source = Noneif path == "global.json":21 unmodified linesapp.mount("/data/initial", OcrMetadataFiles("initial"), name="initial-data")app.mount("/data/sidebar", OcrMetadataFiles("sidebar"), name="sidebar-data")@lru_cache(maxsize=1)def _manifest_payload() -> dict[str, object]:return json.loads((BASE_DIR / "static/manifest.json").read_text(encoding="utf-8"))@app.get("/manifest.json")61 unmodified linesinitial_payload = initial_payload_for_path(rest_of_path)sidebar_payload = sidebar_payload_for_path(rest_of_path)global_sidebar_payload = sidebar_payload_for_path("")scripts: list[str] = []if initial_payload:initial_payload = initial_payload.replace("</", "<\\/")scripts.append(f'<script id="initial-search-data" type="application/json">{initial_payload}</script>')
10 unmodified lines1112131415162 unmodified lines1920212223242526272829303132333435363738391 unmodified line414243444546474812 unmodified lines6162636465666768697071724 unmodified lines77787980818283848586878889909192939495969798991001011025 unmodified lines10810911011111211311411511611711811912011 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571581591 unmodified line1611621631641651661671681691701713 unmodified lines1751761771781791801811821831845 unmodified lines19019119219319419519616 unmodified lines2132142152162172182192 unmodified lines2222232242252262272282 unmodified lines2312322332342352362372382392402412 unmodified lines2442452462472482492502512522533 unmodified lines25725825926026126226326426526626726826927027127227327427527610 unmodified linesimport sqlite3import tempfileimport unicodedataBUCKET = "vomebook/ccrd-index"2 unmodified linesSOURCE_NAME = "VoiceOfML"def canonical(value) -> bytes:return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n").encode()def digest(value) -> str:return hashlib.sha256(value).hexdigest()def sha(value) -> str:if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):raise ValueError("invalid release SHA-256")return valuedef safe_path(value: str) -> str:if (not isinstance(value, str) or not value or value.startswith("/") or "\\" in valueor any(part in {"", ".", ".."} for part in value.split("/"))or any(ord(char) < 32 for char in value)):1 unmodified linereturn valuedef read_resource(root: Path, ref: dict) -> bytes:if not isinstance(ref, dict) or ref.get("bucket") != BUCKET:raise ValueError("wrong OCR release bucket")path = safe_path(ref.get("path"))if not path.startswith(("text/objects/", "text/exports/", "indexes/ocr/")):12 unmodified linesreturn rawdef export_record(root: Path, ref: dict) -> tuple[dict, dict]:export = json.loads(read_resource(root, ref))if (export.get("kind") != "ccrd-ocr-text-export" or export.get("version") != 1or export.get("complete") is not True or export.get("recipe") != "ocr-plain-utf8-pages-v1"):raise ValueError("unsupported OCR export schema")if not re.fullmatch(r"OCR:[1-9][0-9]*", str(export.get("doc_id", ""))) or int(export["doc_id"].split(":")[1]) >= 1 << 63:raise ValueError("invalid OCR document identity")repo, original = export.get("origin_repo"), safe_path(export.get("origin_rel_path"))if not isinstance(repo, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", repo):4 unmodified linesexpected_path = repo + "/" + str(PurePosixPath(original).with_suffix(".txt"))if readable != expected_path:raise ValueError("OCR readable path does not preserve its origin")raw = read_resource(root, export.get("text"))body = raw.decode("utf-8", errors="strict")if body.startswith("\ufeff"):raise ValueError("plain OCR export must not hide a BOM in its indexed text")identity = {key: export[key] for key in ("recipe", "origin_repo", "origin_rel_path", "origin_revision", "origin_sha256","source_sha256", "doc_id", "text_generation", "txt_sha256")}if 'body_admission' in export or 'body_admission_sha256' in export:admission = export.get('body_admission', {})summary = admission.get('quality_check', {})if (admission.get('policy') != 'complete-body-quality-v1'or admission.get('source_sha256') != export.get('source_sha256')or admission.get('text_generation') != export.get('text_generation')or summary.get('status') != 'passed' or summary.get('issues') != []or summary.get('checked_pages') != export.get('page_count')or summary.get('page_count') != export.get('page_count')or [p.get('page') for p in admission.get('pages', [])] != list(range(1, export.get('page_count', 0) + 1))or any(p.get('quality_check', {}).get('status') != 'passed'or p.get('quality_check', {}).get('issues') != []or p.get('quality_check', {}).get('page') != p.get('page')for p in admission.get('pages', []))or digest(canonical(admission).rstrip(b'\n')) != export.get('body_admission_sha256')):raise ValueError('invalid complete-body quality admission')identity['body_admission_sha256'] = sha(export['body_admission_sha256'])5 unmodified linesif (generation != export["generation"] or digest(raw) != export["txt_sha256"]or export["book_id"] != digest((repo + "\0" + original).encode())):raise ValueError("OCR export generation mismatch")pages, count = export.get("pages"), export.get("page_count")if type(count) is not int or count < 1 or not isinstance(pages, list) or len(pages) != count:raise ValueError("OCR export is missing pages")if export.get("offset_unit") != "unicode-codepoint" or export.get("page_separator") != "\n\n":raise ValueError("unsupported page offset recipe")cursor, reviewed = 0, 0for number, page in enumerate(pages, 1):start, end = page.get("start"), page.get("end")if (page.get("page") != number or type(start) is not int or type(end) is not intor start != cursor or not start <= end <= len(body)):11 unmodified linescursor += 2if cursor != len(body) or export.get("accepted_pages") != reviewed or export.get("quality") != ("partially-reviewed" if reviewed else "unreviewed"):raise ValueError("OCR whole-book coverage/quality mismatch")resources = export.get("retained_reader_resources")if not isinstance(resources, list) or not resources:raise ValueError("OCR provenance retention references are missing")for resource in resources:if resource.get("bucket") not in {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2", "melsm/pdf-archive-v2"}:raise ValueError("unknown retained Reader bucket")safe_path(resource.get("path")); sha(resource.get("sha256"))if type(resource.get("bytes")) is not int or resource["bytes"] < 1:raise ValueError("invalid retained Reader resource")path = PurePosixPath(readable)record = {"doc_id": export["doc_id"], "source": SOURCE, "source_name": SOURCE_NAME,"display_name": path.stem, "display_dirs": list(path.parts[:-1]), "display_rel_path": readable,"extension": "txt", "size": len(raw), "has_preview": True, "has_fulltext": True,"storage_root": ".", "storage_rel_path": export["text"]["path"],"text_generation": export["text_generation"], "text_quality": export["quality"]}return record, exportdef directory_payloads(records: list[dict]) -> tuple[list[dict], dict]:browser = defaultdict(lambda: {"folders": [], "files": []})counts, direct = defaultdict(int), defaultdict(list)children = defaultdict(set)for record in records:parts = record["display_dirs"]for depth in range(len(parts) + 1):1 unmodified lineif depth < len(parts): children[path].add(parts[depth])direct["/".join(parts)].append(record)for path in counts:browser[path]["folders"] = [{"name": name, "path": (path + "/" if path else "") + name,"count": counts[(path + "/" if path else "") + name]} for name in sorted(children[path])]browser[path]["files"] = [{"name": item["display_name"], "ext": "txt", "size": item["size"],"doc_id": item["doc_id"]} for item in sorted(direct[path], key=lambda item: (item["display_name"], item["doc_id"]))]def node(name, path):return {"name": name, "path": path, "count": counts[path], "hasDirectFiles": bool(direct[path]),"hasChildren": bool(children[path]), "showSelfToggle": bool(path and direct[path] and children[path]),"children": [node(child, (path + "/" if path else "") + child) for child in sorted(children[path])]}3 unmodified linesreturn [node(child, child) for child in sorted(children[""])], dict(browser)def zip_member(record: dict) -> str:"""Keep legal origin hierarchy; bound non-portable components deterministically."""replacements = {":": ":", "*": "*", "?": "?", '"': """, "<": "<", ">": ">", "|": "|", "\\": "\"}def component(original):value = re.sub(r'[:*?"<>|\\\x00-\x1f]', lambda match: replacements.get(match[0], "_"), original).rstrip(" .") or "_"if value != original or len(value.encode()) > 180:suffix = "-" + digest(original.encode())[:12]5 unmodified linesreturn "/".join([component(part) for part in parts])def validate_database(path: Path, records: list[dict], text_root: Path) -> None:with sqlite3.connect(f"file:{path.resolve()}?mode=ro&immutable=1", uri=True) as db:if db.execute("PRAGMA integrity_check").fetchone()[0] != "ok":raise ValueError("invalid OCR SQLite integrity")16 unmodified linesraise ValueError("OCR snippet anchor schema missing")def load_release(bucket: Path, manifest_path: str, expected_sha256: str, base_metadata_sha256: str) -> dict:safe_path(manifest_path); sha(expected_sha256); sha(base_metadata_sha256)bucket = bucket.resolve()target = (bucket / manifest_path).resolve()2 unmodified linesraw = target.read_bytes()if digest(raw) != expected_sha256:raise ValueError("OCR release manifest checksum mismatch")manifest = json.loads(raw)if (manifest.get("kind") != "ccrd-ocr-search-release" or manifest.get("version") != 1or manifest.get("tokenizer_version") != TOKENIZER or manifest.get("base_metadata_sha256") != base_metadata_sha256):raise ValueError("incompatible OCR release/base snapshot")2 unmodified linesif (manifest["generation"] != digest(canonical(identity))or manifest_path != f'releases/ocr-{manifest["generation"]}/manifest.json'):raise ValueError("OCR release identity/path mismatch")refs = manifest.get("exports")if not isinstance(refs, list) or not refs:raise ValueError("empty OCR release")records, exports = [], []ids, paths = set(), set()for ref in refs:record, export = export_record(bucket, ref)if record["doc_id"] in ids or record["display_rel_path"] in paths:2 unmodified linesrecords.append(record); exports.append(export)if manifest.get("documents") != len(records):raise ValueError("OCR release count mismatch")database = manifest.get("database")read_resource(bucket, database)db_path = (bucket / database["path"]).resolve()if database["path"] != f'indexes/ocr/{manifest["generation"]}/OCR.sqlite3':raise ValueError("OCR database must retain its source namespace")validate_database(db_path, records, bucket)tree, browser = directory_payloads(records)3 unmodified linesdef pin_release(bucket: Path, manifest_path: str, expected_sha256: str,base_metadata_sha256: str, cache: Path) -> dict:"""Verify the whole candidate before pinning a process-local immutable copy."""candidate = load_release(bucket, manifest_path, expected_sha256, base_metadata_sha256)cache.mkdir(parents=True, exist_ok=True)destination = cache / candidate["manifest"]["generation"]if destination.exists():return load_release(destination, manifest_path, expected_sha256, base_metadata_sha256)stage = Path(tempfile.mkdtemp(prefix="ocr-stage-", dir=cache))try:refs = [*candidate["manifest"]["exports"], candidate["manifest"]["database"],*[export["text"] for export in candidate["exports"]]]for ref in refs:raw = read_resource(bucket, ref)target = stage / ref["path"]target.parent.mkdir(parents=True, exist_ok=True)with target.open("wb") as output:output.write(raw); output.flush(); os.fsync(output.fileno())10 unmodified lines11121314151617182 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311 unmodified line13313413513613713813914014112 unmodified lines1541551561571581591601611621631641651664 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012025 unmodified lines20820921021121221321421521621721821922022122222322411 unmodified lines2362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682691 unmodified line2712722732742752762772782792802812822833 unmodified lines2872882892902912922932942952965 unmodified lines30230330430530630730816 unmodified lines3253263273283293303312 unmodified lines3343353363373383393402 unmodified lines3433443453463473483493503513523533543552 unmodified lines3583593603613623633643653663673683 unmodified lines37237337437537637737837938038138238338438538638738838939039110 unmodified linesimport sqlite3import tempfileimport unicodedatafrom collections.abc import Mapping, Sequencefrom typing import NotRequired, TypedDict, castBUCKET = "vomebook/ccrd-index"2 unmodified linesSOURCE_NAME = "VoiceOfML"class RecordCore(TypedDict):doc_id: strsource: strsource_name: strdisplay_name: strdisplay_dirs: list[str]display_rel_path: strextension: strsize: inthas_preview: boolhas_fulltext: boolstorage_root: strstorage_rel_path: strclass OcrRecord(RecordCore):text_generation: strtext_quality: strclass PublicRecord(RecordCore, total=False):text_generation: strtext_quality: strpublic_source: strpublic_source_name: strpublic_dirs: list[str]public_rel_path: str_file_search_text: str_path_search_text: str_search_text: str_rank_path_key: strtext_storage: strtext_sha256: strclass DirectoryFile(TypedDict):name: strext: strsize: intdoc_id: strclass DirectoryFolder(TypedDict):name: strpath: strcount: intclass BrowserEntry(TypedDict):folders: list[DirectoryFolder]files: list[DirectoryFile]# Older prebuilt browser payloads may carry extra presentation metadata.count: NotRequired[int]class DirectoryNode(TypedDict):name: strpath: strcount: inthasDirectFiles: boolhasChildren: boolshowSelfToggle: boolchildren: list[DirectoryNode]class Release(TypedDict):manifest: dict[str, object]records: list[OcrRecord]exports: list[dict[str, object]]database: Pathtext_paths: dict[str, Path]tree: list[DirectoryNode]browser: dict[str, BrowserEntry]def json_object(value: object, message: str) -> dict[str, object]:if not isinstance(value, dict):raise ValueError(message)raw = cast(dict[object, object], value)if any(not isinstance(key, str) for key in raw):raise ValueError(message)return cast(dict[str, object], raw)def json_list(value: object, message: str) -> list[object]:if not isinstance(value, list):raise ValueError(message)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()def digest(value: bytes) -> str:return hashlib.sha256(value).hexdigest()def sha(value: object) -> str:if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):raise ValueError("invalid release SHA-256")return valuedef safe_path(value: object) -> str:if (not isinstance(value, str) or not value or value.startswith("/") or "\\" in valueor any(part in {"", ".", ".."} for part in value.split("/"))or any(ord(char) < 32 for char in value)):1 unmodified linereturn valuedef read_resource(root: Path, ref: object) -> bytes:ref = json_object(ref, "wrong OCR release bucket")if ref.get("bucket") != BUCKET:raise ValueError("wrong OCR release bucket")path = safe_path(ref.get("path"))if not path.startswith(("text/objects/", "text/exports/", "indexes/ocr/")):12 unmodified linesreturn rawdef export_record(root: Path, ref: object) -> tuple[OcrRecord, dict[str, object]]:export = json_object(json.loads(read_resource(root, ref)), "invalid OCR export object")if (export.get("kind") != "ccrd-ocr-text-export" or export.get("version") != 1or export.get("complete") is not True or export.get("recipe") != "ocr-plain-utf8-pages-v1"):raise ValueError("unsupported OCR export schema")doc_id = export.get("doc_id")if not isinstance(doc_id, str) or not re.fullmatch(r"OCR:[1-9][0-9]*", doc_id) or int(doc_id.split(":")[1]) >= 1 << 63:raise ValueError("invalid OCR document identity")repo, original = export.get("origin_repo"), safe_path(export.get("origin_rel_path"))if not isinstance(repo, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", repo):4 unmodified linesexpected_path = repo + "/" + str(PurePosixPath(original).with_suffix(".txt"))if readable != expected_path:raise ValueError("OCR readable path does not preserve its origin")text_ref = json_object(export.get("text"), "invalid OCR text reference")raw = read_resource(root, text_ref)body = raw.decode("utf-8", errors="strict")if body.startswith("\ufeff"):raise ValueError("plain OCR export must not hide a BOM in its indexed text")identity = {key: export[key] for key in ("recipe", "origin_repo", "origin_rel_path", "origin_revision", "origin_sha256","source_sha256", "doc_id", "text_generation", "txt_sha256")}if 'body_admission' in export or 'body_admission_sha256' in export:admission = json_object(export.get('body_admission'), 'invalid complete-body quality admission')summary = json_object(admission.get('quality_check'), 'invalid complete-body quality admission')admission_pages = [json_object(page, 'invalid complete-body quality admission')for page in json_list(admission.get('pages'), 'invalid complete-body quality admission')]checks = [json_object(page.get('quality_check'), 'invalid complete-body quality admission') for page in admission_pages]admission_page_count = export.get('page_count')if type(admission_page_count) is not int or admission_page_count < 1:raise ValueError('invalid complete-body quality admission')if (admission.get('policy') != 'complete-body-quality-v1'or admission.get('source_sha256') != export.get('source_sha256')or admission.get('text_generation') != export.get('text_generation')or summary.get('status') != 'passed' or summary.get('issues') != []or summary.get('checked_pages') != export.get('page_count')or summary.get('page_count') != export.get('page_count')or [page.get('page') for page in admission_pages] != list(range(1, admission_page_count + 1))or any(check.get('status') != 'passed' or check.get('issues') != []or check.get('page') != page.get('page')for page, check in zip(admission_pages, checks))or digest(canonical(admission).rstrip(b'\n')) != export.get('body_admission_sha256')):raise ValueError('invalid complete-body quality admission')identity['body_admission_sha256'] = sha(export['body_admission_sha256'])5 unmodified linesif (generation != export["generation"] or digest(raw) != export["txt_sha256"]or export["book_id"] != digest((repo + "\0" + original).encode())):raise ValueError("OCR export generation mismatch")count = export.get("page_count")if type(count) is not int or count < 1:raise ValueError("OCR export is missing pages")pages = json_list(export.get("pages"), "OCR export is missing pages")if len(pages) != count:raise ValueError("OCR export is missing pages")if export.get("offset_unit") != "unicode-codepoint" or export.get("page_separator") != "\n\n":raise ValueError("unsupported page offset recipe")cursor, reviewed = 0, 0for number, raw_page in enumerate(pages, 1):page = json_object(raw_page, "OCR page order/offset mismatch")start, end = page.get("start"), page.get("end")if (page.get("page") != number or type(start) is not int or type(end) is not intor start != cursor or not start <= end <= len(body)):11 unmodified linescursor += 2if cursor != len(body) or export.get("accepted_pages") != reviewed or export.get("quality") != ("partially-reviewed" if reviewed else "unreviewed"):raise ValueError("OCR whole-book coverage/quality mismatch")resources = json_list(export.get("retained_reader_resources"), "OCR provenance retention references are missing")if not resources:raise ValueError("OCR provenance retention references are missing")for raw_resource in resources:resource = json_object(raw_resource, "invalid retained Reader resource")if resource.get("bucket") not in {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2", "melsm/pdf-archive-v2"}:raise ValueError("unknown retained Reader bucket")safe_path(resource.get("path")); sha(resource.get("sha256"))resource_size = resource.get("bytes")if type(resource_size) is not int or resource_size < 1:raise ValueError("invalid retained Reader resource")path = PurePosixPath(readable)quality = export.get("quality")if not isinstance(quality, str):raise ValueError("invalid OCR whole-book quality")record: OcrRecord = {"doc_id": doc_id, "source": SOURCE, "source_name": SOURCE_NAME,"display_name": path.stem, "display_dirs": list(path.parts[:-1]), "display_rel_path": readable,"extension": "txt", "size": len(raw), "has_preview": True, "has_fulltext": True,"storage_root": ".", "storage_rel_path": safe_path(text_ref.get("path")),"text_generation": sha(export.get("text_generation")), "text_quality": quality}return record, exportdef directory_payloads(records: Sequence[OcrRecord]) -> tuple[list[DirectoryNode], dict[str, BrowserEntry]]:browser: dict[str, BrowserEntry] = {}counts: defaultdict[str, int] = defaultdict(int)direct: defaultdict[str, list[OcrRecord]] = defaultdict(list)children: defaultdict[str, set[str]] = defaultdict(set)for record in records:parts = record["display_dirs"]for depth in range(len(parts) + 1):1 unmodified lineif depth < len(parts): children[path].add(parts[depth])direct["/".join(parts)].append(record)for path in counts:browser[path] = {"folders": [{"name": name, "path": (path + "/" if path else "") + name,"count": counts[(path + "/" if path else "") + name]} for name in sorted(children[path])],"files": [{"name": item["display_name"], "ext": "txt", "size": item["size"], "doc_id": item["doc_id"]}for item in sorted(direct[path], key=lambda item: (item["display_name"], item["doc_id"]))],}def node(name: str, path: str) -> DirectoryNode:return {"name": name, "path": path, "count": counts[path], "hasDirectFiles": bool(direct[path]),"hasChildren": bool(children[path]), "showSelfToggle": bool(path and direct[path] and children[path]),"children": [node(child, (path + "/" if path else "") + child) for child in sorted(children[path])]}3 unmodified linesreturn [node(child, child) for child in sorted(children[""])], dict(browser)def zip_member(record: Mapping[str, object]) -> str:"""Keep legal origin hierarchy; bound non-portable components deterministically."""replacements = {":": ":", "*": "*", "?": "?", '"': """, "<": "<", ">": ">", "|": "|", "\\": "\"}def component(original: str) -> str:value = re.sub(r'[:*?"<>|\\\x00-\x1f]', lambda match: replacements.get(match[0], "_"), original).rstrip(" .") or "_"if value != original or len(value.encode()) > 180:suffix = "-" + digest(original.encode())[:12]5 unmodified linesreturn "/".join([component(part) for part in parts])def validate_database(path: Path, records: Sequence[OcrRecord], text_root: Path) -> None:with sqlite3.connect(f"file:{path.resolve()}?mode=ro&immutable=1", uri=True) as db:if db.execute("PRAGMA integrity_check").fetchone()[0] != "ok":raise ValueError("invalid OCR SQLite integrity")16 unmodified linesraise ValueError("OCR snippet anchor schema missing")def load_release(bucket: Path, manifest_path: str, expected_sha256: str, base_metadata_sha256: str) -> Release:safe_path(manifest_path); sha(expected_sha256); sha(base_metadata_sha256)bucket = bucket.resolve()target = (bucket / manifest_path).resolve()2 unmodified linesraw = target.read_bytes()if digest(raw) != expected_sha256:raise ValueError("OCR release manifest checksum mismatch")manifest = json_object(json.loads(raw), "invalid OCR release manifest")if (manifest.get("kind") != "ccrd-ocr-search-release" or manifest.get("version") != 1or manifest.get("tokenizer_version") != TOKENIZER or manifest.get("base_metadata_sha256") != base_metadata_sha256):raise ValueError("incompatible OCR release/base snapshot")2 unmodified linesif (manifest["generation"] != digest(canonical(identity))or manifest_path != f'releases/ocr-{manifest["generation"]}/manifest.json'):raise ValueError("OCR release identity/path mismatch")refs = json_list(manifest.get("exports"), "empty OCR release")if not refs:raise ValueError("empty OCR release")records: list[OcrRecord] = []exports: list[dict[str, object]] = []ids: set[str] = set()paths: set[str] = set()for ref in refs:record, export = export_record(bucket, ref)if record["doc_id"] in ids or record["display_rel_path"] in paths:2 unmodified linesrecords.append(record); exports.append(export)if manifest.get("documents") != len(records):raise ValueError("OCR release count mismatch")database = json_object(manifest.get("database"), "invalid OCR database reference")read_resource(bucket, database)db_ref_path = safe_path(database.get("path"))db_path = (bucket / db_ref_path).resolve()if db_ref_path != f'indexes/ocr/{manifest["generation"]}/OCR.sqlite3':raise ValueError("OCR database must retain its source namespace")validate_database(db_path, records, bucket)tree, browser = directory_payloads(records)3 unmodified linesdef pin_release(bucket: Path, manifest_path: str, expected_sha256: str,base_metadata_sha256: str, cache: Path) -> Release:"""Verify the whole candidate before pinning a process-local immutable copy."""candidate = load_release(bucket, manifest_path, expected_sha256, base_metadata_sha256)cache.mkdir(parents=True, exist_ok=True)destination = cache / sha(candidate["manifest"].get("generation"))if destination.exists():return load_release(destination, manifest_path, expected_sha256, base_metadata_sha256)stage = Path(tempfile.mkdtemp(prefix="ocr-stage-", dir=cache))try:refs = [*json_list(candidate["manifest"].get("exports"), "empty OCR release"), candidate["manifest"]["database"],*[export["text"] for export in candidate["exports"]]]for ref in refs:raw = read_resource(bucket, ref)target = stage / safe_path(json_object(ref, "invalid OCR resource reference").get("path"))target.parent.mkdir(parents=True, exist_ok=True)with target.open("wb") as output:output.write(raw); output.flush(); os.fsync(output.fileno())
12345{"include": ["build_fulltext_db.py", "prepare_fulltext_index.py"],"pythonVersion": "3.11","typeCheckingMode": "strict"}12345{"include": ["app.py", "build_fulltext_db.py", "prepare_fulltext_index.py", "ocr_release.py"],"pythonVersion": "3.11","typeCheckingMode": "strict"}
12345678910115 unmodified lines1718192021225 unmodified lines2829303132334 unmodified lines38394041424344454647484950515253545556575859609 unmodified lines70717273747576774 unmodified lines8283848586878816 unmodified lines1051061071081091108 unmodified lines1191201211221231241251261271281291301311321336 unmodified lines1401411421431441451461471481491501511521531541557 unmodified lines1631641651661671688 unmodified lines17717817918018118218318418518618718818919019119219335 unmodified lines229230231232233234"use strict";// Pure, bounded rolling source planner. All offsets refer to original UTF-16.globalThis.CCRDSpeechPlan = (() => {const ending = /[。!?!?;;\n]/u;const ascii = /[A-Za-z0-9]/u;const words = typeof Intl.Segmenter === "function" ? new Intl.Segmenter("zh", { granularity: "word" }) : null;const connectors = "但是|可是|不过|然而|同时|而且|并且|因此|所以|此外|另外|于是|但是同时|与此同时|但是也|但是又|同时也|而是|或者|以及";const connectorWords = connectors.split("|").sort((a, b) => b.length - a.length);function connectorOnly(text) {let index = 0, found = false;while (index < text.length) {5 unmodified linesreturn found;}const dangling = new Set(["的", "地", "得", "和", "与", "及", "或", "把", "被", "在", "对", "向", "为", "将", "不", "一", "很", "更", "最", "也", "还", "都", "就", "再", "又", "才", "没", "没有", "关于", "以及", "因为", "为了", "由于", "如果", ...connectors.split("|"), "一个", "这个", "那个", "今后", "目前", "当时", "现在", "已经", "正在", "需要", "应该", "必须", "可以", "能够", "不能", "有关", "一些"]);function numberSpans(text) {const label = "(?:订单编号|訂單編號|订单号|訂單號|编号|編號|手机号|手機號|电话|電話|学号|學號|邮编|郵編|ISBN(?:-13|-10)?|IP)";const pattern = new RegExp(label + "[ \\t]*[::]?[ \\t]*[A-Za-z0-9]+(?:[._/\\-][A-Za-z0-9]+)*" +5 unmodified lines"|[+-]?[0-9]+(?:,[0-9]{3})*(?:\\.[0-9]+)?(?:[%%]|℃)?", "gu");return Array.from(text.matchAll(pattern), match => ({ start: match.index, end: match.index + match[0].length }));}function wordEnds(text) {const atoms = numberSpans(text);const values = words ? Array.from(words.segment(text), value => ({ end: value.index + value.segment.length, word: value.segment.trim() })) :4 unmodified lines// chunk_length_schedule. Production CPU synthesis runs at ~0.65-0.72 s per// second of audio (2026-10-20 cold CW:0), so a clip may be at most ~1.4x the// previous one or it is not ready when the previous clip's speech ends.const RAMP = [[16, 30], [24, 40], [34, 56], [50, 78], [72, 110]];function phraseEnds(text, first = false, carry = 0) {const cuts = wordEnds(text), chars = Array.from(text), offsets = [0], ends = [];for (const char of chars) offsets.push(offsets[offsets.length - 1] + char.length);// While ramping (the first batch, or a batch after a short final clip),// every clip follows the previous clip's length: its playback is all the// time the next clip has to be synthesized. A short clip after the ramp// (e.g. 17 chars before 61, 2.6 s late cold) re-enters it.let ramping = first || (carry > 0 && carry < 72);const stage = length => Math.max(1, RAMP.findIndex(([, limit]) => length * 1.45 <= limit));let start = 0;while (start < text.length) {const position = offsets.indexOf(start), short = first && !ends.length;// Streaming ramp (as ElevenLabs' chunk_length_schedule): each early clip// is short enough to be synthesized while the one before it still plays,// so the first sentence is quick and the second does not wait ~5 s for a// 90-character clip on the shared CPU worker.const marks = (goal, limit) => {const ceiling = offsets[Math.min(chars.length, position + limit)];return { target: offsets[Math.min(chars.length, position + goal)],9 unmodified lines// cuts mid-phrase: without a mark in its range it widens to the next size.// The preferred range follows the previous clip's actual length (<= 1.45x).const previous = ends.length ? ends[ends.length - 1] - (ends[ends.length - 2] || 0) : first ? 0 : carry;const fit = ([goal, limit]) => previous ? [goal, Math.min(limit, Math.max(goal + 4, Math.round(previous * 1.45)))] : [goal, limit];const index = !previous ? 0 : previous < 72 ? stage(previous) : -1;const sizes = ramping && index >= 0 ? [fit(RAMP[index]), ...RAMP.slice(index + 1), [90, 120]] : [[90, 120]];let found = marks(...sizes[0]);for (const size of sizes.slice(1)) {4 unmodified linesfound = wider;}const { target, hard } = found, natural = found.natural.length ? found.natural : found.weak;let end;if (short && natural.length && (!hard || natural[0].end < hard.end)) end = natural[0].end; // Earliest mark keeps first audio fast.else if (hard) end = hard.end; // Never merge different spoken sentences in one part.else if (natural.length) end = short ? natural[0].end : natural[natural.length - 1].end;16 unmodified lines}return ends;}function wordStart(text, offset) {offset = safe(text, offset);if (!offset || offset === text.length) return offset;8 unmodified lines}return offset;}function safe(text, offset) {offset = Math.max(0, Math.min(text.length, Math.floor(offset)));return offset && /[\uDC00-\uDFFF]/u.test(text[offset] || "") && /[\uD800-\uDBFF]/u.test(text[offset - 1]) ? offset - 1 : offset;}function boundary(text, index) {return ending.test(text[index]) || (text[index] === "." && !ascii.test(text[index + 1] || "") && !listMarker(text, index));}// "1." / "12." / "一." / "(3)." at a line or clause start number the item that// follows; that period must not end a sentence ("1." spoken alone, then the item).function listMarker(text, index) {let cursor = index;const closed = cursor > 0 && /[))]/u.test(text[cursor - 1]);6 unmodified linesreturn cursor === 0 || /[\s。!?!?;;::,,、]/u.test(text[cursor - 1]);}// Whether text[0..end) finishes a sentence (ignoring closing quotes/space).function endsSentence(text, end) {let index = end - 1;while (index > 0 && /[”’"'」』))\t \r]/u.test(text[index])) index -= 1;return index >= 0 && boundary(text, index);}// Clause marks for natural cut points; ASCII , and : only outside numbers/times.function clause(text, index) {const char = text[index];return /[,、:;—…]/u.test(char) || ((char === "," || char === ":") && !ascii.test(text[index + 1] || ""));}function clauseStart(text, offset) {// Start/seek at the nearest preceding clause or sentence mark when it is// close; otherwise keep the whole-word start.7 unmodified lines}return wordStart(text, offset);}function sentence(text, offset) {offset = safe(text, offset);// Navigation examines nearby source, not a document-sized sentence/DOM list.8 unmodified lineswhile (end < text.length && /[”’"'」』))\s]/u.test(text[end])) end += 1;return { start: safe(text, start), end: safe(text, end) };}function partIndex(batch, offset) {const relative = offset - batch.start;if (relative === 0) return 0;const previous = batch.segment_ends.indexOf(relative);return previous >= 0 && previous + 1 < batch.segment_ends.length ? previous + 1 : -1;}function previousSentence(text, offset) {let cursor = sentence(text, offset).start - 1;while (cursor > 0 && /[”’"'」』))\s]/u.test(text[cursor])) cursor -= 1;return sentence(text, Math.max(0, cursor)).start;}function batch(text, offset, first = false, carry = 0) {// The first batch holds the whole short-to-long clip ramp (see RAMP).const start = first ? clauseStart(text, offset) : safe(text, offset), limit = first ? 260 : 480;35 unmodified lines}return { safe, sentence, batch, phraseEnds, wordEnds, wordStart, clauseStart, numberSpans, partIndex, previousSentence };})();if (typeof document !== "undefined") window.CCRDSpeech = (() => {const ORIGIN = "https://vomebook-hitokoto.hf.space";12345678910111213141516171819205 unmodified lines262728293031325 unmodified lines383940414243444 unmodified lines49505152535455565758596061626364656667686970717273747576779 unmodified lines878889909192939495964 unmodified lines10110210310410510610716 unmodified lines1241251261271281291308 unmodified lines1391401411421431441451461471481491501511521531541551566 unmodified lines1631641651661671681691701711721731741751761771781791801817 unmodified lines1891901911921931941958 unmodified lines20420520620720820921021121221321421521621721821922022122222335 unmodified lines259260261262263264265"use strict";// Pure, bounded rolling source planner. All offsets refer to original UTF-16.// Keep this section in tts-client.js because cached shells and Reader consume// the planner without loading a second script. The source-level check below// is enforced on the exact bytes between these markers.// BEGIN STRICT SPEECH PLANNER/** @typedef {{start: number, end: number}} SpeechSpan *//** @typedef {{end: number, word: string}} SpeechWord *//** @typedef {{start: number, end: number, text: string, first: boolean, segment_ends: number[], context_before: string, context_after: string}} SpeechBatch */const speechPlanHost = /** @type {typeof globalThis & {CCRDSpeechPlan?: unknown}} */ (globalThis);speechPlanHost.CCRDSpeechPlan = (() => {const ending = /[。!?!?;;\n]/u;const ascii = /[A-Za-z0-9]/u;const words = typeof Intl.Segmenter === "function" ? new Intl.Segmenter("zh", { granularity: "word" }) : null;const connectors = "但是|可是|不过|然而|同时|而且|并且|因此|所以|此外|另外|于是|但是同时|与此同时|但是也|但是又|同时也|而是|或者|以及";const connectorWords = connectors.split("|").sort((a, b) => b.length - a.length);/** @param {string} text */function connectorOnly(text) {let index = 0, found = false;while (index < text.length) {5 unmodified linesreturn found;}const dangling = new Set(["的", "地", "得", "和", "与", "及", "或", "把", "被", "在", "对", "向", "为", "将", "不", "一", "很", "更", "最", "也", "还", "都", "就", "再", "又", "才", "没", "没有", "关于", "以及", "因为", "为了", "由于", "如果", ...connectors.split("|"), "一个", "这个", "那个", "今后", "目前", "当时", "现在", "已经", "正在", "需要", "应该", "必须", "可以", "能够", "不能", "有关", "一些"]);/** @param {string} text @returns {SpeechSpan[]} */function numberSpans(text) {const label = "(?:订单编号|訂單編號|订单号|訂單號|编号|編號|手机号|手機號|电话|電話|学号|學號|邮编|郵編|ISBN(?:-13|-10)?|IP)";const pattern = new RegExp(label + "[ \\t]*[::]?[ \\t]*[A-Za-z0-9]+(?:[._/\\-][A-Za-z0-9]+)*" +5 unmodified lines"|[+-]?[0-9]+(?:,[0-9]{3})*(?:\\.[0-9]+)?(?:[%%]|℃)?", "gu");return Array.from(text.matchAll(pattern), match => ({ start: match.index, end: match.index + match[0].length }));}/** @param {string} text @returns {SpeechWord[]} */function wordEnds(text) {const atoms = numberSpans(text);const values = words ? Array.from(words.segment(text), value => ({ end: value.index + value.segment.length, word: value.segment.trim() })) :4 unmodified lines// chunk_length_schedule. Production CPU synthesis runs at ~0.65-0.72 s per// second of audio (2026-10-20 cold CW:0), so a clip may be at most ~1.4x the// previous one or it is not ready when the previous clip's speech ends./** @type {[number, number][]} */const RAMP = [[16, 30], [24, 40], [34, 56], [50, 78], [72, 110]];/** @param {string} text @param {boolean} [first] @param {number} [carry] @returns {number[]} */function phraseEnds(text, first = false, carry = 0) {const cuts = wordEnds(text), chars = Array.from(text), offsets = [0];/** @type {number[]} */ const ends = [];for (const char of chars) offsets.push(offsets[offsets.length - 1] + char.length);// While ramping (the first batch, or a batch after a short final clip),// every clip follows the previous clip's length: its playback is all the// time the next clip has to be synthesized. A short clip after the ramp// (e.g. 17 chars before 61, 2.6 s late cold) re-enters it.let ramping = first || (carry > 0 && carry < 72);/** @param {number} length */const stage = length => Math.max(1, RAMP.findIndex(([, limit]) => length * 1.45 <= limit));let start = 0;while (start < text.length) {const position = offsets.indexOf(start);/** @type {boolean} */ const short = first && !ends.length;// Streaming ramp (as ElevenLabs' chunk_length_schedule): each early clip// is short enough to be synthesized while the one before it still plays,// so the first sentence is quick and the second does not wait ~5 s for a// 90-character clip on the shared CPU worker./** @param {number} goal @param {number} limit @returns {{target: number, hard: SpeechWord | undefined, natural: SpeechWord[], weak: SpeechWord[]}} */const marks = (goal, limit) => {const ceiling = offsets[Math.min(chars.length, position + limit)];return { target: offsets[Math.min(chars.length, position + goal)],9 unmodified lines// cuts mid-phrase: without a mark in its range it widens to the next size.// The preferred range follows the previous clip's actual length (<= 1.45x).const previous = ends.length ? ends[ends.length - 1] - (ends[ends.length - 2] || 0) : first ? 0 : carry;/** @param {[number, number]} size @returns {[number, number]} */const fit = ([goal, limit]) => previous ? [goal, Math.min(limit, Math.max(goal + 4, Math.round(previous * 1.45)))] : [goal, limit];const index = !previous ? 0 : previous < 72 ? stage(previous) : -1;/** @type {[number, number][]} */const sizes = ramping && index >= 0 ? [fit(RAMP[index]), ...RAMP.slice(index + 1), [90, 120]] : [[90, 120]];let found = marks(...sizes[0]);for (const size of sizes.slice(1)) {4 unmodified linesfound = wider;}const { target, hard } = found, natural = found.natural.length ? found.natural : found.weak;/** @type {number} */ let end;if (short && natural.length && (!hard || natural[0].end < hard.end)) end = natural[0].end; // Earliest mark keeps first audio fast.else if (hard) end = hard.end; // Never merge different spoken sentences in one part.else if (natural.length) end = short ? natural[0].end : natural[natural.length - 1].end;16 unmodified lines}return ends;}/** @param {string} text @param {number} offset */function wordStart(text, offset) {offset = safe(text, offset);if (!offset || offset === text.length) return offset;8 unmodified lines}return offset;}/** @param {string} text @param {number} offset */function safe(text, offset) {offset = Math.max(0, Math.min(text.length, Math.floor(offset)));return offset && /[\uDC00-\uDFFF]/u.test(text[offset] || "") && /[\uD800-\uDBFF]/u.test(text[offset - 1]) ? offset - 1 : offset;}/** @param {string} text @param {number} index */function boundary(text, index) {return ending.test(text[index]) || (text[index] === "." && !ascii.test(text[index + 1] || "") && !listMarker(text, index));}// "1." / "12." / "一." / "(3)." at a line or clause start number the item that// follows; that period must not end a sentence ("1." spoken alone, then the item)./** @param {string} text @param {number} index */function listMarker(text, index) {let cursor = index;const closed = cursor > 0 && /[))]/u.test(text[cursor - 1]);6 unmodified linesreturn cursor === 0 || /[\s。!?!?;;::,,、]/u.test(text[cursor - 1]);}// Whether text[0..end) finishes a sentence (ignoring closing quotes/space)./** @param {string} text @param {number} end */function endsSentence(text, end) {let index = end - 1;while (index > 0 && /[”’"'」』))\t \r]/u.test(text[index])) index -= 1;return index >= 0 && boundary(text, index);}// Clause marks for natural cut points; ASCII , and : only outside numbers/times./** @param {string} text @param {number} index */function clause(text, index) {const char = text[index];return /[,、:;—…]/u.test(char) || ((char === "," || char === ":") && !ascii.test(text[index + 1] || ""));}/** @param {string} text @param {number} offset */function clauseStart(text, offset) {// Start/seek at the nearest preceding clause or sentence mark when it is// close; otherwise keep the whole-word start.7 unmodified lines}return wordStart(text, offset);}/** @param {string} text @param {number} offset @returns {SpeechSpan} */function sentence(text, offset) {offset = safe(text, offset);// Navigation examines nearby source, not a document-sized sentence/DOM list.8 unmodified lineswhile (end < text.length && /[”’"'」』))\s]/u.test(text[end])) end += 1;return { start: safe(text, start), end: safe(text, end) };}/** @param {SpeechBatch} batch @param {number} offset */function partIndex(batch, offset) {const relative = offset - batch.start;if (relative === 0) return 0;const previous = batch.segment_ends.indexOf(relative);return previous >= 0 && previous + 1 < batch.segment_ends.length ? previous + 1 : -1;}/** @param {string} text @param {number} offset */function previousSentence(text, offset) {let cursor = sentence(text, offset).start - 1;while (cursor > 0 && /[”’"'」』))\s]/u.test(text[cursor])) cursor -= 1;return sentence(text, Math.max(0, cursor)).start;}/** @param {string} text @param {number} offset @param {boolean} [first] @param {number} [carry] @returns {SpeechBatch | null} */function batch(text, offset, first = false, carry = 0) {// The first batch holds the whole short-to-long clip ramp (see RAMP).const start = first ? clauseStart(text, offset) : safe(text, offset), limit = first ? 260 : 480;35 unmodified lines}return { safe, sentence, batch, phraseEnds, wordEnds, wordStart, clauseStart, numberSpans, partIndex, previousSentence };})();// END STRICT SPEECH PLANNERif (typeof document !== "undefined") window.CCRDSpeech = (() => {const ORIGIN = "https://vomebook-hitokoto.hf.space";
117 unmodified lines118119120121122123117 unmodified lineswith self.subTest(change=list(change)), self.assertRaises(ValueError):release.export_record(self.bucket, ref)def test_pin_copies_verified_data_and_is_independent_of_the_mount(self):pinned = release.pin_release(self.bucket, self.manifest_path, self.manifest_sha, self.base_sha, self.root / "cache")self.assertNotIn(self.bucket, pinned["database"].parents)117 unmodified lines118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155117 unmodified lineswith self.subTest(change=list(change)), self.assertRaises(ValueError):release.export_record(self.bucket, ref)def test_malformed_nested_manifest_values_are_rejected_at_the_boundary(self):for change in ({"pages": [None, {}, {}]},{"retained_reader_resources": [None]},{"text": []},{"page_count": True},{"body_admission": None, "body_admission_sha256": "a" * 64},{"body_admission": {"quality_check": [], "pages": []}, "body_admission_sha256": "a" * 64},{"body_admission": {"quality_check": {}, "pages": [None]}, "body_admission_sha256": "a" * 64},):value = {**copy.deepcopy(self.export), **change}ref = self.ref(self.export_path, release.canonical(value))with self.subTest(change=change), self.assertRaises(ValueError):release.export_record(self.bucket, ref)def test_resource_rejects_escape_bad_size_and_unmanaged_paths(self):ref = self.export["text"]for change in ({"path": "text/objects/../escape"}, {"path": "/text/objects/a"},{"path": "documents/original.pdf"}, {"bytes": True},{"sha256": "bad"}, {"bucket": "unexpected"}):with self.subTest(change=change), self.assertRaises(ValueError):release.read_resource(self.bucket, {**ref, **change})def test_static_release_types_describe_verified_outputs(self):record, _export = release.export_record(self.bucket, self.export_ref)self.assertEqual(record["doc_id"], "OCR:1")self.assertEqual(record["display_dirs"], ["VoiceOfML", "Test", "原目录"])self.assertEqual(record["storage_rel_path"], self.export["text"]["path"])tree, browser = release.directory_payloads([record])self.assertEqual(tree[0]["children"][0]["name"], "Test")self.assertEqual(browser["VoiceOfML/Test/原目录"]["files"][0]["doc_id"], "OCR:1")def test_pin_copies_verified_data_and_is_independent_of_the_mount(self):pinned = release.pin_release(self.bucket, self.manifest_path, self.manifest_sha, self.base_sha, self.root / "cache")self.assertNotIn(self.bucket, pinned["database"].parents)
123456789101112131415161718192021222324252627"use strict";// Exercise the actual, marked source section rather than a copied planner.const assert = require("node:assert/strict");const fs = require("node:fs");const path = require("node:path");const vm = require("node:vm");const source = fs.readFileSync(path.join(__dirname, "../static/tts-client.js"), "utf8");const start = "// BEGIN STRICT SPEECH PLANNER", end = "// END STRICT SPEECH PLANNER";assert.equal(source.split(start).length, 2);assert.equal(source.split(end).length, 2);const planner = source.slice(source.indexOf(start), source.indexOf(end) + end.length);const sandbox = {};vm.runInNewContext(planner, sandbox);const plan = sandbox.CCRDSpeechPlan;assert.ok(plan);const text = "第一句含😀和编号123。第二句继续,最后结束。";assert.equal(plan.safe(text, text.indexOf("😀") + 1), text.indexOf("😀"));const batch = plan.batch(text, 0, true);assert.equal(batch.text, text);assert.equal(batch.segment_ends.at(-1), batch.text.length);assert.ok(batch.segment_ends.every((end, i, ends) => end > (i ? ends[i - 1] : 0)));assert.equal(plan.partIndex(batch, batch.start), 0);assert.equal(plan.partIndex(batch, batch.end + 1), -1);assert.equal(plan.sentence(text, text.indexOf("第二句")).start, text.indexOf("第二句"));assert.equal(plan.previousSentence(text, text.indexOf("第二句")), 0);assert.equal(plan.batch("", 0), null);console.log("speech planner UTF-16, segmentation and navigation passed");12345678910111213141516171819202122232425262728293031323334353637383940"""Strictly check the actual planner section, without excluding its controller by pretending it is checked."""import jsonimport subprocessimport tempfileimport unittestfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]BEGIN = "// BEGIN STRICT SPEECH PLANNER"END = "// END STRICT SPEECH PLANNER"
class SpeechPlanStaticTests(unittest.TestCase): def test_planner_is_strict_and_real_errors_fail(self): source = (ROOT / "static/tts-client.js").read_text(encoding="utf-8") self.assertEqual(source.count(BEGIN), 1) self.assertEqual(source.count(END), 1) planner = source[source.index(BEGIN):source.index(END) + len(END)] self.assertNotIn("@ts-ignore", planner) self.assertNotIn("@ts-nocheck", planner) with tempfile.TemporaryDirectory(prefix="speech-typecheck-") as directory: root = Path(directory) entry = root / "planner.js" entry.write_text(planner, encoding="utf-8") (root / "tsconfig.json").write_text(json.dumps({ "compilerOptions": {"allowJs": True, "checkJs": True, "strict": True, "noEmit": True, "target": "ES2022", "lib": ["ES2022", "ES2022.Intl", "DOM"]}, "files": ["planner.js"], })) cmd = ("node", str(ROOT / "node_modules/typescript/bin/tsc"), "-p", str(root / "tsconfig.json"), "--pretty", "false") result = subprocess.run(cmd, text=True, capture_output=True, timeout=60) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) entry.write_text(planner.replace("function safe(text, offset) {", 'function safe(text, offset) {\n offset = "wrong";', 1), encoding="utf-8") result = subprocess.run(cmd, text=True, capture_output=True, timeout=60) self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) self.assertIn("error TS", result.stdout)
if __name__ == "__main__": unittest.main()14 unmodified lines1516171819202110 unmodified lines3233343536373839404119 unmodified lines61626364656614 unmodified linesself.addCleanup(self.temporary.cleanup)self.root = Path(self.temporary.name)for name in ("pyrightconfig.json", "jsconfig.service-worker.json","build_fulltext_db.py", "prepare_fulltext_index.py", "static/sw.js"):target = self.root / nametarget.parent.mkdir(parents=True, exist_ok=True)shutil.copyfile(ROOT / name, target)10 unmodified linesself.assertTrue(jsconfig["compilerOptions"]["strict"])self.assertTrue(jsconfig["compilerOptions"]["checkJs"])checks = [("build_fulltext_db.py", '\n_bad_static_check: int = "wrong"\n',("node", str(ROOT / "node_modules/pyright/index.js"), "-p", "pyrightconfig.json")),("prepare_fulltext_index.py", '\n_bad_static_check: int = "wrong"\n',("node", str(ROOT / "node_modules/pyright/index.js"), "-p", "pyrightconfig.json")),("static/sw.js", '\n/** @type {number} */ const badStaticCheck = "wrong";\n',("node", str(ROOT / "node_modules/typescript/bin/tsc"), "-p", "jsconfig.service-worker.json")),]19 unmodified linesself.assertIn("tests.test_coverage_gate", dockerfile)self.assertIn("tests/__init__.py tests/test_static_checks.py tests/test_coverage_gate.py", dockerfile)self.assertIn("python -m coverage report --fail-under=65", dockerfile)if __name__ == "__main__":14 unmodified lines1516171819202110 unmodified lines323334353637383940414243444519 unmodified lines656667686970717214 unmodified linesself.addCleanup(self.temporary.cleanup)self.root = Path(self.temporary.name)for name in ("pyrightconfig.json", "jsconfig.service-worker.json","app.py", "build_fulltext_db.py", "prepare_fulltext_index.py", "ocr_release.py", "static/sw.js"):target = self.root / nametarget.parent.mkdir(parents=True, exist_ok=True)shutil.copyfile(ROOT / name, target)10 unmodified linesself.assertTrue(jsconfig["compilerOptions"]["strict"])self.assertTrue(jsconfig["compilerOptions"]["checkJs"])checks = [("app.py", '\n_bad_static_check: int = "wrong"\n',("node", str(ROOT / "node_modules/pyright/index.js"), "-p", "pyrightconfig.json")),("build_fulltext_db.py", '\n_bad_static_check: int = "wrong"\n',("node", str(ROOT / "node_modules/pyright/index.js"), "-p", "pyrightconfig.json")),("prepare_fulltext_index.py", '\n_bad_static_check: int = "wrong"\n',("node", str(ROOT / "node_modules/pyright/index.js"), "-p", "pyrightconfig.json")),("ocr_release.py", '\n_bad_static_check: int = "wrong"\n',("node", str(ROOT / "node_modules/pyright/index.js"), "-p", "pyrightconfig.json")),("static/sw.js", '\n/** @type {number} */ const badStaticCheck = "wrong";\n',("node", str(ROOT / "node_modules/typescript/bin/tsc"), "-p", "jsconfig.service-worker.json")),]19 unmodified linesself.assertIn("tests.test_coverage_gate", dockerfile)self.assertIn("tests/__init__.py tests/test_static_checks.py tests/test_coverage_gate.py", dockerfile)self.assertIn("python -m coverage report --fail-under=65", dockerfile)self.assertIn("unittest tests.test_speech_static", dockerfile)self.assertIn("node tests/test_speech_plan.cjs", dockerfile)if __name__ == "__main__":
6 unmodified lines7891011121314156 unmodified linesimport build_fulltext_db as builderimport prepare_fulltext_index as prepareclass TypedBoundaryTests(unittest.TestCase):def test_database_reference_requires_size_and_stays_in_bucket(self):with tempfile.TemporaryDirectory() as directory:bucket = Path(directory).resolve()6 unmodified lines78910111213141516171819202122232425262728293031323334356 unmodified linesimport build_fulltext_db as builderimport prepare_fulltext_index as prepareimport appclass TypedBoundaryTests(unittest.TestCase):def test_fulltext_search_unknown_sort_falls_back_without_unbound_page(self):class FakeFulltext:def search_source(self, source, query, exact):return {1}record = {"doc_id": "CCRD:1", "source": "CCRD", "source_name": "CCRD", "display_name": "题目","display_dirs": [], "display_rel_path": "题目.txt", "extension": "txt", "size": 1,"storage_root": "CCRD", "storage_rel_path": "题目.txt", "has_preview": True, "has_fulltext": True,"_file_search_text": "题目", "_path_search_text": "题目.txt", "_search_text": "题目", "_rank_path_key": "题目"}with patch.object(app, "fulltext_databases", FakeFulltext()), \patch.object(app, "records", [record]), \patch.object(app, "source_counts", {"CCRD": 1}), \patch.object(app, "source_physical_map", {"CCRD": "CCRD"}), \patch.object(app, "source_doc_number_index", {"CCRD": {1: 0}}), \patch.object(app, "metadata_matches", return_value=set()), \patch.object(app, "add_summaries", side_effect=lambda items, *_args, **_kwargs: items):result = app.fulltext_search("题目", sort="unknown")self.assertEqual(result["total"], 1)self.assertEqual(result["results"][0]["doc_id"], "CCRD:1")def test_database_reference_requires_size_and_stays_in_bucket(self):with tempfile.TemporaryDirectory() as directory:bucket = Path(directory).resolve()
.dockerignore+2
Dockerfile+4
app.py+263-153
ocr_release.py+167-52
pyrightconfig.json+1-1
static/tts-client.js+35-4
tests/test_ocr_release.py+32
tests/test_speech_plan.cjsAdded+27
tests/test_speech_static.pyAdded+40
tests/test_static_checks.py+7-1
tests/test_typed_contracts.py+20