Elffuss BraidHub

kikocis/GraphRAG-SDK public

main · 8.4 KiBRawPermalink
1import json
2import re
3import logging
4from .attribute import Attribute
5from falkordb import Node as GraphNode, Edge as GraphEdge
6from graphrag_sdk.fixtures.regex import (
7 EDGE_LABEL_REGEX,
8 NODE_LABEL_REGEX,
9 EDGE_REGEX,
10)
11
12
13logger = logging.getLogger(__name__)
14
15
16class _RelationEntity:
17 """
18 Represents a relation entity.
19
20 Attributes:
21 label (str): The label of the relation entity.
22 """
23
24 def __init__(self, label: str):
25 """
26 Initializes a Relation object with the given label.
27
28 Args:
29 label (str): The label of the relation.
30
31 Returns:
32 None
33 """
34 self.label = re.sub(r"([^a-zA-Z0-9_])", "", label)
35
36 @staticmethod
37 def from_json(txt: str):
38 """
39 Creates a _RelationEntity object from a JSON string.
40
41 Args:
42 txt (str): The JSON string representing the _RelationEntity object.
43
44 Returns:
45 _RelationEntity: The created _RelationEntity object.
46 """
47 txt = txt if isinstance(txt, dict) else json.loads(txt)
48 return _RelationEntity(txt.get("label", txt))
49
50 def to_json(self):
51 """
52 Converts the _RelationEntity object to a JSON string.
53
54 Returns:
55 str: The JSON string representation of the _RelationEntity object.
56 """
57 return {"label": self.label}
58
59 def __str__(self) -> str:
60 """
61 Returns a string representation of the Relation object.
62
63 The string representation includes the label of the Relation object.
64
65 Returns:
66 str: The string representation of the Relation object.
67 """
68 return f"(:{self.label})"
69
70
71class Relation:
72 """
73 Represents a relation between two entities in a graph.
74
75 Attributes:
76 label (str): The label of the relation.
77 source (_RelationEntity | str): The source entity of the relation.
78 target (_RelationEntity | str): The target entity of the relation.
79 attributes (list[Attribute]): The attributes associated with the relation.
80
81 Methods:
82 from_graph(relation: GraphEdge, entities: list[GraphNode]) -> Relation:
83 Creates a Relation object from a graph edge and a list of graph nodes.
84 from_json(txt: dict | str) -> Relation:
85 Creates a Relation object from a JSON string or dictionary.
86 from_string(txt: str) -> Relation:
87 Creates a Relation object from a string representation.
88 to_json() -> dict:
89 Converts the Relation object to a JSON dictionary.
90 combine(relation2: "Relation") -> Relation:
91 Combines the attributes of another Relation object with this Relation object.
92 to_graph_query() -> str:
93 Generates a Cypher query string for creating the relation in a graph database.
94 __str__() -> str:
95 Returns a string representation of the Relation object.
96 """
97
98 def __init__(
99 self,
100 label: str,
101 source: _RelationEntity | str,
102 target: _RelationEntity | str,
103 attributes: list[Attribute] = None,
104 ):
105 """
106 Initializes a Relation object.
107
108 Args:
109 label (str): The label of the relation.
110 source (_RelationEntity | str): The source entity of the relation.
111 target (_RelationEntity | str): The target entity of the relation.
112 attributes (list[Attribute], optional): The attributes associated with the relation. Defaults to None.
113 """
114 attributes = attributes or []
115 if isinstance(source, str):
116 source = _RelationEntity(source)
117 if isinstance(target, str):
118 target = _RelationEntity(target)
119
120 assert isinstance(label, str), "Label must be a string"
121 assert isinstance(source, _RelationEntity), "Source must be an EdgeNode"
122 assert isinstance(target, _RelationEntity), "Target must be an EdgeNode"
123 assert isinstance(attributes, list), "Attributes must be a list"
124
125 self.label = re.sub(r"([^a-zA-Z0-9_])", "", label.upper())
126 self.source = source
127 self.target = target
128 self.attributes = attributes
129
130 @staticmethod
131 def from_graph(relation: GraphEdge, entities: list[GraphNode]):
132 """
133 Creates a Relation object from a graph edge and a list of graph nodes.
134
135 Args:
136 relation (GraphEdge): The graph edge representing the relation.
137 entities (list[GraphNode]): The list of graph nodes representing the entities.
138
139 Returns:
140 Relation: The created Relation object.
141 """
142 logger.debug(f"Relation.from_graph: {relation}")
143 return Relation(
144 relation.relation,
145 _RelationEntity(
146 next(n.labels[0] for n in entities if n.id == relation.src_node)
147 ),
148 _RelationEntity(
149 next(n.labels[0] for n in entities if n.id == relation.dest_node)
150 ),
151 [
152 Attribute.from_string(f"{attr}:{relation.properties[attr]}")
153 for attr in relation.properties
154 ],
155 )
156
157 @staticmethod
158 def from_json(txt: dict | str):
159 """
160 Creates a Relation object from a JSON string or dictionary.
161
162 Args:
163 txt (dict | str): The JSON string or dictionary representing the relation.
164
165 Returns:
166 Relation: The created Relation object.
167 """
168 txt = txt if isinstance(txt, dict) else json.loads(txt)
169 return Relation(
170 txt["label"],
171 _RelationEntity.from_json(txt["source"]),
172 _RelationEntity.from_json(txt["target"]),
173 (
174 [Attribute.from_json(attr) for attr in txt["attributes"]]
175 if "attributes" in txt
176 else []
177 ),
178 )
179
180 @staticmethod
181 def from_string(txt: str):
182 """
183 Creates a Relation object from a string representation.
184
185 Args:
186 txt (str): The string representation of the relation.
187
188 Returns:
189 Relation: The created Relation object.
190 """
191 label = re.search(EDGE_LABEL_REGEX, txt).group(0).strip()
192 source = re.search(NODE_LABEL_REGEX, txt).group(0).strip()
193 target = re.search(NODE_LABEL_REGEX, txt).group(1).strip()
194 relation = re.search(EDGE_REGEX, txt).group(0)
195 attributes = (
196 relation.split("{")[1].split("}")[0].strip().split(",")
197 if "{" in relation
198 else []
199 )
200
201 return Relation(
202 label,
203 _RelationEntity(source),
204 _RelationEntity(target),
205 [Attribute.from_string(attr) for attr in attributes],
206 )
207
208 def to_json(self):
209 """
210 Converts the Relation object to a JSON dictionary.
211
212 Returns:
213 dict: The JSON dictionary representing the Relation object.
214 """
215 return {
216 "label": self.label,
217 "source": self.source.to_json(),
218 "target": self.target.to_json(),
219 "attributes": [attr.to_json() for attr in self.attributes],
220 }
221
222 def combine(self, relation2: "Relation"):
223 """
224 Overwrites attributes of self with attributes of relation2.
225
226 Args:
227 relation2 (Relation): The Relation object whose attributes will be combined.
228
229 Returns:
230 Relation: The combined Relation object.
231 """
232 if self.label != relation2.label:
233 raise Exception("Relations must have the same label to be combined")
234
235 for attr in relation2.attributes:
236 if attr.name not in [a.name for a in self.attributes]:
237 logger.debug(f"Adding attribute {attr.name} to relation {self.label}")
238 self.attributes.append(attr)
239
240 return self
241
242 def to_graph_query(self):
243 """
244 Generates a Cypher query string for creating the relation in a graph database.
245
246 Returns:
247 str: The Cypher query string.
248 """
249 return f"MATCH (s:{self.source.label}) MATCH (t:{self.target.label}) MERGE (s)-[r:{self.label} {{{', '.join([str(attr) for attr in self.attributes])}}}]->(t) RETURN r"
250
251 def __str__(self) -> str:
252 """
253 Returns a string representation of the Relation object.
254
255 Returns:
256 str: The string representation of the Relation object.
257 """
258 return f"{self.source}-[:{self.label} {{{', '.join([str(attr) for attr in self.attributes])}}}]->{self.target}"