""" FILE: app/frontend/ui_graph_cytoscape.py DESCRIPTION: Moderner Graph-Explorer (Cytoscape.js). Features: COSE-Layout, Deep-Linking (URL Params), Active Inspector Pattern (CSS-Styling ohne Re-Render). VERSION: 2.6.0 STATUS: Active DEPENDENCIES: streamlit, st_cytoscape, qdrant_client, ui_config, ui_callbacks LAST_ANALYSIS: 2025-12-15 """ 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 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): st.header("🕸️ Graph Explorer (Cytoscape)") # --------------------------------------------------------- # 1. STATE & PERSISTENZ # --------------------------------------------------------- if "graph_center_id" not in st.session_state: st.session_state.graph_center_id = None if "graph_inspected_id" not in st.session_state: st.session_state.graph_inspected_id = None # Lade Einstellungen aus der URL (falls vorhanden), sonst Defaults params = st.query_params # 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]) # --------------------------------------------------------- # 2. LINKES PANEL (Steuerung) # --------------------------------------------------------- with col_ctrl: st.subheader("Fokus") search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search") if search_term: try: 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 = {} for h in hits: if h.payload and 'title' in h.payload and 'note_id' in h.payload: title = h.payload['title'] note_id = h.payload['note_id'] # Vermeide Duplikate (falls mehrere Chunks/Notes denselben Titel haben) if title not in options: options[title] = note_id 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] st.session_state.graph_center_id = new_id st.session_state.graph_inspected_id = new_id st.rerun() else: # Zeige Info, wenn keine Ergebnisse gefunden wurden st.info(f"Keine Notizen mit '{search_term}' im Titel gefunden.") except Exception as e: st.error(f"Fehler bei der Suche: {e}") import traceback st.code(traceback.format_exc()) st.divider() # LAYOUT EINSTELLUNGEN (Mit URL Sync) with st.expander("👁️ Layout Einstellungen", expanded=True): 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.slider("Kantenlänge", 50, 600, 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"): st.rerun() st.divider() st.caption("Legende") for k, v in list(GRAPH_COLORS.items())[:8]: st.markdown(f" {k}", unsafe_allow_html=True) # --------------------------------------------------------- # 3. RECHTES PANEL (GRAPH & INSPECTOR) # --------------------------------------------------------- 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 Inspection 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 nodes_data, edges_data = graph_service.get_ego_graph( center_id, depth=st.session_state.cy_depth ) # 2. Detail Daten (Inspector) inspected_data = graph_service.get_note_with_full_content(inspected_id) # DEBUG: Zeige Debug-Informationen with st.expander("🔍 Debug-Informationen", expanded=False): st.write(f"**Gefundene Knoten:** {len(nodes_data) if nodes_data else 0}") st.write(f"**Gefundene Kanten:** {len(edges_data) if edges_data else 0}") if nodes_data: st.write("**Knoten-IDs:**") for n in nodes_data[:10]: nid = getattr(n, 'id', 'N/A') st.write(f" - {nid}") if len(nodes_data) > 10: st.write(f" ... und {len(nodes_data) - 10} weitere") if edges_data: st.write("**Kanten:**") for e in edges_data[:10]: src = getattr(e, "source", "N/A") tgt = getattr(e, "to", getattr(e, "target", "N/A")) st.write(f" - {src} -> {tgt}") if len(edges_data) > 10: st.write(f" ... und {len(edges_data) - 10} weitere") # --- ACTION BAR --- action_container = st.container() with action_container: c1, c2, c3 = st.columns([2, 1, 1]) with c1: title_show = inspected_data.get('title', inspected_id) if inspected_data else inspected_id st.info(f"**Ausgewählt:** {title_show}") with c2: # NAVIGATION 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 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 --- with st.expander("🕵️ Data Inspector (Details)", expanded=False): if inspected_data: 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')}`") with col_i2: tags = inspected_data.get('tags', []) if isinstance(tags, list): tags_str = ', '.join(tags) if tags else "Keine" else: tags_str = str(tags) if tags else "Keine" st.markdown(f"**Tags:** {tags_str}") path_check = "✅" if inspected_data.get('path') else "❌" st.markdown(f"**Pfad:** {path_check}") st.caption("Inhalt (Vorschau):") st.text_area("Content Preview", inspected_data.get('fulltext', '')[:1000], height=200, disabled=True, label_visibility="collapsed") with st.expander("📄 Raw JSON anzeigen"): st.json(inspected_data) else: st.warning("Keine Daten geladen.") # --- GRAPH ELEMENTS --- cy_elements = [] # Validierung: Prüfe ob nodes_data vorhanden ist if not nodes_data: st.warning("⚠️ Keine Knoten gefunden. Bitte wähle eine andere Notiz.") # Zeige trotzdem den Inspector, falls Daten vorhanden if inspected_data: st.info(f"**Hinweis:** Die Notiz '{inspected_data.get('title', inspected_id)}' wurde gefunden, hat aber keine Verbindungen im Graphen.") return # Erstelle Set aller Node-IDs für schnelle Validierung node_ids = {n.id for n in nodes_data if hasattr(n, 'id') and n.id} # Nodes hinzufügen for n in nodes_data: if not hasattr(n, 'id') or not n.id: continue is_center = (n.id == center_id) is_inspected = (n.id == inspected_id) tooltip_text = getattr(n, 'title', None) or getattr(n, 'label', '') display_label = getattr(n, 'label', str(n.id)) 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": getattr(n, 'color', '#8395a7'), "tooltip": tooltip_text }, # Wir steuern das Aussehen rein über Klassen (.inspected / .center) "classes": " ".join([c for c in ["center" if is_center else "", "inspected" if is_inspected else ""] if c]), "selected": False } cy_elements.append(cy_node) # Edges hinzufügen - nur wenn beide Nodes im Graph vorhanden sind if edges_data: for e in edges_data: source_id = getattr(e, "source", None) target_id = getattr(e, "to", getattr(e, "target", None)) # Nur hinzufügen, wenn beide IDs vorhanden UND beide Nodes im Graph sind if source_id and target_id and source_id in node_ids and target_id in node_ids: cy_edge = { "data": { "source": source_id, "target": target_id, "label": getattr(e, "label", ""), "line_color": getattr(e, "color", "#bdc3c7") } } cy_elements.append(cy_edge) # --- STYLESHEET --- stylesheet = [ { "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)" } }, # Inspiziert (Gelber Rahmen) { "selector": ".inspected", "style": { "border-width": 6, "border-color": "#FFC300", "width": "50px", "height": "50px", "font-weight": "bold", "z-index": 999 } }, # Zentrum (Roter Rahmen) { "selector": ".center", "style": { "border-width": 4, "border-color": "#FF5733", "width": "40px", "height": "40px" } }, # Mix { "selector": ".center.inspected", "style": { "border-width": 6, "border-color": "#FF5733", "width": "55px", "height": "55px" } }, # Default Selection unterdrücken { "selector": "node:selected", "style": { "border-width": 0, "overlay-opacity": 0 } }, { "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" } } ] # --- RENDER --- # Nur rendern, wenn Elemente vorhanden sind if not cy_elements: st.warning("⚠️ Keine Graph-Elemente zum Anzeigen gefunden.") else: 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, "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" ) # --- EVENT HANDLING --- if clicked_elements: clicked_nodes = clicked_elements.get("nodes", []) if clicked_nodes: clicked_id = clicked_nodes[0] if clicked_id != st.session_state.graph_inspected_id: st.session_state.graph_inspected_id = clicked_id st.rerun() else: st.info("👈 Bitte wähle links eine Notiz aus.")