Cok-temsilli chunking - cocuk+ust, span-id korumali (Faz 1.1)
Browse files at this commit6c42fe83d48c68db22312a5db28a3cbf6c72e63dParent: 75c5638- feat
- cok-temsilli chunking - cocuk+ust, span-id korumali (Faz 1.1)
4 changed files +278 -0
- src/chunk/__init__.py +9 -0
- src/chunk/chunker.py +126 -0
- tests/integration/test_chunk.py +52 -0
- tests/unit/test_chunk.py +91 -0
src/chunk/__init__.pyadded+9 -0
| @@ -0,0 +1,9 @@ | ||
| 1 | +"""Chunking (Faz 1.1) — CanonicalDoc birimlerinden çok-temsilli chunk. | |
| 2 | + | |
| 3 | +çocuk (150-300 tok, normal QA) + üst (700-1500 tok, bağlam genişletme). Her chunk | |
| 4 | +kaynak birimlerin **span-id**'lerini taşır (atıf/provenance korunur). Atomik önerme | |
| 5 | +temsili LLM gerektirir → Faz 1 sonrası (API gelince). Bkz. mimari §2. | |
| 6 | +""" | |
| 7 | +from .chunker import Chunk, chunk_document, approx_tokens | |
| 8 | + | |
| 9 | +__all__ = ["Chunk", "chunk_document", "approx_tokens"] |
src/chunk/chunker.pyadded+126 -0
| @@ -0,0 +1,126 @@ | ||
| 1 | +"""Faz 1.1 — Çok-temsilli chunking (çocuk + üst), başlık-sınırı farkında. | |
| 2 | + | |
| 3 | +Kaynak: `CanonicalDoc` (retrievable birimler). Çıktı: child + parent chunk'lar; | |
| 4 | +her chunk kaynak birim **span_id**'lerini taşır → atıf korunur. Tokenizer henüz | |
| 5 | +yok; `approx_tokens` yaklaşık ölçüdür (embedding modeli gelince gerçek sayım, 1.2). | |
| 6 | +""" | |
| 7 | +from __future__ import annotations | |
| 8 | +from collections import Counter | |
| 9 | +from dataclasses import dataclass, field, asdict | |
| 10 | + | |
| 11 | +from ..ingest.canonical import CanonicalDoc, CanonicalUnit | |
| 12 | +from ..ingest.pdf_parse import HEADING | |
| 13 | + | |
| 14 | +# Yaklaşık token: Türkçe eklemeli → kelime başına ~1.4 subword. | |
| 15 | +_TOK_PER_WORD = 1.4 | |
| 16 | +CHILD_MIN = 150 # bir çocuk en az bu kadar (küçük bloklar birleşir) | |
| 17 | +CHILD_FLUSH = 250 # bu değere ulaşınca çocuğu kapat (150-300 bandının ortası) | |
| 18 | +PARENT_MIN = 700 # bir üst en az bu kadar | |
| 19 | +PARENT_FLUSH = 1000 # üst chunk flush eşiği (700-1500 bandı) | |
| 20 | + | |
| 21 | + | |
| 22 | +def approx_tokens(text: str) -> int: | |
| 23 | + return round(len(text.split()) * _TOK_PER_WORD) | |
| 24 | + | |
| 25 | + | |
| 26 | +@dataclass | |
| 27 | +class Chunk: | |
| 28 | + chunk_id: str | |
| 29 | + level: str # "child" | "parent" | |
| 30 | + text: str | |
| 31 | + span_ids: list[str] # kaynak birimlerin span-id'leri (atıf) | |
| 32 | + doc_id: str | |
| 33 | + sinif: str | |
| 34 | + ders: str | |
| 35 | + kaynak_turu: str | |
| 36 | + page_start: int | |
| 37 | + page_end: int | |
| 38 | + kinds: list[str] | |
| 39 | + page_visual: str # baskın görsel sınıfı | |
| 40 | + approx_tokens: int | |
| 41 | + parent_id: str | None = None # child için | |
| 42 | + child_ids: list[str] = field(default_factory=list) # parent için | |
| 43 | + | |
| 44 | + | |
| 45 | +def _mk(units: list[CanonicalUnit], doc: CanonicalDoc, level: str, n: int) -> Chunk: | |
| 46 | + text = "\n".join(u.text for u in units) | |
| 47 | + pages = [u.page for u in units] | |
| 48 | + vis = Counter(u.page_visual for u in units).most_common(1)[0][0] | |
| 49 | + return Chunk( | |
| 50 | + chunk_id=f"{doc.doc_id}:{'c' if level=='child' else 'p'}{n}", | |
| 51 | + level=level, text=text, span_ids=[u.span_id for u in units], | |
| 52 | + doc_id=doc.doc_id, sinif=doc.sinif, ders=doc.ders, kaynak_turu=doc.kaynak_turu, | |
| 53 | + page_start=min(pages), page_end=max(pages), | |
| 54 | + kinds=sorted({u.kind for u in units}), page_visual=vis, | |
| 55 | + approx_tokens=approx_tokens(text)) | |
| 56 | + | |
| 57 | + | |
| 58 | +def chunk_document(doc: CanonicalDoc) -> list[Chunk]: | |
| 59 | + """CanonicalDoc → child + parent chunk'lar (başlık sınırlarına saygılı).""" | |
| 60 | + units = doc.retrievable_units | |
| 61 | + | |
| 62 | + # --- çocuk chunk'lar --- | |
| 63 | + children: list[Chunk] = [] | |
| 64 | + buf: list[CanonicalUnit] = [] | |
| 65 | + tok = 0 | |
| 66 | + cn = 0 | |
| 67 | + | |
| 68 | + def flush_child(): | |
| 69 | + nonlocal buf, tok, cn | |
| 70 | + if buf: | |
| 71 | + children.append(_mk(buf, doc, "child", cn)); cn += 1 | |
| 72 | + buf = []; tok = 0 | |
| 73 | + | |
| 74 | + for u in units: | |
| 75 | + # başlık yeni bölüm başlatır — ama yalnız çocuk zaten yeterince doluysa | |
| 76 | + # (aksi halde küçük bloklu + çok-başlıklı kitapta chunk'lar minik kalır). | |
| 77 | + if u.kind == HEADING and tok >= CHILD_MIN: | |
| 78 | + flush_child() | |
| 79 | + buf.append(u) | |
| 80 | + tok += approx_tokens(u.text) | |
| 81 | + if tok >= CHILD_FLUSH: | |
| 82 | + flush_child() | |
| 83 | + flush_child() | |
| 84 | + | |
| 85 | + # --- üst chunk'lar (çocukları grupla; başlıkla başlayan çocuk yeni bölüm) --- | |
| 86 | + parents: list[Chunk] = [] | |
| 87 | + pbuf: list[Chunk] = [] | |
| 88 | + ptok = 0 | |
| 89 | + pn = 0 | |
| 90 | + | |
| 91 | + def flush_parent(): | |
| 92 | + nonlocal pbuf, ptok, pn | |
| 93 | + if pbuf: | |
| 94 | + # parent metni = çocuk metinleri; span_id'ler birleşik | |
| 95 | + merged_units_text = "\n".join(c.text for c in pbuf) | |
| 96 | + span_ids = [sid for c in pbuf for sid in c.span_ids] | |
| 97 | + pages = [p for c in pbuf for p in (c.page_start, c.page_end)] | |
| 98 | + vis = Counter(c.page_visual for c in pbuf).most_common(1)[0][0] | |
| 99 | + pid = f"{doc.doc_id}:p{pn}" | |
| 100 | + parents.append(Chunk( | |
| 101 | + chunk_id=pid, level="parent", text=merged_units_text, span_ids=span_ids, | |
| 102 | + doc_id=doc.doc_id, sinif=doc.sinif, ders=doc.ders, kaynak_turu=doc.kaynak_turu, | |
| 103 | + page_start=min(pages), page_end=max(pages), | |
| 104 | + kinds=sorted({k for c in pbuf for k in c.kinds}), page_visual=vis, | |
| 105 | + approx_tokens=approx_tokens(merged_units_text), | |
| 106 | + child_ids=[c.chunk_id for c in pbuf])) | |
| 107 | + for c in pbuf: | |
| 108 | + c.parent_id = pid | |
| 109 | + pbuf = []; ptok = 0; pn += 1 | |
| 110 | + | |
| 111 | + for c in children: | |
| 112 | + # başlıkla başlayan çocuk yeni bölümdür — ama yalnız üst zaten dolmuşsa böl | |
| 113 | + starts_section = HEADING in c.kinds | |
| 114 | + if starts_section and ptok >= PARENT_MIN: | |
| 115 | + flush_parent() | |
| 116 | + pbuf.append(c) | |
| 117 | + ptok += c.approx_tokens | |
| 118 | + if ptok >= PARENT_FLUSH: | |
| 119 | + flush_parent() | |
| 120 | + flush_parent() | |
| 121 | + | |
| 122 | + return children + parents | |
| 123 | + | |
| 124 | + | |
| 125 | +def to_dicts(chunks: list[Chunk]) -> list[dict]: | |
| 126 | + return [asdict(c) for c in chunks] |
tests/integration/test_chunk.pyadded+52 -0
| @@ -0,0 +1,52 @@ | ||
| 1 | +"""Faz 1.1 integration testi — 12-bio kanonik doküman üzerinde chunking (gerçek veri).""" | |
| 2 | +import os | |
| 3 | +import unittest | |
| 4 | + | |
| 5 | +from src.ingest.canonical import build_canonical | |
| 6 | +from src.chunk import chunk_document | |
| 7 | + | |
| 8 | +BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") | |
| 9 | + | |
| 10 | + | |
| 11 | +@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK}") | |
| 12 | +class Chunk12BioTests(unittest.TestCase): | |
| 13 | + @classmethod | |
| 14 | + def setUpClass(cls): | |
| 15 | + cls.doc = build_canonical(BOOK, sinif="12", ders="biyoloji") | |
| 16 | + cls.chunks = chunk_document(cls.doc) | |
| 17 | + cls.children = [c for c in cls.chunks if c.level == "child"] | |
| 18 | + cls.parents = [c for c in cls.chunks if c.level == "parent"] | |
| 19 | + | |
| 20 | + def test_children_and_parents_produced(self): | |
| 21 | + self.assertGreater(len(self.children), 20) | |
| 22 | + self.assertGreater(len(self.parents), 5) | |
| 23 | + | |
| 24 | + def test_child_span_ids_exist_in_doc(self): | |
| 25 | + doc_spans = {u.span_id for u in self.doc.units} | |
| 26 | + child_spans = {sid for c in self.children for sid in c.span_ids} | |
| 27 | + self.assertTrue(child_spans.issubset(doc_spans)) | |
| 28 | + # tüm retrievable birimler bir çocukta yer almalı | |
| 29 | + self.assertEqual(child_spans, {u.span_id for u in self.doc.retrievable_units}) | |
| 30 | + | |
| 31 | + def test_children_linked_to_real_parents(self): | |
| 32 | + pids = {p.chunk_id for p in self.parents} | |
| 33 | + linked = [c for c in self.children if c.parent_id] | |
| 34 | + self.assertGreater(len(linked), 0) | |
| 35 | + for c in linked: | |
| 36 | + self.assertIn(c.parent_id, pids) | |
| 37 | + | |
| 38 | + def test_child_token_sizes_reasonable(self): | |
| 39 | + # çoğu çocuk üst sınırın çok üstünde olmamalı (tek dev birim istisnası olabilir) | |
| 40 | + big = [c for c in self.children if c.approx_tokens > 600] | |
| 41 | + self.assertLess(len(big), len(self.children) * 0.1) | |
| 42 | + | |
| 43 | + def test_chunks_have_provenance_and_meta(self): | |
| 44 | + for c in self.chunks[:100]: | |
| 45 | + self.assertTrue(c.span_ids) | |
| 46 | + self.assertTrue(c.text.strip()) | |
| 47 | + self.assertEqual((c.sinif, c.ders), ("12", "biyoloji")) | |
| 48 | + self.assertIn(c.page_visual, {"figure_heavy", "mixed", "low_visual"}) | |
| 49 | + | |
| 50 | + | |
| 51 | +if __name__ == "__main__": | |
| 52 | + unittest.main() |
tests/unit/test_chunk.pyadded+91 -0
| @@ -0,0 +1,91 @@ | ||
| 1 | +"""Faz 1.1 birim testleri — chunking (sentetik CanonicalUnit'ler, deterministik).""" | |
| 2 | +import unittest | |
| 3 | + | |
| 4 | +from src.ingest.canonical import CanonicalUnit, CanonicalDoc | |
| 5 | +from src.ingest.pdf_parse import HEADING, PARAGRAPH | |
| 6 | +from src.chunk import chunk_document, approx_tokens | |
| 7 | + | |
| 8 | +WORDS40 = " ".join(f"kelime{i}" for i in range(40)) # ~56 approx token | |
| 9 | + | |
| 10 | + | |
| 11 | +def _u(n, text, kind=PARAGRAPH, page=1, vis="mixed", disi=False): | |
| 12 | + return CanonicalUnit(span_id=f"doc#{page}.{n}", doc_id="doc", sinif="12", | |
| 13 | + ders="biyoloji", kaynak_turu="ders_kitabi", page=page, | |
| 14 | + bbox=(0, 0, 100, 20), block_no=n, kind=kind, text=text, | |
| 15 | + page_visual=vis, retrieval_disi=disi) | |
| 16 | + | |
| 17 | + | |
| 18 | +def _doc(units): | |
| 19 | + return CanonicalDoc(source_path="x", doc_id="doc", source_version="v", sinif="12", | |
| 20 | + ders="biyoloji", kaynak_turu="ders_kitabi", page_count=1, units=units) | |
| 21 | + | |
| 22 | + | |
| 23 | +class TokenTests(unittest.TestCase): | |
| 24 | + def test_approx(self): | |
| 25 | + self.assertEqual(approx_tokens("a b c d"), round(4 * 1.4)) | |
| 26 | + self.assertEqual(approx_tokens(""), 0) | |
| 27 | + | |
| 28 | + | |
| 29 | +class ChunkTests(unittest.TestCase): | |
| 30 | + def setUp(self): | |
| 31 | + units = [_u(i, WORDS40) for i in range(8)] # 8 paragraf ~56 tok | |
| 32 | + self.doc = _doc(units) | |
| 33 | + self.chunks = chunk_document(self.doc) | |
| 34 | + self.children = [c for c in self.chunks if c.level == "child"] | |
| 35 | + self.parents = [c for c in self.chunks if c.level == "parent"] | |
| 36 | + | |
| 37 | + def test_children_created_and_sized(self): | |
| 38 | + self.assertGreaterEqual(len(self.children), 2) # 8×56≈450 tok → ≥2 çocuk | |
| 39 | + # her çocuk makul boyutta (tek dev birim yoksa CHILD_MAX civarını çok aşmaz) | |
| 40 | + for c in self.children: | |
| 41 | + self.assertGreater(c.approx_tokens, 0) | |
| 42 | + | |
| 43 | + def test_all_span_ids_preserved(self): | |
| 44 | + got = {sid for c in self.children for sid in c.span_ids} | |
| 45 | + want = {u.span_id for u in self.doc.units} | |
| 46 | + self.assertEqual(got, want) # hiçbir birim kaybolmadı | |
| 47 | + | |
| 48 | + def test_heading_starts_new_child_when_buffer_full(self): | |
| 49 | + # çocuk CHILD_MIN'i (150) geçtikten sonra başlık yeni çocuğu başlatır | |
| 50 | + units = [_u(0, WORDS40), _u(1, WORDS40), _u(2, WORDS40), # ~168 tok | |
| 51 | + _u(3, "1.2 Yeni Bölüm", HEADING), _u(4, WORDS40)] | |
| 52 | + chunks = [c for c in chunk_document(_doc(units)) if c.level == "child"] | |
| 53 | + heading_chunk = next(c for c in chunks if "doc#1.3" in c.span_ids) | |
| 54 | + self.assertNotIn("doc#1.0", heading_chunk.span_ids) # başlık öncesi ayrı çocukta | |
| 55 | + | |
| 56 | + def test_small_heading_does_not_split(self): | |
| 57 | + # küçük tampon + başlık → bölmez (minik chunk oluşmaz) | |
| 58 | + units = [_u(0, "kısa"), _u(1, "1.2 Yeni Bölüm", HEADING), _u(2, WORDS40)] | |
| 59 | + chunks = [c for c in chunk_document(_doc(units)) if c.level == "child"] | |
| 60 | + self.assertEqual(len(chunks), 1) # hepsi tek çocukta | |
| 61 | + | |
| 62 | + def test_parents_link_children(self): | |
| 63 | + self.assertGreaterEqual(len(self.parents), 1) | |
| 64 | + for p in self.parents: | |
| 65 | + self.assertTrue(p.child_ids) | |
| 66 | + for cid in p.child_ids: | |
| 67 | + child = next(c for c in self.children if c.chunk_id == cid) | |
| 68 | + self.assertEqual(child.parent_id, p.chunk_id) | |
| 69 | + | |
| 70 | + def test_parent_span_ids_union_of_children(self): | |
| 71 | + p = self.parents[0] | |
| 72 | + child_spans = {sid for cid in p.child_ids | |
| 73 | + for c in self.children if c.chunk_id == cid for sid in c.span_ids} | |
| 74 | + self.assertEqual(set(p.span_ids), child_spans) | |
| 75 | + | |
| 76 | + def test_excluded_units_not_chunked(self): | |
| 77 | + units = [_u(0, WORDS40), _u(1, "Değerlendirme Soruları " + WORDS40, disi=True)] | |
| 78 | + chunks = chunk_document(_doc(units)) | |
| 79 | + allspans = {sid for c in chunks for sid in c.span_ids} | |
| 80 | + self.assertIn("doc#1.0", allspans) | |
| 81 | + self.assertNotIn("doc#1.1", allspans) # sızıntı chunk'a girmez | |
| 82 | + | |
| 83 | + def test_metadata_propagated(self): | |
| 84 | + c = self.children[0] | |
| 85 | + self.assertEqual((c.doc_id, c.sinif, c.ders, c.kaynak_turu), | |
| 86 | + ("doc", "12", "biyoloji", "ders_kitabi")) | |
| 87 | + self.assertLessEqual(c.page_start, c.page_end) | |
| 88 | + | |
| 89 | + | |
| 90 | +if __name__ == "__main__": | |
| 91 | + unittest.main() |