Download src/build_index.py from Talayhan/task4.2: direct link, hf CLI and curl.
- Browser
- Download file 3.49 kB
-
https://huggingface.co/datasets/Talayhan/task4.2/resolve/main/src/build_index.py
- Command line
-
hf download hf://datasets/Talayhan/task4.2/src/build_index.py
-
curl -L -o build_index.py https://huggingface.co/datasets/Talayhan/task4.2/resolve/main/src/build_index.py
3.49 kB
| """ | |
| 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() | |