WP07 #7

Merged
Lars merged 11 commits from WP07 into main 2025-12-10 18:57:14 +01:00
Showing only changes of commit 1fefc538ac - Show all commits

View File

@ -5,6 +5,7 @@ import os
import json import json
import re import re
import yaml import yaml
from datetime import datetime
from pathlib import Path from pathlib import Path
from dotenv import load_dotenv from dotenv import load_dotenv
@ -25,10 +26,8 @@ st.set_page_config(page_title="mindnet v2.3.2", page_icon="🧠", layout="wide")
# --- CSS STYLING --- # --- CSS STYLING ---
st.markdown(""" st.markdown("""
<style> <style>
/* Hauptcontainer enger machen für Lesbarkeit */
.block-container { padding-top: 2rem; max_width: 1000px; margin: auto; } .block-container { padding-top: 2rem; max_width: 1000px; margin: auto; }
/* Intent Badges */
.intent-badge { .intent-badge {
background-color: #e8f0fe; color: #1a73e8; background-color: #e8f0fe; color: #1a73e8;
padding: 4px 10px; border-radius: 12px; padding: 4px 10px; border-radius: 12px;
@ -36,20 +35,23 @@ st.markdown("""
border: 1px solid #d2e3fc; display: inline-block; margin-bottom: 0.5rem; border: 1px solid #d2e3fc; display: inline-block; margin-bottom: 0.5rem;
} }
/* Editor Styling */ /* Editor Box Styling */
.draft-box { .draft-box {
border: 1px solid #e0e0e0; border: 1px solid #d0d7de;
border-radius: 8px; border-radius: 6px;
padding: 15px; padding: 16px;
background-color: #fafafa; background-color: #f6f8fa;
margin-top: 10px; margin-top: 10px;
margin-bottom: 10px;
} }
/* Preview Styling mimics GitHub Markdown */
.preview-box { .preview-box {
border: 1px solid #e0e0e0; border: 1px solid #e0e0e0;
border-radius: 8px; border-radius: 6px;
padding: 20px; padding: 24px;
background-color: white; background-color: white;
margin-top: 10px; font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
} }
</style> </style>
""", unsafe_allow_html=True) """, unsafe_allow_html=True)
@ -62,15 +64,19 @@ if "user_id" not in st.session_state: st.session_state.user_id = str(uuid.uuid4(
def parse_markdown_draft(full_text): def parse_markdown_draft(full_text):
""" """
Zerlegt einen Markdown-Text in Frontmatter (Dict) und Body (String). Zerlegt die LLM-Antwort in Frontmatter (Dict) und Body (String).
Robust gegen Einleitungstexte vor dem Codeblock.
""" """
# 1. Versuch: Markdown Codeblock entfernen # 1. Extrahiere Codeblock
pattern_block = r"```markdown\s*(.*?)\s*```" pattern_block = r"```markdown\s*(.*?)\s*```"
match_block = re.search(pattern_block, full_text, re.DOTALL) match_block = re.search(pattern_block, full_text, re.DOTALL)
# Fallback: Wenn kein Codeblock, nimm ganzen Text
clean_text = match_block.group(1).strip() if match_block else full_text clean_text = match_block.group(1).strip() if match_block else full_text
# 2. Frontmatter parsen (YAML zwischen ---) # 2. Trenne Frontmatter (YAML) vom Body
pattern_fm = r"^---\s+(.*?)\s+---\s+(.*)$" # Sucht nach --- am Anfang, gefolgt von YAML, gefolgt von ---
pattern_fm = r"^---\s+(.*?)\s+---\s*(.*)$"
match_fm = re.search(pattern_fm, clean_text, re.DOTALL) match_fm = re.search(pattern_fm, clean_text, re.DOTALL)
if match_fm: if match_fm:
@ -78,15 +84,30 @@ def parse_markdown_draft(full_text):
body = match_fm.group(2) body = match_fm.group(2)
try: try:
meta = yaml.safe_load(yaml_str) or {} meta = yaml.safe_load(yaml_str) or {}
except: except Exception:
meta = {} meta = {} # Fallback bei kaputtem YAML
return meta, body return meta, body
else: else:
# Kein Frontmatter gefunden -> Alles ist Body
return {}, clean_text return {}, clean_text
def build_markdown_draft(meta, body): def generate_filename(meta):
"""Baut das Dokument aus Metadaten und Text wieder zusammen.""" """Generiert einen Dateinamen basierend auf Typ und Datum."""
yaml_str = yaml.dump(meta, default_flow_style=None, sort_keys=False).strip() date_str = datetime.now().strftime("%Y%m%d")
n_type = meta.get("type", "note")
# Versuche Titel aus Body zu raten wäre zu komplex, wir nehmen Generic
return f"{date_str}-{n_type}-draft.md"
def build_markdown_doc(meta, body):
"""Baut das finale Dokument zusammen."""
# ID Generierung beim 'Speichern' (hier simuliert für Download)
if "id" not in meta or meta["id"] == "generated_on_save":
meta["id"] = f"{datetime.now().strftime('%Y%m%d')}-{meta.get('type', 'note')}-{uuid.uuid4().hex[:6]}"
# Updated timestamp
meta["updated"] = datetime.now().strftime("%Y-%m-%d")
yaml_str = yaml.dump(meta, default_flow_style=None, sort_keys=False, allow_unicode=True).strip()
return f"---\n{yaml_str}\n---\n\n{body}" return f"---\n{yaml_str}\n---\n\n{body}"
def load_history_from_logs(limit=10): def load_history_from_logs(limit=10):
@ -103,8 +124,7 @@ def load_history_from_logs(limit=10):
queries.append(q) queries.append(q)
if len(queries) >= limit: break if len(queries) >= limit: break
except: continue except: continue
except Exception as e: except: pass
st.sidebar.warning(f"Log-Fehler: {e}")
return queries return queries
def send_chat_message(message: str, top_k: int, explain: bool): def send_chat_message(message: str, top_k: int, explain: bool):
@ -123,7 +143,7 @@ def submit_feedback(query_id, node_id, score, comment=None):
try: try:
requests.post(FEEDBACK_ENDPOINT, json={"query_id": query_id, "node_id": node_id, "score": score, "comment": comment}, timeout=2) 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" target = "Antwort" if node_id == "generated_answer" else "Quelle"
st.toast(f"Feedback für {target} gespeichert! (Score: {score})") st.toast(f"Feedback ({score}) gesendet!")
except: pass except: pass
# --- UI COMPONENTS --- # --- UI COMPONENTS ---
@ -133,7 +153,7 @@ def render_sidebar():
st.title("🧠 mindnet") st.title("🧠 mindnet")
st.caption("v2.3.2 | WP-10 UI") st.caption("v2.3.2 | WP-10 UI")
mode = st.radio("Modus", ["💬 Chat", "📝 Manueller Eintrag"], index=0) mode = st.radio("Modus", ["💬 Chat", "📝 Manueller Editor"], index=0)
st.divider() st.divider()
st.subheader("⚙️ Settings") st.subheader("⚙️ Settings")
@ -142,69 +162,75 @@ def render_sidebar():
st.divider() st.divider()
st.subheader("🕒 Verlauf") st.subheader("🕒 Verlauf")
history = load_history_from_logs(8) for q in load_history_from_logs(8):
if not history: if st.button(f"🔎 {q[:25]}...", key=f"hist_{q}", use_container_width=True):
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.session_state.messages.append({"role": "user", "content": q})
st.rerun() st.rerun()
return mode, top_k, explain return mode, top_k, explain
def render_draft_editor(msg): def render_draft_editor(msg):
""" """
Spezial-Widget für den INTERVIEW Intent. Rendert den Split-Screen Editor für INTERVIEW Drafts.
Zeigt Tabs für Edit/Preview und separiert Metadaten.
""" """
qid = msg.get('query_id', str(uuid.uuid4())) qid = msg.get('query_id', str(uuid.uuid4()))
key_base = f"draft_{qid}" key_base = f"draft_{qid}"
# 1. Parsing (Initialisierung) # 1. State Initialisierung (Nur einmal pro Nachricht)
if f"{key_base}_initialized" not in st.session_state: if f"{key_base}_init" not in st.session_state:
meta, body = parse_markdown_draft(msg["content"]) meta, body = parse_markdown_draft(msg["content"])
st.session_state[f"{key_base}_type"] = meta.get("type", "concept") st.session_state[f"{key_base}_type"] = meta.get("type", "default")
st.session_state[f"{key_base}_tags"] = meta.get("tags", [])
st.session_state[f"{key_base}_body"] = body.strip()
st.session_state[f"{key_base}_initialized"] = True
# 2. Container Style # Tags Behandlung (Liste oder String)
tags_raw = meta.get("tags", [])
if isinstance(tags_raw, list):
st.session_state[f"{key_base}_tags"] = ", ".join(tags_raw)
else:
st.session_state[f"{key_base}_tags"] = str(tags_raw)
st.session_state[f"{key_base}_body"] = body.strip()
st.session_state[f"{key_base}_init"] = True
# 2. Editor Container
st.markdown(f'<div class="draft-box">', unsafe_allow_html=True) st.markdown(f'<div class="draft-box">', unsafe_allow_html=True)
st.markdown("### 📝 Entwurf bearbeiten") st.markdown("### 📝 Entwurf bearbeiten")
st.caption("Das System hat diesen Entwurf vorbereitet. Ergänze die fehlenden [TODO] Bereiche.")
# 3. Metadaten-Controls (Oberer Bereich) # 3. Metadaten (Grid Layout)
c1, c2 = st.columns([1, 2]) c1, c2 = st.columns([1, 2])
with c1: with c1:
# Typ-Auswahl (Liste synchron mit types.yaml) # Typen müssen mit types.yaml synchron sein
valid_types = ["concept", "project", "decision", "experience", "journal", "person", "value", "goal"] known_types = ["concept", "project", "decision", "experience", "journal", "person", "value", "goal", "principle"]
# Fallback falls LLM etwas Exotisches erfunden hat curr_type = st.session_state[f"{key_base}_type"]
current_type = st.session_state[f"{key_base}_type"] if curr_type not in known_types: known_types.append(curr_type)
if current_type not in valid_types: valid_types.append(current_type)
new_type = st.selectbox("Typ", valid_types, key=f"{key_base}_sel_type", index=valid_types.index(current_type)) new_type = st.selectbox("Typ", known_types, index=known_types.index(curr_type), key=f"{key_base}_sel_type")
with c2: with c2:
# Tag-Editor (als Chips) new_tags = st.text_input("Tags (kommagetrennt)", value=st.session_state[f"{key_base}_tags"], key=f"{key_base}_inp_tags")
current_tags = st.session_state[f"{key_base}_tags"]
if isinstance(current_tags, str): current_tags = [current_tags] # Safety catch
new_tags = st.text_input("Tags (Kommagetrennt)", value=", ".join(current_tags), key=f"{key_base}_inp_tags")
# 4. Tabs: Edit vs Preview # 4. Inhalt (Tabs)
tab_edit, tab_view = st.tabs(["✏️ Bearbeiten", "👁️ Vorschau"]) tab_edit, tab_view = st.tabs(["✏️ Editor", "👁️ Vorschau"])
with tab_edit: with tab_edit:
# Hier landet der Body mit den ## Headings und [TODO]s
new_body = st.text_area( new_body = st.text_area(
"Inhalt", "Inhalt",
value=st.session_state[f"{key_base}_body"], value=st.session_state[f"{key_base}_body"],
height=400, height=500,
key=f"{key_base}_txt_body", key=f"{key_base}_txt_body",
label_visibility="collapsed" label_visibility="collapsed",
help="Hier kannst du Markdown schreiben."
) )
# 5. Rekonstruktion des Dokuments # Live-Zusammenbau für Vorschau & Download
final_tags = [t.strip() for t in new_tags.split(",") if t.strip()] final_tags_list = [t.strip() for t in new_tags.split(",") if t.strip()]
final_meta = {"type": new_type, "tags": final_tags, "status": "draft"} # Basic meta final_meta = {
final_doc = build_markdown_draft(final_meta, new_body) "id": "generated_on_save", # Placeholder, wird beim Download ersetzt
"type": new_type,
"status": "draft",
"tags": final_tags_list
}
final_doc = build_markdown_doc(final_meta, new_body)
with tab_view: with tab_view:
st.markdown('<div class="preview-box">', unsafe_allow_html=True) st.markdown('<div class="preview-box">', unsafe_allow_html=True)
@ -213,25 +239,25 @@ def render_draft_editor(msg):
st.markdown("---") st.markdown("---")
# 6. Actions # 5. Actions (Writeback Simulation)
b1, b2, b3 = st.columns([1, 1, 2]) b1, b2 = st.columns([1, 1])
with b1: with b1:
# Download Button (Client-Side)
st.download_button( st.download_button(
"💾 Download .md", label="💾 Als .md Datei speichern",
data=final_doc, data=final_doc,
file_name=f"draft_{new_type}_{qid[:6]}.md", file_name=generate_filename(final_meta),
mime="text/markdown" mime="text/markdown"
) )
with b2: with b2:
if st.button("📋 Copy Code", key=f"{key_base}_btn_copy"): # Copy Button Logic
if st.button("📋 Code anzeigen (Copy)", key=f"{key_base}_btn_copy"):
st.code(final_doc, language="markdown") st.code(final_doc, language="markdown")
st.toast("Code unten ausgeklappt zum Kopieren!")
st.markdown("</div>", unsafe_allow_html=True) st.markdown("</div>", unsafe_allow_html=True)
def render_chat_interface(top_k, explain): def render_chat_interface(top_k, explain):
# Render History
for msg in st.session_state.messages: for msg in st.session_state.messages:
with st.chat_message(msg["role"]): with st.chat_message(msg["role"]):
if msg["role"] == "assistant": if msg["role"] == "assistant":
@ -239,16 +265,16 @@ def render_chat_interface(top_k, explain):
if "intent" in msg: if "intent" in msg:
intent = msg["intent"] intent = msg["intent"]
icon = {"EMPATHY": "❤️", "DECISION": "⚖️", "CODING": "💻", "FACT": "📚", "INTERVIEW": "📝"}.get(intent, "🧠") icon = {"EMPATHY": "❤️", "DECISION": "⚖️", "CODING": "💻", "FACT": "📚", "INTERVIEW": "📝"}.get(intent, "🧠")
source_info = msg.get("intent_source", "Unknown") src = msg.get("intent_source", "?")
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) st.markdown(f'<div class="intent-badge">{icon} Intent: {intent} <span style="opacity:0.6; font-size:0.8em">({src})</span></div>', unsafe_allow_html=True)
# WEICHE: Editor vs. Text # INTERVIEW Logic vs NORMAL Chat
if msg.get("intent") == "INTERVIEW": if msg.get("intent") == "INTERVIEW":
render_draft_editor(msg) render_draft_editor(msg)
else: else:
st.markdown(msg["content"]) st.markdown(msg["content"])
# Sources & Feedback (nur bei non-interview meist sinnvoll, oder immer?) # Sources & Feedback (nur bei RAG sinnvoll)
if "sources" in msg and msg["sources"]: if "sources" in msg and msg["sources"]:
for hit in msg["sources"]: for hit in msg["sources"]:
score = hit.get('total_score', 0) score = hit.get('total_score', 0)
@ -260,67 +286,57 @@ def render_chat_interface(top_k, explain):
def _cb(qid=msg["query_id"], nid=hit['node_id']): def _cb(qid=msg["query_id"], nid=hit['node_id']):
val = st.session_state.get(f"fb_src_{qid}_{nid}") val = st.session_state.get(f"fb_src_{qid}_{nid}")
if val is not None: submit_feedback(qid, nid, val+1, "Faces UI") if val is not None: submit_feedback(qid, nid, val+1)
st.feedback("faces", key=f"fb_src_{msg['query_id']}_{hit['node_id']}", on_change=_cb) st.feedback("faces", key=f"fb_src_{msg['query_id']}_{hit['node_id']}", on_change=_cb)
if "query_id" in msg: if "query_id" in msg:
qid = msg["query_id"] 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)) 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: else:
st.markdown(msg["content"]) st.markdown(msg["content"])
# Input Logic # Input Loop
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')"):
if prompt := st.chat_input("Frage Mindnet..."):
st.session_state.messages.append({"role": "user", "content": prompt}) st.session_state.messages.append({"role": "user", "content": prompt})
st.rerun() st.rerun()
last_msg_is_user = len(st.session_state.messages) > 0 and st.session_state.messages[-1]["role"] == "user"
if last_msg_is_user: if last_msg_is_user:
last_prompt = st.session_state.messages[-1]["content"]
with st.chat_message("assistant"): with st.chat_message("assistant"):
with st.spinner("Thinking..."): with st.spinner("Thinking..."):
resp = send_chat_message(last_prompt, top_k, explain) resp = send_chat_message(st.session_state.messages[-1]["content"], top_k, explain)
if "error" in resp: if "error" in resp:
st.error(resp["error"]) st.error(resp["error"])
else: else:
msg_data = { st.session_state.messages.append({
"role": "assistant", "role": "assistant",
"content": resp.get("answer"), "content": resp.get("answer"),
"intent": resp.get("intent", "FACT"), "intent": resp.get("intent", "FACT"),
"intent_source": resp.get("intent_source", "Unknown"), "intent_source": resp.get("intent_source", "Unknown"),
"sources": resp.get("sources", []), "sources": resp.get("sources", []),
"query_id": resp.get("query_id") "query_id": resp.get("query_id")
} })
st.session_state.messages.append(msg_data)
st.rerun() st.rerun()
def render_creation_interface(): def render_manual_editor():
st.header("📝 Manueller Eintrag (Legacy)") st.header("📝 Manueller Editor")
st.info("Nutze lieber den Chat ('Neues Projekt anlegen') für den Interview-Modus.") st.info("Hier kannst du eine Notiz komplett von Null erstellen.")
with st.form("new_entry"): # Wiederverwendung der Editor-Logik wäre ideal, hier vereinfacht:
col1, col2 = st.columns([3, 1]) c1, c2 = st.columns([1, 2])
title = col1.text_input("Titel der Notiz", placeholder="z.B. Projekt Gamma Meeting") n_type = c1.selectbox("Typ", ["concept", "project", "decision", "experience", "value", "goal"])
n_type = col2.selectbox("Typ", ["concept", "meeting", "person", "project", "decision"]) tags = c2.text_input("Tags")
body = st.text_area("Inhalt", height=400, placeholder="# Titel\n\nText...")
content = st.text_area("Inhalt (Markdown)", height=300, placeholder="# Protokoll\n\n- Punkt 1...") if st.button("Generieren & Download"):
meta = {"type": n_type, "status": "draft", "tags": [t.strip() for t in tags.split(",")]}
doc = build_markdown_doc(meta, body)
st.code(doc, language="markdown")
st.markdown("**Automatische Vernetzung:**") # --- MAIN ---
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() mode, top_k, explain = render_sidebar()
if mode == "💬 Chat": if mode == "💬 Chat":
render_chat_interface(top_k, explain) render_chat_interface(top_k, explain)
else: else:
render_creation_interface() render_manual_editor()