#!/usr/bin/env python3 """ chunk_pubs.py — chunk the 725 parsed CMIP6 publications for the L3 RAG. Reuses the proven CMIP6 chunker (chunk_papers_lib.py, copied verbatim — never modify the original) for section parsing, OCR fixes, noise/reference/boilerplate filtering, sentence-aware 1000-token chunking, 5% overlap, table/caption handling. Metadata (title/journal/year/doi/domains) comes from out/papers.jsonl. Output: out/chunks.jsonl chunk_id = __NNN (NNN zero-padded sequential per paper) payload: {paper_id, doi, title, journal, year, domains, section, chunk_type, text_raw, text_with_prefix} (+ token_count for stats) """ import hashlib import json import sys from pathlib import Path import chunk_papers_lib as L ROOT = Path(__file__).resolve().parent OUT = ROOT / "out" PAPERS = OUT / "papers.jsonl" CHUNKS = OUT / "chunks.jsonl" def build_prefix(title, doi, year, journal, section, domains): prefix = f'Paper: "{title}"' if title else f"Paper: {doi}" if year: prefix += f" ({year}" if journal: prefix += f", {journal}" prefix += ")" elif journal: prefix += f" ({journal})" prefix += f"\nDOI: {doi}" if domains: prefix += f"\nDomains: {', '.join(domains)}" prefix += f"\nSection: {section}" prefix += "\n---\n" return prefix def chunk_paper(rec) -> list[dict]: paper_id = rec["paper_id"] doi = rec["doi"] title = rec["title"] journal = rec["journal"] year = rec["year"] domains = rec["domains"] md_path = Path(rec["md_path"]) md_text = md_path.read_text(encoding="utf-8", errors="replace") sections = L.parse_markdown_sections(md_text) out = [] seen = set() def emit(chunk_type, section, text_raw): prefix = build_prefix(title, doi, year, journal, section, domains) twp = prefix + text_raw out.append({ "chunk_type": chunk_type, "section": section, "text_raw": text_raw, "text_with_prefix": twp, "token_count": L.count_tokens(twp), }) for section in sections: if section.paragraphs == ["__EXCLUDED__"]: continue section_path = section.path if L.is_garbage_section_path(section.name): section_path = "[section unknown]" # ── Text chunks ── if section.paragraphs: full_text = "\n\n".join(section.paragraphs) full_text = L.fix_ocr_ris_stripping(full_text) is_abstract = section.name.strip().lower() == "abstract" chunk_type = "abstract" if is_abstract else "text" if L.count_tokens(full_text) <= L.MAX_TOKENS: raw_chunks = [full_text] else: raw_chunks = L.chunk_text_block(full_text, L.MAX_TOKENS) if len(raw_chunks) > 1: raw_chunks = L.add_overlap(raw_chunks, L.OVERLAP_RATIO) capped = [] for rc in raw_chunks: if L.count_tokens(rc) > L.MAX_TOKENS + 50: capped.extend(L.chunk_text_block(rc, L.MAX_TOKENS)) else: capped.append(rc) for ct in capped: if L.count_tokens(ct) < L.MIN_QUALITY_TOKENS: continue ct = L.clean_ui_from_text(ct) if not ct or L.count_tokens(ct) < L.MIN_QUALITY_TOKENS: continue if L.is_figure_axis_gibberish(ct): continue if L.is_digit_heavy_garbage(ct): continue if L.is_boilerplate_noise(ct): continue if L.is_affiliation_fragment(ct): continue if L.is_reference_block(ct): continue if L.has_repeating_loop(ct): continue h = hashlib.md5(ct.encode()).hexdigest() if h in seen: continue seen.add(h) emit(chunk_type, section_path, ct) # ── Table chunks ── for j, tbl in enumerate(section.tables): tbl_text = tbl.get("text", "") if not tbl_text or L.count_tokens(tbl_text) < 10: continue caption = section.captions[j] if j < len(section.captions) else "" context = f"[TABLE in section: {section_path}]" if caption: context += f"\nCaption: {caption}" if L.count_tokens(tbl_text) > L.TABLE_MAX_TOKENS: lines = tbl_text.split("\n") kept, tok = [], 0 for ln in lines: lt = L.count_tokens(ln) if tok + lt > L.TABLE_MAX_TOKENS - 20: break kept.append(ln) tok += lt tbl_text = "\n".join(kept) + "\n[... TABLE TRUNCATED ...]" emit("table", section_path, context + "\n\n" + tbl_text) # ── Standalone captions ── for cap in section.captions[len(section.tables):]: if L.count_tokens(cap) < 10 or L.is_url_only(cap): continue cap = L.clean_ui_from_text(cap) if not cap or L.count_tokens(cap) < 10: continue cap = L.fix_ocr_ris_stripping(cap) emit("caption", section_path, f"[FIGURE CAPTION]\n{cap}") # ── merge tiny text chunks into neighbour (same section) ── merged = [] i = 0 while i < len(out): c = out[i] if (c["chunk_type"] == "text" and c["token_count"] < L.MIN_TOKENS and i + 1 < len(out) and out[i + 1]["section"] == c["section"] and out[i + 1]["chunk_type"] == "text"): nxt = out[i + 1] nxt["text_raw"] = c["text_raw"] + "\n\n" + nxt["text_raw"] nxt["text_with_prefix"] = (nxt["text_with_prefix"].split("---\n", 1)[0] + "---\n" + nxt["text_raw"]) nxt["token_count"] = L.count_tokens(nxt["text_with_prefix"]) i += 1 continue merged.append(c) i += 1 # assign sequential chunk_ids + full payload result = [] for idx, c in enumerate(merged): result.append({ "chunk_id": f"{paper_id}__{idx:03d}", "paper_id": paper_id, "doi": doi, "title": title, "journal": journal, "year": year, "domains": domains, "section": c["section"], "chunk_type": c["chunk_type"], "text_raw": c["text_raw"], "text_with_prefix": c["text_with_prefix"], "token_count": c["token_count"], }) return result def main(): papers = [json.loads(l) for l in open(PAPERS, encoding="utf-8")] total_chunks = 0 tok_sum = 0 tok_min = 10**9 tok_max = 0 type_counter = {} empty_papers = 0 with open(CHUNKS, "w", encoding="utf-8") as f: for n, rec in enumerate(papers, 1): try: chunks = chunk_paper(rec) except Exception as e: print(f"ERR {rec['paper_id']}: {str(e)[:100]}", file=sys.stderr) continue if not chunks: empty_papers += 1 for c in chunks: f.write(json.dumps(c, ensure_ascii=False) + "\n") total_chunks += 1 tk = c["token_count"] tok_sum += tk tok_min = min(tok_min, tk) tok_max = max(tok_max, tk) type_counter[c["chunk_type"]] = type_counter.get(c["chunk_type"], 0) + 1 if n % 100 == 0: print(f" {n}/{len(papers)} papers, {total_chunks} chunks", file=sys.stderr) print(f"papers: {len(papers)} (empty: {empty_papers})", file=sys.stderr) print(f"chunks: {total_chunks}", file=sys.stderr) print(f"tokens/chunk: mean={tok_sum/max(total_chunks,1):.0f} " f"min={tok_min} max={tok_max} total={tok_sum:,}", file=sys.stderr) print(f"chunk types: {type_counter}", file=sys.stderr) print(f"wrote {CHUNKS}", file=sys.stderr) if __name__ == "__main__": main()