WP19 #10

Merged
Lars merged 36 commits from WP19 into main 2025-12-14 20:50:04 +01:00
Showing only changes of commit eccdf43cd3 - Show all commits

View File

@ -4,25 +4,50 @@ from qdrant_client import models
from ui_config import COLLECTION_PREFIX, GRAPH_COLORS from ui_config import COLLECTION_PREFIX, GRAPH_COLORS
from ui_callbacks import switch_to_editor_callback from ui_callbacks import switch_to_editor_callback
def update_url_params():
"""Callback: Schreibt Slider-Werte in die URL und synchronisiert den State."""
# Werte aus den Slider-Keys in die Logik-Variablen übertragen
if "cy_depth_slider" in st.session_state:
st.session_state.cy_depth = st.session_state.cy_depth_slider
if "cy_len_slider" in st.session_state:
st.session_state.cy_ideal_edge_len = st.session_state.cy_len_slider
if "cy_rep_slider" in st.session_state:
st.session_state.cy_node_repulsion = st.session_state.cy_rep_slider
# In URL schreiben
st.query_params["depth"] = st.session_state.cy_depth
st.query_params["len"] = st.session_state.cy_ideal_edge_len
st.query_params["rep"] = st.session_state.cy_node_repulsion
def render_graph_explorer_cytoscape(graph_service): def render_graph_explorer_cytoscape(graph_service):
st.header("🕸️ Graph Explorer (Cytoscape)") st.header("🕸️ Graph Explorer (Cytoscape)")
# --------------------------------------------------------- # ---------------------------------------------------------
# 1. STATE MANAGEMENT # 1. STATE & PERSISTENZ
# --------------------------------------------------------- # ---------------------------------------------------------
# Graph Zentrum (Roter Rahmen, bestimmt die geladenen Daten)
if "graph_center_id" not in st.session_state: if "graph_center_id" not in st.session_state:
st.session_state.graph_center_id = None st.session_state.graph_center_id = None
# Inspizierter Knoten (Gelber Rahmen, bestimmt Inspector & Editor)
# Getrennt vom Zentrum, damit man klicken kann ohne neu zu laden.
if "graph_inspected_id" not in st.session_state: if "graph_inspected_id" not in st.session_state:
st.session_state.graph_inspected_id = None st.session_state.graph_inspected_id = None
# Layout Defaults für COSE Algorithmus # Lade Einstellungen aus der URL (falls vorhanden), sonst Defaults
st.session_state.setdefault("cy_node_repulsion", 1000000) params = st.query_params
st.session_state.setdefault("cy_ideal_edge_len", 150)
st.session_state.setdefault("cy_depth", 2) # Helper um sicher int zu parsen
def get_param(key, default):
try: return int(params.get(key, default))
except: return default
# Initialisiere Session State Variablen, falls noch nicht vorhanden
if "cy_depth" not in st.session_state:
st.session_state.cy_depth = get_param("depth", 2)
if "cy_ideal_edge_len" not in st.session_state:
st.session_state.cy_ideal_edge_len = get_param("len", 150)
if "cy_node_repulsion" not in st.session_state:
st.session_state.cy_node_repulsion = get_param("rep", 1000000)
col_ctrl, col_graph = st.columns([1, 4]) col_ctrl, col_graph = st.columns([1, 4])
@ -32,7 +57,6 @@ def render_graph_explorer_cytoscape(graph_service):
with col_ctrl: with col_ctrl:
st.subheader("Fokus") st.subheader("Fokus")
# Suchfeld
search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search") search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search")
if search_term: if search_term:
@ -47,33 +71,39 @@ def render_graph_explorer_cytoscape(graph_service):
selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select") selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select")
if st.button("Laden", use_container_width=True, key="cy_load"): if st.button("Laden", use_container_width=True, key="cy_load"):
new_id = options[selected_title] new_id = options[selected_title]
# Bei neuer Suche setzen wir beides auf das Ziel
st.session_state.graph_center_id = new_id st.session_state.graph_center_id = new_id
st.session_state.graph_inspected_id = new_id st.session_state.graph_inspected_id = new_id
st.rerun() st.rerun()
st.divider() st.divider()
# Layout Einstellungen # LAYOUT EINSTELLUNGEN (Mit URL Sync)
with st.expander("👁️ Layout Einstellungen", expanded=True): with st.expander("👁️ Layout Einstellungen", expanded=True):
st.session_state.cy_depth = st.slider("Tiefe (Tier)", 1, 3, st.session_state.cy_depth, key="cy_depth_slider") st.slider("Tiefe (Tier)", 1, 3,
value=st.session_state.cy_depth,
key="cy_depth_slider",
on_change=update_url_params)
st.markdown("**COSE Layout**") st.markdown("**COSE Layout**")
st.session_state.cy_ideal_edge_len = st.slider("Kantenlänge", 50, 600, st.session_state.cy_ideal_edge_len, key="cy_len_slider") st.slider("Kantenlänge", 50, 600,
st.session_state.cy_node_repulsion = st.slider("Knoten-Abstoßung", 100000, 5000000, st.session_state.cy_node_repulsion, step=100000, key="cy_rep_slider") value=st.session_state.cy_ideal_edge_len,
key="cy_len_slider",
on_change=update_url_params)
st.slider("Knoten-Abstoßung", 100000, 5000000, step=100000,
value=st.session_state.cy_node_repulsion,
key="cy_rep_slider",
on_change=update_url_params)
if st.button("Neu berechnen", key="cy_rerun"): if st.button("Neu berechnen", key="cy_rerun"):
st.rerun() st.rerun()
st.divider() st.divider()
# Legende
st.caption("Legende") st.caption("Legende")
for k, v in list(GRAPH_COLORS.items())[:8]: for k, v in list(GRAPH_COLORS.items())[:8]:
st.markdown(f"<span style='color:{v}'>●</span> {k}", unsafe_allow_html=True) st.markdown(f"<span style='color:{v}'>●</span> {k}", unsafe_allow_html=True)
# --------------------------------------------------------- # ---------------------------------------------------------
# 3. RECHTES PANEL (Graph & Tools) # 3. RECHTES PANEL (GRAPH & INSPECTOR)
# --------------------------------------------------------- # ---------------------------------------------------------
with col_graph: with col_graph:
center_id = st.session_state.graph_center_id center_id = st.session_state.graph_center_id
@ -84,7 +114,7 @@ def render_graph_explorer_cytoscape(graph_service):
st.session_state.graph_center_id = center_id st.session_state.graph_center_id = center_id
if center_id: if center_id:
# Sync: Falls Inspektion leer ist, mit Zentrum füllen # Sync Inspection
if not st.session_state.graph_inspected_id: if not st.session_state.graph_inspected_id:
st.session_state.graph_inspected_id = center_id st.session_state.graph_inspected_id = center_id
@ -92,13 +122,12 @@ def render_graph_explorer_cytoscape(graph_service):
# --- DATEN LADEN --- # --- DATEN LADEN ---
with st.spinner(f"Lade Graph (Tiefe {st.session_state.cy_depth})..."): with st.spinner(f"Lade Graph (Tiefe {st.session_state.cy_depth})..."):
# 1. Graph Daten (Abhängig vom Zentrum) # 1. Graph Daten
nodes_data, edges_data = graph_service.get_ego_graph( nodes_data, edges_data = graph_service.get_ego_graph(
center_id, center_id,
depth=st.session_state.cy_depth depth=st.session_state.cy_depth
) )
# 2. Detail Daten (Abhängig von der Inspektion) # 2. Detail Daten (Inspector)
# Holt Metadaten UND den gestitchten Volltext
inspected_data = graph_service.get_note_with_full_content(inspected_id) inspected_data = graph_service.get_note_with_full_content(inspected_id)
# --- ACTION BAR --- # --- ACTION BAR ---
@ -107,12 +136,11 @@ def render_graph_explorer_cytoscape(graph_service):
c1, c2, c3 = st.columns([2, 1, 1]) c1, c2, c3 = st.columns([2, 1, 1])
with c1: with c1:
# Titel anzeigen
title_show = inspected_data.get('title', inspected_id) if inspected_data else inspected_id title_show = inspected_data.get('title', inspected_id) if inspected_data else inspected_id
st.info(f"**Info:** {title_show}") st.info(f"**Ausgewählt:** {title_show}")
with c2: with c2:
# NAVIGATION: Nur aktiv, wenn wir nicht schon im Zentrum sind # NAVIGATION
if inspected_id != center_id: if inspected_id != center_id:
if st.button("🎯 Als Zentrum setzen", use_container_width=True, key="cy_nav_btn"): if st.button("🎯 Als Zentrum setzen", use_container_width=True, key="cy_nav_btn"):
st.session_state.graph_center_id = inspected_id st.session_state.graph_center_id = inspected_id
@ -121,7 +149,7 @@ def render_graph_explorer_cytoscape(graph_service):
st.caption("_(Ist aktuelles Zentrum)_") st.caption("_(Ist aktuelles Zentrum)_")
with c3: with c3:
# EDITIEREN: Startet den Editor mit den Daten des inspizierten Knotens # EDITIEREN
if inspected_data: if inspected_data:
st.button("📝 Bearbeiten", st.button("📝 Bearbeiten",
use_container_width=True, use_container_width=True,
@ -129,56 +157,33 @@ def render_graph_explorer_cytoscape(graph_service):
args=(inspected_data,), args=(inspected_data,),
key="cy_edit_btn") key="cy_edit_btn")
# --- DATA INSPECTOR (Raw Data restored!) --- # --- DATA INSPECTOR ---
with st.expander("🕵️ Data Inspector (Details)", expanded=False): with st.expander("🕵️ Data Inspector (Details)", expanded=False):
if inspected_data: if inspected_data:
# Spalte 1: IDs und Typen
col_i1, col_i2 = st.columns(2) col_i1, col_i2 = st.columns(2)
with col_i1: with col_i1:
st.markdown(f"**ID:** `{inspected_data.get('note_id')}`") st.markdown(f"**ID:** `{inspected_data.get('note_id')}`")
st.markdown(f"**Typ:** `{inspected_data.get('type')}`") st.markdown(f"**Typ:** `{inspected_data.get('type')}`")
# Spalte 2: Tags und Pfad-Status
with col_i2: with col_i2:
tags = inspected_data.get('tags', []) st.markdown(f"**Tags:** {', '.join(inspected_data.get('tags', []))}")
st.markdown(f"**Tags:** {', '.join(tags) if tags else '-'}") path_check = "" if inspected_data.get('path') else ""
st.markdown(f"**Pfad:** {path_check}")
has_path = bool(inspected_data.get('path')) st.caption("Inhalt (Vorschau):")
path_icon = "" if has_path else "" st.text_area("Content Preview", inspected_data.get('fulltext', '')[:1000], height=200, disabled=True, label_visibility="collapsed")
st.markdown(f"**Pfad:** {path_icon}")
if has_path:
st.caption(f"_{inspected_data.get('path')}_")
st.divider()
# Content Preview
st.caption("Inhalt (Vorschau aus Stitching):")
fulltext = inspected_data.get('fulltext', '')
st.text_area("Body", fulltext[:1200] + "...", height=200, disabled=True, label_visibility="collapsed")
# Raw Data Expander
with st.expander("📄 Raw JSON anzeigen"): with st.expander("📄 Raw JSON anzeigen"):
st.json(inspected_data) st.json(inspected_data)
else: else:
st.warning("Keine Daten für diesen Knoten gefunden.") st.warning("Keine Daten geladen.")
# --------------------------------------------------------- # --- GRAPH ELEMENTS ---
# 4. GRAPH VORBEREITUNG (Elemente & Styles)
# ---------------------------------------------------------
cy_elements = [] cy_elements = []
# Nodes erstellen
for n in nodes_data: for n in nodes_data:
# Logik für visuelle Klassen is_center = (n.id == center_id)
classes = [] is_inspected = (n.id == inspected_id)
if n.id == center_id:
classes.append("center")
# Wir markieren den inspizierten Knoten visuell
if n.id == inspected_id:
classes.append("inspected")
# Label für Anzeige kürzen
tooltip_text = n.title if n.title else n.label tooltip_text = n.title if n.title else n.label
display_label = n.label display_label = n.label
if len(display_label) > 15 and " " in display_label: if len(display_label) > 15 and " " in display_label:
@ -191,14 +196,12 @@ def render_graph_explorer_cytoscape(graph_service):
"bg_color": n.color, "bg_color": n.color,
"tooltip": tooltip_text "tooltip": tooltip_text
}, },
"classes": " ".join(classes), # Wir steuern das Aussehen rein über Klassen (.inspected / .center)
# WICHTIG: Wir deaktivieren die interne Selektion (:selected) komplett "classes": " ".join([c for c in ["center" if is_center else "", "inspected" if is_inspected else ""] if c]),
# und nutzen nur unsere CSS Klassen (.inspected), um Mehrfachauswahl zu verhindern.
"selected": False "selected": False
} }
cy_elements.append(cy_node) cy_elements.append(cy_node)
# Edges erstellen
for e in edges_data: for e in edges_data:
target_id = getattr(e, "to", getattr(e, "target", None)) target_id = getattr(e, "to", getattr(e, "target", None))
if target_id: if target_id:
@ -212,69 +215,58 @@ def render_graph_explorer_cytoscape(graph_service):
} }
cy_elements.append(cy_edge) cy_elements.append(cy_edge)
# Stylesheet (Design Definitionen) # --- STYLESHEET ---
stylesheet = [ stylesheet = [
# BASIS NODE
{ {
"selector": "node", "selector": "node",
"style": { "style": {
"label": "data(label)", "label": "data(label)",
"width": "30px", "width": "30px", "height": "30px",
"height": "30px",
"background-color": "data(bg_color)", "background-color": "data(bg_color)",
"color": "#333", "color": "#333", "font-size": "12px",
"font-size": "12px", "text-valign": "center", "text-halign": "center",
"text-valign": "center", "text-wrap": "wrap", "text-max-width": "90px",
"text-halign": "center", "border-width": 2, "border-color": "#fff",
"text-wrap": "wrap", "title": "data(tooltip)"
"text-max-width": "90px",
"border-width": 2,
"border-color": "#fff",
"title": "data(tooltip)" # Hover Text
} }
}, },
# INSPECTED (Gelber Rahmen) - Ersetzt :selected # Inspiziert (Gelber Rahmen)
{ {
"selector": ".inspected", "selector": ".inspected",
"style": { "style": {
"border-width": 6, "border-width": 6,
"border-color": "#FFC300", # Gelb/Gold "border-color": "#FFC300",
"width": "50px", "width": "50px", "height": "50px",
"height": "50px",
"font-weight": "bold", "font-weight": "bold",
"z-index": 999 "z-index": 999
} }
}, },
# CENTER (Roter Rahmen) # Zentrum (Roter Rahmen)
{ {
"selector": ".center", "selector": ".center",
"style": { "style": {
"border-width": 4, "border-width": 4,
"border-color": "#FF5733", # Rot "border-color": "#FF5733",
"width": "40px", "width": "40px", "height": "40px"
"height": "40px"
} }
}, },
# CENTER + INSPECTED (Kombination) # Mix
{ {
"selector": ".center.inspected", "selector": ".center.inspected",
"style": { "style": {
"border-width": 6, "border-width": 6,
"border-color": "#FF5733", # Rot gewinnt (oder Mix) "border-color": "#FF5733",
"width": "55px", "width": "55px", "height": "55px"
"height": "55px"
} }
}, },
# NATIVE SELEKTION (Unterdrücken) # Default Selection unterdrücken
# Das verhindert das "blaue Leuchten" oder Rahmen von Cytoscape selbst
{ {
"selector": "node:selected", "selector": "node:selected",
"style": { "style": {
"overlay-opacity": 0,
"border-width": 0, "border-width": 0,
"overlay-opacity": 0
} }
}, },
# EDGE STYLE
{ {
"selector": "edge", "selector": "edge",
"style": { "style": {
@ -290,13 +282,7 @@ def render_graph_explorer_cytoscape(graph_service):
} }
] ]
# --------------------------------------------------------- # --- RENDER ---
# 5. RENDERING
# ---------------------------------------------------------
# KEY STRATEGIE:
# Der Key bestimmt, wann der Graph komplett neu gebaut wird.
# Wir nutzen hier center_id und settings.
# NICHT inspected_id -> Das verhindert das Springen beim Klicken!
graph_key = f"cy_{center_id}_{st.session_state.cy_depth}_{st.session_state.cy_ideal_edge_len}" graph_key = f"cy_{center_id}_{st.session_state.cy_depth}_{st.session_state.cy_ideal_edge_len}"
clicked_elements = cytoscape( clicked_elements = cytoscape(
@ -309,7 +295,7 @@ def render_graph_explorer_cytoscape(graph_service):
"refresh": 20, "refresh": 20,
"fit": True, "fit": True,
"padding": 50, "padding": 50,
"randomize": False, # Wichtig für Stabilität "randomize": False,
"componentSpacing": 100, "componentSpacing": 100,
"nodeRepulsion": st.session_state.cy_node_repulsion, "nodeRepulsion": st.session_state.cy_node_repulsion,
"edgeElasticity": 100, "edgeElasticity": 100,
@ -325,24 +311,14 @@ def render_graph_explorer_cytoscape(graph_service):
height="700px" height="700px"
) )
# --------------------------------------------------------- # --- EVENT HANDLING ---
# 6. EVENT HANDLING
# ---------------------------------------------------------
if clicked_elements: if clicked_elements:
clicked_nodes = clicked_elements.get("nodes", []) clicked_nodes = clicked_elements.get("nodes", [])
if clicked_nodes: if clicked_nodes:
# Wir nehmen die erste Node aus dem Event
clicked_id = clicked_nodes[0] clicked_id = clicked_nodes[0]
# Wenn auf einen neuen Knoten geklickt wurde:
if clicked_id != st.session_state.graph_inspected_id: if clicked_id != st.session_state.graph_inspected_id:
# 1. State aktualisieren (Inspektion verschieben)
st.session_state.graph_inspected_id = clicked_id st.session_state.graph_inspected_id = clicked_id
# 2. Rerun triggern
# Da graph_key sich NICHT ändert, bleibt der Graph stabil,
# nur die CSS-Klassen (.inspected) werden aktualisiert.
st.rerun() st.rerun()
else: else: