Spaces:
Sleeping
Sleeping
Add progress logging during index build for container visibility
Browse filesPDF/YouTube parsing and embedding/indexing steps now log
progress with counts and percentages via the arkanum logger.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (2)
- scripts/build_index.py+12-13
- src/rag/vectorstore.py+19-6
7 unmodified lines8910111213141516171819202113 unmodified lines35363738394041424344454647481 unmodified line50515253545556575859606162636465666768697071727 unmodified lines"""import argparseimport globimport osfrom tqdm import tqdmfrom src.ingestion.pdf import parse_pdffrom src.ingestion.youtube import parse_transcriptfrom src.rag.vectorstore import build_indexdef build_game_index(game: str, data_dir: str = "data/raw") -> None:"""13 unmodified linesif not pdf_files:raise FileNotFoundError(f"Keine PDFs in {game_dir}")print(f"Verarbeite {len(pdf_files)} PDFs für '{game}'...\n")all_chunks = []for pdf_path in pdf_files:rel_path = os.path.relpath(pdf_path, game_dir)print(f" 📄 {rel_path}")chunks = parse_pdf(pdf_path, game)print(f" → {len(chunks)} Chunks")all_chunks.extend(chunks)# YouTube-Transkripte verarbeiten1 unmodified lineif os.path.isdir(transcript_dir):vtt_files = sorted(glob.glob(os.path.join(transcript_dir, "*.vtt")))if vtt_files:print(f"\nVerarbeite {len(vtt_files)} YouTube-Transkripte...\n")for vtt_path in vtt_files:rel_path = os.path.relpath(vtt_path, game_dir)print(f" 🎬 {rel_path}")yt_chunks = parse_transcript(vtt_path, game)print(f" → {len(yt_chunks)} Chunks")all_chunks.extend(yt_chunks)print(f"\nGesamt: {len(all_chunks)} Chunks")print(f"\nBaue Vektorindex auf...")build_index(all_chunks, game)if __name__ == "__main__":parser = argparse.ArgumentParser(description="Vektordatenbank aufbauen")parser.add_argument("--game", required=True, help="Spielname (z.B. stalker)")args = parser.parse_args()build_game_index(args.game)print("\nFertig.")7 unmodified lines891011121314151617181920212213 unmodified lines363738394041424344454647481 unmodified line505152535455565758596061626364656667686970717 unmodified lines"""import argparseimport globimport loggingimport osfrom src.ingestion.pdf import parse_pdffrom src.ingestion.youtube import parse_transcriptfrom src.rag.vectorstore import build_indexlogger = logging.getLogger("arkanum")def build_game_index(game: str, data_dir: str = "data/raw") -> None:"""13 unmodified linesif 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 verarbeiten1 unmodified lineif 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...")build_index(all_chunks, game)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)")args = parser.parse_args()build_game_index(args.game)logger.info("Fertig.")
7 unmodified lines891011121314151617181947 unmodified lines67686970717273747576779 unmodified lines87888990919293949596973 unmodified lines1011021031041051061071087 unmodified linesbuild_index(chunks, game="stalker")results = retrieve("Wie viele Aktionen hat ein Spieler?", game="stalker")"""import osimport chromadbimport openaifrom dotenv import load_dotenvload_dotenv()CHROMA_BASE_DIR = "data/processed"47 unmodified linesgame: Spielname – bestimmt den Speicherort"""collection = _get_collection(game)# Bestehende Daten löschen für sauberen Rebuildexisting = collection.count()if existing > 0:print(f" Lösche {existing} bestehende Einträge...")all_ids = collection.get()["ids"]collection.delete(ids=all_ids)9 unmodified linesfor c in chunks]print(f" Erstelle Embeddings für {len(texts)} Chunks...")embeddings = _embed(texts)print(f" Indexiere in ChromaDB...")# ChromaDB erlaubt max ~41666 pro upsertbatch_size = 500for i in range(0, len(ids), batch_size):end = min(i + batch_size, len(ids))3 unmodified linesdocuments=texts[i:end],metadatas=metadatas[i:end],)print(f" ✓ {len(ids)} Chunks indexiert in '{collection.name}'")def retrieve(query: str, game: str, k: int = 5) -> list[dict]:7 unmodified lines891011121314151617181920212247 unmodified lines7071727374757677787980819 unmodified lines9192939495969798991001011021031041051061071081093 unmodified lines1131141151161171181191201217 unmodified linesbuild_index(chunks, game="stalker")results = retrieve("Wie viele Aktionen hat ein Spieler?", game="stalker")"""import loggingimport osimport chromadbimport openaifrom dotenv import load_dotenvlogger = logging.getLogger("arkanum")load_dotenv()CHROMA_BASE_DIR = "data/processed"47 unmodified linesgame: Spielname – bestimmt den Speicherort"""collection = _get_collection(game)client = _get_openai_client()# Bestehende Daten löschen für sauberen Rebuildexisting = collection.count()if existing > 0:logger.info(f"Lösche {existing} bestehende Einträge...")all_ids = collection.get()["ids"]collection.delete(ids=all_ids)9 unmodified linesfor c in chunks]# Embeddings in Batches erstellen mit Fortschrittlogger.info(f"Erstelle Embeddings für {len(texts)} Chunks...")embeddings = []embed_batch_size = 512for i in range(0, len(texts), embed_batch_size):batch = texts[i : i + embed_batch_size]end = min(i + embed_batch_size, len(texts))logger.info(f" Embeddings: {end}/{len(texts)} ({end * 100 // len(texts)}%)")resp = client.embeddings.create(model=EMBEDDING_MODEL, input=batch)embeddings.extend([d.embedding for d in resp.data])# ChromaDB-Indexierung mit Fortschrittlogger.info(f"Indexiere {len(ids)} Chunks in ChromaDB...")batch_size = 500for i in range(0, len(ids), batch_size):end = min(i + batch_size, len(ids))3 unmodified linesdocuments=texts[i:end],metadatas=metadatas[i:end],)logger.info(f" Indexiert: {end}/{len(ids)} ({end * 100 // len(ids)}%)")logger.info(f"✓ {len(ids)} Chunks indexiert in '{collection.name}'")def retrieve(query: str, game: str, k: int = 5) -> list[dict]:
scripts/build_index.py+12-13
src/rag/vectorstore.py+19-6