forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiB184b84dAhmet Kaan Gümüş2 months ago189 commits

chunker.py160 lines, 6.5 KiBHistoryRawDownload
1"""Faz 1.1 — Çok-temsilli chunking (çocuk + üst), başlık-sınırı farkında.
2
3Kaynak: `CanonicalDoc` (retrievable birimler). Çıktı: child + parent chunk'lar;
4her chunk kaynak birim **span_id**'lerini taşır → atıf korunur. Tokenizer henüz
5yok; `approx_tokens` yaklaşık ölçüdür (embedding modeli gelince gerçek sayım, 1.2).
6"""
7from __future__ import annotations
8import os
9from collections import Counter
10from dataclasses import dataclass, field, asdict
11
12from ..ingest.canonical import CanonicalDoc, CanonicalUnit
13from ..ingest.pdf_parse import HEADING
14
15# Yaklaşık token: Türkçe eklemeli → kelime başına ~1.4 subword.
16_TOK_PER_WORD = 1.4
17CHILD_MIN = 150 # bir çocuk en az bu kadar (küçük bloklar birleşir)
18CHILD_FLUSH = 250 # bu değere ulaşınca çocuğu kapat (150-300 bandının ortası)
19PARENT_MIN = 700 # bir üst en az bu kadar
20PARENT_FLUSH = 1000 # üst chunk flush eşiği (700-1500 bandı)
21
22# M2-1 (#53, EXP-010/ACC-02 + EVAL-07) -- SAYFA HIZALI CHILD CHUNK.
23#
24# Atif chunk duzeyinde uretiliyor (`generator.py`: citations[i].pages =
25# _pages_for_span_ids(ctx.span_ids)), yani atif chunk'in TUM span'larinin
26# sayfalarini tasiyor. Child chunk'lar sayfa sinirini serbestce astigi icin
27# her asan chunk atifa FAZLADAN sayfa ekliyor.
28#
29# GERCEK KITAPLA OLCULDU (10-biyoloji, 194 sayfa): child chunk'larin %63,4'u
30# (147/232) sayfa sinirini asiyordu. 136 item'da dogru sayfa %100 bulunmus ama
31# ortalama 0,94 FAZLA sayfa atiflanmisti (gold 1,24 <-> model 2,01 sayfa).
32# `precision_page`'in teorik tavani min(1, gold/cited) ~= 0,712; olculen 0,645
33# bu tavanin %91'i. Yani 0,99 kapisi eski chunk'lamayla MATEMATIKSEL OLARAK
34# ulasilamazdi -- daha buyuk embedding modeli bunu duzeltmez.
35#
36# DURUST SINIR: bu degisiklik chunk SAYISINI artirir ve sayfa sonunda kalan
37# kucuk parcalar CHILD_MIN'in altina duser; bu retrieval recall'unu bozabilir.
38# Bu yuzden varsayilan env ile secilir ve karar ABLATION'a baglidir (#53 kabul
39# kriteri: precision_page yukselmeli VE recall@5/@20 dusmemeli).
40PAGE_ALIGNED_DEFAULT = os.environ.get("RAG_CHUNK_PAGE_ALIGNED", "1") not in (
41 "0", "", "false", "False")
42
43
44def approx_tokens(text: str) -> int:
45 return round(len(text.split()) * _TOK_PER_WORD)
46
47
48@dataclass
49class Chunk:
50 chunk_id: str
51 level: str # "child" | "parent"
52 text: str
53 span_ids: list[str] # kaynak birimlerin span-id'leri (atıf)
54 doc_id: str
55 sinif: str
56 ders: str
57 kaynak_turu: str
58 page_start: int
59 page_end: int
60 kinds: list[str]
61 page_visual: str # baskın görsel sınıfı
62 approx_tokens: int
63 parent_id: str | None = None # child için
64 child_ids: list[str] = field(default_factory=list) # parent için
65
66
67def _mk(units: list[CanonicalUnit], doc: CanonicalDoc, level: str, n: int) -> Chunk:
68 text = "\n".join(u.text for u in units)
69 pages = [u.page for u in units]
70 vis = Counter(u.page_visual for u in units).most_common(1)[0][0]
71 return Chunk(
72 chunk_id=f"{doc.doc_id}:{'c' if level=='child' else 'p'}{n}",
73 level=level, text=text, span_ids=[u.span_id for u in units],
74 doc_id=doc.doc_id, sinif=doc.sinif, ders=doc.ders, kaynak_turu=doc.kaynak_turu,
75 page_start=min(pages), page_end=max(pages),
76 kinds=sorted({u.kind for u in units}), page_visual=vis,
77 approx_tokens=approx_tokens(text))
78
79
80def chunk_document(doc: CanonicalDoc, *, page_aligned: bool | None = None) -> list[Chunk]:
81 """CanonicalDoc → child + parent chunk'lar (başlık sınırlarına saygılı).
82
83 `page_aligned=True` iken her **child** chunk tek bir sayfaya bağlanır
84 (sayfa değişiminde zorunlu flush) → `page_start == page_end`. Parent'lar
85 bilerek sayfa aşar: onlar bağlam genişletme içindir, atıf kaynağı değil
86 (parent'ın atıfı ayrı bir hata, bkz. #54).
87 """
88 if page_aligned is None:
89 page_aligned = PAGE_ALIGNED_DEFAULT
90 units = doc.retrievable_units
91
92 # --- çocuk chunk'lar ---
93 children: list[Chunk] = []
94 buf: list[CanonicalUnit] = []
95 tok = 0
96 cn = 0
97
98 def flush_child():
99 nonlocal buf, tok, cn
100 if buf:
101 children.append(_mk(buf, doc, "child", cn)); cn += 1
102 buf = []; tok = 0
103
104 for u in units:
105 # #53: sayfa degisimi ZORUNLU sinir -- baslik kuralindan farkli olarak
106 # doluluk sartina baglanmaz, yoksa asma yine olur.
107 if page_aligned and buf and u.page != buf[-1].page:
108 flush_child()
109 # başlık yeni bölüm başlatır — ama yalnız çocuk zaten yeterince doluysa
110 # (aksi halde küçük bloklu + çok-başlıklı kitapta chunk'lar minik kalır).
111 if u.kind == HEADING and tok >= CHILD_MIN:
112 flush_child()
113 buf.append(u)
114 tok += approx_tokens(u.text)
115 if tok >= CHILD_FLUSH:
116 flush_child()
117 flush_child()
118
119 # --- üst chunk'lar (çocukları grupla; başlıkla başlayan çocuk yeni bölüm) ---
120 parents: list[Chunk] = []
121 pbuf: list[Chunk] = []
122 ptok = 0
123 pn = 0
124
125 def flush_parent():
126 nonlocal pbuf, ptok, pn
127 if pbuf:
128 # parent metni = çocuk metinleri; span_id'ler birleşik
129 merged_units_text = "\n".join(c.text for c in pbuf)
130 span_ids = [sid for c in pbuf for sid in c.span_ids]
131 pages = [p for c in pbuf for p in (c.page_start, c.page_end)]
132 vis = Counter(c.page_visual for c in pbuf).most_common(1)[0][0]
133 pid = f"{doc.doc_id}:p{pn}"
134 parents.append(Chunk(
135 chunk_id=pid, level="parent", text=merged_units_text, span_ids=span_ids,
136 doc_id=doc.doc_id, sinif=doc.sinif, ders=doc.ders, kaynak_turu=doc.kaynak_turu,
137 page_start=min(pages), page_end=max(pages),
138 kinds=sorted({k for c in pbuf for k in c.kinds}), page_visual=vis,
139 approx_tokens=approx_tokens(merged_units_text),
140 child_ids=[c.chunk_id for c in pbuf]))
141 for c in pbuf:
142 c.parent_id = pid
143 pbuf = []; ptok = 0; pn += 1
144
145 for c in children:
146 # başlıkla başlayan çocuk yeni bölümdür — ama yalnız üst zaten dolmuşsa böl
147 starts_section = HEADING in c.kinds
148 if starts_section and ptok >= PARENT_MIN:
149 flush_parent()
150 pbuf.append(c)
151 ptok += c.approx_tokens
152 if ptok >= PARENT_FLUSH:
153 flush_parent()
154 flush_parent()
155
156 return children + parents
157
158
159def to_dicts(chunks: list[Chunk]) -> list[dict]:
160 return [asdict(c) for c in chunks]