""" Index-Aufbau Script ==================== Verarbeitet heruntergeladene PDFs und baut die Vektordatenbank auf. Verwendung: python scripts/build_index.py --game stalker # baut Index + Cache python scripts/build_index.py --game stalker --no-cache # ohne Cache-Export """ import argparse import glob import json import logging import os from src.ingestion.pdf import parse_pdf from src.ingestion.youtube import parse_transcript from src.rag.vectorstore import CHROMA_BASE_DIR, build_index logger = logging.getLogger("arkanum") def build_game_index(game: str, data_dir: str = "data/raw", export: bool = False) -> None: """ Vollständige Pipeline: PDF-Dateien → Chunks → Vektordatenbank. Args: game: Spielname (z.B. "stalker") data_dir: Basisverzeichnis für Rohdaten export: Wenn True, speichert Chunks+Embeddings als index_cache.json """ game_dir = os.path.join(data_dir, game) if not os.path.isdir(game_dir): raise FileNotFoundError(f"Kein Datenverzeichnis: {game_dir}") # PDFs rekursiv finden (inkl. Unterordner wie de_files/) pdf_files = [] for root, _dirs, files in os.walk(game_dir): for f in sorted(files): if f.endswith(".pdf"): pdf_files.append(os.path.join(root, f)) if not pdf_files: raise FileNotFoundError(f"Keine PDFs in {game_dir}") logger.info(f"Verarbeite {len(pdf_files)} PDFs für '{game}'...") all_chunks = [] for i, pdf_path in enumerate(pdf_files, 1): rel_path = os.path.relpath(pdf_path, game_dir) chunks = parse_pdf(pdf_path, game) logger.info(f" PDF {i}/{len(pdf_files)}: {rel_path} → {len(chunks)} Chunks") all_chunks.extend(chunks) # YouTube-Transkripte verarbeiten transcript_dir = os.path.join(game_dir, "youtube_transcripts") if os.path.isdir(transcript_dir): vtt_files = sorted(glob.glob(os.path.join(transcript_dir, "*.vtt"))) if vtt_files: logger.info(f"Verarbeite {len(vtt_files)} YouTube-Transkripte...") for i, vtt_path in enumerate(vtt_files, 1): rel_path = os.path.relpath(vtt_path, game_dir) yt_chunks = parse_transcript(vtt_path, game) logger.info(f" YouTube {i}/{len(vtt_files)}: {rel_path} → {len(yt_chunks)} Chunks") all_chunks.extend(yt_chunks) logger.info(f"Gesamt: {len(all_chunks)} Chunks – starte Vektorindex-Aufbau...") embeddings = build_index(all_chunks, game) if export: _export_cache(all_chunks, embeddings, game) def _export_cache(chunks: list[dict], embeddings: list[list[float]], game: str) -> None: """Speichert Chunks + Embeddings als JSON-Cache für schnellen Startup.""" cache_dir = os.path.join(CHROMA_BASE_DIR, game) os.makedirs(cache_dir, exist_ok=True) cache_path = os.path.join(cache_dir, "index_cache.json") cache_data = { "version": 1, "game": game, "chunk_count": len(chunks), "chunks": [ {**chunk, "embedding": emb} for chunk, emb in zip(chunks, embeddings) ], } with open(cache_path, "w", encoding="utf-8") as f: json.dump(cache_data, f, ensure_ascii=False) size_mb = os.path.getsize(cache_path) / (1024 * 1024) logger.info(f"✓ Cache exportiert: {cache_path} ({size_mb:.1f} MB, {len(chunks)} Chunks)") if __name__ == "__main__": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description="Vektordatenbank aufbauen") parser.add_argument("--game", required=True, help="Spielname (z.B. stalker)") parser.add_argument("--no-cache", action="store_true", help="Cache-Export (index_cache.json) überspringen") args = parser.parse_args() build_game_index(args.game, export=not args.no_cache) logger.info("Fertig.")