File size: 7,327 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
#!/usr/bin/env python3
"""
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))


# ── section parsing (markdown heading aware) ─────────────────────────────────
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]] = []  # (level, title)
    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:
    # collapse admonition fences markers but keep content
    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

    # merge tiny adjacent chunks within a section
    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"]]  # skip scaffold
    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()