File size: 3,130 Bytes
cb26a54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5515280
 
cb26a54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Medical Park Makaleleri — Embedding Script
chunks.json icindeki her chunk_text icin embeddingmagibu-200m ile
768 boyutlu, L2-normalize chunk_vector uretir.

ONEMLI: Bu script CORPUS (dokuman) tarafi icindir -> encode_document() kullanilir.
Benchmarking asamasinda 30 test sorusunu embed ederken encode_query() kullanilmalidir.
Ikisini karistirmak benzerlik skorlarini bozar.

Kurulum:
    pip install -U sentence-transformers transformers

Calistirma:
    python embed_chunks.py
"""

import json
import os
import time

import torch
from sentence_transformers import SentenceTransformer

INPUT_PATH = "chunks.json"
OUTPUT_PATH = "chunks_with_vectors.json"
MODEL_NAME = "magibu/embeddingmagibu-200m"
BATCH_SIZE = 32          # GPU yoksa 8-16'ya dusurebilirsin
TEST_FIRST_N = 5         # once kucuk bir denemeyle dogrula, sonra tumunu calistir


def load_chunks(path: str) -> list[dict]:
    with open(path, encoding="utf-8") as f:
        return json.load(f)


def save_chunks(chunks: list[dict], path: str) -> None:
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        json.dump(chunks, f, ensure_ascii=False)


def main():
    # GPU gorunuyor mu kontrol et
    cuda_ok = torch.cuda.is_available()
    print(f"CUDA kullanilabilir mi: {cuda_ok}")
    if cuda_ok:
        print(f"  GPU: {torch.cuda.get_device_name(0)}")
    else:
        print("  UYARI: GPU gorunmuyor, CPU'da calisacak (daha yavas olur).")
        print("  torch'u CUDA destekli kurduğundan emin ol: https://pytorch.org/get-started/locally/")

    chunks = load_chunks(INPUT_PATH)
    print(f"\nYuklenen chunk sayisi: {len(chunks)}")

    print(f"Model yukleniyor: {MODEL_NAME} (ilk calistirmada indirme suresi alabilir, ~yuzlerce MB)")
    model = SentenceTransformer(MODEL_NAME, trust_remote_code=True)
    print(f"Model cihazi: {model.device}")

    texts = [c["chunk_text"] for c in chunks]

    # --- Kucuk bir on-test: ilk birkac chunk uzerinde dogrula ---
    print(f"\nOn test: ilk {TEST_FIRST_N} chunk encode ediliyor...")
    sample_vecs = model.encode_document(texts[:TEST_FIRST_N])
    print(f"Ornek vektor boyutu: {sample_vecs.shape}")  # (TEST_FIRST_N, 768) olmali
    assert sample_vecs.shape[1] == 768, "Beklenmeyen embedding boyutu!"

    # --- Tum corpus'u encode et ---
    print(f"\nTum chunk'lar encode ediliyor (batch_size={BATCH_SIZE})...")
    t0 = time.time()
    embeddings = model.encode_document(
        texts,
        batch_size=BATCH_SIZE,
        show_progress_bar=True,
    )
    print(f"Bitti: {time.time() - t0:.1f} sn")

    # --- Vektorleri chunk'lara ekle ---
    for chunk, vec in zip(chunks, embeddings):
        chunk["chunk_vector"] = vec.tolist()

    save_chunks(chunks, OUTPUT_PATH)
    print(f"\n[OK] Kaydedildi: {OUTPUT_PATH}")
    print(f"  Sutunlar: url, title, chunk_text, chunk_index, __source, chunk_vector")
    print(f"  Vektor boyutu: {len(chunks[0]['chunk_vector'])}")

    # Dosya boyutu uyarisi
    size_mb = os.path.getsize(OUTPUT_PATH) / (1024 * 1024)
    print(f"  Dosya boyutu: {size_mb:.1f} MB")


if __name__ == "__main__":
    main()