bug fixing

This commit is contained in:
Lars committed 2025-12-14 12:42:24 +01:00
1 parent cf91730e45
commit 0b47ffdcb6
2 files changed
+145 -115

No files matched your search

+59 -40
View File
@@ -1,3 +1,4 @@
import re
from qdrant_client import QdrantClient, models
from streamlit_agraph import Node, Edge
from ui_config import GRAPH_COLORS, get_edge_color, SYSTEM_EDGES
@@ -13,8 +14,8 @@ class GraphExplorerService:
def get_ego_graph(self, center_note_id: str, depth=2, show_labels=True):
"""
Erstellt den Graphen.
show_labels=False versteckt die Kantenbeschriftung für mehr Übersicht.
Erstellt den Ego-Graphen um eine zentrale Notiz.
Lädt Volltext für das Zentrum und Snippets für Nachbarn.
"""
nodes_dict = {}
unique_edges = {}
@@ -26,7 +27,7 @@ class GraphExplorerService:
level_1_ids = {center_note_id}
# Suche Kanten für Center
# Suche Kanten für Center (L1)
l1_edges = self._find_connected_edges([center_note_id], center_note.get("title"))
for edge_data in l1_edges:
@@ -43,23 +44,26 @@ class GraphExplorerService:
self._process_edge(edge_data, nodes_dict, unique_edges, current_depth=2)
# --- SMART CONTENT LOADING ---
# 1. Fulltext für Center Node holen (Chunks stitchen)
# A. Fulltext für Center Node holen (Chunks zusammenfügen)
center_text = self._fetch_full_text_stitched(center_note_id)
if center_note_id in nodes_dict:
orig_title = nodes_dict[center_note_id].title
# Titel im Objekt manipulieren für Hover
nodes_dict[center_note_id].title = f"{orig_title}\n\n📄 VOLLTEXT:\n{center_text[:2000]}..."
clean_full = self._clean_markdown(center_text[:2000])
# Wir packen den Text in den Tooltip (title attribute)
nodes_dict[center_note_id].title = f"{orig_title}\n\n📄 INHALT:\n{clean_full}..."
# 2. Previews für alle anderen Nodes holen
# B. Previews für alle Nachbarn holen (Batch)
all_ids = list(nodes_dict.keys())
previews = self._fetch_previews_for_nodes(all_ids)
for nid, node_obj in nodes_dict.items():
if nid != center_note_id:
prev = previews.get(nid, "Kein Vorschau-Text.")
node_obj.title = f"{node_obj.title}\n\n🔍 VORSCHAU:\n{prev[:600]}..."
prev_raw = previews.get(nid, "Kein Vorschau-Text.")
clean_prev = self._clean_markdown(prev_raw[:600])
node_obj.title = f"{node_obj.title}\n\n🔍 VORSCHAU:\n{clean_prev}..."
# Graphen bauen
# Graphen bauen (Nodes & Edges finalisieren)
final_edges = []
for (src, tgt), data in unique_edges.items():
kind = data['kind']
@@ -67,24 +71,38 @@ class GraphExplorerService:
color = get_edge_color(kind)
is_smart = (prov != "explicit" and prov != "rule")
# Label Logik: Wenn show_labels False ist, zeigen wir keinen Text an
# Label Logik
label_text = kind if show_labels else " "
final_edges.append(Edge(
source=src, target=tgt, label=label_text, color=color, dashes=is_smart,
title=f"Relation: {kind}\nProvenance: {prov}" # Tooltip bleibt immer
title=f"Relation: {kind}\nProvenance: {prov}"
))
return list(nodes_dict.values()), final_edges
def _clean_markdown(self, text):
"""Entfernt Markdown-Sonderzeichen für saubere Tooltips im Browser."""
if not text: return ""
# Entferne Header Marker (## )
text = re.sub(r'#+\s', '', text)
# Entferne Bold/Italic (** oder *)
text = re.sub(r'\*\*|__|\*|_', '', text)
# Entferne Links [Text](Url) -> Text
text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
# Entferne Wikilinks [[Link]] -> Link
text = re.sub(r'\[\[([^\]]+)\]\]', r'\1', text)
return text
def _fetch_full_text_stitched(self, note_id):
"""Holt ALLE Chunks einer Note, sortiert sie und baut den Text zusammen."""
"""Lädt alle Chunks einer Note und baut den Text zusammen."""
try:
scroll_filter = models.Filter(
must=[models.FieldCondition(key="note_id", match=models.MatchValue(value=note_id))]
)
# Limit hoch genug setzen
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=scroll_filter, limit=100, with_payload=True)
# Sortieren nach 'ord'
# Sortieren nach 'ord' (Reihenfolge im Dokument)
chunks.sort(key=lambda x: x.payload.get('ord', 999))
full_text = []
@@ -97,51 +115,49 @@ class GraphExplorerService:
return "Fehler beim Laden des Volltexts."
def _fetch_previews_for_nodes(self, node_ids):
"""Holt den ersten Chunk ('window' oder 'text') für eine Liste von Nodes."""
"""Holt Batch-weise den ersten Chunk für eine Liste von Nodes."""
if not node_ids: return {}
previews = {}
try:
scroll_filter = models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=node_ids))])
# Limit = Anzahl Nodes * 3 (Puffer)
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=scroll_filter, limit=len(node_ids)*3, with_payload=True)
for c in chunks:
nid = c.payload.get("note_id")
# Nur den ersten gefundenen Chunk pro Note nehmen
if nid and nid not in previews:
previews[nid] = c.payload.get("window") or c.payload.get("text") or ""
except: pass
return previews
def _find_connected_edges(self, note_ids, note_title=None):
"""Findet In- und Outgoing Edges."""
# Chunks finden
scroll_filter = models.Filter(
must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids))]
)
chunks, _ = self.client.scroll(
collection_name=self.chunks_col, scroll_filter=scroll_filter, limit=200
)
"""Findet eingehende und ausgehende Kanten für Nodes."""
# 1. Chunk IDs ermitteln (da Edges oft an Chunks hängen)
scroll_filter = models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids))])
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=scroll_filter, limit=200)
chunk_ids = [c.id for c in chunks]
results = []
# --- OUTGOING SEARCH (Quelle = Chunk ODER Note) ---
# Wir suchen jetzt auch nach der note_id als source_id, falls Edges direkt an der Note hängen
# 2. Outgoing Edges suchen
# Source kann sein: Eine Chunk ID ODER die Note ID selbst (bei direkten Links)
source_candidates = chunk_ids + note_ids
if source_candidates:
out_f = models.Filter(must=[
models.FieldCondition(key="source_id", match=models.MatchAny(any=source_candidates)),
# FIX: MatchExcept mit **kwargs nutzen wegen 'except' Keyword in Pydantic
# FIX: MatchExcept Workaround für Pydantic
models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))
])
res_out, _ = self.client.scroll(self.edges_col, scroll_filter=out_f, limit=100, with_payload=True)
results.extend(res_out)
# --- INCOMING SEARCH (Ziel = Chunk ODER Title ODER Note) ---
# 3. Incoming Edges suchen
# Target kann sein: Chunk ID, Note ID, oder Note Titel (Wikilinks)
shoulds = []
if chunk_ids: shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=chunk_ids)))
if note_title: shoulds.append(models.FieldCondition(key="target_id", match=models.MatchValue(value=note_title)))
# Target = Note ID
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=note_ids)))
if shoulds:
@@ -150,22 +166,22 @@ class GraphExplorerService:
should=shoulds
)
res_in, _ = self.client.scroll(self.edges_col, scroll_filter=in_f, limit=100, with_payload=True)
results.extend(res_in)
results.extend(res_in)
return results
def _find_connected_edges_batch(self, note_ids):
"""Batch-Suche für Level 2."""
# Wrapper für Level 2 Suche
return self._find_connected_edges(note_ids)
def _process_edge(self, record, nodes_dict, unique_edges, current_depth):
"""Verarbeitet eine rohe Edge, löst IDs auf und fügt sie den Dictionaries hinzu."""
payload = record.payload
src_ref = payload.get("source_id")
tgt_ref = payload.get("target_id")
kind = payload.get("kind")
provenance = payload.get("provenance", "explicit")
# Resolve
# IDs zu Notes auflösen
src_note = self._resolve_note_from_ref(src_ref)
tgt_note = self._resolve_note_from_ref(tgt_ref)
@@ -174,15 +190,16 @@ class GraphExplorerService:
tgt_id = tgt_note['note_id']
if src_id != tgt_id:
# Add Nodes
# Nodes hinzufügen
self._add_node_to_dict(nodes_dict, src_note, level=current_depth)
self._add_node_to_dict(nodes_dict, tgt_note, level=current_depth)
# Add Edge (Deduplication Logic)
# Kante hinzufügen (mit Deduplizierung)
key = (src_id, tgt_id)
existing = unique_edges.get(key)
should_update = True
# Bevorzuge explizite Kanten vor Smart Kanten
is_current_explicit = (provenance in ["explicit", "rule"])
if existing:
is_existing_explicit = (existing['provenance'] in ["explicit", "rule"])
@@ -190,9 +207,7 @@ class GraphExplorerService:
should_update = False
if should_update:
unique_edges[key] = {
"source": src_id, "target": tgt_id, "kind": kind, "provenance": provenance
}
unique_edges[key] = {"source": src_id, "target": tgt_id, "kind": kind, "provenance": provenance}
return src_id, tgt_id
return None, None
@@ -209,18 +224,22 @@ class GraphExplorerService:
return None
def _resolve_note_from_ref(self, ref_str):
"""Löst eine ID (Chunk, Note oder Titel) zu einer Note Payload auf."""
if not ref_str: return None
# Fall A: Chunk ID
# Fall A: Chunk ID (enthält #)
if "#" in ref_str:
try:
# Versuch 1: Chunk ID direkt
res = self.client.retrieve(self.chunks_col, ids=[ref_str], with_payload=True)
if res: return self._fetch_note_cached(res[0].payload.get("note_id"))
except: pass
# Versuch 2: NoteID#Section (Hash abtrennen)
possible_note_id = ref_str.split("#")[0]
if self._fetch_note_cached(possible_note_id): return self._fetch_note_cached(possible_note_id)
# Fall B: Note ID
# Fall B: Note ID direkt
if self._fetch_note_cached(ref_str): return self._fetch_note_cached(ref_str)
# Fall C: Titel
@@ -241,7 +260,7 @@ class GraphExplorerService:
ntype = note_payload.get("type", "default")
color = GRAPH_COLORS.get(ntype, GRAPH_COLORS["default"])
# Tooltip wird später durch smart content angereichert
# Basis-Tooltip (wird später erweitert)
tooltip = f"Titel: {note_payload.get('title')}\nTyp: {ntype}"
if level == 0: size = 45