263 lines
11 KiB
Python
263 lines
11 KiB
Python
import streamlit as st
|
|
import requests
|
|
import uuid
|
|
import os
|
|
import json
|
|
import re
|
|
from pathlib import Path
|
|
from dotenv import load_dotenv
|
|
|
|
# --- CONFIGURATION ---
|
|
load_dotenv()
|
|
API_BASE_URL = os.getenv("MINDNET_API_URL", "http://localhost:8002")
|
|
CHAT_ENDPOINT = f"{API_BASE_URL}/chat"
|
|
FEEDBACK_ENDPOINT = f"{API_BASE_URL}/feedback"
|
|
HISTORY_FILE = Path("data/logs/search_history.jsonl")
|
|
|
|
# Timeout Strategy
|
|
timeout_setting = os.getenv("MINDNET_API_TIMEOUT") or os.getenv("MINDNET_LLM_TIMEOUT")
|
|
API_TIMEOUT = float(timeout_setting) if timeout_setting else 300.0
|
|
|
|
# --- PAGE SETUP ---
|
|
st.set_page_config(page_title="mindnet v2.3.2", page_icon="🧠", layout="wide")
|
|
|
|
# --- CSS STYLING ---
|
|
st.markdown("""
|
|
<style>
|
|
/* Hauptcontainer enger machen für Lesbarkeit */
|
|
.block-container { padding-top: 2rem; max_width: 900px; margin: auto; }
|
|
|
|
/* Intent Badges */
|
|
.intent-badge {
|
|
background-color: #e8f0fe; color: #1a73e8;
|
|
padding: 4px 10px; border-radius: 12px;
|
|
font-size: 0.8rem; font-weight: 600;
|
|
border: 1px solid #d2e3fc; display: inline-block; margin-bottom: 0.5rem;
|
|
}
|
|
|
|
/* Chat Message Styling */
|
|
.stChatMessage { padding: 1rem; border-radius: 8px; margin-bottom: 1rem;}
|
|
div[data-testid="stChatMessageContent"] p { font-size: 1.05rem; line-height: 1.6; }
|
|
|
|
/* Expander Cleaner */
|
|
.streamlit-expanderHeader { font-size: 0.9rem; font-weight: 600; color: #444; }
|
|
|
|
/* Editor Label */
|
|
.editor-label { font-weight: bold; margin-bottom: 5px; display: block; color: #333; }
|
|
</style>
|
|
""", unsafe_allow_html=True)
|
|
|
|
# --- SESSION STATE ---
|
|
if "messages" not in st.session_state: st.session_state.messages = []
|
|
if "user_id" not in st.session_state: st.session_state.user_id = str(uuid.uuid4())
|
|
if "draft_note" not in st.session_state: st.session_state.draft_note = {"title": "", "content": "", "type": "concept"}
|
|
|
|
# --- HELPER FUNCTIONS ---
|
|
|
|
def extract_markdown_content(text):
|
|
"""Extrahiert den Inhalt aus einem Markdown-Codeblock."""
|
|
pattern = r"```markdown\s*(.*?)\s*```"
|
|
match = re.search(pattern, text, re.DOTALL)
|
|
if match:
|
|
return match.group(1).strip()
|
|
return text # Fallback: Ganzen Text zurückgeben, wenn kein Block gefunden
|
|
|
|
def load_history_from_logs(limit=10):
|
|
"""Liest die letzten N Queries aus dem Logfile."""
|
|
queries = []
|
|
if HISTORY_FILE.exists():
|
|
try:
|
|
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
|
|
lines = f.readlines()
|
|
for line in reversed(lines):
|
|
try:
|
|
entry = json.loads(line)
|
|
q = entry.get("query_text")
|
|
if q and q not in queries:
|
|
queries.append(q)
|
|
if len(queries) >= limit: break
|
|
except: continue
|
|
except Exception as e:
|
|
st.sidebar.warning(f"Log-Fehler: {e}")
|
|
return queries
|
|
|
|
def send_chat_message(message: str, top_k: int, explain: bool):
|
|
try:
|
|
response = requests.post(
|
|
CHAT_ENDPOINT,
|
|
json={"message": message, "top_k": top_k, "explain": explain},
|
|
timeout=API_TIMEOUT
|
|
)
|
|
response.raise_for_status()
|
|
return response.json()
|
|
except Exception as e:
|
|
return {"error": str(e)}
|
|
|
|
def submit_feedback(query_id, node_id, score, comment=None):
|
|
try:
|
|
requests.post(FEEDBACK_ENDPOINT, json={"query_id": query_id, "node_id": node_id, "score": score, "comment": comment}, timeout=2)
|
|
target = "Antwort" if node_id == "generated_answer" else "Quelle"
|
|
st.toast(f"Feedback für {target} gespeichert! (Score: {score})")
|
|
except: pass
|
|
|
|
# --- UI COMPONENTS ---
|
|
|
|
def render_sidebar():
|
|
with st.sidebar:
|
|
st.title("🧠 mindnet")
|
|
st.caption("v2.3.2 | WP-10 UI")
|
|
|
|
mode = st.radio("Modus", ["💬 Chat", "📝 Manueller Eintrag"], index=0)
|
|
|
|
st.divider()
|
|
st.subheader("⚙️ Settings")
|
|
top_k = st.slider("Quellen (Top-K)", 1, 10, 5)
|
|
explain = st.toggle("Explanation Layer", True)
|
|
|
|
st.divider()
|
|
st.subheader("🕒 Verlauf")
|
|
history = load_history_from_logs(8)
|
|
if not history:
|
|
st.caption("Noch keine Einträge.")
|
|
for q in history:
|
|
if st.button(f"🔎 {q[:30]}...", key=f"hist_{q}", help=q, use_container_width=True):
|
|
st.session_state.messages.append({"role": "user", "content": q})
|
|
st.rerun()
|
|
|
|
return mode, top_k, explain
|
|
|
|
def render_chat_interface(top_k, explain):
|
|
# Render History
|
|
for msg in st.session_state.messages:
|
|
with st.chat_message(msg["role"]):
|
|
if msg["role"] == "assistant":
|
|
# 1. INTENT BADGE (mit Source)
|
|
if "intent" in msg:
|
|
intent = msg["intent"]
|
|
icon = {"EMPATHY": "❤️", "DECISION": "⚖️", "CODING": "💻", "FACT": "📚", "INTERVIEW": "📝"}.get(intent, "🧠")
|
|
source_info = msg.get("intent_source", "Unknown")
|
|
st.markdown(f'<div class="intent-badge">{icon} Intent: {intent} <span style="opacity:0.6; font-size: 0.9em; margin-left:5px;">via {source_info}</span></div>', unsafe_allow_html=True)
|
|
|
|
# 2. CONTENT RENDERING (Weiche für INTERVIEW vs. NORMAL)
|
|
if msg.get("intent") == "INTERVIEW":
|
|
# --- INTERVIEW EDITOR MODUS ---
|
|
|
|
# Markdown extrahieren (nur beim ersten Mal, dann aus State)
|
|
raw_content = msg["content"]
|
|
draft_content = extract_markdown_content(raw_content)
|
|
|
|
# Eindeutiger Key für diesen Editor (basierend auf query_id)
|
|
editor_key = f"editor_{msg.get('query_id', uuid.uuid4())}"
|
|
|
|
# Init State falls noch nicht vorhanden
|
|
if editor_key not in st.session_state:
|
|
st.session_state[editor_key] = draft_content
|
|
|
|
st.markdown('<span class="editor-label">Entwurf bearbeiten (Draft):</span>', unsafe_allow_html=True)
|
|
|
|
# Der Editor
|
|
edited_text = st.text_area(
|
|
label="Editor",
|
|
value=st.session_state[editor_key],
|
|
height=350,
|
|
key=editor_key,
|
|
label_visibility="collapsed"
|
|
)
|
|
|
|
# Action Buttons
|
|
c1, c2 = st.columns([1, 1])
|
|
with c1:
|
|
st.download_button(
|
|
label="💾 Als .md herunterladen",
|
|
data=edited_text,
|
|
file_name=f"draft_{msg.get('query_id', 'unknown')[:8]}.md",
|
|
mime="text/markdown"
|
|
)
|
|
with c2:
|
|
# Copy Mockup (Browser-Security verhindert oft direkten Zugriff)
|
|
if st.button("📋 In Zwischenablage kopieren", key=f"copy_{editor_key}"):
|
|
st.toast("Tipp: Klicke in das Textfeld, drücke Strg+A dann Strg+C.")
|
|
|
|
else:
|
|
# --- STANDARD CHAT MODUS ---
|
|
st.markdown(msg["content"])
|
|
|
|
# 3. SOURCES (Nur anzeigen, wenn vorhanden)
|
|
if "sources" in msg and msg["sources"]:
|
|
for hit in msg["sources"]:
|
|
score = hit.get('total_score', 0)
|
|
icon = "🟢" if score > 0.8 else "🟡" if score > 0.5 else "⚪"
|
|
with st.expander(f"{icon} {hit.get('note_id', '?')} ({score:.2f})"):
|
|
st.markdown(f"_{hit.get('source', {}).get('text', '')[:300]}..._")
|
|
if hit.get('explanation'):
|
|
st.caption(f"Grund: {hit['explanation']['reasons'][0]['message']}")
|
|
|
|
# Granular Feedback
|
|
def _cb(qid=msg["query_id"], nid=hit['node_id']):
|
|
val = st.session_state.get(f"fb_src_{qid}_{nid}")
|
|
if val is not None: submit_feedback(qid, nid, val+1, "Faces UI")
|
|
|
|
st.feedback("faces", key=f"fb_src_{msg['query_id']}_{hit['node_id']}", on_change=_cb)
|
|
|
|
# 4. GLOBAL FEEDBACK
|
|
if "query_id" in msg:
|
|
qid = msg["query_id"]
|
|
st.feedback("stars", key=f"fb_glob_{qid}", on_change=lambda: submit_feedback(qid, "generated_answer", st.session_state[f"fb_glob_{qid}"]+1))
|
|
|
|
else:
|
|
# User Message
|
|
st.markdown(msg["content"])
|
|
|
|
# Input Logic
|
|
last_msg_is_user = len(st.session_state.messages) > 0 and st.session_state.messages[-1]["role"] == "user"
|
|
|
|
if prompt := st.chat_input("Frage Mindnet... (z.B. 'Neues Projekt anlegen')"):
|
|
st.session_state.messages.append({"role": "user", "content": prompt})
|
|
st.rerun()
|
|
|
|
if last_msg_is_user:
|
|
last_prompt = st.session_state.messages[-1]["content"]
|
|
with st.chat_message("assistant"):
|
|
with st.spinner("Thinking..."):
|
|
resp = send_chat_message(last_prompt, top_k, explain)
|
|
|
|
if "error" in resp:
|
|
st.error(resp["error"])
|
|
else:
|
|
msg_data = {
|
|
"role": "assistant",
|
|
"content": resp.get("answer"),
|
|
"intent": resp.get("intent", "FACT"),
|
|
"intent_source": resp.get("intent_source", "Unknown"),
|
|
"sources": resp.get("sources", []),
|
|
"query_id": resp.get("query_id")
|
|
}
|
|
st.session_state.messages.append(msg_data)
|
|
st.rerun()
|
|
|
|
def render_creation_interface():
|
|
st.header("📝 Manueller Eintrag (Legacy)")
|
|
st.info("Nutze lieber den Chat ('Neues Projekt anlegen') für den Interview-Modus.")
|
|
|
|
with st.form("new_entry"):
|
|
col1, col2 = st.columns([3, 1])
|
|
title = col1.text_input("Titel der Notiz", placeholder="z.B. Projekt Gamma Meeting")
|
|
n_type = col2.selectbox("Typ", ["concept", "meeting", "person", "project", "decision"])
|
|
|
|
content = st.text_area("Inhalt (Markdown)", height=300, placeholder="# Protokoll\n\n- Punkt 1...")
|
|
|
|
st.markdown("**Automatische Vernetzung:**")
|
|
st.caption("Verwende `[[Link]]` für Referenzen und `[[rel:depends_on X]]` für logische Kanten.")
|
|
|
|
submitted = st.form_submit_button("💾 Speichern & Indizieren")
|
|
if submitted:
|
|
st.success(f"Mockup: Notiz '{title}' ({n_type}) wäre jetzt gespeichert worden!")
|
|
st.balloons()
|
|
|
|
# --- MAIN LOOP ---
|
|
mode, top_k, explain = render_sidebar()
|
|
|
|
if mode == "💬 Chat":
|
|
render_chat_interface(top_k, explain)
|
|
else:
|
|
render_creation_interface() |