| """ |
| Chunking Modülü — Sabit Token Sayısı + Overlap |
| -------------------------------------------------- |
| Neden bu strateji? (Detaylı gerekçe README'de.) |
| - Embedding modelinin (magibu/embeddingmagibu-200m) kendi tokenizer'ını kullanarak |
| token bazlı bölme yapmak, "chunk boyutu" ile "modelin gerçekte işlediği birim" |
| arasında birebir eşleşme sağlar (paragraf bazlı bölmede paragraf uzunlukları |
| çok değişken olabilir, semantik bölme ise fazladan bir model/karmaşıklık |
| gerektirir). |
| - Overlap (örtüşme), bir cümlenin/bilginin tam chunk sınırında kesilip anlamının |
| bölünmesini önler; chunk sonundaki bağlamın bir kısmı bir sonraki chunk'ın |
| başında da tekrar eder. |
| |
| Gerçek kullanımda tokenizer, embedding modelinin kendi AutoTokenizer'ıdır |
| (get_tokenizer -> transformers.AutoTokenizer.from_pretrained(EMBEDDING_MODEL_ID)). |
| Offline/mock modda basit bir whitespace tokenizer'a düşülür (yaklaşık ama |
| pipeline'ı test etmek için yeterli). |
| """ |
| import sys |
| import os |
|
|
| sys.path.append(os.path.join(os.path.dirname(__file__), "..")) |
| from src import config |
|
|
|
|
| class _WhitespaceTokenizer: |
| """Mock/offline mod için basit tokenizer (gerçek tokenizer indirilemediğinde).""" |
|
|
| def encode(self, text, add_special_tokens=False): |
| return text.split() |
|
|
| def decode(self, tokens): |
| return " ".join(tokens) |
|
|
|
|
| _tokenizer_cache = {} |
|
|
|
|
| def get_tokenizer(): |
| """Embedding modelinin gerçek tokenizer'ını döner; indirilemezse whitespace fallback.""" |
| if "tokenizer" in _tokenizer_cache: |
| return _tokenizer_cache["tokenizer"] |
|
|
| if config.EMBEDDING_BACKEND == "real": |
| try: |
| from transformers import AutoTokenizer |
| tok = AutoTokenizer.from_pretrained(config.EMBEDDING_MODEL_ID) |
| _tokenizer_cache["tokenizer"] = tok |
| return tok |
| except Exception as e: |
| print(f"[UYARI] Gerçek tokenizer indirilemedi ({e}), whitespace tokenizer kullanılıyor.") |
|
|
| tok = _WhitespaceTokenizer() |
| _tokenizer_cache["tokenizer"] = tok |
| return tok |
|
|
|
|
| def chunk_text(text: str, chunk_size: int = None, overlap: int = None, tokenizer=None): |
| """ |
| Metni sabit token sayısı + overlap ile parçalara böler. |
| Dönüş: list[str] (her biri bir chunk metni) |
| """ |
| chunk_size = chunk_size or config.CHUNK_SIZE_TOKENS |
| overlap = overlap or config.CHUNK_OVERLAP_TOKENS |
| tokenizer = tokenizer or get_tokenizer() |
|
|
| if overlap >= chunk_size: |
| raise ValueError("overlap, chunk_size'dan küçük olmalıdır.") |
|
|
| token_ids = tokenizer.encode(text, add_special_tokens=False) |
| if len(token_ids) == 0: |
| return [] |
|
|
| chunks = [] |
| step = chunk_size - overlap |
| start = 0 |
| while start < len(token_ids): |
| end = min(start + chunk_size, len(token_ids)) |
| chunk_tokens = token_ids[start:end] |
| chunk_str = tokenizer.decode(chunk_tokens).strip() |
| if chunk_str: |
| chunks.append(chunk_str) |
| if end == len(token_ids): |
| break |
| start += step |
|
|
| return chunks |
|
|
|
|
| def chunk_articles(articles: list, chunk_size: int = None, overlap: int = None): |
| """ |
| Bir makale listesini ([{url, title, text, __source}, ...]) chunk'lara böler. |
| Dönüş: list[dict] — her biri {url, title, __source, parent_id, chunk_id, chunk_text} |
| """ |
| tokenizer = get_tokenizer() |
| all_chunks = [] |
| for parent_id, article in enumerate(articles): |
| text = article.get("text", "") or "" |
| pieces = chunk_text(text, chunk_size=chunk_size, overlap=overlap, tokenizer=tokenizer) |
| for i, piece in enumerate(pieces): |
| all_chunks.append({ |
| "url": article.get("url", ""), |
| "title": article.get("title", ""), |
| "__source": article.get("__source", ""), |
| "parent_id": parent_id, |
| "chunk_id": f"{parent_id}_{i}", |
| "chunk_text": piece, |
| }) |
| return all_chunks |
|
|
|
|
| if __name__ == "__main__": |
| from data.synthetic_corpus import SYNTHETIC_ARTICLES |
| chunks = chunk_articles(SYNTHETIC_ARTICLES, chunk_size=60, overlap=15) |
| print(f"{len(SYNTHETIC_ARTICLES)} makaleden {len(chunks)} chunk üretildi.") |
| for c in chunks[:3]: |
| print(f"\n[{c['chunk_id']}] {c['title']}") |
| print(c["chunk_text"][:150], "...") |
|
|