diff --git a/src/chunk/__init__.py b/src/chunk/__init__.py new file mode 100644 index 0000000..c27c54b --- /dev/null +++ b/src/chunk/__init__.py @@ -0,0 +1,9 @@ +"""Chunking (Faz 1.1) — CanonicalDoc birimlerinden çok-temsilli chunk. + +çocuk (150-300 tok, normal QA) + üst (700-1500 tok, bağlam genişletme). Her chunk +kaynak birimlerin **span-id**'lerini taşır (atıf/provenance korunur). Atomik önerme +temsili LLM gerektirir → Faz 1 sonrası (API gelince). Bkz. mimari §2. +""" +from .chunker import Chunk, chunk_document, approx_tokens + +__all__ = ["Chunk", "chunk_document", "approx_tokens"] diff --git a/src/chunk/chunker.py b/src/chunk/chunker.py new file mode 100644 index 0000000..1c3a9b4 --- /dev/null +++ b/src/chunk/chunker.py @@ -0,0 +1,126 @@ +"""Faz 1.1 — Çok-temsilli chunking (çocuk + üst), başlık-sınırı farkında. + +Kaynak: `CanonicalDoc` (retrievable birimler). Çıktı: child + parent chunk'lar; +her chunk kaynak birim **span_id**'lerini taşır → atıf korunur. Tokenizer henüz +yok; `approx_tokens` yaklaşık ölçüdür (embedding modeli gelince gerçek sayım, 1.2). +""" +from __future__ import annotations +from collections import Counter +from dataclasses import dataclass, field, asdict + +from ..ingest.canonical import CanonicalDoc, CanonicalUnit +from ..ingest.pdf_parse import HEADING + +# Yaklaşık token: Türkçe eklemeli → kelime başına ~1.4 subword. +_TOK_PER_WORD = 1.4 +CHILD_MIN = 150 # bir çocuk en az bu kadar (küçük bloklar birleşir) +CHILD_FLUSH = 250 # bu değere ulaşınca çocuğu kapat (150-300 bandının ortası) +PARENT_MIN = 700 # bir üst en az bu kadar +PARENT_FLUSH = 1000 # üst chunk flush eşiği (700-1500 bandı) + + +def approx_tokens(text: str) -> int: + return round(len(text.split()) * _TOK_PER_WORD) + + +@dataclass +class Chunk: + chunk_id: str + level: str # "child" | "parent" + text: str + span_ids: list[str] # kaynak birimlerin span-id'leri (atıf) + doc_id: str + sinif: str + ders: str + kaynak_turu: str + page_start: int + page_end: int + kinds: list[str] + page_visual: str # baskın görsel sınıfı + approx_tokens: int + parent_id: str | None = None # child için + child_ids: list[str] = field(default_factory=list) # parent için + + +def _mk(units: list[CanonicalUnit], doc: CanonicalDoc, level: str, n: int) -> Chunk: + text = "\n".join(u.text for u in units) + pages = [u.page for u in units] + vis = Counter(u.page_visual for u in units).most_common(1)[0][0] + return Chunk( + chunk_id=f"{doc.doc_id}:{'c' if level=='child' else 'p'}{n}", + level=level, text=text, span_ids=[u.span_id for u in units], + doc_id=doc.doc_id, sinif=doc.sinif, ders=doc.ders, kaynak_turu=doc.kaynak_turu, + page_start=min(pages), page_end=max(pages), + kinds=sorted({u.kind for u in units}), page_visual=vis, + approx_tokens=approx_tokens(text)) + + +def chunk_document(doc: CanonicalDoc) -> list[Chunk]: + """CanonicalDoc → child + parent chunk'lar (başlık sınırlarına saygılı).""" + units = doc.retrievable_units + + # --- çocuk chunk'lar --- + children: list[Chunk] = [] + buf: list[CanonicalUnit] = [] + tok = 0 + cn = 0 + + def flush_child(): + nonlocal buf, tok, cn + if buf: + children.append(_mk(buf, doc, "child", cn)); cn += 1 + buf = []; tok = 0 + + for u in units: + # başlık yeni bölüm başlatır — ama yalnız çocuk zaten yeterince doluysa + # (aksi halde küçük bloklu + çok-başlıklı kitapta chunk'lar minik kalır). + if u.kind == HEADING and tok >= CHILD_MIN: + flush_child() + buf.append(u) + tok += approx_tokens(u.text) + if tok >= CHILD_FLUSH: + flush_child() + flush_child() + + # --- üst chunk'lar (çocukları grupla; başlıkla başlayan çocuk yeni bölüm) --- + parents: list[Chunk] = [] + pbuf: list[Chunk] = [] + ptok = 0 + pn = 0 + + def flush_parent(): + nonlocal pbuf, ptok, pn + if pbuf: + # parent metni = çocuk metinleri; span_id'ler birleşik + merged_units_text = "\n".join(c.text for c in pbuf) + span_ids = [sid for c in pbuf for sid in c.span_ids] + pages = [p for c in pbuf for p in (c.page_start, c.page_end)] + vis = Counter(c.page_visual for c in pbuf).most_common(1)[0][0] + pid = f"{doc.doc_id}:p{pn}" + parents.append(Chunk( + chunk_id=pid, level="parent", text=merged_units_text, span_ids=span_ids, + doc_id=doc.doc_id, sinif=doc.sinif, ders=doc.ders, kaynak_turu=doc.kaynak_turu, + page_start=min(pages), page_end=max(pages), + kinds=sorted({k for c in pbuf for k in c.kinds}), page_visual=vis, + approx_tokens=approx_tokens(merged_units_text), + child_ids=[c.chunk_id for c in pbuf])) + for c in pbuf: + c.parent_id = pid + pbuf = []; ptok = 0; pn += 1 + + for c in children: + # başlıkla başlayan çocuk yeni bölümdür — ama yalnız üst zaten dolmuşsa böl + starts_section = HEADING in c.kinds + if starts_section and ptok >= PARENT_MIN: + flush_parent() + pbuf.append(c) + ptok += c.approx_tokens + if ptok >= PARENT_FLUSH: + flush_parent() + flush_parent() + + return children + parents + + +def to_dicts(chunks: list[Chunk]) -> list[dict]: + return [asdict(c) for c in chunks] diff --git a/tests/integration/test_chunk.py b/tests/integration/test_chunk.py new file mode 100644 index 0000000..200a7b5 --- /dev/null +++ b/tests/integration/test_chunk.py @@ -0,0 +1,52 @@ +"""Faz 1.1 integration testi — 12-bio kanonik doküman üzerinde chunking (gerçek veri).""" +import os +import unittest + +from src.ingest.canonical import build_canonical +from src.chunk import chunk_document + +BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") + + +@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK}") +class Chunk12BioTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.doc = build_canonical(BOOK, sinif="12", ders="biyoloji") + cls.chunks = chunk_document(cls.doc) + cls.children = [c for c in cls.chunks if c.level == "child"] + cls.parents = [c for c in cls.chunks if c.level == "parent"] + + def test_children_and_parents_produced(self): + self.assertGreater(len(self.children), 20) + self.assertGreater(len(self.parents), 5) + + def test_child_span_ids_exist_in_doc(self): + doc_spans = {u.span_id for u in self.doc.units} + child_spans = {sid for c in self.children for sid in c.span_ids} + self.assertTrue(child_spans.issubset(doc_spans)) + # tüm retrievable birimler bir çocukta yer almalı + self.assertEqual(child_spans, {u.span_id for u in self.doc.retrievable_units}) + + def test_children_linked_to_real_parents(self): + pids = {p.chunk_id for p in self.parents} + linked = [c for c in self.children if c.parent_id] + self.assertGreater(len(linked), 0) + for c in linked: + self.assertIn(c.parent_id, pids) + + def test_child_token_sizes_reasonable(self): + # çoğu çocuk üst sınırın çok üstünde olmamalı (tek dev birim istisnası olabilir) + big = [c for c in self.children if c.approx_tokens > 600] + self.assertLess(len(big), len(self.children) * 0.1) + + def test_chunks_have_provenance_and_meta(self): + for c in self.chunks[:100]: + self.assertTrue(c.span_ids) + self.assertTrue(c.text.strip()) + self.assertEqual((c.sinif, c.ders), ("12", "biyoloji")) + self.assertIn(c.page_visual, {"figure_heavy", "mixed", "low_visual"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/test_chunk.py b/tests/unit/test_chunk.py new file mode 100644 index 0000000..6bf58f7 --- /dev/null +++ b/tests/unit/test_chunk.py @@ -0,0 +1,91 @@ +"""Faz 1.1 birim testleri — chunking (sentetik CanonicalUnit'ler, deterministik).""" +import unittest + +from src.ingest.canonical import CanonicalUnit, CanonicalDoc +from src.ingest.pdf_parse import HEADING, PARAGRAPH +from src.chunk import chunk_document, approx_tokens + +WORDS40 = " ".join(f"kelime{i}" for i in range(40)) # ~56 approx token + + +def _u(n, text, kind=PARAGRAPH, page=1, vis="mixed", disi=False): + return CanonicalUnit(span_id=f"doc#{page}.{n}", doc_id="doc", sinif="12", + ders="biyoloji", kaynak_turu="ders_kitabi", page=page, + bbox=(0, 0, 100, 20), block_no=n, kind=kind, text=text, + page_visual=vis, retrieval_disi=disi) + + +def _doc(units): + return CanonicalDoc(source_path="x", doc_id="doc", source_version="v", sinif="12", + ders="biyoloji", kaynak_turu="ders_kitabi", page_count=1, units=units) + + +class TokenTests(unittest.TestCase): + def test_approx(self): + self.assertEqual(approx_tokens("a b c d"), round(4 * 1.4)) + self.assertEqual(approx_tokens(""), 0) + + +class ChunkTests(unittest.TestCase): + def setUp(self): + units = [_u(i, WORDS40) for i in range(8)] # 8 paragraf ~56 tok + self.doc = _doc(units) + self.chunks = chunk_document(self.doc) + self.children = [c for c in self.chunks if c.level == "child"] + self.parents = [c for c in self.chunks if c.level == "parent"] + + def test_children_created_and_sized(self): + self.assertGreaterEqual(len(self.children), 2) # 8×56≈450 tok → ≥2 çocuk + # her çocuk makul boyutta (tek dev birim yoksa CHILD_MAX civarını çok aşmaz) + for c in self.children: + self.assertGreater(c.approx_tokens, 0) + + def test_all_span_ids_preserved(self): + got = {sid for c in self.children for sid in c.span_ids} + want = {u.span_id for u in self.doc.units} + self.assertEqual(got, want) # hiçbir birim kaybolmadı + + def test_heading_starts_new_child_when_buffer_full(self): + # çocuk CHILD_MIN'i (150) geçtikten sonra başlık yeni çocuğu başlatır + units = [_u(0, WORDS40), _u(1, WORDS40), _u(2, WORDS40), # ~168 tok + _u(3, "1.2 Yeni Bölüm", HEADING), _u(4, WORDS40)] + chunks = [c for c in chunk_document(_doc(units)) if c.level == "child"] + heading_chunk = next(c for c in chunks if "doc#1.3" in c.span_ids) + self.assertNotIn("doc#1.0", heading_chunk.span_ids) # başlık öncesi ayrı çocukta + + def test_small_heading_does_not_split(self): + # küçük tampon + başlık → bölmez (minik chunk oluşmaz) + units = [_u(0, "kısa"), _u(1, "1.2 Yeni Bölüm", HEADING), _u(2, WORDS40)] + chunks = [c for c in chunk_document(_doc(units)) if c.level == "child"] + self.assertEqual(len(chunks), 1) # hepsi tek çocukta + + def test_parents_link_children(self): + self.assertGreaterEqual(len(self.parents), 1) + for p in self.parents: + self.assertTrue(p.child_ids) + for cid in p.child_ids: + child = next(c for c in self.children if c.chunk_id == cid) + self.assertEqual(child.parent_id, p.chunk_id) + + def test_parent_span_ids_union_of_children(self): + p = self.parents[0] + child_spans = {sid for cid in p.child_ids + for c in self.children if c.chunk_id == cid for sid in c.span_ids} + self.assertEqual(set(p.span_ids), child_spans) + + def test_excluded_units_not_chunked(self): + units = [_u(0, WORDS40), _u(1, "Değerlendirme Soruları " + WORDS40, disi=True)] + chunks = chunk_document(_doc(units)) + allspans = {sid for c in chunks for sid in c.span_ids} + self.assertIn("doc#1.0", allspans) + self.assertNotIn("doc#1.1", allspans) # sızıntı chunk'a girmez + + def test_metadata_propagated(self): + c = self.children[0] + self.assertEqual((c.doc_id, c.sinif, c.ders, c.kaynak_turu), + ("doc", "12", "biyoloji", "ders_kitabi")) + self.assertLessEqual(c.page_start, c.page_end) + + +if __name__ == "__main__": + unittest.main()