Files
mdscrap/rag_local/ingest.py
Beyhan Oğur 9630a33ec1 first commit
2026-04-26 22:00:50 +03:00

89 lines
3.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
import glob
import logging
from langchain_text_splitters import MarkdownTextSplitter
import chromadb
from chromadb.utils import embedding_functions
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
def ingest_docs(docs_dir="data/md_docs", chroma_path="chroma_db", collection_name="docs"):
logging.info(f"ChromaDB başlatılıyor... ({chroma_path})")
# ChromaDB client oluştur (klasöre kaydeder)
client = chromadb.PersistentClient(path=chroma_path)
# Default embedding function (sentence-transformers: all-MiniLM-L6-v2)
# Bu model boyut olarak küçük (yaklaşık 80MB) ve lokalde çok hızlı çalışır.
sentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")
# Collection oluştur veya var olanı al
collection = client.get_or_create_collection(name=collection_name, embedding_function=sentence_transformer_ef)
# Markdown dosyalarını bul
md_files = glob.glob(os.path.join(docs_dir, "**", "*.md"), recursive=True)
logging.info(f"Toplam {len(md_files)} markdown dosyası bulundu.")
# Metinleri anlamlı parçalara bölecek (chunk) nesne
# Her parça yaklaşık 1000 karakter olacak, aralarında 200 karakter örtüşme (overlap) olacak.
splitter = MarkdownTextSplitter(chunk_size=1000, chunk_overlap=200)
batch_documents = []
batch_metadatas = []
batch_ids = []
count = 0
for file_path in md_files:
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Metni parçalara böl
chunks = splitter.split_text(content)
for i, chunk in enumerate(chunks):
# ID örneği: data/md_docs/nextjs.org/docs.md_chunk_0
chunk_id = f"{file_path}_chunk_{i}"
batch_documents.append(chunk)
batch_metadatas.append({"source": file_path, "chunk_index": i})
batch_ids.append(chunk_id)
# Belleği doldurmamak için her 100 parçada bir veritabanına yaz
if len(batch_documents) >= 100:
collection.add(
documents=batch_documents,
metadatas=batch_metadatas,
ids=batch_ids
)
count += len(batch_documents)
logging.info(f"{count} parça vektörleştirildi ve veritabanına eklendi...")
batch_documents = []
batch_metadatas = []
batch_ids = []
except Exception as e:
logging.error(f"Dosya okunamadı ({file_path}): {e}")
# Kalan son parçaları yaz
if batch_documents:
collection.add(
documents=batch_documents,
metadatas=batch_metadatas,
ids=batch_ids
)
count += len(batch_documents)
logging.info(f"İşlem tamam! Toplam {count} metin parçası (chunk) vektörleştirilerek ChromaDB'ye işlendi.")
if __name__ == "__main__":
# Bu dosya rag_local dizininde olsa bile, çalışma dizini olarak mdscrap/ ana dizinini kullanalım
# böylece 'data/md_docs' ve 'chroma_db' ana dizinde oluşur.
# Çalışma dizinini ana dizine ayarla
script_dir = os.path.dirname(os.path.abspath(__file__))
main_dir = os.path.dirname(script_dir)
os.chdir(main_dir)
ingest_docs()