| |
| """ |
| chunk_docs.py — section-aware chunking of the fetched CDS/ADS/EWDS deep docs. |
| |
| Mirrors eqc_qa/chunk_reports.py. One chunk-set per UNIQUE doc (a doc shared by |
| several datasets is chunked once; its chunks carry dataset_ids[] = all datasets |
| that reference it, so the server can filter per dataset). |
| |
| Input : deep_docs/manifest.jsonl (status==ok rows) + their parsed/*.md |
| Output: deep_docs/chunks.jsonl — payload: |
| chunk_id, doc_url, doc_title, doc_kind, dataset_ids[], store, stores[], |
| section, chunk_index, token_count, text_raw, text_with_prefix |
| """ |
| import hashlib |
| import json |
| import re |
| import sys |
| from pathlib import Path |
|
|
| import tiktoken |
|
|
| ROOT = Path(__file__).resolve().parent.parent |
| MANIFEST = ROOT / "deep_docs" / "manifest.jsonl" |
| OUT = ROOT / "deep_docs" / "chunks.jsonl" |
| META = ROOT / "meta_harvest" / "unified_metadata.json" |
|
|
| 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): return len(_enc.encode(t)) |
|
|
|
|
| HEADING = re.compile(r"^(#{1,4})\s+(.*)$") |
|
|
|
|
| def parse_sections(md): |
| lines = md.splitlines() |
| stack, cur_path, buf, sections, in_fence = [], "[intro]", [], [], 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() |
| 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 split_by_tokens(text, max_tokens): |
| paras = re.split(r"\n\s*\n", text) |
| chunks, cur, 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, ratio): |
| if len(chunks) < 2 or ratio <= 0: |
| return chunks |
| out = [chunks[0]] |
| for i in range(1, len(chunks)): |
| ptoks = _enc.encode(chunks[i - 1]) |
| n = max(1, int(len(ptoks) * ratio)) |
| out.append(_enc.decode(ptoks[-n:]) + "\n\n" + chunks[i]) |
| return out |
|
|
|
|
| def main(): |
| meta = json.loads(META.read_text()) if META.exists() else {} |
| store_of = {} |
| for k, v in meta.items(): |
| pid = v.get("product_id") or k |
| store_of[pid] = (v.get("store") or "").upper() |
|
|
| recs = [json.loads(l) for l in MANIFEST.read_text().splitlines() if l.strip()] |
| ok = [r for r in recs if r["status"] == "ok" and r.get("md_path")] |
| |
| seen_url = {} |
| for r in ok: |
| seen_url[r["url"]] = r |
| log(f"chunking {len(seen_url)} unique docs") |
|
|
| n_docs = n_chunks = 0 |
| with open(OUT, "w", encoding="utf-8") as f: |
| for url, r in seen_url.items(): |
| p = ROOT / r["md_path"] |
| if not p.exists(): |
| continue |
| md = p.read_text(encoding="utf-8", errors="replace") |
| dsids = sorted(set(r["datasets"])) |
| stores = sorted({store_of.get(d, "") for d in dsids} - {""}) |
| store = stores[0] if stores else "CDS" |
| title = r.get("title") or "" |
| counter = 0 |
| seen_h = set() |
| for section, body in parse_sections(md): |
| body = re.sub(r"\n{3,}", "\n\n", body).strip() |
| 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_h: |
| continue |
| seen_h.add(h) |
| prefix = (f'Copernicus documentation: "{title}"\n' |
| f'Dataset(s): {", ".join(dsids[:6])} [{store}]\n' |
| f'Section: {section}\n---\n') |
| twp = prefix + ct |
| f.write(json.dumps({ |
| "chunk_id": f"{hashlib.md5(url.encode()).hexdigest()[:12]}__{h[:12]}", |
| "doc_url": url, |
| "doc_title": title, |
| "doc_kind": r.get("kind"), |
| "dataset_ids": dsids, |
| "store": store, |
| "stores": stores, |
| "doc_type": "DEEP_DOC", |
| "section": section, |
| "chunk_index": counter, |
| "token_count": count_tokens(twp), |
| "text_raw": ct, |
| "text_with_prefix": twp, |
| }, ensure_ascii=False) + "\n") |
| counter += 1 |
| n_docs += 1 |
| n_chunks += counter |
| toks = sum(json.loads(l)["token_count"] for l in open(OUT)) |
| log(f"DONE: {n_docs} docs -> {n_chunks} chunks ({toks:,} tokens) -> {OUT}") |
| log(f"est batch embed ${toks/1e6*0.125:.2f} (realtime ${toks/1e6*0.25:.2f})") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|