File size: 3,491 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
"""
Ana Pipeline: Veri Yükleme -> Chunking -> Embedding -> ChromaDB -> Parquet Export
------------------------------------------------------------------------------------
Çalıştırma:
    EMBEDDING_BACKEND=mock python src/build_index.py          # offline test
    EMBEDDING_BACKEND=real python src/build_index.py          # gerçek model (internet+GPU önerilir)

Çıktılar:
    - chroma_db/  (persist edilmiş vektör veritabanı)
    - output/turkish_medical_chunks.parquet  (url, chunk_text, chunk_vector, title,
      __source, parent_id, chunk_id sütunlarını içeren, HF Hub'a yüklenebilir dataset)
"""
import sys
import os
import time

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from src import config
from src.data_loader import load_articles
from src.chunking import chunk_articles
from src.embedder import get_embedder
from src.vector_store import VectorStore


def build_index(sample_size: int = None, force_synthetic: bool = False, reset: bool = True):
    t0 = time.time()

    print(f"[1/4] Veri seti yükleniyor (hedef: {sample_size or config.SAMPLE_SIZE} makale)...")
    articles, used_synthetic = load_articles(sample_size=sample_size, force_synthetic=force_synthetic)
    print(f"      -> {len(articles)} makale yüklendi. (sentetik veri kullanıldı mı: {used_synthetic})")

    print(f"[2/4] Chunking (chunk_size={config.CHUNK_SIZE_TOKENS} token, "
          f"overlap={config.CHUNK_OVERLAP_TOKENS} token)...")
    chunks = chunk_articles(articles)
    print(f"      -> {len(chunks)} chunk üretildi.")

    print(f"[3/4] Embedding üretiliyor (backend={config.EMBEDDING_BACKEND})...")
    chunk_texts = [c["chunk_text"] for c in chunks]
    embedder = get_embedder(fit_corpus=chunk_texts)
    vectors = embedder.embed(chunk_texts)
    print(f"      -> {vectors.shape[0]} vektör üretildi, boyut={vectors.shape[1]}")

    from src.embedder import MockEmbedder
    if isinstance(embedder, MockEmbedder):
        embedder.save()
        print(f"      -> Mock embedder durumu kaydedildi: {config.MOCK_EMBEDDER_STATE_PATH}")

    print(f"[4/4] ChromaDB'ye yazılıyor ve parquet dışa aktarılıyor...")
    store = VectorStore(reset=reset)
    store.upsert_chunks(chunks, vectors)
    print(f"      -> ChromaDB koleksiyonunda toplam {store.count()} chunk.")

    export_parquet(chunks, vectors)

    print(f"\nTamamlandı ({time.time() - t0:.1f}s). "
          f"{len(articles)} makale -> {len(chunks)} chunk -> {vectors.shape[1]} boyutlu vektörler.")
    return chunks, vectors, used_synthetic


def export_parquet(chunks: list, vectors):
    """Ödevin istediği 3 zorunlu sütun (url, chunk_text, chunk_vector) + opsiyonel
    metadata (title, __source, parent_id, chunk_id) ile parquet dosyası üretir.
    Bu dosya doğrudan bir Hugging Face Dataset reposuna yüklenebilir."""
    import pandas as pd

    os.makedirs(config.OUTPUT_DIR, exist_ok=True)
    df = pd.DataFrame({
        "url": [c["url"] for c in chunks],
        "chunk_text": [c["chunk_text"] for c in chunks],
        "chunk_vector": [v.tolist() for v in vectors],
        "title": [c["title"] for c in chunks],
        "__source": [c["__source"] for c in chunks],
        "parent_id": [c["parent_id"] for c in chunks],
        "chunk_id": [c["chunk_id"] for c in chunks],
    })
    df.to_parquet(config.CHUNKS_PARQUET_PATH, index=False)
    print(f"      -> Parquet: {config.CHUNKS_PARQUET_PATH} ({len(df)} satır)")


if __name__ == "__main__":
    build_index()