Elffuss BraidHub

kikocis/GraphRAG-SDK public

ca14f368bce9 · 2.4 KiBRawPermalink
1from .schema import Schema
2from .entity import Entity
3from .relation import Relation
4
5def relation_to_create_func(r:Relation):
6 src_lbl = r.src.name
7 dest_lbl = r.dest.name
8 #func_name = r.name
9 func_name = f"{src_lbl}_{r.name}_{dest_lbl}"
10
11 func = f"def {func_name}(args):\n" # def MovieStream(args):
12 func += "\targs = remove_none_values(args)\n" # args = remove_none_values(args)
13
14 # extract required src arguments
15 src_attrs = r.src.unique_attributes()
16
17 # extract required src arguments
18 func += "\tq = \"MERGE (s:" + src_lbl + " {"
19 func += ", ".join([f"{attr.name}: " + f"${src_lbl}_{attr.name}" for attr in src_attrs])
20 func += "}) "
21
22 # extract required dest arguments
23 dest_attrs = r.dest.unique_attributes()
24
25 func += "MERGE (d:" + dest_lbl + " {"
26 func += ", ".join([f"{attr.name}: " + f"${dest_lbl}_{attr.name}" for attr in dest_attrs])
27 func += "}) "
28
29 func += "MERGE (s)-[r:" + r.name + "]->(d)\"\n"
30
31 # construct query params
32 func += "\tparams = {"
33 func += ", ".join([f"'{src_lbl}_{attr.name}': args['{src_lbl}_{attr.name}']" for attr in src_attrs])
34 func += ", "
35 func += ", ".join([f"'{dest_lbl}_{attr.name}': args['{dest_lbl}_{attr.name}']" for attr in dest_attrs])
36 func += "}\n"
37
38 func += "\tg.query(q, params)\n"
39
40 return (func_name, func)
41
42def entity_to_create_func(e:Entity):
43 func_name = f"Create_{e.name}" # Create_Actor
44 func = f"def {func_name}(args):\n" # def Create_Actor(args):
45
46 func += "\targs = remove_none_values(args)\n"
47 func += "\tquery = \"MERGE (n:" + e.name + " {" # query = "MERGE (n:Actor {
48
49 unique_attributes = e.unique_attributes()
50
51 func += ", ".join([f"{attr.name}: ${attr.name}" for attr in unique_attributes]) + "})"
52 func += " SET n += $args\"\n"
53
54 func += "\tparams = {"
55 func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in unique_attributes])
56 func += ", 'args': args}\n"
57
58 func += "\tg.query(query, params)\n"
59
60 return (func_name, func)
61
62def schema_to_functions(s:Schema):
63 if not isinstance(s, Schema):
64 raise Exception("Invalid argument, expecting a Schema object")
65
66 functions = []
67 for e in s.entities:
68 func = entity_to_create_func(e)
69 functions.append(func)
70
71 for r in s.relations:
72 func = relation_to_create_func(r)
73 functions.append(func)
74
75 return functions