Spaces:
Sleeping
Sleeping
Pre-build embedding cache for fast startup, fix voice recording stop bug
Browse filesCache chunks+embeddings as index_cache.json (~38 MB, Git LFS) so container
startup loads ChromaDB in ~3s instead of calling OpenAI embeddings API (~30-60s).
Cache is generated by default on every index build.
Fix walkthrough voice input not stopping: add 15s auto-timeout, show stop
icon on mic button while listening, and centralize cleanup in vgStopListening().
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (7)
33 unmodified lines34353633 unmodified lines*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.pdf filter=lfs diff=lfs merge=lfs -text33 unmodified lines3435363733 unmodified lines*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.pdf filter=lfs diff=lfs merge=lfs -textdata/processed/stalker/index_cache.json filter=lfs diff=lfs merge=lfs -text
12 unmodified lines1314151617181912 unmodified linesbuild/# Verarbeitete Daten (werden generiert)data/processed/# Vektordatenbank*.chroma/12 unmodified lines1314151617181920212212 unmodified linesbuild/# Verarbeitete Daten (werden generiert)data/processed/*!data/processed/stalker/data/processed/stalker/*!data/processed/stalker/index_cache.json# Vektordatenbank*.chroma/
123version https://git-lfs.github.com/spec/v1oid sha256:0c4cf93e2deb48d17e3920e3739685f8ab28008877b22e27d4c988ec98a0f96fsize 396231821139 unmodified lines1140114111421143114411451146114711481149115011511152115311541 unmodified line1156115711581159116011614 unmodified lines1166116711681169117011711172117311742 unmodified lines11771178117911801181118211831139 unmodified lines};recog.onend = () => {vg.isListening = false;document.getElementById('vgBtnMic').classList.remove('listening');document.getElementById('vgStatus').textContent = '';};recog.onerror = (event) => {vg.isListening = false;document.getElementById('vgBtnMic').classList.remove('listening');if (event.error !== 'no-speech') {document.getElementById('vgStatus').textContent = `Mikrofon-Fehler: ${event.error}`;}};1 unmodified linereturn recog;}function vgToggleMic() {if (!vg.recognition) {vg.recognition = vgInitSpeechRecognition();4 unmodified lines}if (vg.isListening) {vg.recognition.stop();vg.isListening = false;document.getElementById('vgBtnMic').classList.remove('listening');} else {// Pause audio while listeningif (vg.audio && vg.isPlaying) {2 unmodified linesvg.recognition.start();vg.isListening = true;document.getElementById('vgBtnMic').classList.add('listening');document.getElementById('vgStatus').textContent = 'Höre zu...';}}1139 unmodified lines1140114111421143114411451146114711481149115011511 unmodified line115311541155115611571158115911601161116211631164116511661167116811691170117111724 unmodified lines11771178117911801181118211832 unmodified lines1186118711881189119011911192119311941195119611971198119912001139 unmodified lines};recog.onend = () => {vgStopListening();};recog.onerror = (event) => {vgStopListening();if (event.error !== 'no-speech' && event.error !== 'aborted') {document.getElementById('vgStatus').textContent = `Mikrofon-Fehler: ${event.error}`;}};1 unmodified linereturn recog;}function vgStopListening() {if (vg.isListening && vg.recognition) {vg.recognition.stop();}if (vg._listenTimeout) {clearTimeout(vg._listenTimeout);vg._listenTimeout = null;}vg.isListening = false;document.getElementById('vgBtnMic').classList.remove('listening');document.getElementById('vgBtnMic').innerHTML = '🎤';document.getElementById('vgStatus').textContent = '';}function vgToggleMic() {if (!vg.recognition) {vg.recognition = vgInitSpeechRecognition();4 unmodified lines}if (vg.isListening) {vgStopListening();} else {// Pause audio while listeningif (vg.audio && vg.isPlaying) {2 unmodified linesvg.recognition.start();vg.isListening = true;document.getElementById('vgBtnMic').classList.add('listening');document.getElementById('vgBtnMic').innerHTML = '■';document.getElementById('vgStatus').textContent = 'Höre zu... (Tap zum Stoppen)';// Auto-stop nach 15 Sekundenvg._listenTimeout = setTimeout(() => {if (vg.isListening) {vgStopListening();}}, 15000);}}
3 unmodified lines456789101112131415161718192021222324252631 unmodified lines58596061626364656667686970713 unmodified linesVerarbeitet heruntergeladene PDFs und baut die Vektordatenbank auf.Verwendung:python scripts/build_index.py --game stalker"""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:"""Vollständige Pipeline: PDF-Dateien → Chunks → Vektordatenbank."""game_dir = os.path.join(data_dir, game)if not os.path.isdir(game_dir):31 unmodified linesall_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.")3 unmodified lines45678910111213141516171819202122232425262728293031323331 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051063 unmodified linesVerarbeitet heruntergeladene PDFs und baut die Vektordatenbank auf.Verwendung:python scripts/build_index.py --game stalker # baut Index + Cachepython scripts/build_index.py --game stalker --no-cache # ohne Cache-Export"""import argparseimport globimport jsonimport loggingimport osfrom src.ingestion.pdf import parse_pdffrom src.ingestion.youtube import parse_transcriptfrom src.rag.vectorstore import CHROMA_BASE_DIR, build_indexlogger = 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 Rohdatenexport: Wenn True, speichert Chunks+Embeddings als index_cache.json"""game_dir = os.path.join(data_dir, game)if not os.path.isdir(game_dir):31 unmodified linesall_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.")
42 unmodified lines4344454647484950515253545556575842 unmodified linesdef _ensure_index(game: str = "stalker") -> None:"""Baut den Vektorindex falls er noch nicht existiert."""from src.rag.vectorstore import _get_collectioncollection = _get_collection(game)if collection.count() > 0:logger.info(f"Index für '{game}' existiert bereits ({collection.count()} Chunks).")returnlogger.info(f"Kein Index für '{game}' gefunden – baue jetzt auf...")from scripts.build_index import build_game_indexbuild_game_index(game)logger.info("Index-Aufbau abgeschlossen.")42 unmodified lines4344454647484950515253545556575859606162636442 unmodified linesdef _ensure_index(game: str = "stalker") -> None:"""Baut den Vektorindex falls er noch nicht existiert."""from src.rag.vectorstore import _get_collection, load_cached_indexcollection = _get_collection(game)if collection.count() > 0:logger.info(f"Index für '{game}' existiert bereits ({collection.count()} Chunks).")return# Versuch 1: Cache laden (schnell, ~3s)if load_cached_index(game):logger.info("Index aus Cache geladen.")return# Versuch 2: Voller Rebuild (Fallback, erzeugt auch neuen Cache)logger.info(f"Kein Cache für '{game}' gefunden – voller Rebuild...")from scripts.build_index import build_game_indexbuild_game_index(game, export=True)logger.info("Index-Aufbau abgeschlossen.")
7 unmodified lines8910111213102 unmodified lines1161171181191201217 unmodified linesbuild_index(chunks, game="stalker")results = retrieve("Wie viele Aktionen hat ein Spieler?", game="stalker")"""import loggingimport os102 unmodified lineslogger.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]:7 unmodified lines891011121314102 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621637 unmodified linesbuild_index(chunks, game="stalker")results = retrieve("Wie viele Aktionen hat ein Spieler?", game="stalker")"""import jsonimport loggingimport os102 unmodified lineslogger.info(f" Indexiert: {end}/{len(ids)} ({end * 100 // len(ids)}%)")logger.info(f"✓ {len(ids)} Chunks indexiert in '{collection.name}'")return embeddingsdef load_cached_index(game: str) -> bool:"""Lädt den Index aus der Cache-Datei. Returns True bei Erfolg."""cache_path = os.path.join(CHROMA_BASE_DIR, game, "index_cache.json")if not os.path.exists(cache_path):return Falselogger.info(f"Lade Index aus Cache: {cache_path}")with open(cache_path, "r", encoding="utf-8") as f:cache = json.load(f)chunks = cache["chunks"]ids = [c["id"] for c in chunks]texts = [c["text"] for c in chunks]embeddings = [c["embedding"] for c in chunks]metadatas = [{"source": c["source"],"page": c["page"],"section": c["section"],"game": c["game"],}for c in chunks]collection = _get_collection(game)batch_size = 500for i in range(0, len(ids), batch_size):end = min(i + batch_size, len(ids))collection.add(ids=ids[i:end],embeddings=embeddings[i:end],documents=texts[i:end],metadatas=metadatas[i:end],)logger.info(f" Cache-Import: {end}/{len(ids)} ({end * 100 // len(ids)}%)")logger.info(f"✓ {len(ids)} Chunks aus Cache geladen")return Truedef retrieve(query: str, game: str, k: int = 5) -> list[dict]:
.gitattributes+1
.gitignore+4-1
data/processed/stalker/index_cache.jsonAdded+3
frontend/index.html+27-10
scripts/build_index.py+40-5
src/api.py+9-3
src/rag/vectorstore.py+42