Spaces:
Sleeping
Sleeping
Create knowledge_graph.py
Browse files- knowledge_graph.py +47 -0
knowledge_graph.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# knowledge_graph.py
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from typing import Dict, List, Optional
|
| 5 |
+
from graphviz import Digraph
|
| 6 |
+
|
| 7 |
+
class QuantumKnowledgeGraph:
|
| 8 |
+
"""
|
| 9 |
+
Represents a dynamic, multi-modal knowledge graph.
|
| 10 |
+
"""
|
| 11 |
+
def __init__(self):
|
| 12 |
+
self.nodes: Dict[int, Dict[str, any]] = {}
|
| 13 |
+
self.relations: List[Dict[str, any]] = []
|
| 14 |
+
self.node_counter = 0
|
| 15 |
+
|
| 16 |
+
def create_node(self, content: Dict, node_type: str) -> int:
|
| 17 |
+
self.node_counter += 1
|
| 18 |
+
self.nodes[self.node_counter] = {
|
| 19 |
+
"id": self.node_counter,
|
| 20 |
+
"content": content,
|
| 21 |
+
"type": node_type,
|
| 22 |
+
"connections": []
|
| 23 |
+
}
|
| 24 |
+
return self.node_counter
|
| 25 |
+
|
| 26 |
+
def create_relation(self, source: int, target: int, rel_type: str, strength: float = 1.0) -> None:
|
| 27 |
+
self.relations.append({
|
| 28 |
+
"source": source,
|
| 29 |
+
"target": target,
|
| 30 |
+
"type": rel_type,
|
| 31 |
+
"strength": strength
|
| 32 |
+
})
|
| 33 |
+
self.nodes[source]["connections"].append(target)
|
| 34 |
+
|
| 35 |
+
def visualize_graph(self, focus_node: Optional[int] = None) -> str:
|
| 36 |
+
dot = Digraph(engine="neato")
|
| 37 |
+
for nid, node in self.nodes.items():
|
| 38 |
+
label = f"{node['type']}\n{self._truncate_content(node['content'])}"
|
| 39 |
+
dot.node(str(nid), label)
|
| 40 |
+
for rel in self.relations:
|
| 41 |
+
dot.edge(str(rel["source"]), str(rel["target"]), label=rel["type"])
|
| 42 |
+
if focus_node:
|
| 43 |
+
dot.node(str(focus_node), color="red", style="filled")
|
| 44 |
+
return dot.source
|
| 45 |
+
|
| 46 |
+
def _truncate_content(self, content: Dict) -> str:
|
| 47 |
+
return json.dumps(content)[:50] + "..."
|