Spaces:
Sleeping

File size: 3,915 Bytes
ebf20cf
 
 
 
 
 
8a2dc22
 
ebf20cf
 
60a07be
8a2dc22
037b655
08f87f1
 
 
60a07be
8a2dc22
ebf20cf
037b655
 
08f87f1
8a2dc22
ebf20cf
 
8a2dc22
 
 
 
 
ebf20cf
08f87f1
 
 
 
e4acb6a
 
 
 
 
 
 
08f87f1
 
 
037b655
08f87f1
 
037b655
e4acb6a
08f87f1
037b655
08f87f1
 
60a07be
 
 
 
 
037b655
 
60a07be
 
037b655
60a07be
 
037b655
8a2dc22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebf20cf
 
 
037b655
ebf20cf
 
8a2dc22
 
ebf20cf
 
8a2dc22
037b655
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""
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.")