commit
Browse files- app.py +205 -0
- build_hg_viewer.py +285 -0
- embeddings.py +24 -0
- llm.py +36 -0
- load_documents.py +128 -0
- rag_pipeline.py +153 -0
- requirements.txt +39 -0
- retriever.py +46 -0
- speech_io.py +102 -0
- split_documents.py +27 -0
- upload_weblink_to_supabase.py +130 -0
- vectorstore.py +56 -0
app.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py – Prüfungsrechts-Chatbot (RAG + Sprache, UI kiểu ChatGPT)
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from gradio_pdf import PDF
|
| 5 |
+
|
| 6 |
+
from load_documents import load_all_documents
|
| 7 |
+
from split_documents import split_documents
|
| 8 |
+
from vectorstore import build_vectorstore
|
| 9 |
+
from retriever import get_retriever
|
| 10 |
+
from llm import load_llm
|
| 11 |
+
from rag_pipeline import answer
|
| 12 |
+
from speech_io import transcribe_audio, synthesize_speech
|
| 13 |
+
|
| 14 |
+
# =====================================================
|
| 15 |
+
# INITIALISIERUNG (global)
|
| 16 |
+
# =====================================================
|
| 17 |
+
|
| 18 |
+
print("📚 Lade Dokumente…")
|
| 19 |
+
docs = load_all_documents()
|
| 20 |
+
|
| 21 |
+
print("🔪 Splitte Dokumente…")
|
| 22 |
+
chunks = split_documents(docs)
|
| 23 |
+
|
| 24 |
+
print("🔍 Erstelle VectorStore…")
|
| 25 |
+
vs = build_vectorstore(chunks)
|
| 26 |
+
|
| 27 |
+
print("🔎 Erzeuge Retriever…")
|
| 28 |
+
retriever = get_retriever(vs)
|
| 29 |
+
|
| 30 |
+
print("🤖 Lade LLM…")
|
| 31 |
+
llm = load_llm()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# =====================================================
|
| 35 |
+
# Quellen formatieren – Markdown für Chat
|
| 36 |
+
# =====================================================
|
| 37 |
+
def format_sources(src):
|
| 38 |
+
if not src:
|
| 39 |
+
return ""
|
| 40 |
+
|
| 41 |
+
out = ["", "## 📚 Quellen"]
|
| 42 |
+
|
| 43 |
+
for s in src:
|
| 44 |
+
line = f"- [{s['source']}]({s['url']})"
|
| 45 |
+
if s.get("page") is not None:
|
| 46 |
+
line += f" (Seite {s['page']})"
|
| 47 |
+
out.append(line)
|
| 48 |
+
|
| 49 |
+
return "\n".join(out)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# =====================================================
|
| 53 |
+
# CORE CHAT-FUNKTION (MultimodalTextbox: Text + Audio)
|
| 54 |
+
# =====================================================
|
| 55 |
+
def chat_fn(message, history):
|
| 56 |
+
"""
|
| 57 |
+
message: dict {"text": str, "files": [...]} von gr.MultimodalTextbox
|
| 58 |
+
history: Liste von OpenAI-ähnlichen Messages (role, content)
|
| 59 |
+
"""
|
| 60 |
+
# 1) Text + evtl. Audio aus message holen
|
| 61 |
+
if isinstance(message, dict):
|
| 62 |
+
text = (message.get("text") or "").strip()
|
| 63 |
+
files = message.get("files") or []
|
| 64 |
+
else:
|
| 65 |
+
text = str(message or "").strip()
|
| 66 |
+
files = []
|
| 67 |
+
|
| 68 |
+
# Audio-Datei (vom Mikrofon) herausziehen
|
| 69 |
+
audio_path = None
|
| 70 |
+
for f in files:
|
| 71 |
+
# gr.MultimodalTextbox liefert i.d.R. Dict mit "path"
|
| 72 |
+
if isinstance(f, dict):
|
| 73 |
+
path = f.get("path")
|
| 74 |
+
else:
|
| 75 |
+
path = f
|
| 76 |
+
if isinstance(path, str) and path:
|
| 77 |
+
audio_path = path
|
| 78 |
+
break
|
| 79 |
+
|
| 80 |
+
# Wenn Audio vorhanden: transkribieren
|
| 81 |
+
if audio_path:
|
| 82 |
+
spoken = transcribe_audio(audio_path)
|
| 83 |
+
if text:
|
| 84 |
+
text = (text + " " + spoken).strip()
|
| 85 |
+
else:
|
| 86 |
+
text = spoken
|
| 87 |
+
|
| 88 |
+
if not text:
|
| 89 |
+
# Nichts zu tun
|
| 90 |
+
return history, None, {"text": "", "files": []}
|
| 91 |
+
|
| 92 |
+
# 2) RAG-Antwort berechnen
|
| 93 |
+
ans, sources = answer(text, retriever, llm)
|
| 94 |
+
bot_msg = ans + format_sources(sources)
|
| 95 |
+
|
| 96 |
+
# 3) History aktualisieren (ChatGPT-Style)
|
| 97 |
+
history = history + [
|
| 98 |
+
{"role": "user", "content": text},
|
| 99 |
+
{"role": "assistant", "content": bot_msg},
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
# 4) TTS für Antwort
|
| 103 |
+
tts_audio = synthesize_speech(bot_msg)
|
| 104 |
+
|
| 105 |
+
# 5) Input-Feld leeren
|
| 106 |
+
cleared_input = {"text": "", "files": []}
|
| 107 |
+
|
| 108 |
+
return history, tts_audio, cleared_input
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# =====================================================
|
| 112 |
+
# LAST ANSWER → TTS (für Button "Antwort erneut vorlesen")
|
| 113 |
+
# =====================================================
|
| 114 |
+
def read_last_answer(history):
|
| 115 |
+
if not history:
|
| 116 |
+
return None
|
| 117 |
+
|
| 118 |
+
for msg in reversed(history):
|
| 119 |
+
if msg.get("role") == "assistant":
|
| 120 |
+
return synthesize_speech(msg.get("content", ""))
|
| 121 |
+
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# =====================================================
|
| 126 |
+
# UI – GRADIO
|
| 127 |
+
# =====================================================
|
| 128 |
+
with gr.Blocks(title="Prüfungsrechts-Chatbot (RAG + Sprache)") as demo:
|
| 129 |
+
gr.Markdown("# 🧑⚖️ Prüfungsrechts-Chatbot")
|
| 130 |
+
gr.Markdown(
|
| 131 |
+
"Dieser Chatbot beantwortet Fragen **ausschließlich** aus der "
|
| 132 |
+
"Prüfungsordnung (PDF) und dem Hochschulgesetz NRW. "
|
| 133 |
+
"Du kannst Text eingeben oder direkt ins Mikrofon sprechen."
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
with gr.Row():
|
| 137 |
+
# ===================== LINKER TEIL: Chat =====================
|
| 138 |
+
with gr.Column(scale=2):
|
| 139 |
+
chatbot = gr.Chatbot(
|
| 140 |
+
label="Chat",
|
| 141 |
+
height=500,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
# Audio-Ausgabe (TTS)
|
| 145 |
+
voice_out = gr.Audio(label="Vorgelesene Antwort", type="numpy")
|
| 146 |
+
|
| 147 |
+
# Multimodal-Textbox mit Mikrofon in der Leiste
|
| 148 |
+
chat_input = gr.MultimodalTextbox(
|
| 149 |
+
label=None,
|
| 150 |
+
placeholder="Stelle deine Frage zum Prüfungsrecht … oder sprich ins Mikrofon",
|
| 151 |
+
show_label=False,
|
| 152 |
+
sources=["microphone"], # nur Mikrofon (kein Upload nötig)
|
| 153 |
+
file_types=["audio"],
|
| 154 |
+
max_lines=6,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# Senden bei Enter / Klick auf Icon
|
| 158 |
+
chat_input.submit(
|
| 159 |
+
chat_fn,
|
| 160 |
+
[chat_input, chatbot],
|
| 161 |
+
[chatbot, voice_out, chat_input],
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
send_btn = gr.Button("Senden")
|
| 165 |
+
send_btn.click(
|
| 166 |
+
chat_fn,
|
| 167 |
+
[chat_input, chatbot],
|
| 168 |
+
[chatbot, voice_out, chat_input],
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# Button: Antwort erneut vorlesen
|
| 172 |
+
read_btn = gr.Button("🔁 Antwort erneut vorlesen")
|
| 173 |
+
read_btn.click(
|
| 174 |
+
read_last_answer,
|
| 175 |
+
[chatbot],
|
| 176 |
+
[voice_out],
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# Chat löschen
|
| 180 |
+
clear_btn = gr.Button("Chat zurücksetzen")
|
| 181 |
+
clear_btn.click(
|
| 182 |
+
lambda: ([], None, {"text": "", "files": []}),
|
| 183 |
+
None,
|
| 184 |
+
[chatbot, voice_out, chat_input],
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
# ===================== RECHTER TEIL: Viewer =====================
|
| 188 |
+
with gr.Column(scale=1):
|
| 189 |
+
# PDF-URL aus metadata holen
|
| 190 |
+
pdf_meta = next(d.metadata for d in docs if d.metadata["type"] == "pdf")
|
| 191 |
+
gr.Markdown("### 📄 Prüfungsordnung (PDF)")
|
| 192 |
+
PDF(pdf_meta["pdf_url"], height=350)
|
| 193 |
+
|
| 194 |
+
# HG-Viewer-URL (hg_clean.html aus Supabase Storage)
|
| 195 |
+
hg_meta = next(d.metadata for d in docs if d.metadata["type"] == "hg")
|
| 196 |
+
hg_url = hg_meta["viewer_url"].split("#")[0]
|
| 197 |
+
|
| 198 |
+
gr.Markdown("### 📘 Hochschulgesetz NRW (Viewer)")
|
| 199 |
+
gr.HTML(
|
| 200 |
+
f'<iframe src="{hg_url}" '
|
| 201 |
+
'style="width:100%;height:350px;border:none;"></iframe>'
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
if __name__ == "__main__":
|
| 205 |
+
demo.queue().launch(ssr_mode=False, show_error=True)
|
build_hg_viewer.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# build_hg_viewer.py
|
| 2 |
+
import os
|
| 3 |
+
from supabase import create_client
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
|
| 8 |
+
SUPABASE_URL = os.environ["SUPABASE_URL"]
|
| 9 |
+
SUPABASE_SERVICE_ROLE = os.environ["SUPABASE_SERVICE_ROLE"]
|
| 10 |
+
|
| 11 |
+
if not SUPABASE_URL or not SUPABASE_SERVICE_ROLE:
|
| 12 |
+
raise RuntimeError("Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE")
|
| 13 |
+
|
| 14 |
+
supabase = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE)
|
| 15 |
+
|
| 16 |
+
from upload_weblink_to_supabase import extract_paragraphs
|
| 17 |
+
|
| 18 |
+
# ======== HTML TEMPLATE ========
|
| 19 |
+
VIEW_TEMPLATE = """
|
| 20 |
+
<!DOCTYPE html>
|
| 21 |
+
<html lang="de">
|
| 22 |
+
<head>
|
| 23 |
+
<meta charset="UTF-8">
|
| 24 |
+
<title>Hochschulgesetz NRW – Paragraph Viewer</title>
|
| 25 |
+
<style>
|
| 26 |
+
body {
|
| 27 |
+
font-family: Arial, sans-serif;
|
| 28 |
+
margin: 0;
|
| 29 |
+
padding: 0;
|
| 30 |
+
display: flex;
|
| 31 |
+
}
|
| 32 |
+
/* ----------- SIDEBAR ------------- */
|
| 33 |
+
#sidebar {
|
| 34 |
+
width: 280px;
|
| 35 |
+
height: 100vh;
|
| 36 |
+
overflow-y: auto;
|
| 37 |
+
background: #f5f5f5;
|
| 38 |
+
border-right: 1px solid #ccc;
|
| 39 |
+
padding: 15px;
|
| 40 |
+
position: sticky;
|
| 41 |
+
top: 0;
|
| 42 |
+
}
|
| 43 |
+
#sidebar h2 {
|
| 44 |
+
margin-top: 0;
|
| 45 |
+
}
|
| 46 |
+
#searchBox {
|
| 47 |
+
width: 100%;
|
| 48 |
+
padding: 8px;
|
| 49 |
+
font-size: 15px;
|
| 50 |
+
margin-bottom: 10px;
|
| 51 |
+
border: 1px solid #aaa;
|
| 52 |
+
border-radius: 5px;
|
| 53 |
+
}
|
| 54 |
+
.sidebar-link {
|
| 55 |
+
display: block;
|
| 56 |
+
padding: 6px 8px;
|
| 57 |
+
margin-bottom: 4px;
|
| 58 |
+
text-decoration: none;
|
| 59 |
+
color: #003366;
|
| 60 |
+
border-radius: 4px;
|
| 61 |
+
}
|
| 62 |
+
.sidebar-link:hover {
|
| 63 |
+
background: #e0e7ff;
|
| 64 |
+
color: #001d4d;
|
| 65 |
+
}
|
| 66 |
+
/* ----------- CONTENT ------------- */
|
| 67 |
+
#content {
|
| 68 |
+
flex: 1;
|
| 69 |
+
padding: 25px;
|
| 70 |
+
max-width: 900px;
|
| 71 |
+
}
|
| 72 |
+
/* Absatz block */
|
| 73 |
+
.para {
|
| 74 |
+
padding: 20px 0;
|
| 75 |
+
border-bottom: 1px solid #ddd;
|
| 76 |
+
}
|
| 77 |
+
.para h2 {
|
| 78 |
+
color: #003366;
|
| 79 |
+
margin-bottom: 10px;
|
| 80 |
+
}
|
| 81 |
+
/* ----------- Fußnoten ------------- */
|
| 82 |
+
.fn-block {
|
| 83 |
+
background: #fafafa;
|
| 84 |
+
border-left: 4px solid #999;
|
| 85 |
+
padding: 12px;
|
| 86 |
+
margin-top: 10px;
|
| 87 |
+
margin-bottom: 25px;
|
| 88 |
+
}
|
| 89 |
+
.fn-toggle {
|
| 90 |
+
cursor: pointer;
|
| 91 |
+
font-weight: bold;
|
| 92 |
+
color: #003366;
|
| 93 |
+
margin-bottom: 5px;
|
| 94 |
+
}
|
| 95 |
+
.fn-content {
|
| 96 |
+
display: none;
|
| 97 |
+
padding-left: 10px;
|
| 98 |
+
}
|
| 99 |
+
.fn-title {
|
| 100 |
+
font-weight: bold;
|
| 101 |
+
margin-bottom: 6px;
|
| 102 |
+
}
|
| 103 |
+
.fn-item {
|
| 104 |
+
margin-bottom: 8px;
|
| 105 |
+
}
|
| 106 |
+
/* ----------- Highlight beim Öffnen ------------- */
|
| 107 |
+
.highlight {
|
| 108 |
+
animation: flash 2s ease-in-out;
|
| 109 |
+
background: #fff8c6 !important;
|
| 110 |
+
}
|
| 111 |
+
@keyframes flash {
|
| 112 |
+
0% { background: #fff8c6; }
|
| 113 |
+
100% { background: transparent; }
|
| 114 |
+
}
|
| 115 |
+
/* Keyword highlight */
|
| 116 |
+
.keyword {
|
| 117 |
+
background: yellow;
|
| 118 |
+
padding: 2px 3px;
|
| 119 |
+
border-radius: 3px;
|
| 120 |
+
}
|
| 121 |
+
/* Back to top button */
|
| 122 |
+
#topBtn {
|
| 123 |
+
position: fixed;
|
| 124 |
+
bottom: 25px;
|
| 125 |
+
right: 25px;
|
| 126 |
+
background: #003366;
|
| 127 |
+
color: white;
|
| 128 |
+
border-radius: 8px;
|
| 129 |
+
padding: 10px 14px;
|
| 130 |
+
cursor: pointer;
|
| 131 |
+
font-size: 16px;
|
| 132 |
+
display: none;
|
| 133 |
+
}
|
| 134 |
+
</style>
|
| 135 |
+
</head>
|
| 136 |
+
<body>
|
| 137 |
+
<div id="sidebar">
|
| 138 |
+
<h2>Inhaltsverzeichnis</h2>
|
| 139 |
+
<input type="text" id="searchBox" placeholder="Suchen nach § …">
|
| 140 |
+
<!-- SIDEBAR_LINKS -->
|
| 141 |
+
</div>
|
| 142 |
+
<div id="content">
|
| 143 |
+
<h1>Hochschulgesetz NRW – Paragraph Viewer</h1>
|
| 144 |
+
<!-- PARAGRAPH_CONTENT -->
|
| 145 |
+
</div>
|
| 146 |
+
<div id="topBtn" onclick="scrollToTop()">⬆️ Top</div>
|
| 147 |
+
<script>
|
| 148 |
+
// ------ TỰ ĐỘNG HIGHLIGHT Absatz khi có #anchor HIGHLIGHT ABSATZ & SCROLL ------
|
| 149 |
+
window.onload = function() {
|
| 150 |
+
const anchor = window.location.hash.substring(1);
|
| 151 |
+
const params = new URLSearchParams(window.location.search);
|
| 152 |
+
const keywords = params.get("k");
|
| 153 |
+
if (anchor) {
|
| 154 |
+
const el = document.getElementById(anchor);
|
| 155 |
+
if (el) {
|
| 156 |
+
el.classList.add("highlight");
|
| 157 |
+
el.scrollIntoView({ behavior: "smooth", block: "center" });
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
/* KEYWORD HIGHLIGHT */
|
| 161 |
+
if (keywords) {
|
| 162 |
+
const words = keywords.split("%20");
|
| 163 |
+
highlightKeywords(words);
|
| 164 |
+
}
|
| 165 |
+
};
|
| 166 |
+
/* --- KEYWORD HIGHLIGHT FUNCTION --- */
|
| 167 |
+
function highlightKeywords(words) {
|
| 168 |
+
const container = document.getElementById("content");
|
| 169 |
+
let html = container.innerHTML;
|
| 170 |
+
words.forEach(word => {
|
| 171 |
+
if (word.length < 2) return;
|
| 172 |
+
const regex = new RegExp(`(${decodeURIComponent(word)})`, "gi");
|
| 173 |
+
html = html.replace(regex, `<span class="keyword">$1</span>`);
|
| 174 |
+
});
|
| 175 |
+
container.innerHTML = html;
|
| 176 |
+
}
|
| 177 |
+
/* --- SEARCH IN SIDEBAR --- */
|
| 178 |
+
document.getElementById("searchBox").addEventListener("input", function() {
|
| 179 |
+
const q = this.value.toLowerCase();
|
| 180 |
+
document.querySelectorAll(".sidebar-link").forEach(link => {
|
| 181 |
+
const txt = link.innerText.toLowerCase();
|
| 182 |
+
link.style.display = txt.includes(q) ? "block" : "none";
|
| 183 |
+
});
|
| 184 |
+
});
|
| 185 |
+
/* --- COLLAPSIBLE FUSSNOTEN --- */
|
| 186 |
+
document.addEventListener("click", function(e) {
|
| 187 |
+
if (e.target.classList.contains("fn-toggle")) {
|
| 188 |
+
const content = e.target.nextElementSibling;
|
| 189 |
+
content.style.display = content.style.display === "block" ? "none" : "block";
|
| 190 |
+
}
|
| 191 |
+
});
|
| 192 |
+
/* --- BACK TO TOP BUTTON --- */
|
| 193 |
+
window.onscroll = function() {
|
| 194 |
+
document.getElementById("topBtn").style.display =
|
| 195 |
+
window.scrollY > 300 ? "block" : "none";
|
| 196 |
+
};
|
| 197 |
+
function scrollToTop() {
|
| 198 |
+
window.scrollTo({ top: 0, behavior: 'smooth' });
|
| 199 |
+
}
|
| 200 |
+
</script>
|
| 201 |
+
</body>
|
| 202 |
+
</html>
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
# -------------------------------------------------------------------
|
| 206 |
+
# 2. BUILD VIEWER
|
| 207 |
+
# -------------------------------------------------------------------
|
| 208 |
+
|
| 209 |
+
def build_html_from_db():
|
| 210 |
+
"""
|
| 211 |
+
Liest alle Paragraphen aus hg_nrw und baut daraus HTML.
|
| 212 |
+
"""
|
| 213 |
+
print(">>> Lade Paragraphen aus Supabase (hg_nrw) …")
|
| 214 |
+
paras = extract_paragraphs()
|
| 215 |
+
# 5.12_2:13
|
| 216 |
+
res = supabase.table("hg_nrw").select("*").order("order_index").execute()
|
| 217 |
+
rows = res.data or []
|
| 218 |
+
|
| 219 |
+
sidebar_links = ""
|
| 220 |
+
content_html = ""
|
| 221 |
+
|
| 222 |
+
for p in paras:
|
| 223 |
+
pid = p["abs_id"]
|
| 224 |
+
title = p["title"]
|
| 225 |
+
body = p["content"]
|
| 226 |
+
|
| 227 |
+
# Sidebar item
|
| 228 |
+
sidebar_links += f'<a class="sidebar-link" href="#{pid}">{title}</a>\n'
|
| 229 |
+
|
| 230 |
+
# Fußnoten tách riêng (bắt đầu bằng "Fn 1", "Fn 2", ...)
|
| 231 |
+
lines = body.split("\n")
|
| 232 |
+
main_text = []
|
| 233 |
+
fn_text = []
|
| 234 |
+
in_fn = False
|
| 235 |
+
|
| 236 |
+
for line in lines:
|
| 237 |
+
if line.startswith("Fn "):
|
| 238 |
+
in_fn = True
|
| 239 |
+
if in_fn:
|
| 240 |
+
fn_text.append(line)
|
| 241 |
+
else:
|
| 242 |
+
main_text.append(line)
|
| 243 |
+
|
| 244 |
+
footnotes_html = ""
|
| 245 |
+
if fn_text:
|
| 246 |
+
footnotes_html += '<div class="fn-block">'
|
| 247 |
+
footnotes_html += '<div class="fn-title">Fußnoten:</div>'
|
| 248 |
+
for fn in fn_text:
|
| 249 |
+
footnotes_html += f'<div class="fn-item">{fn}</div>'
|
| 250 |
+
footnotes_html += "</div>"
|
| 251 |
+
|
| 252 |
+
# Paragraph block
|
| 253 |
+
content_html += f"""
|
| 254 |
+
<div class="para" id="{pid}">
|
| 255 |
+
<h2>{title}</h2>
|
| 256 |
+
<div>{'<br>'.join(main_text)}</div>
|
| 257 |
+
{footnotes_html}
|
| 258 |
+
</div>
|
| 259 |
+
"""
|
| 260 |
+
|
| 261 |
+
html = VIEW_TEMPLATE.replace("<!-- SIDEBAR_LINKS -->", sidebar_links)
|
| 262 |
+
html = html.replace("<!-- PARAGRAPH_CONTENT -->", content_html)
|
| 263 |
+
|
| 264 |
+
return html
|
| 265 |
+
|
| 266 |
+
# -------------------------------------------------------------------
|
| 267 |
+
# 3. UPLOAD TO SUPABASE STORAGE
|
| 268 |
+
# -------------------------------------------------------------------
|
| 269 |
+
|
| 270 |
+
def upload_html():
|
| 271 |
+
html = build_html_from_db()
|
| 272 |
+
|
| 273 |
+
supabase.storage.from_("hg_viewer").update(
|
| 274 |
+
"hg_clean.html",
|
| 275 |
+
html.encode("utf-8"),
|
| 276 |
+
{
|
| 277 |
+
"content-type": "text/html",
|
| 278 |
+
"x-upsert": "true"
|
| 279 |
+
}
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
print("✔ hg_clean.html uploaded!")
|
| 283 |
+
|
| 284 |
+
if __name__ == "__main__":
|
| 285 |
+
upload_html()
|
embeddings.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# embeddings.py – OpenAI Version (text-embedding-3-small)
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from langchain_openai import OpenAIEmbeddings
|
| 5 |
+
|
| 6 |
+
EMBED_MODEL = "text-embedding-3-small"
|
| 7 |
+
|
| 8 |
+
def get_embeddings():
|
| 9 |
+
api_key = os.environ.get("OPENAI_API_KEY")
|
| 10 |
+
if not api_key:
|
| 11 |
+
raise RuntimeError(
|
| 12 |
+
"OPENAI_API_KEY fehlt. Bitte als Secret im HuggingFace Space setzen."
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
print(f">>> Lade OpenAI Embedding Model: {EMBED_MODEL}")
|
| 16 |
+
emb = OpenAIEmbeddings(
|
| 17 |
+
model=EMBED_MODEL,
|
| 18 |
+
api_key=api_key,
|
| 19 |
+
)
|
| 20 |
+
return emb
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
e = get_embeddings()
|
| 24 |
+
print(e.embed_query("Test"))
|
llm.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# llm.py – OpenAI Chatmodell für RAG
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from langchain_openai import ChatOpenAI
|
| 5 |
+
|
| 6 |
+
CHAT_MODEL = "gpt-4o-mini" # günstig & stark
|
| 7 |
+
|
| 8 |
+
def load_llm():
|
| 9 |
+
api_key = os.environ.get("OPENAI_API_KEY")
|
| 10 |
+
if not api_key:
|
| 11 |
+
raise RuntimeError(
|
| 12 |
+
"OPENAI_API_KEY fehlt. Bitte als Secret im HuggingFace Space setzen."
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
print(f">>> Lade OpenAI Chatmodell: {CHAT_MODEL}")
|
| 16 |
+
|
| 17 |
+
# llm = ChatOpenAI(
|
| 18 |
+
# model=CHAT_MODEL,
|
| 19 |
+
# temperature=0.0, # deterministisch, wenig Halluzination
|
| 20 |
+
# api_key=api_key,
|
| 21 |
+
# )
|
| 22 |
+
# return llm
|
| 23 |
+
# 5.12_2:13
|
| 24 |
+
llm = ChatOpenAI(
|
| 25 |
+
model=CHAT_MODEL,
|
| 26 |
+
temperature=0.0,
|
| 27 |
+
top_p=1.0,
|
| 28 |
+
presence_penalty=0.0,
|
| 29 |
+
frequency_penalty=0.0,
|
| 30 |
+
api_key=api_key,
|
| 31 |
+
)
|
| 32 |
+
return llm
|
| 33 |
+
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
llm = load_llm()
|
| 36 |
+
print(llm.invoke("Sag einen Satz zum Prüfungsrecht.").content)
|
load_documents.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LOAD_DOCUMENTS – SINGLE SOURCE OF TRUTH
|
| 3 |
+
Nhiệm vụ:
|
| 4 |
+
1) Lade Prüfungsordnung PDF direkt aus Supabase-Storage.
|
| 5 |
+
2) Lade Hochschulgesetz NRW aus Supabase-Tabelle hg_nrw.
|
| 6 |
+
3) Cung cấp metadata đầy đủ để các file khác KHÔNG PHẢI tính lại URL.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import tempfile
|
| 11 |
+
from dotenv import load_dotenv
|
| 12 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 13 |
+
from langchain_core.documents import Document
|
| 14 |
+
from supabase import create_client
|
| 15 |
+
|
| 16 |
+
load_dotenv()
|
| 17 |
+
|
| 18 |
+
import urllib.parse
|
| 19 |
+
|
| 20 |
+
# ===== Supabase config =====
|
| 21 |
+
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 22 |
+
SUPABASE_SERVICE_ROLE = os.getenv("SUPABASE_SERVICE_ROLE")
|
| 23 |
+
|
| 24 |
+
supabase = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE)
|
| 25 |
+
|
| 26 |
+
# ===== Storage Config =====
|
| 27 |
+
|
| 28 |
+
#import urllib.parse
|
| 29 |
+
PDF_FILE = "f10_bpo_ifb_tei_mif_wii_2021-01-04.pdf"
|
| 30 |
+
|
| 31 |
+
PDF_BUCKET = "File PDF"
|
| 32 |
+
ENC_BUCKET = urllib.parse.quote(PDF_BUCKET) # "File%20PDF"
|
| 33 |
+
|
| 34 |
+
#PDF_URL = f"{SUPABASE_URL}/storage/v1/object/public/{PDF_BUCKET}/{PDF_FILE}"
|
| 35 |
+
PDF_URL = f"{SUPABASE_URL}/storage/v1/object/public/{ENC_BUCKET}/{PDF_FILE}"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ===== Viewer URL =====
|
| 39 |
+
HG_VIEWER_BUCKET = "hg_viewer"
|
| 40 |
+
HG_VIEWER_FILE = "hg_clean.html"
|
| 41 |
+
HG_VIEWER_URL = f"{SUPABASE_URL}/storage/v1/object/public/{HG_VIEWER_BUCKET}/{HG_VIEWER_FILE}"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# ============================================================
|
| 45 |
+
# 1) PDF aus Supabase laden
|
| 46 |
+
# ============================================================
|
| 47 |
+
|
| 48 |
+
def load_pdf_from_supabase() -> list[Document]:
|
| 49 |
+
print("📥 Lade Prüfungsordnung PDF aus Supabase...")
|
| 50 |
+
|
| 51 |
+
response = supabase.storage.from_(PDF_BUCKET).download(PDF_FILE)
|
| 52 |
+
if response is None:
|
| 53 |
+
raise ValueError("❌ Konnte PDF nicht laden!")
|
| 54 |
+
|
| 55 |
+
# Temporäre Datei
|
| 56 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 57 |
+
tmp.write(response)
|
| 58 |
+
temp_pdf_path = tmp.name
|
| 59 |
+
|
| 60 |
+
pages = PyPDFLoader(temp_pdf_path).load()
|
| 61 |
+
|
| 62 |
+
for i, p in enumerate(pages):
|
| 63 |
+
p.metadata = {
|
| 64 |
+
"type": "pdf",
|
| 65 |
+
"source": "Prüfungsordnung",
|
| 66 |
+
"page": i,
|
| 67 |
+
"pdf_url": f"{PDF_URL}#page={i}",
|
| 68 |
+
"filename": PDF_FILE,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
print(f"✔ {len(pages)} PDF-Seiten geladen.")
|
| 72 |
+
return pages
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# ============================================================
|
| 76 |
+
# 2) HG aus Tabelle laden
|
| 77 |
+
# ============================================================
|
| 78 |
+
|
| 79 |
+
def load_hg_from_supabase() -> list[Document]:
|
| 80 |
+
print("📥 Lade Hochschulgesetz NRW aus Tabelle hg_nrw...")
|
| 81 |
+
|
| 82 |
+
res = (
|
| 83 |
+
supabase.table("hg_nrw")
|
| 84 |
+
.select("*")
|
| 85 |
+
.order("order_index", desc=False)
|
| 86 |
+
.execute()
|
| 87 |
+
)
|
| 88 |
+
rows = res.data or []
|
| 89 |
+
docs = []
|
| 90 |
+
|
| 91 |
+
for row in rows:
|
| 92 |
+
abs_id = row["abs_id"]
|
| 93 |
+
title = row["title"]
|
| 94 |
+
content = row["content"]
|
| 95 |
+
|
| 96 |
+
viewer_url = f"{HG_VIEWER_URL}#{abs_id}"
|
| 97 |
+
|
| 98 |
+
docs.append(
|
| 99 |
+
Document(
|
| 100 |
+
page_content=content,
|
| 101 |
+
metadata={
|
| 102 |
+
"type": "hg",
|
| 103 |
+
"source": "Hochschulgesetz NRW",
|
| 104 |
+
"abs_id": abs_id,
|
| 105 |
+
"title": title,
|
| 106 |
+
"viewer_url": viewer_url,
|
| 107 |
+
},
|
| 108 |
+
)
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
print(f"✔ {len(docs)} HG-Absätze geladen.")
|
| 112 |
+
return docs
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# ============================================================
|
| 116 |
+
# 3) ALLES LADEN
|
| 117 |
+
# ============================================================
|
| 118 |
+
|
| 119 |
+
def load_all_documents():
|
| 120 |
+
pdf_docs = load_pdf_from_supabase()
|
| 121 |
+
hg_docs = load_hg_from_supabase()
|
| 122 |
+
return pdf_docs + hg_docs
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
docs = load_all_documents()
|
| 127 |
+
print("📚 Gesamt:", len(docs))
|
| 128 |
+
print("🔎 Beispiel metadata:", docs[0].metadata)
|
rag_pipeline.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
RAG PIPELINE – Version 26.11 (ohne Modi, stabil, juristisch korrekt)
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
# from typing import List, Dict, Any, Tuple
|
| 6 |
+
# from langchain_core.messages import SystemMessage, HumanMessage
|
| 7 |
+
# from load_documents import DATASET, PDF_FILE, HTML_FILE
|
| 8 |
+
|
| 9 |
+
# from typing import List, Dict, Any, Tuple
|
| 10 |
+
# import os
|
| 11 |
+
# from langchain_core.messages import SystemMessage, HumanMessage
|
| 12 |
+
# from load_documents import DATASET, PDF_FILE
|
| 13 |
+
|
| 14 |
+
# 5.12_2:13
|
| 15 |
+
from typing import List, Dict, Any, Tuple
|
| 16 |
+
from langchain_core.messages import SystemMessage, HumanMessage
|
| 17 |
+
|
| 18 |
+
MAX_CHARS = 900
|
| 19 |
+
|
| 20 |
+
# ============================================================
|
| 21 |
+
# Quellenaufbereitung – NUR metadata verwenden!
|
| 22 |
+
# ============================================================
|
| 23 |
+
|
| 24 |
+
def build_sources_metadata(docs: List) -> List[Dict[str, Any]]:
|
| 25 |
+
sources = []
|
| 26 |
+
|
| 27 |
+
for idx, d in enumerate(docs):
|
| 28 |
+
meta = d.metadata
|
| 29 |
+
snippet = d.page_content[:300].replace("\n", " ")
|
| 30 |
+
|
| 31 |
+
# PDF
|
| 32 |
+
if meta.get("type") == "pdf":
|
| 33 |
+
sources.append({
|
| 34 |
+
"id": idx + 1,
|
| 35 |
+
"source": "Prüfungsordnung (PDF)",
|
| 36 |
+
"page": meta.get("page"),
|
| 37 |
+
"url": meta.get("pdf_url"), # KHÔNG tạo lại!
|
| 38 |
+
"snippet": snippet,
|
| 39 |
+
})
|
| 40 |
+
continue
|
| 41 |
+
|
| 42 |
+
# Hochschulgesetz NRW
|
| 43 |
+
if meta.get("type") == "hg":
|
| 44 |
+
sources.append({
|
| 45 |
+
"id": idx + 1,
|
| 46 |
+
"source": "Hochschulgesetz NRW",
|
| 47 |
+
"page": None,
|
| 48 |
+
"url": meta.get("viewer_url"), # KHÔNG tạo lại!
|
| 49 |
+
"snippet": snippet,
|
| 50 |
+
})
|
| 51 |
+
continue
|
| 52 |
+
|
| 53 |
+
return sources
|
| 54 |
+
|
| 55 |
+
# ============================================================
|
| 56 |
+
# Kontextaufbereitung
|
| 57 |
+
# ============================================================
|
| 58 |
+
|
| 59 |
+
def format_context(docs: List) -> str:
|
| 60 |
+
if not docs:
|
| 61 |
+
return "(Kein relevanter Kontext gefunden.)"
|
| 62 |
+
|
| 63 |
+
blocks = []
|
| 64 |
+
|
| 65 |
+
for i, d in enumerate(docs):
|
| 66 |
+
meta = d.metadata
|
| 67 |
+
doc_type = meta.get("type")
|
| 68 |
+
|
| 69 |
+
label = "Prüfungsordnung" if doc_type == "pdf" else "Hochschulgesetz NRW"
|
| 70 |
+
|
| 71 |
+
if doc_type == "pdf":
|
| 72 |
+
page = meta.get("page")
|
| 73 |
+
label += f", Seite {page+1}" if isinstance(page, int) else ""
|
| 74 |
+
|
| 75 |
+
blocks.append(
|
| 76 |
+
f"[KONTEXT {i+1}] ({label})\n{d.page_content[:MAX_CHARS]}"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
return "\n\n".join(blocks)
|
| 80 |
+
|
| 81 |
+
# -----------------------------
|
| 82 |
+
# Systemprompt — verschärft
|
| 83 |
+
# -----------------------------
|
| 84 |
+
|
| 85 |
+
SYSTEM_PROMPT = """
|
| 86 |
+
Du bist ein hochpräziser juristischer Chatbot für Prüfungsrecht
|
| 87 |
+
mit Zugriff nur auf:
|
| 88 |
+
- die Prüfungsordnung (als PDF) und
|
| 89 |
+
- das Hochschulgesetz NRW (als HTML aus der offiziellen Druckversion).
|
| 90 |
+
Strenge Regeln:
|
| 91 |
+
1. Antworte ausschließlich anhand des bereitgestellten Kontextes
|
| 92 |
+
(KONTEXT-Abschnitte). Wenn die Information nicht im Kontext steht,
|
| 93 |
+
sage ausdrücklich, dass dies aus den vorliegenden Dokumenten nicht
|
| 94 |
+
hervorgeht und du dazu nichts Sicheres sagen kannst.
|
| 95 |
+
2.
|
| 96 |
+
Keine Spekulationen, keine Vermutungen.
|
| 97 |
+
3. Antworte in zusammenhängenden, ganzen Sätzen. Verwende keine Mischung aus Deutsch und Englisch.
|
| 98 |
+
4. Nenne, soweit aus dem Kontext erkennbar,
|
| 99 |
+
- die rechtliche Grundlage (z.B. Paragraph, Artikel),
|
| 100 |
+
- das Dokument (Prüfungsordnung / Hochschulgesetz NRW),
|
| 101 |
+
- die Seite (bei der Prüfungsordnung), wenn im Kontext vorhanden.
|
| 102 |
+
5. Füge KEINE externen Informationen hinzu, z.B. aus anderen Gesetzen,
|
| 103 |
+
Webseiten oder allgemeinem Wissen. Nur das, was im Kontext steht,
|
| 104 |
+
darf in der Antwort verwendet werden.
|
| 105 |
+
Wenn der Kontext keine eindeutige Antwort zulässt, erkläre klar,
|
| 106 |
+
warum keine sichere Antwort möglich ist und welche Informationen
|
| 107 |
+
im Dokument fehlen.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
# -----------------------------
|
| 111 |
+
# Hauptfunktion
|
| 112 |
+
# -----------------------------
|
| 113 |
+
|
| 114 |
+
def answer(question: str, retriever, chat_model) -> Tuple[str, List[Dict[str, Any]]]:
|
| 115 |
+
"""
|
| 116 |
+
Haupt-RAG-Funktion:
|
| 117 |
+
- ruft retriever.invoke(question) auf,
|
| 118 |
+
- baut einen präzisen Prompt mit KONTEXT,
|
| 119 |
+
- ruft LLM auf,
|
| 120 |
+
- gibt Antworttext + Quellenliste zurück.
|
| 121 |
+
"""
|
| 122 |
+
# 1. Dokumente holen
|
| 123 |
+
docs = retriever.invoke(question)
|
| 124 |
+
context_str = format_context(docs)
|
| 125 |
+
|
| 126 |
+
# 2. Prompt bauen
|
| 127 |
+
user_prompt = f"""
|
| 128 |
+
FRAGE:
|
| 129 |
+
{question}
|
| 130 |
+
NUTZE AUSSCHLIESSLICH DIESEN KONTEXT:
|
| 131 |
+
{context_str}
|
| 132 |
+
AUFGABE:
|
| 133 |
+
Formuliere eine juristisch korrekte, gut verständliche Antwort
|
| 134 |
+
ausschließlich anhand des obigen Kontextes.
|
| 135 |
+
- Wenn der Kontext aus den Dokumenten eine klare Antwort erlaubt,
|
| 136 |
+
erläutere diese strukturiert und in vollständigen Sätzen.
|
| 137 |
+
- Wenn der Kontext KEINE klare Antwort erlaubt oder wichtige Informationen
|
| 138 |
+
fehlen, erkläre das offen und formuliere KEINE Vermutung.
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
msgs = [
|
| 142 |
+
SystemMessage(content=SYSTEM_PROMPT),
|
| 143 |
+
HumanMessage(content=user_prompt),
|
| 144 |
+
]
|
| 145 |
+
|
| 146 |
+
# 3. LLM aufrufen
|
| 147 |
+
result = chat_model.invoke(msgs)
|
| 148 |
+
answer_text = result.content.strip()
|
| 149 |
+
|
| 150 |
+
# 4. Quellenliste bauen
|
| 151 |
+
sources = build_sources_metadata(docs)
|
| 152 |
+
|
| 153 |
+
return answer_text, sources
|
requirements.txt
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# === UI ===
|
| 2 |
+
gradio
|
| 3 |
+
gradio_pdf
|
| 4 |
+
|
| 5 |
+
# === Supabase ===
|
| 6 |
+
supabase
|
| 7 |
+
postgrest
|
| 8 |
+
httpx
|
| 9 |
+
python-dotenv
|
| 10 |
+
|
| 11 |
+
# === LangChain Core ===
|
| 12 |
+
langchain
|
| 13 |
+
langchain-community
|
| 14 |
+
langchain-text-splitters
|
| 15 |
+
langchain-openai
|
| 16 |
+
huggingface-hub
|
| 17 |
+
|
| 18 |
+
# === VectorStore ===
|
| 19 |
+
faiss-cpu
|
| 20 |
+
|
| 21 |
+
# === PDF + HTTP + HTML ===
|
| 22 |
+
pypdf
|
| 23 |
+
requests
|
| 24 |
+
beautifulsoup4
|
| 25 |
+
lxml
|
| 26 |
+
|
| 27 |
+
# === Audio (STT/TTS local) ===
|
| 28 |
+
transformers
|
| 29 |
+
accelerate
|
| 30 |
+
soundfile
|
| 31 |
+
scipy
|
| 32 |
+
numpy
|
| 33 |
+
torchaudio
|
| 34 |
+
torch
|
| 35 |
+
librosa
|
| 36 |
+
|
| 37 |
+
# === OpenAI + HF Hub ===
|
| 38 |
+
openai
|
| 39 |
+
huggingface_hub
|
retriever.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BƯỚC 5: RETRIEVER
|
| 3 |
+
-----------------
|
| 4 |
+
Tạo LangChain Retriever từ FAISS VectorStore.
|
| 5 |
+
Retriever sẽ dùng trong bước RAG sau này:
|
| 6 |
+
- retriever.get_relevant_documents(query)
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from langchain_community.vectorstores import FAISS
|
| 10 |
+
|
| 11 |
+
# số chunk sẽ lấy cho mỗi câu hỏi
|
| 12 |
+
RETRIEVER_K = 4
|
| 13 |
+
|
| 14 |
+
def get_retriever(vectorstore: FAISS, k: int = RETRIEVER_K):
|
| 15 |
+
"""
|
| 16 |
+
Tạo retriever từ FAISS VectorStore.
|
| 17 |
+
"""
|
| 18 |
+
print(f">>> Creating retriever with k={k} ...")
|
| 19 |
+
retriever = vectorstore.as_retriever(search_kwargs={"k": k})
|
| 20 |
+
print(">>> Retriever ready.\n")
|
| 21 |
+
return retriever
|
| 22 |
+
|
| 23 |
+
if __name__ == "__main__":
|
| 24 |
+
# Test: load -> split -> FAISS -> retriever.get_relevant_documents()
|
| 25 |
+
from load_documents import load_documents
|
| 26 |
+
from split_documents import split_documents
|
| 27 |
+
from vectorstore import build_vectorstore
|
| 28 |
+
|
| 29 |
+
print("=== TEST: retriever.get_relevant_documents ===\n")
|
| 30 |
+
|
| 31 |
+
docs = load_documents()
|
| 32 |
+
chunks = split_documents(docs)
|
| 33 |
+
vs = build_vectorstore(chunks)
|
| 34 |
+
retriever = get_retriever(vs, k=4)
|
| 35 |
+
|
| 36 |
+
query = "Wie lange habe ich Zeit, eine Prüfungsleistung zu wiederholen?"
|
| 37 |
+
print("Test query:")
|
| 38 |
+
print(" ", query, "\n")
|
| 39 |
+
|
| 40 |
+
retrieved_docs = retriever.invoke(query)
|
| 41 |
+
|
| 42 |
+
print(f"Retriever returned {len(retrieved_docs)} documents.")
|
| 43 |
+
for i, d in enumerate(retrieved_docs, start=1):
|
| 44 |
+
print(f"\n=== DOC {i} ===")
|
| 45 |
+
print(d.page_content[:400], "...")
|
| 46 |
+
print("Metadata:", d.metadata)
|
speech_io.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import soundfile as sf
|
| 3 |
+
import librosa
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
|
| 6 |
+
ASR_MODEL_ID = "openai/whisper-small" # multilingual
|
| 7 |
+
TTS_MODEL_ID = "facebook/mms-tts-deu" # bạn có thể thay nếu muốn đa ngôn ngữ
|
| 8 |
+
|
| 9 |
+
_asr = None
|
| 10 |
+
_tts = None
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# ============================================
|
| 14 |
+
# LOAD AUDIO – chuẩn hóa 16kHz mono
|
| 15 |
+
# ============================================
|
| 16 |
+
def load_audio_16k(path):
|
| 17 |
+
audio, sr = sf.read(path)
|
| 18 |
+
|
| 19 |
+
# Stereo → Mono
|
| 20 |
+
if audio.ndim > 1:
|
| 21 |
+
audio = audio.mean(axis=1)
|
| 22 |
+
|
| 23 |
+
# Resample → 16kHz
|
| 24 |
+
if sr != 16000:
|
| 25 |
+
audio = librosa.resample(audio, orig_sr=sr, target_sr=16000)
|
| 26 |
+
sr = 16000
|
| 27 |
+
|
| 28 |
+
return audio.astype(np.float32), sr
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# ============================================
|
| 32 |
+
# LOAD WHISPER PIPELINE (multilingual)
|
| 33 |
+
# ============================================
|
| 34 |
+
def get_asr_pipeline():
|
| 35 |
+
global _asr
|
| 36 |
+
if _asr is None:
|
| 37 |
+
_asr = pipeline(
|
| 38 |
+
task="automatic-speech-recognition",
|
| 39 |
+
model=ASR_MODEL_ID,
|
| 40 |
+
return_timestamps=False,
|
| 41 |
+
chunk_length_s=30,
|
| 42 |
+
)
|
| 43 |
+
return _asr
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# ============================================
|
| 47 |
+
# MULTILINGUAL STT
|
| 48 |
+
# ============================================
|
| 49 |
+
def transcribe_audio(audio_path: str) -> str:
|
| 50 |
+
if audio_path is None:
|
| 51 |
+
return ""
|
| 52 |
+
|
| 53 |
+
audio, sr = load_audio_16k(audio_path)
|
| 54 |
+
|
| 55 |
+
# Nếu quá ngắn → Whisper sẽ sinh ký tự rác
|
| 56 |
+
if len(audio) < sr * 0.4:
|
| 57 |
+
return ""
|
| 58 |
+
|
| 59 |
+
asr = get_asr_pipeline()
|
| 60 |
+
|
| 61 |
+
# Không đặt language → Whisper tự detect ngôn ngữ
|
| 62 |
+
result = asr(
|
| 63 |
+
{"array": audio, "sampling_rate": sr},
|
| 64 |
+
generate_kwargs={
|
| 65 |
+
"task": "transcribe", # không translate — giữ nguyên ngôn ngữ gốc
|
| 66 |
+
"temperature": 0.0 # giảm hallucination như "ვვვ..."
|
| 67 |
+
}
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
text = result.get("text", "").strip()
|
| 71 |
+
|
| 72 |
+
# Fix edge case: nếu Whisper trả về ký tự vô nghĩa → bỏ qua
|
| 73 |
+
if set(text) <= {"ვ", " "}:
|
| 74 |
+
return ""
|
| 75 |
+
|
| 76 |
+
return text
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# ============================================
|
| 80 |
+
# TEXT → SPEECH (chưa multilingual)
|
| 81 |
+
# ============================================
|
| 82 |
+
def get_tts_pipeline():
|
| 83 |
+
global _tts
|
| 84 |
+
if _tts is None:
|
| 85 |
+
_tts = pipeline(task="text-to-speech", model=TTS_MODEL_ID)
|
| 86 |
+
return _tts
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def synthesize_speech(text: str):
|
| 90 |
+
if not text.strip():
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
tts = get_tts_pipeline()
|
| 94 |
+
out = tts(text)
|
| 95 |
+
|
| 96 |
+
audio = np.array(out["audio"], dtype=np.float32)
|
| 97 |
+
sr = out.get("sampling_rate", 16000)
|
| 98 |
+
|
| 99 |
+
max_val = np.max(np.abs(audio)) or 1.0
|
| 100 |
+
audio = audio / max_val
|
| 101 |
+
|
| 102 |
+
return sr, (audio * 32767).astype(np.int16)
|
split_documents.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# split_documents.py – v2
|
| 2 |
+
|
| 3 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 4 |
+
|
| 5 |
+
CHUNK_SIZE = 1500
|
| 6 |
+
CHUNK_OVERLAP = 200
|
| 7 |
+
|
| 8 |
+
def split_documents(docs):
|
| 9 |
+
splitter = RecursiveCharacterTextSplitter(
|
| 10 |
+
chunk_size=CHUNK_SIZE,
|
| 11 |
+
chunk_overlap=CHUNK_OVERLAP,
|
| 12 |
+
separators=["\n\n", "\n", ". ", " ", ""],
|
| 13 |
+
)
|
| 14 |
+
chunks = splitter.split_documents(docs)
|
| 15 |
+
|
| 16 |
+
for c in chunks:
|
| 17 |
+
c.metadata["chunk_size"] = CHUNK_SIZE
|
| 18 |
+
c.metadata["chunk_overlap"] = CHUNK_OVERLAP
|
| 19 |
+
|
| 20 |
+
return chunks
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
from load_documents import load_documents
|
| 24 |
+
docs = load_documents()
|
| 25 |
+
chunks = split_documents(docs)
|
| 26 |
+
print("Docs:", len(docs), "Chunks:", len(chunks))
|
| 27 |
+
print(chunks[0].page_content[:300], chunks[0].metadata)
|
upload_weblink_to_supabase.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
from bs4 import BeautifulSoup
|
| 4 |
+
from supabase import create_client
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
|
| 7 |
+
load_dotenv()
|
| 8 |
+
|
| 9 |
+
SUPABASE_URL = os.environ["SUPABASE_URL"]
|
| 10 |
+
SUPABASE_SERVICE_ROLE = os.environ["SUPABASE_SERVICE_ROLE"]
|
| 11 |
+
|
| 12 |
+
supabase = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE)
|
| 13 |
+
|
| 14 |
+
# URL CHÍNH THỨC – không dùng Druckversion
|
| 15 |
+
LAW_URL = "https://recht.nrw.de/lmi/owa/br_text_anzeigen?v_id=10000000000000000654"
|
| 16 |
+
|
| 17 |
+
def extract_paragraphs():
|
| 18 |
+
"""
|
| 19 |
+
Lädt die aktuelle Fassung des Hochschulgesetzes NRW
|
| 20 |
+
von recht.nrw.de (br_text_anzeigen) und extrahiert Paragraphen.
|
| 21 |
+
Ergebnis: Liste von Dicts mit:
|
| 22 |
+
- abs_id: para_1, para_2, ...
|
| 23 |
+
- title: "§ 1 ...", "§ 2 ..."
|
| 24 |
+
- content: gesamter Text des Paragraphen
|
| 25 |
+
- order_index: laufende Nummer
|
| 26 |
+
"""
|
| 27 |
+
print(">>> Lade offizielles Hochschulgesetz NRW von recht.nrw.de …")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# html = requests.get(LAW_URL, timeout=30).text
|
| 31 |
+
# soup = BeautifulSoup(html, "html.parser")
|
| 32 |
+
# 5.12_2:13
|
| 33 |
+
resp = requests.get(LAW_URL, timeout=30)
|
| 34 |
+
resp.raise_for_status()
|
| 35 |
+
soup = BeautifulSoup(resp.text, "html.parser")
|
| 36 |
+
|
| 37 |
+
# 5.12_2:13
|
| 38 |
+
# Paragraph-Überschriften: häufig in <p>, <b> oder <strong>
|
| 39 |
+
candidates = soup.find_all(["p", "b", "strong"])
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# Tất cả tiêu đề Paragraph xuất hiện trong <h2> hoặc <h3>
|
| 43 |
+
headers = soup.find_all(["h2", "h3"])
|
| 44 |
+
|
| 45 |
+
paragraphs = []
|
| 46 |
+
order = 1
|
| 47 |
+
|
| 48 |
+
# for header in headers:
|
| 49 |
+
# title = header.get_text(" ", strip=True)
|
| 50 |
+
|
| 51 |
+
# if not title.startswith("§"):
|
| 52 |
+
# continue # bỏ các h2/h3 không phải Paragraph
|
| 53 |
+
|
| 54 |
+
# # Gom toàn bộ nội dung từ header đến trước h2/h3 tiếp theo
|
| 55 |
+
# content_parts = []
|
| 56 |
+
# sibling = header.find_next_sibling()
|
| 57 |
+
|
| 58 |
+
# while sibling and sibling.name not in ["h2", "h3"]:
|
| 59 |
+
# text = sibling.get_text(" ", strip=True)
|
| 60 |
+
# if text:
|
| 61 |
+
# content_parts.append(text)
|
| 62 |
+
# sibling = sibling.find_next_sibling()
|
| 63 |
+
|
| 64 |
+
# full_content = "\n".join(content_parts).strip()
|
| 65 |
+
|
| 66 |
+
# para_id = f"para_{order}"
|
| 67 |
+
|
| 68 |
+
# paragraphs.append({
|
| 69 |
+
# "abs_id": para_id,
|
| 70 |
+
# "title": title,
|
| 71 |
+
# "content": full_content,
|
| 72 |
+
# "order_index": order
|
| 73 |
+
# })
|
| 74 |
+
|
| 75 |
+
# order += 1
|
| 76 |
+
|
| 77 |
+
# print(f"✔ Extracted {len(paragraphs)} paragraphs (§).")
|
| 78 |
+
# return paragraphs
|
| 79 |
+
# 5.12_2:13
|
| 80 |
+
for tag in candidates:
|
| 81 |
+
text = tag.get_text(" ", strip=True)
|
| 82 |
+
if not text.startswith("§"):
|
| 83 |
+
continue
|
| 84 |
+
|
| 85 |
+
title = text
|
| 86 |
+
content_parts = []
|
| 87 |
+
sibling = tag.find_next_sibling()
|
| 88 |
+
|
| 89 |
+
while sibling and not (
|
| 90 |
+
(sibling.name in ["p", "b", "strong"])
|
| 91 |
+
and sibling.get_text(" ", strip=True).startswith("§")
|
| 92 |
+
):
|
| 93 |
+
txt = sibling.get_text(" ", strip=True)
|
| 94 |
+
if txt:
|
| 95 |
+
content_parts.append(txt)
|
| 96 |
+
sibling = sibling.find_next_sibling()
|
| 97 |
+
|
| 98 |
+
full_content = "\n".join(content_parts).strip()
|
| 99 |
+
abs_id = f"para_{order}"
|
| 100 |
+
|
| 101 |
+
paragraphs.append(
|
| 102 |
+
{
|
| 103 |
+
"abs_id": abs_id,
|
| 104 |
+
"title": title,
|
| 105 |
+
"content": full_content,
|
| 106 |
+
"order_index": order,
|
| 107 |
+
}
|
| 108 |
+
)
|
| 109 |
+
order += 1
|
| 110 |
+
|
| 111 |
+
print(f"✔ {len(paragraphs)} Paragraphen extrahiert.")
|
| 112 |
+
return paragraphs
|
| 113 |
+
|
| 114 |
+
def upload_to_supabase():
|
| 115 |
+
paras = extract_paragraphs()
|
| 116 |
+
|
| 117 |
+
print(">>> Leere Tabelle hg_nrw …")
|
| 118 |
+
supabase.table("hg_nrw").delete().neq("abs_id", "").execute()
|
| 119 |
+
|
| 120 |
+
print(">>> Upload nach Supabase …")
|
| 121 |
+
BATCH = 100
|
| 122 |
+
for i in range(0, len(paras), BATCH):
|
| 123 |
+
batch = paras[i:i+BATCH]
|
| 124 |
+
print(f" - Upload batch {i} – {i+len(batch)-1}")
|
| 125 |
+
supabase.table("hg_nrw").upsert(batch).execute()
|
| 126 |
+
|
| 127 |
+
print("✔ DONE uploading complete NRW law.")
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
upload_to_supabase()
|
vectorstore.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BƯỚC 4: VECTORSTORE (FAISS in-memory)
|
| 3 |
+
-------------------------------------
|
| 4 |
+
Tạo FAISS index từ các CHUNK văn bản.
|
| 5 |
+
- Không ghi file .faiss nào, tất cả nằm trong RAM.
|
| 6 |
+
- Embeddings được lấy từ get_embeddings() (Bước 3).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from langchain_community.vectorstores import FAISS
|
| 10 |
+
from embeddings import get_embeddings
|
| 11 |
+
|
| 12 |
+
def build_vectorstore(chunks):
|
| 13 |
+
"""
|
| 14 |
+
Nhận danh sách Document (đã split) và trả về FAISS VectorStore.
|
| 15 |
+
"""
|
| 16 |
+
print(">>> Initialising embedding model for FAISS index ...")
|
| 17 |
+
embeddings = get_embeddings()
|
| 18 |
+
|
| 19 |
+
print(f">>> Building FAISS index from {len(chunks)} chunks ...")
|
| 20 |
+
vs = FAISS.from_documents(chunks, embeddings)
|
| 21 |
+
print(">>> FAISS index built.\n")
|
| 22 |
+
return vs
|
| 23 |
+
|
| 24 |
+
if __name__ == "__main__":
|
| 25 |
+
# Test toàn pipeline: load -> split -> FAISS -> similarity_search
|
| 26 |
+
from load_documents import load_documents
|
| 27 |
+
from split_documents import split_documents
|
| 28 |
+
|
| 29 |
+
print("=== TEST: load_documents -> split_documents -> FAISS.similarity_search ===\n")
|
| 30 |
+
|
| 31 |
+
# 1) Load tài liệu (PDF + HTML) từ HuggingFace
|
| 32 |
+
docs = load_documents()
|
| 33 |
+
|
| 34 |
+
# 2) Split thành chunks
|
| 35 |
+
from pprint import pprint
|
| 36 |
+
print(f"Loaded {len(docs)} raw documents.")
|
| 37 |
+
chunks = split_documents(docs)
|
| 38 |
+
print(f"Split into {len(chunks)} chunks.\n")
|
| 39 |
+
|
| 40 |
+
# 3) Xây FAISS vectorstore
|
| 41 |
+
vectorstore = build_vectorstore(chunks)
|
| 42 |
+
|
| 43 |
+
# 4) Test similarity_search
|
| 44 |
+
query = "Fristen für die Prüfungsanmeldung im Bachelorstudium"
|
| 45 |
+
print("Test query:")
|
| 46 |
+
print(" ", query, "\n")
|
| 47 |
+
|
| 48 |
+
results = vectorstore.similarity_search(query, k=3)
|
| 49 |
+
|
| 50 |
+
print("Top-3 ähnliche Chunks aus dem VectorStore:")
|
| 51 |
+
for i, doc in enumerate(results, start=1):
|
| 52 |
+
print(f"\n=== RESULT {i} ===")
|
| 53 |
+
print(doc.page_content[:400], "...")
|
| 54 |
+
print("Metadata:", doc.metadata)
|
| 55 |
+
|
| 56 |
+
|