| |
| """ |
| chunk_reports.py — section-aware chunking of parsed EQC QA markdown. |
| |
| Mirrors marine_rag/chunk_docs.py: ~1000-token section-aware chunks, small |
| overlap, tiktoken (cl100k_base ≈ Gemini) budget, a metadata prefix per chunk |
| (dataset + report + aspect + section path). Self-contained (no cmip6 import). |
| |
| Output: eqc_qa/chunks.jsonl — payload fields: |
| chunk_id, report_id, dataset_id, store, doc_type="EQC_QA", |
| aspect, aspect_base, category, section, title, text_raw, text_with_prefix, token_count |
| """ |
| import hashlib |
| import json |
| import re |
| import sys |
| from pathlib import Path |
|
|
| import tiktoken |
|
|
| ROOT = Path(__file__).resolve().parent |
| PARSED = ROOT / "parsed" |
| MANIFEST = ROOT / "reports.jsonl" |
| OUT = ROOT / "chunks.jsonl" |
|
|
| MAX_TOKENS = 1000 |
| MIN_QUALITY_TOKENS = 30 |
| MIN_TOKENS = 80 |
| OVERLAP_RATIO = 0.05 |
|
|
| _enc = tiktoken.get_encoding("cl100k_base") |
|
|
|
|
| def log(*a): |
| print(*a, file=sys.stderr, flush=True) |
|
|
|
|
| def count_tokens(t: str) -> int: |
| return len(_enc.encode(t)) |
|
|
|
|
| |
| HEADING = re.compile(r"^(#{1,4})\s+(.*)$") |
|
|
|
|
| def parse_sections(md: str) -> list[tuple[str, str]]: |
| """Return [(section_path, body_text)] splitting on ATX headings, tracking |
| the heading breadcrumb. Fenced code blocks are left intact (skip heading |
| detection inside ``` fences).""" |
| lines = md.splitlines() |
| stack: list[tuple[int, str]] = [] |
| cur_path = "[intro]" |
| buf: list[str] = [] |
| sections: list[tuple[str, str]] = [] |
| in_fence = False |
|
|
| def flush(): |
| body = "\n".join(buf).strip() |
| if body: |
| sections.append((cur_path, body)) |
|
|
| for ln in lines: |
| if ln.lstrip().startswith("```"): |
| in_fence = not in_fence |
| buf.append(ln) |
| continue |
| m = None if in_fence else HEADING.match(ln) |
| if m: |
| flush() |
| buf = [] |
| level = len(m.group(1)) |
| title = re.sub(r"[#*`]", "", m.group(2)).strip() |
| title = re.sub(r"[\U0001F000-\U0001FAFF☀-➿]", "", title).strip() |
| while stack and stack[-1][0] >= level: |
| stack.pop() |
| stack.append((level, title)) |
| cur_path = " > ".join(t for _, t in stack) or "[section]" |
| else: |
| buf.append(ln) |
| flush() |
| return sections |
|
|
|
|
| def strip_noise(t: str) -> str: |
| |
| t = re.sub(r"```\{[^}]*\}", "", t) |
| t = re.sub(r"^:class:.*$", "", t, flags=re.MULTILINE) |
| t = re.sub(r"\n{3,}", "\n\n", t) |
| return t.strip() |
|
|
|
|
| def split_by_tokens(text: str, max_tokens: int) -> list[str]: |
| """Greedy paragraph-packing; hard-split any oversized paragraph on tokens.""" |
| paras = re.split(r"\n\s*\n", text) |
| chunks: list[str] = [] |
| cur: list[str] = [] |
| cur_tok = 0 |
| for p in paras: |
| p = p.strip() |
| if not p: |
| continue |
| pt = count_tokens(p) |
| if pt > max_tokens: |
| if cur: |
| chunks.append("\n\n".join(cur)); cur, cur_tok = [], 0 |
| ids = _enc.encode(p) |
| for i in range(0, len(ids), max_tokens): |
| chunks.append(_enc.decode(ids[i:i + max_tokens])) |
| continue |
| if cur_tok + pt > max_tokens and cur: |
| chunks.append("\n\n".join(cur)); cur, cur_tok = [], 0 |
| cur.append(p); cur_tok += pt |
| if cur: |
| chunks.append("\n\n".join(cur)) |
| return chunks |
|
|
|
|
| def add_overlap(chunks: list[str], ratio: float) -> list[str]: |
| if len(chunks) < 2 or ratio <= 0: |
| return chunks |
| out = [chunks[0]] |
| for i in range(1, len(chunks)): |
| prev = chunks[i - 1] |
| ptoks = _enc.encode(prev) |
| n = max(1, int(len(ptoks) * ratio)) |
| tail = _enc.decode(ptoks[-n:]) |
| out.append(tail + "\n\n" + chunks[i]) |
| return out |
|
|
|
|
| def make_prefix(rec: dict, section: str) -> str: |
| ds = rec["matched_dataset_id"] or rec["dataset_id"] or "(unmapped)" |
| return (f'EQC Quality Assessment: "{rec["title"]}"\n' |
| f'Dataset: {ds} [{rec["store"] or "CDS"}]\n' |
| f'Aspect: {rec["aspect"]} | Category: {rec["category"]}\n' |
| f'Section: {section}\n---\n') |
|
|
|
|
| def chunk_report(rec: dict) -> list[dict]: |
| md = (PARSED / Path(rec["md_path"]).name).read_text(encoding="utf-8", errors="replace") |
| sections = parse_sections(md) |
| out: list[dict] = [] |
| seen: set[str] = set() |
| counter = 0 |
| for section, body in sections: |
| body = strip_noise(body) |
| if not body: |
| continue |
| raw = split_by_tokens(body, MAX_TOKENS) |
| if len(raw) > 1: |
| raw = add_overlap(raw, OVERLAP_RATIO) |
| for ct in raw: |
| ct = ct.strip() |
| if count_tokens(ct) < MIN_QUALITY_TOKENS: |
| continue |
| h = hashlib.md5(ct.encode()).hexdigest() |
| if h in seen: |
| continue |
| seen.add(h) |
| twp = make_prefix(rec, section) + ct |
| out.append({ |
| "chunk_id": f"{rec['report_id']}__{h[:12]}", |
| "report_id": rec["report_id"], |
| "dataset_id": rec["matched_dataset_id"] or rec["dataset_id"], |
| "store": rec["store"] or "CDS", |
| "doc_type": "EQC_QA", |
| "aspect": rec["aspect"], |
| "aspect_base": rec["aspect_base"], |
| "category": rec["category"], |
| "match_confidence": rec["match_confidence"], |
| "section": section, |
| "title": rec["title"], |
| "chunk_index": counter, |
| "token_count": count_tokens(twp), |
| "text_raw": ct, |
| "text_with_prefix": twp, |
| }) |
| counter += 1 |
|
|
| |
| merged: list[dict] = [] |
| i = 0 |
| while i < len(out): |
| c = out[i] |
| if (c["token_count"] < MIN_TOKENS and i + 1 < len(out) |
| and out[i + 1]["section"] == c["section"]): |
| nxt = out[i + 1] |
| mt = c["text_raw"] + "\n\n" + nxt["text_raw"] |
| nxt["text_raw"] = mt |
| nxt["text_with_prefix"] = nxt["text_with_prefix"].split("---\n", 1)[0] + "---\n" + mt |
| nxt["token_count"] = count_tokens(nxt["text_with_prefix"]) |
| i += 1 |
| else: |
| merged.append(c); i += 1 |
| for j, c in enumerate(merged): |
| c["chunk_index"] = j |
| return merged |
|
|
|
|
| def main() -> None: |
| recs = [json.loads(l) for l in open(MANIFEST)] |
| recs = [r for r in recs if not r["is_template"]] |
| log(f"chunking {len(recs)} reports") |
| n_docs = n_chunks = 0 |
| with open(OUT, "w", encoding="utf-8") as f: |
| for r in recs: |
| chunks = chunk_report(r) |
| for c in chunks: |
| f.write(json.dumps(c, ensure_ascii=False) + "\n") |
| n_docs += 1 |
| n_chunks += len(chunks) |
| toks = 0 |
| for l in open(OUT): |
| toks += json.loads(l)["token_count"] |
| log(f"DONE: {n_docs} reports -> {n_chunks} chunks ({toks:,} tokens) -> {OUT}") |
| log(f"avg {n_chunks/n_docs:.1f} chunks/report; est realtime ${toks/1e6*0.25:.2f}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|