File size: 4,351 Bytes
ab773bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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], "...")