349 lines
15 KiB
Python
349 lines
15 KiB
Python
import streamlit as st
|
|
from st_cytoscape import cytoscape
|
|
from qdrant_client import models
|
|
from ui_config import COLLECTION_PREFIX, GRAPH_COLORS
|
|
from ui_callbacks import switch_to_editor_callback
|
|
|
|
def render_graph_explorer_cytoscape(graph_service):
|
|
st.header("🕸️ Graph Explorer (Cytoscape)")
|
|
|
|
# ---------------------------------------------------------
|
|
# 1. STATE MANAGEMENT
|
|
# ---------------------------------------------------------
|
|
# Graph Zentrum (Roter Rahmen, bestimmt die geladenen Daten)
|
|
if "graph_center_id" not in st.session_state:
|
|
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:
|
|
st.session_state.graph_inspected_id = None
|
|
|
|
# Layout Defaults für COSE Algorithmus
|
|
st.session_state.setdefault("cy_node_repulsion", 1000000)
|
|
st.session_state.setdefault("cy_ideal_edge_len", 150)
|
|
st.session_state.setdefault("cy_depth", 2)
|
|
|
|
col_ctrl, col_graph = st.columns([1, 4])
|
|
|
|
# ---------------------------------------------------------
|
|
# 2. LINKES PANEL (Steuerung)
|
|
# ---------------------------------------------------------
|
|
with col_ctrl:
|
|
st.subheader("Fokus")
|
|
|
|
# Suchfeld
|
|
search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search")
|
|
|
|
if search_term:
|
|
hits, _ = graph_service.client.scroll(
|
|
collection_name=f"{COLLECTION_PREFIX}_notes",
|
|
limit=10,
|
|
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchText(text=search_term))])
|
|
)
|
|
options = {h.payload['title']: h.payload['note_id'] for h in hits}
|
|
|
|
if options:
|
|
selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select")
|
|
if st.button("Laden", use_container_width=True, key="cy_load"):
|
|
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_inspected_id = new_id
|
|
st.rerun()
|
|
|
|
st.divider()
|
|
|
|
# Layout Einstellungen
|
|
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.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.session_state.cy_node_repulsion = st.slider("Knoten-Abstoßung", 100000, 5000000, st.session_state.cy_node_repulsion, step=100000, key="cy_rep_slider")
|
|
|
|
if st.button("Neu berechnen", key="cy_rerun"):
|
|
st.rerun()
|
|
|
|
st.divider()
|
|
|
|
# Legende
|
|
st.caption("Legende")
|
|
for k, v in list(GRAPH_COLORS.items())[:8]:
|
|
st.markdown(f"<span style='color:{v}'>●</span> {k}", unsafe_allow_html=True)
|
|
|
|
# ---------------------------------------------------------
|
|
# 3. RECHTES PANEL (Graph & Tools)
|
|
# ---------------------------------------------------------
|
|
with col_graph:
|
|
center_id = st.session_state.graph_center_id
|
|
|
|
# Fallback Init
|
|
if not center_id and st.session_state.graph_inspected_id:
|
|
center_id = st.session_state.graph_inspected_id
|
|
st.session_state.graph_center_id = center_id
|
|
|
|
if center_id:
|
|
# Sync: Falls Inspektion leer ist, mit Zentrum füllen
|
|
if not st.session_state.graph_inspected_id:
|
|
st.session_state.graph_inspected_id = center_id
|
|
|
|
inspected_id = st.session_state.graph_inspected_id
|
|
|
|
# --- DATEN LADEN ---
|
|
with st.spinner(f"Lade Graph (Tiefe {st.session_state.cy_depth})..."):
|
|
# 1. Graph Daten (Abhängig vom Zentrum)
|
|
nodes_data, edges_data = graph_service.get_ego_graph(
|
|
center_id,
|
|
depth=st.session_state.cy_depth
|
|
)
|
|
# 2. Detail Daten (Abhängig von der Inspektion)
|
|
# Holt Metadaten UND den gestitchten Volltext
|
|
inspected_data = graph_service.get_note_with_full_content(inspected_id)
|
|
|
|
# --- ACTION BAR ---
|
|
action_container = st.container()
|
|
with action_container:
|
|
c1, c2, c3 = st.columns([2, 1, 1])
|
|
|
|
with c1:
|
|
# Titel anzeigen
|
|
title_show = inspected_data.get('title', inspected_id) if inspected_data else inspected_id
|
|
st.info(f"**Info:** {title_show}")
|
|
|
|
with c2:
|
|
# NAVIGATION: Nur aktiv, wenn wir nicht schon im Zentrum sind
|
|
if inspected_id != center_id:
|
|
if st.button("🎯 Als Zentrum setzen", use_container_width=True, key="cy_nav_btn"):
|
|
st.session_state.graph_center_id = inspected_id
|
|
st.rerun()
|
|
else:
|
|
st.caption("_(Ist aktuelles Zentrum)_")
|
|
|
|
with c3:
|
|
# EDITIEREN: Startet den Editor mit den Daten des inspizierten Knotens
|
|
if inspected_data:
|
|
st.button("📝 Bearbeiten",
|
|
use_container_width=True,
|
|
on_click=switch_to_editor_callback,
|
|
args=(inspected_data,),
|
|
key="cy_edit_btn")
|
|
|
|
# --- DATA INSPECTOR (Raw Data restored!) ---
|
|
with st.expander("🕵️ Data Inspector (Details)", expanded=False):
|
|
if inspected_data:
|
|
# Spalte 1: IDs und Typen
|
|
col_i1, col_i2 = st.columns(2)
|
|
with col_i1:
|
|
st.markdown(f"**ID:** `{inspected_data.get('note_id')}`")
|
|
st.markdown(f"**Typ:** `{inspected_data.get('type')}`")
|
|
|
|
# Spalte 2: Tags und Pfad-Status
|
|
with col_i2:
|
|
tags = inspected_data.get('tags', [])
|
|
st.markdown(f"**Tags:** {', '.join(tags) if tags else '-'}")
|
|
|
|
has_path = bool(inspected_data.get('path'))
|
|
path_icon = "✅" if has_path else "❌"
|
|
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"):
|
|
st.json(inspected_data)
|
|
else:
|
|
st.warning("Keine Daten für diesen Knoten gefunden.")
|
|
|
|
# ---------------------------------------------------------
|
|
# 4. GRAPH VORBEREITUNG (Elemente & Styles)
|
|
# ---------------------------------------------------------
|
|
cy_elements = []
|
|
|
|
# Nodes erstellen
|
|
for n in nodes_data:
|
|
# Logik für visuelle Klassen
|
|
classes = []
|
|
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
|
|
display_label = n.label
|
|
if len(display_label) > 15 and " " in display_label:
|
|
display_label = display_label.replace(" ", "\n", 1)
|
|
|
|
cy_node = {
|
|
"data": {
|
|
"id": n.id,
|
|
"label": display_label,
|
|
"bg_color": n.color,
|
|
"tooltip": tooltip_text
|
|
},
|
|
"classes": " ".join(classes),
|
|
# WICHTIG: Wir deaktivieren die interne Selektion (:selected) komplett
|
|
# und nutzen nur unsere CSS Klassen (.inspected), um Mehrfachauswahl zu verhindern.
|
|
"selected": False
|
|
}
|
|
cy_elements.append(cy_node)
|
|
|
|
# Edges erstellen
|
|
for e in edges_data:
|
|
target_id = getattr(e, "to", getattr(e, "target", None))
|
|
if target_id:
|
|
cy_edge = {
|
|
"data": {
|
|
"source": e.source,
|
|
"target": target_id,
|
|
"label": e.label,
|
|
"line_color": e.color
|
|
}
|
|
}
|
|
cy_elements.append(cy_edge)
|
|
|
|
# Stylesheet (Design Definitionen)
|
|
stylesheet = [
|
|
# BASIS NODE
|
|
{
|
|
"selector": "node",
|
|
"style": {
|
|
"label": "data(label)",
|
|
"width": "30px",
|
|
"height": "30px",
|
|
"background-color": "data(bg_color)",
|
|
"color": "#333",
|
|
"font-size": "12px",
|
|
"text-valign": "center",
|
|
"text-halign": "center",
|
|
"text-wrap": "wrap",
|
|
"text-max-width": "90px",
|
|
"border-width": 2,
|
|
"border-color": "#fff",
|
|
"title": "data(tooltip)" # Hover Text
|
|
}
|
|
},
|
|
# INSPECTED (Gelber Rahmen) - Ersetzt :selected
|
|
{
|
|
"selector": ".inspected",
|
|
"style": {
|
|
"border-width": 6,
|
|
"border-color": "#FFC300", # Gelb/Gold
|
|
"width": "50px",
|
|
"height": "50px",
|
|
"font-weight": "bold",
|
|
"z-index": 999
|
|
}
|
|
},
|
|
# CENTER (Roter Rahmen)
|
|
{
|
|
"selector": ".center",
|
|
"style": {
|
|
"border-width": 4,
|
|
"border-color": "#FF5733", # Rot
|
|
"width": "40px",
|
|
"height": "40px"
|
|
}
|
|
},
|
|
# CENTER + INSPECTED (Kombination)
|
|
{
|
|
"selector": ".center.inspected",
|
|
"style": {
|
|
"border-width": 6,
|
|
"border-color": "#FF5733", # Rot gewinnt (oder Mix)
|
|
"width": "55px",
|
|
"height": "55px"
|
|
}
|
|
},
|
|
# NATIVE SELEKTION (Unterdrücken)
|
|
# Das verhindert das "blaue Leuchten" oder Rahmen von Cytoscape selbst
|
|
{
|
|
"selector": "node:selected",
|
|
"style": {
|
|
"overlay-opacity": 0,
|
|
"border-width": 0,
|
|
}
|
|
},
|
|
# EDGE STYLE
|
|
{
|
|
"selector": "edge",
|
|
"style": {
|
|
"width": 2,
|
|
"line-color": "data(line_color)",
|
|
"target-arrow-color": "data(line_color)",
|
|
"target-arrow-shape": "triangle",
|
|
"curve-style": "bezier",
|
|
"label": "data(label)",
|
|
"font-size": "10px", "color": "#666",
|
|
"text-background-opacity": 0.8, "text-background-color": "#fff"
|
|
}
|
|
}
|
|
]
|
|
|
|
# ---------------------------------------------------------
|
|
# 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}"
|
|
|
|
clicked_elements = cytoscape(
|
|
elements=cy_elements,
|
|
stylesheet=stylesheet,
|
|
layout={
|
|
"name": "cose",
|
|
"idealEdgeLength": st.session_state.cy_ideal_edge_len,
|
|
"nodeOverlap": 20,
|
|
"refresh": 20,
|
|
"fit": True,
|
|
"padding": 50,
|
|
"randomize": False, # Wichtig für Stabilität
|
|
"componentSpacing": 100,
|
|
"nodeRepulsion": st.session_state.cy_node_repulsion,
|
|
"edgeElasticity": 100,
|
|
"nestingFactor": 5,
|
|
"gravity": 80,
|
|
"numIter": 1000,
|
|
"initialTemp": 200,
|
|
"coolingFactor": 0.95,
|
|
"minTemp": 1.0,
|
|
"animate": False
|
|
},
|
|
key=graph_key,
|
|
height="700px"
|
|
)
|
|
|
|
# ---------------------------------------------------------
|
|
# 6. EVENT HANDLING
|
|
# ---------------------------------------------------------
|
|
if clicked_elements:
|
|
clicked_nodes = clicked_elements.get("nodes", [])
|
|
|
|
if clicked_nodes:
|
|
# Wir nehmen die erste Node aus dem Event
|
|
clicked_id = clicked_nodes[0]
|
|
|
|
# Wenn auf einen neuen Knoten geklickt wurde:
|
|
if clicked_id != st.session_state.graph_inspected_id:
|
|
# 1. State aktualisieren (Inspektion verschieben)
|
|
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()
|
|
|
|
else:
|
|
st.info("👈 Bitte wähle links eine Notiz aus.") |