Elffuss BraidHub

kikocis/GraphRAG-SDK public

main · 4.8 KiBRawPermalink
1import json
2from graphrag_sdk.fixtures.regex import *
3import logging
4import re
5
6logger = logging.getLogger(__name__)
7
8
9class AttributeType:
10 """
11 Represents the types of attributes in the system.
12 """
13
14 STRING = "string"
15 NUMBER = "number"
16 BOOLEAN = "boolean"
17
18 @staticmethod
19 def from_string(txt: str):
20 """
21 Converts a string representation of an attribute type to its corresponding AttributeType value.
22
23 Args:
24 txt (str): The string representation of the attribute type.
25
26 Returns:
27 AttributeType: The corresponding AttributeType value.
28
29 Raises:
30 Exception: If the provided attribute type is invalid.
31 """
32 if txt.lower() == AttributeType.STRING:
33 return AttributeType.STRING
34 if txt.lower() == AttributeType.NUMBER:
35 return AttributeType.NUMBER
36 if txt.lower() == AttributeType.BOOLEAN:
37 return AttributeType.BOOLEAN
38 raise Exception(f"Invalid attribute type: {txt}")
39
40
41class Attribute:
42 """ Represents an attribute of an entity or relation in the ontology.
43
44 Args:
45 name (str): The name of the attribute.
46 attr_type (AttributeType): The type of the attribute.
47 unique (bool): Whether the attribute is unique.
48 required (bool): Whether the attribute is required.
49
50 Examples:
51 >>> attr = Attribute("name", AttributeType.STRING, True, True)
52 >>> print(attr)
53 name: "string!*"
54 """
55
56 def __init__(
57 self, name: str, attr_type: AttributeType, unique: bool, required: bool = False
58 ):
59 """
60 Initialize a new Attribute object.
61
62 Args:
63 name (str): The name of the attribute.
64 attr_type (AttributeType): The type of the attribute.
65 unique (bool): Indicates whether the attribute should be unique.
66 required (bool, optional): Indicates whether the attribute is required. Defaults to False.
67 """
68 self.name = re.sub(r"([^a-zA-Z0-9_])", "_", name)
69 self.type = attr_type
70 self.unique = unique
71 self.required = required
72
73 @staticmethod
74 def from_json(txt: str | dict):
75 """
76 Creates an Attribute object from a JSON string or dictionary.
77
78 Args:
79 txt (str | dict): The JSON string or dictionary representing the Attribute.
80
81 Returns:
82 Attribute: The created Attribute object.
83
84 """
85 txt = txt if isinstance(txt, dict) else json.loads(txt)
86
87 return Attribute(
88 txt["name"],
89 AttributeType.from_string(txt["type"]),
90 txt["unique"],
91 txt["required"] if "required" in txt else False,
92 )
93
94 @staticmethod
95 def from_string(txt: str):
96 """
97 Parses an attribute from a string.
98 The "!" symbol indicates that the attribute is unique.
99 The "*" symbol indicates that the attribute is required
100
101 Args:
102 txt (str): The string to parse.
103
104 Returns:
105 Attribute: The parsed attribute.
106
107 Examples:
108 >>> attr = Attribute.from_string("name:string!*")
109 >>> print(attr.name)
110 name
111
112 Raises:
113 Exception: If the attribute type is invalid.
114 """
115 name = txt.split(":")[0].strip()
116 attr_type = txt.split(":")[1].split("!")[0].split("*")[0].strip()
117 unique = "!" in txt
118 required = "*" in txt
119
120 if attr_type not in [
121 AttributeType.STRING,
122 AttributeType.NUMBER,
123 AttributeType.BOOLEAN,
124 ]:
125 raise Exception(f"Invalid attribute type: {attr_type}")
126
127 return Attribute(name, AttributeType.from_string(attr_type), unique, required)
128
129 def to_json(self):
130 """
131 Converts the attribute object to a JSON representation.
132
133 Returns:
134 dict: A dictionary representing the attribute object in JSON format.
135 The dictionary contains the following keys:
136 - "name": The name of the attribute.
137 - "type": The type of the attribute.
138 - "unique": A boolean indicating whether the attribute is unique.
139 - "required": A boolean indicating whether the attribute is required.
140 """
141 return {
142 "name": self.name,
143 "type": self.type,
144 "unique": self.unique,
145 "required": self.required,
146 }
147
148 def __str__(self) -> str:
149 """
150 Returns a string representation of the Attribute object.
151
152 The string representation includes the attribute name, type, uniqueness, and requirement status.
153
154 Returns:
155 str: A string representation of the Attribute object.
156 """
157 return f"{self.name}: \"{self.type}{'!' if self.unique else ''}{'*' if self.required else ''}\""