Upload embed_chunks.py with huggingface_hub
Browse files- embed_chunks.py +92 -0
embed_chunks.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Medical Park Makaleleri — Embedding Script
|
| 3 |
+
chunks.json icindeki her chunk_text icin embeddingmagibu-200m ile
|
| 4 |
+
768 boyutlu, L2-normalize chunk_vector uretir.
|
| 5 |
+
|
| 6 |
+
ONEMLI: Bu script CORPUS (dokuman) tarafi icindir -> encode_document() kullanilir.
|
| 7 |
+
Benchmarking asamasinda 30 test sorusunu embed ederken encode_query() kullanilmalidir.
|
| 8 |
+
Ikisini karistirmak benzerlik skorlarini bozar.
|
| 9 |
+
|
| 10 |
+
Kurulum:
|
| 11 |
+
pip install -U sentence-transformers transformers
|
| 12 |
+
|
| 13 |
+
Calistirma:
|
| 14 |
+
python embed_chunks.py
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import time
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from sentence_transformers import SentenceTransformer
|
| 23 |
+
|
| 24 |
+
INPUT_PATH = "data/chunks.json"
|
| 25 |
+
OUTPUT_PATH = "data/chunks_with_vectors.json"
|
| 26 |
+
MODEL_NAME = "magibu/embeddingmagibu-200m"
|
| 27 |
+
BATCH_SIZE = 32 # GPU yoksa 8-16'ya dusurebilirsin
|
| 28 |
+
TEST_FIRST_N = 5 # once kucuk bir denemeyle dogrula, sonra tumunu calistir
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def load_chunks(path: str) -> list[dict]:
|
| 32 |
+
with open(path, encoding="utf-8") as f:
|
| 33 |
+
return json.load(f)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def save_chunks(chunks: list[dict], path: str) -> None:
|
| 37 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 38 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 39 |
+
json.dump(chunks, f, ensure_ascii=False)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main():
|
| 43 |
+
# GPU gorunuyor mu kontrol et
|
| 44 |
+
cuda_ok = torch.cuda.is_available()
|
| 45 |
+
print(f"CUDA kullanilabilir mi: {cuda_ok}")
|
| 46 |
+
if cuda_ok:
|
| 47 |
+
print(f" GPU: {torch.cuda.get_device_name(0)}")
|
| 48 |
+
else:
|
| 49 |
+
print(" UYARI: GPU gorunmuyor, CPU'da calisacak (daha yavas olur).")
|
| 50 |
+
print(" torch'u CUDA destekli kurduğundan emin ol: https://pytorch.org/get-started/locally/")
|
| 51 |
+
|
| 52 |
+
chunks = load_chunks(INPUT_PATH)
|
| 53 |
+
print(f"\nYuklenen chunk sayisi: {len(chunks)}")
|
| 54 |
+
|
| 55 |
+
print(f"Model yukleniyor: {MODEL_NAME} (ilk calistirmada indirme suresi alabilir, ~yuzlerce MB)")
|
| 56 |
+
model = SentenceTransformer(MODEL_NAME, trust_remote_code=True)
|
| 57 |
+
print(f"Model cihazi: {model.device}")
|
| 58 |
+
|
| 59 |
+
texts = [c["chunk_text"] for c in chunks]
|
| 60 |
+
|
| 61 |
+
# --- Kucuk bir on-test: ilk birkac chunk uzerinde dogrula ---
|
| 62 |
+
print(f"\nOn test: ilk {TEST_FIRST_N} chunk encode ediliyor...")
|
| 63 |
+
sample_vecs = model.encode_document(texts[:TEST_FIRST_N])
|
| 64 |
+
print(f"Ornek vektor boyutu: {sample_vecs.shape}") # (TEST_FIRST_N, 768) olmali
|
| 65 |
+
assert sample_vecs.shape[1] == 768, "Beklenmeyen embedding boyutu!"
|
| 66 |
+
|
| 67 |
+
# --- Tum corpus'u encode et ---
|
| 68 |
+
print(f"\nTum chunk'lar encode ediliyor (batch_size={BATCH_SIZE})...")
|
| 69 |
+
t0 = time.time()
|
| 70 |
+
embeddings = model.encode_document(
|
| 71 |
+
texts,
|
| 72 |
+
batch_size=BATCH_SIZE,
|
| 73 |
+
show_progress_bar=True,
|
| 74 |
+
)
|
| 75 |
+
print(f"Bitti: {time.time() - t0:.1f} sn")
|
| 76 |
+
|
| 77 |
+
# --- Vektorleri chunk'lara ekle ---
|
| 78 |
+
for chunk, vec in zip(chunks, embeddings):
|
| 79 |
+
chunk["chunk_vector"] = vec.tolist()
|
| 80 |
+
|
| 81 |
+
save_chunks(chunks, OUTPUT_PATH)
|
| 82 |
+
print(f"\n[OK] Kaydedildi: {OUTPUT_PATH}")
|
| 83 |
+
print(f" Sutunlar: url, title, chunk_text, chunk_index, __source, chunk_vector")
|
| 84 |
+
print(f" Vektor boyutu: {len(chunks[0]['chunk_vector'])}")
|
| 85 |
+
|
| 86 |
+
# Dosya boyutu uyarisi
|
| 87 |
+
size_mb = os.path.getsize(OUTPUT_PATH) / (1024 * 1024)
|
| 88 |
+
print(f" Dosya boyutu: {size_mb:.1f} MB")
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
main()
|