File size: 8,344 Bytes
0ec8fd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | #!/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 = <paper_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()
|