Elffuss BraidHub

kikocis/GraphRAG-SDK public

main · 7.2 KiBRawPermalink
1import re
2import graphrag_sdk
3import logging
4from fix_busted_json import repair_json
5
6logger = logging.getLogger(__name__)
7
8
9def extract_json(text: str | dict, skip_repair=False) -> str:
10 if not isinstance(text, str):
11 text = str(text)
12 regex = r"(?:```)?(?:json)?([^`]*)(?:\\n)?(?:```)?"
13 matches = re.findall(regex, text, re.DOTALL)
14
15 try:
16 return repair_json("".join(matches)) if not skip_repair else "".join(matches)
17 except Exception as e:
18 logger.error(f"Failed to repair JSON: {e} - {text}")
19 return "".join(matches)
20
21
22def map_dict_to_cypher_properties(d: dict):
23 cypher = "{"
24 if isinstance(d, list):
25 if len(d) == 0:
26 return "{}"
27 for i, item in enumerate(d):
28 cypher += f"{i}: {item}, "
29 cypher = (cypher[:-2] if len(cypher) > 1 else cypher) + "}"
30 return cypher
31 for key, value in d.items():
32 # Check value type
33 if isinstance(value, str):
34 # Find unescaped quotes
35 reg = r"((?<!\\)(\"))|((?<!\\)(\'))"
36 search = re.search(reg, value)
37 if search:
38 i = 0
39 for match in re.finditer(reg, value):
40 value = (
41 value[: match.start() + i] + "\\" + value[match.start() + i :]
42 )
43 i += 1
44 value = f'"{value}"' if f"{value}" != "None" else '""'
45 else:
46 value = str(value) if f"{value}" != "None" else '""'
47 cypher += f"{key}: {value}, "
48 cypher = (cypher[:-2] if len(cypher) > 1 else cypher) + "}"
49 return cypher
50
51
52def stringify_falkordb_response(response):
53 if not isinstance(response, list) or len(response) == 0:
54 data = str(response).strip()
55 elif not isinstance(response[0], list):
56 data = str(response).strip()
57 else:
58 for l, _ in enumerate(response):
59 if not isinstance(response[l], list):
60 response[l] = str(response[l])
61 else:
62 for i, __ in enumerate(response[l]):
63 response[l][i] = str(response[l][i])
64 data = str(response).strip()
65
66 return data
67
68
69def extract_cypher(text: str):
70
71 if not text.startswith("```"):
72 return text
73
74 regex = r"```(?:cypher)?(.*?)```"
75 matches = re.findall(regex, text, re.DOTALL)
76
77 return "".join(matches)
78
79
80def validate_cypher(
81 cypher: str, ontology: graphrag_sdk.Ontology
82) -> list[str] | None:
83 try:
84 if not cypher or len(cypher) == 0:
85 return ["Cypher statement is empty"]
86
87 errors = []
88
89 # Check if entities exist in ontology
90 errors.extend(validate_cypher_entities_exist(cypher, ontology))
91
92 # Check if relations exist in ontology
93 errors.extend(validate_cypher_relations_exist(cypher, ontology))
94
95 # Check if relation directions are correct
96 errors.extend(validate_cypher_relation_directions(cypher, ontology))
97
98 if len(errors) > 0:
99 return errors
100
101 return None
102 except Exception as e:
103 print(f"Failed to verify cypher labels: {e}")
104 return None
105
106
107def validate_cypher_entities_exist(cypher: str, ontology: graphrag_sdk.Ontology):
108 # Check if entities exist in ontology
109 not_found_entity_labels = []
110 entity_labels = re.findall(r"\(:(.*?)\)", cypher)
111 for label in entity_labels:
112 label = label.split(":")[1] if ":" in label else label
113 label = label.split("{")[0].strip() if "{" in label else label
114 if label not in [entity.label for entity in ontology.entities]:
115 not_found_entity_labels.append(label)
116
117 return [
118 f"Entity {label} not found in ontology" for label in not_found_entity_labels
119 ]
120
121
122def validate_cypher_relations_exist(cypher: str, ontology: graphrag_sdk.Ontology):
123 # Check if relations exist in ontology
124 not_found_relation_labels = []
125 relation_labels = re.findall(r"\[:(.*?)\]", cypher)
126 for label in relation_labels:
127 label = label.split(":")[1] if ":" in label else label
128 label = label.split("{")[0].strip() if "{" in label else label
129 if label not in [relation.label for relation in ontology.relations]:
130 not_found_relation_labels.append(label)
131
132 return [
133 f"Relation {label} not found in ontology" for label in not_found_relation_labels
134 ]
135
136
137def validate_cypher_relation_directions(
138 cypher: str, ontology: graphrag_sdk.Ontology
139):
140
141 errors = []
142 relations = list(re.finditer(r"\[.*?\]", cypher))
143 i = 0
144 for relation in relations:
145 try:
146 relation_label = (
147 re.search(r"(?:\[)(?:\w)*(?:\:)([^{\]]+)", relation.group(0))
148 .group(1)
149 .strip()
150 )
151 prev_relation = relations[i - 1] if i > 0 else None
152 next_relation = relations[i + 1] if i < len(relations) - 1 else None
153 before = (
154 cypher[prev_relation.end() : relation.start()]
155 if prev_relation
156 else cypher[: relation.start()]
157 )
158 if "," in before:
159 before = before.split(",")[-1]
160 rel_before = re.search(r"([^\)\],]+)", before[::-1]).group(0)[::-1]
161 after = (
162 cypher[relation.end() : next_relation.start()]
163 if next_relation
164 else cypher[relation.end() :]
165 )
166 rel_after = re.search(r"([^\(\[,]+)", after).group(0)
167 entity_before = re.search(r"\(.+:(.*?)\)", before).group(0)
168 entity_after = re.search(r"\(([^\),]+)(\)?)", after).group(0)
169 if rel_before == "-" and rel_after == "->":
170 source = entity_before
171 target = entity_after
172 elif rel_before == "<-" and rel_after == "-":
173 source = entity_after
174 target = entity_before
175 else:
176 continue
177
178 source_label = re.search(r"(?:\:)([^\)\{]+)", source).group(1).strip()
179 target_label = re.search(r"(?:\:)([^\)\{]+)", target).group(1).strip()
180
181 ontology_relations = ontology.get_relations_with_label(relation_label)
182
183 if len(ontology_relations) == 0:
184 errors.append(f"Relation {relation_label} not found in ontology")
185
186 found_relation = False
187 for ontology_relation in ontology_relations:
188 if (
189 ontology_relation.source.label == source_label
190 and ontology_relation.target.label == target_label
191 ):
192 found_relation = True
193 break
194
195 if not found_relation:
196 errors.append(
197 """
198 Relation {relation_label} does not connect {source_label} to {target_label}. Make sure the relation direction is correct.
199 Valid relations:
200 {valid_relations}
201""".format(
202 relation_label=relation_label,
203 source_label=source_label,
204 target_label=target_label,
205 valid_relations="\n".join([str(e) for e in ontology_relations]),
206 )
207 )
208
209 i += 1
210 except Exception:
211 continue
212
213 return errors