spezial UI für das Bearbeiten von MD
This commit is contained in:
parent
1063c94f5d
commit
a520b62d08
|
|
@ -4,6 +4,7 @@ import uuid
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
|
import yaml
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
|
@ -25,7 +26,7 @@ st.set_page_config(page_title="mindnet v2.3.2", page_icon="🧠", layout="wide")
|
||||||
st.markdown("""
|
st.markdown("""
|
||||||
<style>
|
<style>
|
||||||
/* Hauptcontainer enger machen für Lesbarkeit */
|
/* Hauptcontainer enger machen für Lesbarkeit */
|
||||||
.block-container { padding-top: 2rem; max_width: 900px; margin: auto; }
|
.block-container { padding-top: 2rem; max_width: 1000px; margin: auto; }
|
||||||
|
|
||||||
/* Intent Badges */
|
/* Intent Badges */
|
||||||
.intent-badge {
|
.intent-badge {
|
||||||
|
|
@ -35,35 +36,60 @@ st.markdown("""
|
||||||
border: 1px solid #d2e3fc; display: inline-block; margin-bottom: 0.5rem;
|
border: 1px solid #d2e3fc; display: inline-block; margin-bottom: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Chat Message Styling */
|
/* Editor Styling */
|
||||||
.stChatMessage { padding: 1rem; border-radius: 8px; margin-bottom: 1rem;}
|
.draft-box {
|
||||||
div[data-testid="stChatMessageContent"] p { font-size: 1.05rem; line-height: 1.6; }
|
border: 1px solid #e0e0e0;
|
||||||
|
border-radius: 8px;
|
||||||
/* Expander Cleaner */
|
padding: 15px;
|
||||||
.streamlit-expanderHeader { font-size: 0.9rem; font-weight: 600; color: #444; }
|
background-color: #fafafa;
|
||||||
|
margin-top: 10px;
|
||||||
/* Editor Label */
|
}
|
||||||
.editor-label { font-weight: bold; margin-bottom: 5px; display: block; color: #333; }
|
.preview-box {
|
||||||
|
border: 1px solid #e0e0e0;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 20px;
|
||||||
|
background-color: white;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
""", unsafe_allow_html=True)
|
""", unsafe_allow_html=True)
|
||||||
|
|
||||||
# --- SESSION STATE ---
|
# --- SESSION STATE ---
|
||||||
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())
|
||||||
if "draft_note" not in st.session_state: st.session_state.draft_note = {"title": "", "content": "", "type": "concept"}
|
|
||||||
|
|
||||||
# --- HELPER FUNCTIONS ---
|
# --- HELPER FUNCTIONS ---
|
||||||
|
|
||||||
def extract_markdown_content(text):
|
def parse_markdown_draft(full_text):
|
||||||
"""Extrahiert den Inhalt aus einem Markdown-Codeblock."""
|
"""
|
||||||
pattern = r"```markdown\s*(.*?)\s*```"
|
Zerlegt einen Markdown-Text in Frontmatter (Dict) und Body (String).
|
||||||
match = re.search(pattern, text, re.DOTALL)
|
"""
|
||||||
if match:
|
# 1. Versuch: Markdown Codeblock entfernen
|
||||||
return match.group(1).strip()
|
pattern_block = r"```markdown\s*(.*?)\s*```"
|
||||||
return text # Fallback: Ganzen Text zurückgeben, wenn kein Block gefunden
|
match_block = re.search(pattern_block, full_text, re.DOTALL)
|
||||||
|
clean_text = match_block.group(1).strip() if match_block else full_text
|
||||||
|
|
||||||
|
# 2. Frontmatter parsen (YAML zwischen ---)
|
||||||
|
pattern_fm = r"^---\s+(.*?)\s+---\s+(.*)$"
|
||||||
|
match_fm = re.search(pattern_fm, clean_text, re.DOTALL)
|
||||||
|
|
||||||
|
if match_fm:
|
||||||
|
yaml_str = match_fm.group(1)
|
||||||
|
body = match_fm.group(2)
|
||||||
|
try:
|
||||||
|
meta = yaml.safe_load(yaml_str) or {}
|
||||||
|
except:
|
||||||
|
meta = {}
|
||||||
|
return meta, body
|
||||||
|
else:
|
||||||
|
return {}, clean_text
|
||||||
|
|
||||||
|
def build_markdown_draft(meta, body):
|
||||||
|
"""Baut das Dokument aus Metadaten und Text wieder zusammen."""
|
||||||
|
yaml_str = yaml.dump(meta, default_flow_style=None, sort_keys=False).strip()
|
||||||
|
return f"---\n{yaml_str}\n---\n\n{body}"
|
||||||
|
|
||||||
def load_history_from_logs(limit=10):
|
def load_history_from_logs(limit=10):
|
||||||
"""Liest die letzten N Queries aus dem Logfile."""
|
|
||||||
queries = []
|
queries = []
|
||||||
if HISTORY_FILE.exists():
|
if HISTORY_FILE.exists():
|
||||||
try:
|
try:
|
||||||
|
|
@ -126,63 +152,103 @@ def render_sidebar():
|
||||||
|
|
||||||
return mode, top_k, explain
|
return mode, top_k, explain
|
||||||
|
|
||||||
|
def render_draft_editor(msg):
|
||||||
|
"""
|
||||||
|
Spezial-Widget für den INTERVIEW Intent.
|
||||||
|
Zeigt Tabs für Edit/Preview und separiert Metadaten.
|
||||||
|
"""
|
||||||
|
qid = msg.get('query_id', str(uuid.uuid4()))
|
||||||
|
key_base = f"draft_{qid}"
|
||||||
|
|
||||||
|
# 1. Parsing (Initialisierung)
|
||||||
|
if f"{key_base}_initialized" not in st.session_state:
|
||||||
|
meta, body = parse_markdown_draft(msg["content"])
|
||||||
|
st.session_state[f"{key_base}_type"] = meta.get("type", "concept")
|
||||||
|
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
|
||||||
|
st.markdown(f'<div class="draft-box">', unsafe_allow_html=True)
|
||||||
|
st.markdown("### 📝 Entwurf bearbeiten")
|
||||||
|
|
||||||
|
# 3. Metadaten-Controls (Oberer Bereich)
|
||||||
|
c1, c2 = st.columns([1, 2])
|
||||||
|
with c1:
|
||||||
|
# Typ-Auswahl (Liste synchron mit types.yaml)
|
||||||
|
valid_types = ["concept", "project", "decision", "experience", "journal", "person", "value", "goal"]
|
||||||
|
# Fallback falls LLM etwas Exotisches erfunden hat
|
||||||
|
current_type = st.session_state[f"{key_base}_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))
|
||||||
|
|
||||||
|
with c2:
|
||||||
|
# Tag-Editor (als Chips)
|
||||||
|
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
|
||||||
|
tab_edit, tab_view = st.tabs(["✏️ Bearbeiten", "👁️ Vorschau"])
|
||||||
|
|
||||||
|
with tab_edit:
|
||||||
|
new_body = st.text_area(
|
||||||
|
"Inhalt",
|
||||||
|
value=st.session_state[f"{key_base}_body"],
|
||||||
|
height=400,
|
||||||
|
key=f"{key_base}_txt_body",
|
||||||
|
label_visibility="collapsed"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 5. Rekonstruktion des Dokuments
|
||||||
|
final_tags = [t.strip() for t in new_tags.split(",") if t.strip()]
|
||||||
|
final_meta = {"type": new_type, "tags": final_tags, "status": "draft"} # Basic meta
|
||||||
|
final_doc = build_markdown_draft(final_meta, new_body)
|
||||||
|
|
||||||
|
with tab_view:
|
||||||
|
st.markdown('<div class="preview-box">', unsafe_allow_html=True)
|
||||||
|
st.markdown(final_doc) # Rendered Markdown
|
||||||
|
st.markdown('</div>', unsafe_allow_html=True)
|
||||||
|
|
||||||
|
st.markdown("---")
|
||||||
|
|
||||||
|
# 6. Actions
|
||||||
|
b1, b2, b3 = st.columns([1, 1, 2])
|
||||||
|
with b1:
|
||||||
|
st.download_button(
|
||||||
|
"💾 Download .md",
|
||||||
|
data=final_doc,
|
||||||
|
file_name=f"draft_{new_type}_{qid[:6]}.md",
|
||||||
|
mime="text/markdown"
|
||||||
|
)
|
||||||
|
with b2:
|
||||||
|
if st.button("📋 Copy Code", key=f"{key_base}_btn_copy"):
|
||||||
|
st.code(final_doc, language="markdown")
|
||||||
|
st.toast("Code unten ausgeklappt zum Kopieren!")
|
||||||
|
|
||||||
|
st.markdown("</div>", unsafe_allow_html=True)
|
||||||
|
|
||||||
|
|
||||||
def render_chat_interface(top_k, explain):
|
def render_chat_interface(top_k, explain):
|
||||||
# Render History
|
# 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":
|
||||||
# 1. INTENT BADGE (mit Source)
|
# Intent Badge
|
||||||
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")
|
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)
|
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)
|
# WEICHE: Editor vs. Text
|
||||||
if msg.get("intent") == "INTERVIEW":
|
if msg.get("intent") == "INTERVIEW":
|
||||||
# --- INTERVIEW EDITOR MODUS ---
|
render_draft_editor(msg)
|
||||||
|
|
||||||
# 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:
|
else:
|
||||||
# --- STANDARD CHAT MODUS ---
|
|
||||||
st.markdown(msg["content"])
|
st.markdown(msg["content"])
|
||||||
|
|
||||||
# 3. SOURCES (Nur anzeigen, wenn vorhanden)
|
# Sources & Feedback (nur bei non-interview meist sinnvoll, oder immer?)
|
||||||
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)
|
||||||
|
|
@ -192,26 +258,23 @@ def render_chat_interface(top_k, explain):
|
||||||
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']}")
|
||||||
|
|
||||||
# Granular Feedback
|
|
||||||
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, "Faces UI")
|
||||||
|
|
||||||
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)
|
||||||
|
|
||||||
# 4. GLOBAL FEEDBACK
|
|
||||||
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:
|
||||||
# User Message
|
|
||||||
st.markdown(msg["content"])
|
st.markdown(msg["content"])
|
||||||
|
|
||||||
# Input Logic
|
# Input Logic
|
||||||
last_msg_is_user = len(st.session_state.messages) > 0 and st.session_state.messages[-1]["role"] == "user"
|
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()
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user