"""Turn the rendered markdown into retrieval chunks. Reads `data/manifest.json` and the markdown under `data/sources/`, and writes one JSON object per chunk to `data/chunks.jsonl`. We slide a window down each page one line at a time. The window tracks what it needs in order to describe itself — the headings above it, whether it is inside a fence, which code it has taken in — so that we can read a chunk's metadata off it at the moment it closes, rather than working it out again afterwards. The window closes on a heading, or on a paragraph break once it is over budget, and never inside a fence in order to keep code blocks whole. uv run python -m ingest.parse_books uv run python -m ingest.parse_books --book book --limit 5 --show """ import argparse import hashlib import json import re import sys from collections import Counter from dataclasses import dataclass, field from transformers import AutoTokenizer from rag.config import ( BOOKS, CHUNK_HEADING_LEVEL, CHUNK_MAX_TOKENS, CHUNK_TARGET_TOKENS, CHUNKS_PATH, EMBED_MODEL, HEADING_SEPARATOR, MANIFEST_PATH, SOURCES_DIR, ) from rag.types import Chunk, ManifestBook, Page QUOTE = re.compile(r"^(\s*>\s?)+") FENCE = re.compile(r"^\s*```(?P[^`]*)$") HEADING = re.compile(r"^(?P#{1,6})\s+(?P.+?)\s*$") HIDDEN_LINE = re.compile(r"^#(\s|$)") RUST_FENCE_TAGS = ("rust", "ignore", "should_panic", "no_run", "compile_fail", "edition") RULE_MARKER = re.compile(r"^r\[[a-z0-9._-]+\]$") LINK_DEFINITION = re.compile(r"^\[[^^\]]+\]:\s*\S+$") LEGACY_ANCHOR = re.compile(r'^\s*$') CALLOUT = re.compile(r"^\[!\w+\]\s*$") LISTING_OPEN = re.compile(r"[^>]*)>") LISTING_CLOSE = "" ATTRIBUTE = re.compile(r'(?P[\w-]+)="(?P[^"]*)"') COMMENT_OPEN, COMMENT_CLOSE = "" INLINE_LINK = re.compile(r"!?\[(?P