This commit is contained in:
Lars 2025-12-10 17:43:03 +01:00
parent f50ae4c934
commit 5c0a36c9ea

View File

@ -21,7 +21,7 @@ timeout_setting = os.getenv("MINDNET_API_TIMEOUT") or os.getenv("MINDNET_LLM_TIM
API_TIMEOUT = float(timeout_setting) if timeout_setting else 300.0 API_TIMEOUT = float(timeout_setting) if timeout_setting else 300.0
# --- PAGE SETUP --- # --- PAGE SETUP ---
st.set_page_config(page_title="mindnet v2.3.2 (Debug Mode)", page_icon="🐞", layout="wide") st.set_page_config(page_title="mindnet v2.3.2", page_icon="🧠", layout="wide")
# --- CSS STYLING --- # --- CSS STYLING ---
st.markdown(""" st.markdown("""
@ -51,6 +51,12 @@ st.markdown("""
background-color: white; background-color: white;
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif; font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
} }
.debug-info {
font-size: 0.7rem;
color: #888;
margin-bottom: 5px;
}
</style> </style>
""", unsafe_allow_html=True) """, unsafe_allow_html=True)
@ -58,7 +64,7 @@ st.markdown("""
if "messages" not in st.session_state: st.session_state.messages = [] 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 "user_id" not in st.session_state: st.session_state.user_id = str(uuid.uuid4())
# --- HELPER FUNCTIONS (ROBUST PARSING) --- # --- HELPER FUNCTIONS ---
def parse_markdown_draft(full_text): def parse_markdown_draft(full_text):
""" """
@ -66,42 +72,36 @@ def parse_markdown_draft(full_text):
""" """
clean_text = full_text clean_text = full_text
# 1. Versuch: Markdown Fences entfernen (egal ob ```markdown, ```md oder nur ```) # 1. Versuch: Codeblock isolieren
# re.IGNORECASE und re.DOTALL sind wichtig!
pattern_block = r"```(?:markdown|md)?\s*(.*?)\s*```" pattern_block = r"```(?:markdown|md)?\s*(.*?)\s*```"
match_block = re.search(pattern_block, full_text, re.DOTALL | re.IGNORECASE) match_block = re.search(pattern_block, full_text, re.DOTALL | re.IGNORECASE)
if match_block: if match_block:
clean_text = match_block.group(1).strip() clean_text = match_block.group(1).strip()
# Debugging Info im UI anzeigen ist schwer hier, wir verlassen uns auf den Return
# 2. Versuch: YAML Frontmatter finden # 2. Versuch: Frontmatter finden (--- YAML ---)
# Suche nach --- am Anfang (oder nach Whitespace), gefolgt von Inhalt, gefolgt von --- # Verbesserter Regex: Sucht nach dem ersten Vorkommen von --- am Zeilenanfang
pattern_fm = r"^\s*---\s+(.*?)\s+---\s*(.*)$" pattern_fm = r"(-{3,})\s*(.*?)\s*\1\s*(.*)"
match_fm = re.search(pattern_fm, clean_text, re.DOTALL) match_fm = re.search(pattern_fm, clean_text, re.DOTALL)
meta = {} meta = {}
body = clean_text body = clean_text
if match_fm: if match_fm:
yaml_str = match_fm.group(1) yaml_str = match_fm.group(2)
body = match_fm.group(2) body_content = match_fm.group(3)
try: try:
# YAML laden, aber Fehler abfangen
parsed = yaml.safe_load(yaml_str) parsed = yaml.safe_load(yaml_str)
if isinstance(parsed, dict): if isinstance(parsed, dict):
meta = parsed meta = parsed
except Exception as e: body = body_content.strip()
print(f"YAML Parsing Error: {e}") # Geht in Server Log except Exception:
# Wir behalten body, meta bleibt leer pass # YAML kaputt -> alles als Body behandeln
return meta, body return meta, body
def build_markdown_doc(meta, body): def build_markdown_doc(meta, body):
"""Baut das finale Dokument zusammen."""
if "id" not in meta or meta["id"] == "generated_on_save": 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]}" meta["id"] = f"{datetime.now().strftime('%Y%m%d')}-{meta.get('type', 'note')}-{uuid.uuid4().hex[:6]}"
meta["updated"] = datetime.now().strftime("%Y-%m-%d") meta["updated"] = datetime.now().strftime("%Y-%m-%d")
try: try:
@ -143,7 +143,6 @@ def send_chat_message(message: str, top_k: int, explain: bool):
def submit_feedback(query_id, node_id, score, comment=None): 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"
st.toast(f"Feedback ({score}) gesendet!") st.toast(f"Feedback ({score}) gesendet!")
except: pass except: pass
@ -152,15 +151,12 @@ def submit_feedback(query_id, node_id, score, comment=None):
def render_sidebar(): def render_sidebar():
with st.sidebar: with st.sidebar:
st.title("🧠 mindnet") st.title("🧠 mindnet")
st.caption("DEBUG MODE | WP-10 UI") st.caption("DEBUG MODE ACTIVATED")
mode = st.radio("Modus", ["💬 Chat", "📝 Manueller Editor"], index=0) mode = st.radio("Modus", ["💬 Chat", "📝 Manueller Editor"], index=0)
st.divider() st.divider()
st.subheader("⚙️ Settings") st.subheader("⚙️ Settings")
top_k = st.slider("Quellen (Top-K)", 1, 10, 5) top_k = st.slider("Quellen (Top-K)", 1, 10, 5)
explain = st.toggle("Explanation Layer", True) explain = st.toggle("Explanation Layer", True)
st.divider() st.divider()
st.subheader("🕒 Verlauf") st.subheader("🕒 Verlauf")
for q in load_history_from_logs(8): for q in load_history_from_logs(8):
@ -170,67 +166,46 @@ def render_sidebar():
return mode, top_k, explain return mode, top_k, explain
def render_draft_editor(msg): def render_draft_editor(msg):
"""
Rendert den Split-Screen Editor für INTERVIEW Drafts.
"""
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. State Initialisierung (Nur einmal pro Nachricht)
# Wir parsen IMMER neu, wenn der Key noch nicht im State ist
if f"{key_base}_init" 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"])
# Fallback Defaults
st.session_state[f"{key_base}_type"] = meta.get("type", "default") st.session_state[f"{key_base}_type"] = meta.get("type", "default")
# Tags Behandlung (Liste oder String)
tags_raw = meta.get("tags", []) tags_raw = meta.get("tags", [])
if isinstance(tags_raw, list): st.session_state[f"{key_base}_tags"] = ", ".join(tags_raw) if isinstance(tags_raw, list) else str(tags_raw)
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}_body"] = body.strip()
st.session_state[f"{key_base}_init"] = True 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")
# 3. Metadaten (Grid Layout) # Metadata Controls
c1, c2 = st.columns([1, 2]) c1, c2 = st.columns([1, 2])
with c1: with c1:
known_types = ["concept", "project", "decision", "experience", "journal", "person", "value", "goal", "principle", "default"] known_types = ["concept", "project", "decision", "experience", "journal", "person", "value", "goal", "principle", "default"]
curr_type = st.session_state.get(f"{key_base}_type", "default") curr_type = st.session_state.get(f"{key_base}_type", "default")
if curr_type not in known_types: known_types.append(curr_type) if curr_type not in known_types: known_types.append(curr_type)
# Selectbox mit State-Sync
new_type = st.selectbox("Typ", known_types, index=known_types.index(curr_type), key=f"{key_base}_sel_type") new_type = st.selectbox("Typ", known_types, index=known_types.index(curr_type), key=f"{key_base}_sel_type")
with c2: with c2:
new_tags = st.text_input("Tags (kommagetrennt)", value=st.session_state.get(f"{key_base}_tags", ""), key=f"{key_base}_inp_tags") new_tags = st.text_input("Tags", value=st.session_state.get(f"{key_base}_tags", ""), key=f"{key_base}_inp_tags")
# 4. Inhalt (Tabs) # Editor / Preview Tabs
tab_edit, tab_view = st.tabs(["✏️ Editor", "👁️ Vorschau"]) tab_edit, tab_view = st.tabs(["✏️ Editor", "👁️ Vorschau"])
with tab_edit: with tab_edit:
new_body = st.text_area( new_body = st.text_area(
"Inhalt (Markdown Body)", "Inhalt",
value=st.session_state.get(f"{key_base}_body", ""), value=st.session_state.get(f"{key_base}_body", ""),
height=500, height=500,
key=f"{key_base}_txt_body", key=f"{key_base}_txt_body",
label_visibility="collapsed" label_visibility="collapsed"
) )
# Live-Zusammenbau # Live Reassembly
final_tags_list = [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 = { final_meta = {"id": "generated_on_save", "type": new_type, "status": "draft", "tags": final_tags_list}
"id": "generated_on_save",
"type": new_type,
"status": "draft",
"tags": final_tags_list
}
final_doc = build_markdown_doc(final_meta, new_body) final_doc = build_markdown_doc(final_meta, new_body)
with tab_view: with tab_view:
@ -240,48 +215,41 @@ def render_draft_editor(msg):
st.markdown("---") st.markdown("---")
# 5. Actions # Actions
b1, b2 = st.columns([1, 1]) b1, b2 = st.columns([1, 1])
with b1: with b1:
st.download_button( st.download_button("💾 Download .md", data=final_doc, file_name=f"draft_{new_type}.md", mime="text/markdown")
label="💾 Download .md",
data=final_doc,
file_name=generate_filename(final_meta),
mime="text/markdown"
)
with b2: with b2:
if st.button("📋 Code Copy", key=f"{key_base}_btn_copy"): if st.button("📋 Code Copy", key=f"{key_base}_btn_copy"):
st.code(final_doc, language="markdown") st.code(final_doc, language="markdown")
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):
for idx, msg in enumerate(st.session_state.messages): for idx, msg in enumerate(st.session_state.messages):
with st.chat_message(msg["role"]): with st.chat_message(msg["role"]):
if msg["role"] == "assistant": if msg["role"] == "assistant":
# Intent Badge # Meta Info
intent = msg.get("intent", "UNKNOWN") intent = msg.get("intent", "UNKNOWN")
src = msg.get("intent_source", "?") src = msg.get("intent_source", "?")
icon = {"EMPATHY":"❤️", "DECISION":"⚖️", "CODING":"💻", "FACT":"📚", "INTERVIEW":"📝"}.get(intent, "🧠")
# Icon Mapping
icon_map = {"EMPATHY":"❤️", "DECISION":"⚖️", "CODING":"💻", "FACT":"📚", "INTERVIEW":"📝"}
icon = icon_map.get(intent, "🧠")
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) 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)
# --- LOGIC SWITCH --- # --- WICHTIG: DEBUGGING JETZT GANZ OBEN ---
with st.expander("🐞 Debug Raw Payload", expanded=False):
st.text("Hier siehst du, was das Backend wirklich geschickt hat:")
st.json(msg)
# --- CONTENT LOGIC ---
if intent == "INTERVIEW": if intent == "INTERVIEW":
render_draft_editor(msg) render_draft_editor(msg)
else: else:
st.markdown(msg["content"]) st.markdown(msg["content"])
# --- SOURCES --- # Sources & Feedback
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) with st.expander(f"📄 {hit.get('note_id', '?')} ({hit.get('total_score', 0):.2f})"):
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]}..._") st.markdown(f"_{hit.get('source', {}).get('text', '')[:300]}..._")
if hit.get('explanation'): if hit.get('explanation'):
st.caption(f"Grund: {hit['explanation']['reasons'][0]['message']}") st.caption(f"Grund: {hit['explanation']['reasons'][0]['message']}")
@ -289,27 +257,23 @@ def render_chat_interface(top_k, explain):
def _cb(qid=msg.get("query_id"), nid=hit.get('node_id')): def _cb(qid=msg.get("query_id"), nid=hit.get('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) if val is not None: submit_feedback(qid, nid, val+1)
st.feedback("faces", key=f"fb_src_{msg.get('query_id')}_{hit.get('node_id')}", on_change=_cb) st.feedback("faces", key=f"fb_src_{msg.get('query_id')}_{hit.get('node_id')}", on_change=_cb)
# --- DEBUGGING (NEU) --- if "query_id" in msg:
with st.expander("🐞 Debug Raw Payload"): qid = msg["query_id"]
st.json(msg) # Zeigt exakt, was das Backend geschickt hat 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 # Input Logic
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 len(st.session_state.messages) > 0 and st.session_state.messages[-1]["role"] == "user":
if last_msg_is_user:
with st.chat_message("assistant"): with st.chat_message("assistant"):
with st.spinner("Thinking..."): with st.spinner("Thinking..."):
resp = send_chat_message(st.session_state.messages[-1]["content"], 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:
@ -325,18 +289,14 @@ def render_chat_interface(top_k, explain):
def render_manual_editor(): def render_manual_editor():
st.header("📝 Manueller Editor") st.header("📝 Manueller Editor")
st.info("Hier kannst du eine Notiz komplett von Null erstellen.")
c1, c2 = st.columns([1, 2]) c1, c2 = st.columns([1, 2])
n_type = c1.selectbox("Typ", ["concept", "project", "decision", "experience", "value", "goal"]) n_type = c1.selectbox("Typ", ["concept", "project", "decision", "experience", "value", "goal"])
tags = c2.text_input("Tags") tags = c2.text_input("Tags")
body = st.text_area("Inhalt", height=400, placeholder="# Titel\n\nText...") body = st.text_area("Inhalt", height=400, placeholder="# Titel\n\nText...")
if st.button("Code anzeigen"):
if st.button("Generieren & Download"):
meta = {"type": n_type, "status": "draft", "tags": [t.strip() for t in tags.split(",")]} meta = {"type": n_type, "status": "draft", "tags": [t.strip() for t in tags.split(",")]}
doc = build_markdown_doc(meta, body) st.code(build_markdown_doc(meta, body), language="markdown")
st.code(doc, language="markdown")
# --- MAIN ---
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)