Files
akyldash/tools/rag-pilot/rag_size_sample.py
codex 1d43f2e99d
CI / tests-and-images (pull_request) Successful in 26m52s
Runner smoke test / runner-smoke (pull_request) Successful in 6s
Add bilingual local RAG pilot and Codex search plan
2026-11-22 19:51:02 +00:00

50 lines
2.2 KiB
Python

"""Estimate latest-edition chunk count with a fixed uniform document sample."""
import json
from pathlib import Path
import random
import sqlite3
import statistics
import sys
from tokenizers import Tokenizer
from rag_pilot import LANGUAGES, load_json, sections, token_windows
def main(root, tokenizer_file):
with sqlite3.connect((root / "manifest.sqlite3").resolve().as_uri() + "?mode=ro", uri=True) as db:
codes = [row[0] for row in db.execute("SELECT code FROM documents WHERE state='success' ORDER BY code")]
tokenizer = Tokenizer.from_file(str(tokenizer_file))
rng = random.Random(20261122)
sample = rng.sample(codes, 512)
counts = []
language_counts = dict.fromkeys(LANGUAGES, 0)
for code in sample:
directory = root / "documents" / code
document = load_json(directory / "document.json")
editions = document.get("editions") or []
count = 0
if editions:
for language in language_counts:
edition = str(editions[-1]["source_code"])
path = directory / "editions" / edition / language / "fragments.json"
if not path.is_file():
continue
blocks = ["\n".join(fragment["text"] for fragment in section)
for section in sections(load_json(path), code, edition, language)]
encoded = tokenizer.encode_batch(blocks, add_special_tokens=False)
windows = sum(1 for entry in encoded for _ in token_windows(len(entry.ids)))
language_counts[language] += windows
count += windows
counts.append(count)
# Resample at document level so the language and article lengths stay linked.
estimates = sorted(statistics.mean(rng.choices(counts, k=len(counts))) * len(codes) for _ in range(2000))
print(json.dumps({"documents": len(codes), "sample": len(sample), "languages": language_counts,
"largest_sampled_document": max(counts), "projected_chunks": round(statistics.mean(counts) * len(codes)),
"bootstrap_low": round(estimates[50]), "bootstrap_high": round(estimates[1949])}))
if __name__ == "__main__":
main(*map(Path, sys.argv[1:]))