""" PDF Ingestion Pipeline ====================== Parst Regelwerk-PDFs und erstellt strukturierte Chunks für die RAG-Datenbank. Verwendung: from src.ingestion.pdf import parse_pdf chunks = parse_pdf("data/raw/stalker/STALKER_rules.pdf", game="stalker") """ import os import re import unicodedata import fitz # PyMuPDF import tiktoken # Tokenizer für Chunk-Größenberechnung _enc = tiktoken.encoding_for_model("gpt-4") def _clean_text(text: str) -> str: """Bereinigt extrahierten PDF-Text von Artefakten.""" # Garbled Unicode-Header/Footer-Artefakte entfernen (z.B. ǽǻ | T½aü«Ä£...) text = re.sub(r"^[^\n]*[½¼¾«»æÞÄ£ɮɫȅȆƄƨȷ]{3,}[^\n]*$", "", text, flags=re.MULTILINE) # Seitenzahl-Footer entfernen (z.B. "12 | Mission Map | Tiles & Spaces |") text = re.sub(r"^\d+\s*\|[^\n]*\|?\s*$", "", text, flags=re.MULTILINE) # Mehrfache Leerzeilen zusammenfassen text = re.sub(r"\n{3,}", "\n\n", text) return text.strip() def _detect_sections(doc: fitz.Document) -> list[dict]: """ Extrahiert Seiten mit Abschnittserkennung basierend auf Schriftgröße. Returns: Liste von dicts: {page, section, text} """ pages = [] current_section = "Introduction" for page_num in range(len(doc)): page = doc[page_num] text = page.get_text() if not text or len(text.strip()) < 20: continue # Abschnittserkennung: Suche nach großen/fetten Überschriften blocks = page.get_text("dict")["blocks"] for block in blocks: if "lines" not in block: continue for line in block["lines"]: for span in line["spans"]: # Große Schrift (>= 14pt) und Großbuchstaben = Section Header if span["size"] >= 14 and span["text"].strip(): candidate = span["text"].strip() # Nur sinnvolle Überschriften (mind. 3 Buchstaben, nicht nur Zahlen) if len(candidate) >= 3 and re.search(r"[A-Za-z]{3,}", candidate): current_section = candidate cleaned = _clean_text(text) if cleaned: pages.append({ "page": page_num + 1, # 1-basiert "section": current_section, "text": cleaned, }) return pages def _token_count(text: str) -> int: return len(_enc.encode(text)) def _hard_split(text: str, chunk_size: int) -> list[str]: """Teilt Text wortweise auf wenn keine Satz-/Absatzgrenzen vorhanden sind.""" words = text.split() parts = [] current = [] for word in words: current.append(word) if _token_count(" ".join(current)) > chunk_size: current.pop() if current: parts.append(" ".join(current)) current = [word] if current: parts.append(" ".join(current)) return parts def chunk_text( text: str, page: int, section: str, source: str, game: str, chunk_size: int = 500, overlap: int = 50, ) -> list[dict]: """ Teilt Text in RAG-kompatible Chunks auf. Grenzen werden an Absätzen/Sätzen ausgerichtet. """ if _token_count(text) <= chunk_size: return [{ "id": f"{source}_p{page}_chunk0", "source": source, "page": page, "section": section, "text": text, "game": game, }] # An Absätzen splitten paragraphs = re.split(r"\n\n+", text) chunks = [] current_chunk = "" chunk_idx = 0 for para in paragraphs: para = para.strip() if not para: continue candidate = (current_chunk + "\n\n" + para).strip() if current_chunk else para if _token_count(candidate) <= chunk_size: current_chunk = candidate else: # Aktuellen Chunk speichern if current_chunk: chunks.append({ "id": f"{source}_p{page}_chunk{chunk_idx}", "source": source, "page": page, "section": section, "text": current_chunk, "game": game, }) chunk_idx += 1 # Overlap: letzte Sätze für Kontext mitnehmen sentences = re.split(r"(?<=[.!?])\s+", current_chunk) overlap_text = "" for s in reversed(sentences): candidate_overlap = (s + " " + overlap_text).strip() if _token_count(candidate_overlap) <= overlap: overlap_text = candidate_overlap else: break current_chunk = (overlap_text + "\n\n" + para).strip() if overlap_text else para else: # Einzelner Paragraph ist zu groß -> Satz-weise splitten sentences = re.split(r"(?<=[.!?])\s+", para) for sent in sentences: candidate = (current_chunk + " " + sent).strip() if current_chunk else sent if _token_count(candidate) <= chunk_size: current_chunk = candidate else: if current_chunk: chunks.append({ "id": f"{source}_p{page}_chunk{chunk_idx}", "source": source, "page": page, "section": section, "text": current_chunk, "game": game, }) chunk_idx += 1 # Einzelner Satz überschreitet chunk_size -> Hard-Split if _token_count(sent) > chunk_size: parts = _hard_split(sent, chunk_size) for part in parts[:-1]: chunks.append({ "id": f"{source}_p{page}_chunk{chunk_idx}", "source": source, "page": page, "section": section, "text": part, "game": game, }) chunk_idx += 1 current_chunk = parts[-1] if parts else "" else: current_chunk = sent # Letzten Chunk speichern if current_chunk: chunks.append({ "id": f"{source}_p{page}_chunk{chunk_idx}", "source": source, "page": page, "section": section, "text": current_chunk, "game": game, }) return chunks def parse_pdf(pdf_path: str, game: str, chunk_size: int = 500, overlap: int = 50) -> list[dict]: """ Parst ein PDF und gibt eine Liste von Chunks zurück. Args: pdf_path: Pfad zur PDF-Datei game: Spielname (z.B. "stalker") chunk_size: Maximale Chunk-Größe in Tokens overlap: Überlapp zwischen Chunks in Tokens Returns: Liste von Chunk-Dicts mit Feldern: id, source, page, section, text, game """ source = os.path.splitext(os.path.basename(pdf_path))[0] doc = fitz.open(pdf_path) pages = _detect_sections(doc) all_chunks = [] for page_data in pages: chunks = chunk_text( text=page_data["text"], page=page_data["page"], section=page_data["section"], source=source, game=game, chunk_size=chunk_size, overlap=overlap, ) all_chunks.extend(chunks) return all_chunks if __name__ == "__main__": import json import sys if len(sys.argv) < 2: print("Verwendung: python -m src.ingestion.pdf [game]") sys.exit(1) pdf_path = sys.argv[1] game = sys.argv[2] if len(sys.argv) > 2 else "stalker" chunks = parse_pdf(pdf_path, game) print(f"Extrahiert: {len(chunks)} Chunks aus {pdf_path}") for c in chunks[:3]: print(f"\n--- {c['id']} (S.{c['page']}, {c['section']}) ---") print(c["text"][:200] + "...")