dmpantiu's picture
Upload folder using huggingface_hub
0ec8fd6 verified
Raw
History Blame Contribute Delete
9.17 kB
#!/usr/bin/env python3
"""
chunk_docs.py — Section-aware chunking of marine_parsed VLM markdown.
Reuses the battle-tested chunker from cmip6_gpt/rag/chunk_papers.py
(noise filters, OCR-ris fixes, dedup, overlap, token budget) but assembles
a marine-specific prefix: product, document type (PUM/QUID/SQO), section path.
Images are ignored (markdown image refs are skipped by the parser).
Output: out/chunks.jsonl — one JSON object per chunk. Resumable per md file.
"""
import hashlib
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent
WS = ROOT.parent
PARSED = WS / "marine_parsed"
OUT = ROOT / "out"
CMIP6_RAG = Path("/Users/dmpantiu/cmip6/cmip6_gpt/rag")
sys.path.insert(0, str(CMIP6_RAG))
from chunk_papers import ( # noqa: E402
parse_markdown_sections, fix_ocr_ris_stripping, clean_ui_from_text,
is_garbage_section_path, is_figure_axis_gibberish, is_digit_heavy_garbage,
is_boilerplate_noise, is_affiliation_fragment, is_reference_block,
has_repeating_loop, is_url_only, chunk_text_block, add_overlap, count_tokens,
MAX_TOKENS, MIN_QUALITY_TOKENS, MIN_TOKENS, OVERLAP_RATIO, TABLE_MAX_TOKENS,
)
DOC_TYPES = ("PUM", "QUID", "SQO")
def doc_type_of(doc_id: str) -> str:
u = doc_id.upper()
for t in DOC_TYPES:
if re.search(rf"(^|[-_]){t}([-_]|$)", u) or t in u:
return t
return "OTHER"
def is_noise_table(tbl_text: str) -> bool:
"""Drop document-meta tables (change record, approval, acronyms) — pure noise."""
head = "\n".join(tbl_text.lower().splitlines()[:3])
if "description of change" in head:
return True
if ("validated by" in head or "checked by" in head) and ("issue" in head or "date" in head):
return True
if "acronym" in head and "description" in head:
return True
if head.count("|") >= 4 and ("abbreviation" in head and "meaning" in head):
return True
return False
def make_prefix(product_id: str, title: str, doc_id: str, doc_type: str, section_path: str) -> str:
head = f'Product: "{title}" [{product_id}]' if title else f"Product: {product_id}"
return (head + f"\nDocument: {doc_type} ({doc_id})"
+ f"\nSection: {section_path}\n---\n")
def chunk_marine_md(md_path: Path, product_id: str, title: str, doc_id: str | None = None) -> list[dict]:
if doc_id is None:
doc_id = md_path.stem
doc_type = doc_type_of(doc_id)
md_text = md_path.read_text(encoding="utf-8", errors="replace")
sections = parse_markdown_sections(md_text)
out: list[dict] = []
counter = 0
seen: set[str] = set()
for section in sections:
if section.paragraphs == ["__EXCLUDED__"]:
continue
section_path = section.path
if is_garbage_section_path(section.name):
section_path = "[section unknown]"
# ── text ──
if section.paragraphs:
full = fix_ocr_ris_stripping("\n\n".join(section.paragraphs))
raw = [full] if count_tokens(full) <= MAX_TOKENS else chunk_text_block(full, MAX_TOKENS)
if len(raw) > 1:
raw = add_overlap(raw, OVERLAP_RATIO)
capped = []
for rc in raw:
capped.extend(chunk_text_block(rc, MAX_TOKENS) if count_tokens(rc) > MAX_TOKENS + 50 else [rc])
for ct in capped:
if count_tokens(ct) < MIN_QUALITY_TOKENS:
continue
ct = clean_ui_from_text(ct)
if not ct or count_tokens(ct) < MIN_QUALITY_TOKENS:
continue
if (is_figure_axis_gibberish(ct) or is_digit_heavy_garbage(ct)
or is_boilerplate_noise(ct) or is_affiliation_fragment(ct)
or is_reference_block(ct) or has_repeating_loop(ct)):
continue
h = hashlib.md5(ct.encode()).hexdigest()
if h in seen:
continue
seen.add(h)
twp = make_prefix(product_id, title, doc_id, doc_type, section_path) + ct
out.append({
"chunk_id": f"{product_id}__{doc_id}__{h[:12]}",
"product_id": product_id, "product_title": title,
"doc_id": doc_id, "doc_type": doc_type,
"section_path": section_path, "section_name": section.name,
"chunk_type": "text", "chunk_index": counter,
"token_count": count_tokens(twp),
"text_with_prefix": twp, "text_raw": ct,
})
counter += 1
# ── tables ──
for j, tbl in enumerate(section.tables):
tbl_text = tbl.get("text", "")
if not tbl_text or count_tokens(tbl_text) < 10:
continue
if is_noise_table(tbl_text):
continue
caption = section.captions[j] if j < len(section.captions) else ""
ctx = f"[TABLE in section: {section_path}]" + (f"\nCaption: {caption}" if caption else "")
if count_tokens(tbl_text) > TABLE_MAX_TOKENS:
kept, tok = [], 0
for tl in tbl_text.split("\n"):
lt = count_tokens(tl)
if tok + lt > TABLE_MAX_TOKENS - 20:
break
kept.append(tl); tok += lt
tbl_text = "\n".join(kept) + "\n[... TABLE TRUNCATED ...]"
body = ctx + "\n\n" + tbl_text
twp = make_prefix(product_id, title, doc_id, doc_type, section_path) + body
cid = hashlib.md5(f"{product_id}{doc_id}tbl{section_path}{j}".encode()).hexdigest()[:12]
out.append({
"chunk_id": f"{product_id}__{doc_id}__tbl_{cid}",
"product_id": product_id, "product_title": title,
"doc_id": doc_id, "doc_type": doc_type,
"section_path": section_path, "section_name": section.name,
"chunk_type": "table", "chunk_index": counter,
"token_count": count_tokens(twp),
"text_with_prefix": twp, "text_raw": body,
})
counter += 1
# merge tiny adjacent text chunks
merged: list[dict] = []
ii = 0
while ii < len(out):
c = out[ii]
if (c["token_count"] < MIN_TOKENS and c["chunk_type"] == "text"
and ii + 1 < len(out) and out[ii + 1]["section_path"] == c["section_path"]
and out[ii + 1]["chunk_type"] == "text"):
nxt = out[ii + 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"])
ii += 1
else:
merged.append(c); ii += 1
for i, c in enumerate(merged):
c["chunk_index"] = i
return merged
def main() -> None:
catalog = json.loads((OUT / "catalog.json").read_text())
title_by_pid = {c["product_id"]: c["product_title"] for c in catalog}
# Prefer CLEANED markdown (clean_md.py output) over raw marine_parsed.
clean_dir = OUT / "cleaned"
use_clean = clean_dir.exists() and any(clean_dir.glob("*.md"))
if use_clean:
md_files = sorted(clean_dir.glob("*.md"))
print(f"source: CLEANED ({len(md_files)} files)")
def product_of(md: Path) -> str:
return md.stem.split("__", 1)[0]
else:
md_files = sorted(PARSED.rglob("vlm/*.md"))
print(f"source: RAW marine_parsed ({len(md_files)} files)")
def product_of(md: Path) -> str:
return md.relative_to(PARSED).parts[0]
out_path = OUT / "chunks.jsonl"
done_docs: set[str] = set()
if out_path.exists():
with open(out_path) as f:
for line in f:
try:
r = json.loads(line)
done_docs.add(f"{r['product_id']}__{r['doc_id']}")
except Exception:
pass
print(f"resume: {len(done_docs)} docs already chunked")
n_docs = n_chunks = 0
with open(out_path, "a", encoding="utf-8") as fout:
for md in md_files:
pid = product_of(md)
doc_id = md.stem.split("__", 1)[1] if use_clean and "__" in md.stem else md.stem
doc_key = f"{pid}__{doc_id}"
if doc_key in done_docs:
continue
try:
chunks = chunk_marine_md(md, pid, title_by_pid.get(pid, ""), doc_id)
except Exception as e:
print(f" ERROR {doc_key}: {repr(e)[:120]}", file=sys.stderr)
continue
for c in chunks:
fout.write(json.dumps(c, ensure_ascii=False) + "\n")
fout.flush()
n_docs += 1
n_chunks += len(chunks)
if n_docs % 50 == 0:
print(f" [{n_docs} docs] {n_chunks} chunks")
print(f"DONE: {n_docs} docs newly chunked, {n_chunks} chunks → {out_path}")
if __name__ == "__main__":
main()