Elffuss BraidHub

kikocis/GraphRAG-SDK public

ca14f368bce9 · 2.8 KiBRawPermalink
1import builtins
2from .entity import Entity
3from json import JSONDecoder
4
5# Decode Schema from JSON
6class SchemaDecoder():
7 def from_JSON(self, schema, json:str):
8 # Validate argument
9 if not isinstance(json, str) or json == "":
10 raise Exception("Unable to decode schema, make sure data is a none empty string")
11
12 return self.decode(schema, JSONDecoder().decode(json))
13
14 # Create Schema from dict
15 def decode(self, schema, data:dict):
16 if not isinstance(data, dict):
17 raise Exception("Unable to decode schema, make sure data is a dict")
18
19 # Validate JSON schema structure
20 if 'entities' not in data or 'relations' not in data:
21 raise Exception("Invalid schema format")
22
23 entities = data['entities']
24 relations = data['relations']
25
26 # Decode entities
27 for e in entities:
28 name, attributes = self._entity_decode(e)
29 e = schema.add_entity(name)
30 for attr in attributes:
31 e.add_attribute(attr['name'], attr['type'], attr['desc'], attr['unique'], attr['mandatory'])
32
33 # Decode relations
34 for r in relations:
35 # Validate relation
36 if not isinstance(r, dict):
37 raise Exception("Invalid argument, expecting dict")
38 if 'name' not in r:
39 raise Exception("Invalid Relation format, missing 'name'")
40 if 'src' not in r:
41 raise Exception("Invalid Relation format, missing 'src'")
42 if 'dest' not in r:
43 raise Exception("Invalid Relation format, missing 'dest'")
44
45 src = r['src']
46 dest = r['dest']
47 name = r['name']
48
49 src = schema.get_entity(src)
50 dest = schema.get_entity(dest)
51
52 if src is None:
53 raise Exception(f"Missing src entity {r['src']}")
54 if dest is None:
55 raise Exception(f"Missing dest entity {r['dest']}")
56
57 schema.add_relation(name, src, dest)
58
59 return schema
60
61 # Load Entity from dict
62 # see entityEncode generated structure
63 def _entity_decode(self, raw: dict):
64 if not isinstance(raw, dict):
65 raise Exception("Invalid argument, expecting dict")
66 if 'name' not in raw:
67 raise Exception("Invalid format, missing 'name'")
68 if 'attributes' not in raw:
69 raise Exception("Invalid format, missing 'attributes'")
70
71 name = raw['name']
72 attributes = raw['attributes']
73
74 for attr in attributes:
75 if 'name' not in attr or 'type' not in attr or 'unique' not in attr:
76 raise Exception("Invalid format, attribute must include a 'name', 'type' and 'unique' fields")
77
78 attr['type'] = getattr(builtins, attr['type'])
79
80 return name, attributes