import streamlit as st # WICHTIG: Wir nutzen jetzt 'st-cytoscape' (pip install st-cytoscape) 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)") if "graph_center_id" not in st.session_state: st.session_state.graph_center_id = None # Layout Defaults für COSE (Compound Spring Embedder) st.session_state.setdefault("cy_node_repulsion", 1000000) # Starke Abstoßung st.session_state.setdefault("cy_ideal_edge_len", 200) # Ziel-Abstand col_ctrl, col_graph = st.columns([1, 4]) # --- CONTROLS --- with col_ctrl: st.subheader("Fokus") 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"): st.session_state.graph_center_id = options[selected_title] st.rerun() st.divider() with st.expander("👁️ Layout Einstellungen", expanded=True): st.caption("COSE Layout (Optimiert für Abstände)") st.session_state.cy_ideal_edge_len = st.slider("Kantenlänge (Ideal)", 50, 600, st.session_state.cy_ideal_edge_len) st.session_state.cy_node_repulsion = st.slider("Knoten-Abstoßung", 100000, 5000000, st.session_state.cy_node_repulsion, step=100000) 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) # --- GRAPH AREA --- with col_graph: center_id = st.session_state.graph_center_id if center_id: action_container = st.container() # 1. Daten laden with st.spinner("Lade Graph..."): # Wir holen die Agraph-Objekte vom Service nodes_data, edges_data = graph_service.get_ego_graph(center_id) # Note Data für Editor Button note_data = graph_service.get_note_with_full_content(center_id) # 2. Action Bar with action_container: c1, c2 = st.columns([3, 1]) with c1: st.caption(f"Zentrum: **{center_id}**") with c2: if note_data: st.button("📝 Bearbeiten", use_container_width=True, on_click=switch_to_editor_callback, args=(note_data,), key="cy_edit") # 3. Konvertierung zu Cytoscape JSON Format cy_elements = [] # Nodes konvertieren for n in nodes_data: # Wir bauen das 'label' so um, dass lange Titel umbrechen (optional) label_display = n.label if len(label_display) > 20: label_display = label_display[:20] + "..." cy_node = { "data": { "id": n.id, "label": label_display, "full_label": n.label, "color": n.color, # Größe skalieren: Center größer "size": 60 if n.id == center_id else 40, # Tooltip Inhalt "tooltip": n.title }, # Zentrum markieren "selected": (n.id == center_id) } cy_elements.append(cy_node) # Edges konvertieren for e in edges_data: # FIX: Agraph Edges nutzen .to, nicht .target # Wir prüfen sicherheitshalber beide Attribute target_id = getattr(e, "to", getattr(e, "target", None)) if target_id: cy_edge = { "data": { "source": e.source, "target": target_id, "label": e.label, "color": e.color } } cy_elements.append(cy_edge) # 4. Stylesheet (Design Definitionen) stylesheet = [ { "selector": "node", "style": { "label": "data(label)", "width": "data(size)", "height": "data(size)", "background-color": "data(color)", "color": "#333", "font-size": "14px", "text-valign": "center", "text-halign": "center", "border-width": 2, "border-color": "#fff", "text-wrap": "wrap", "text-max-width": "100px" } }, { "selector": "node:selected", "style": { "border-width": 5, "border-color": "#FF5733", "background-color": "#FF5733", "color": "#fff" } }, { "selector": "edge", "style": { "width": 3, "line-color": "data(color)", "target-arrow-color": "data(color)", "target-arrow-shape": "triangle", "curve-style": "bezier", "label": "data(label)", "font-size": "11px", "color": "#555", "text-background-opacity": 0.8, "text-background-color": "#ffffff", "text-rotation": "autorotate" } } ] # 5. Rendering mit COSE Layout # COSE ist der Schlüssel für gute Abstände! with st.spinner("Berechne Layout..."): selected_element = 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": 200, "nodeRepulsion": st.session_state.cy_node_repulsion, "edgeElasticity": 100, "nestingFactor": 5, "gravity": 50, "numIter": 1000, "initialTemp": 200, "coolingFactor": 0.95, "minTemp": 1.0 }, key="cyto_graph_obj", # Ein fester Key ist hier okay, da das Layout-Dict sich ändert height="700px" ) # Interaktion: Klick Event verarbeiten # st-cytoscape gibt ein Dictionary zurück if selected_element: # Prüfen, ob es ein Node-Klick war # Die Struktur ist: {'nodes': ['id1', 'id2'], 'edges': [...]} clicked_nodes = selected_element.get("nodes", []) if clicked_nodes: # Wir nehmen den ersten (und meist einzigen) selektierten Node clicked_id = clicked_nodes[0] if clicked_id and clicked_id != center_id: st.session_state.graph_center_id = clicked_id st.rerun() else: st.info("👈 Bitte wähle links eine Notiz aus.")