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