| 1 | import json |
| 2 | from falkordb import Graph |
| 3 | from graphrag_sdk.source import AbstractSource |
| 4 | from graphrag_sdk.models import GenerativeModel |
| 5 | import graphrag_sdk |
| 6 | import logging |
| 7 | from .relation import Relation |
| 8 | from .entity import Entity |
| 9 | from typing import Optional |
| 10 | |
| 11 | |
| 12 | logger = logging.getLogger(__name__) |
| 13 | |
| 14 | |
| 15 | class Ontology(object): |
| 16 | """ |
| 17 | Represents an ontology, which is a collection of entities and relations. |
| 18 | |
| 19 | Attributes: |
| 20 | entities (list[Entity]): The list of entities in the ontology. |
| 21 | relations (list[Relation]): The list of relations in the ontology. |
| 22 | """ |
| 23 | |
| 24 | def __init__(self, entities: list[Entity] = None, relations: list[Relation] = None): |
| 25 | """ |
| 26 | Initialize the Ontology class. |
| 27 | |
| 28 | Args: |
| 29 | entities (list[Entity], optional): List of Entity objects. Defaults to None. |
| 30 | relations (list[Relation], optional): List of Relation objects. Defaults to None. |
| 31 | """ |
| 32 | self.entities = entities or [] |
| 33 | self.relations = relations or [] |
| 34 | |
| 35 | @staticmethod |
| 36 | def from_sources( |
| 37 | sources: list[AbstractSource], |
| 38 | model: GenerativeModel, |
| 39 | boundaries: Optional[str] = None, |
| 40 | ) -> "Ontology": |
| 41 | """ |
| 42 | Create an Ontology object from a list of sources. |
| 43 | |
| 44 | Args: |
| 45 | sources (list[AbstractSource]): A list of AbstractSource objects representing the sources. |
| 46 | boundaries (Optinal[str]): The boundaries for the ontology. |
| 47 | model (GenerativeModel): The generative model to use. |
| 48 | |
| 49 | Returns: |
| 50 | The created Ontology object. |
| 51 | """ |
| 52 | step = graphrag_sdk.CreateOntologyStep( |
| 53 | sources=sources, |
| 54 | ontology=Ontology(), |
| 55 | model=model, |
| 56 | ) |
| 57 | |
| 58 | return step.run(boundaries=boundaries) |
| 59 | |
| 60 | @staticmethod |
| 61 | def from_json(txt: dict | str): |
| 62 | """ |
| 63 | Creates an Ontology object from a JSON representation. |
| 64 | |
| 65 | Args: |
| 66 | txt (dict | str): The JSON representation of the ontology. It can be either a dictionary or a string. |
| 67 | |
| 68 | Returns: |
| 69 | The Ontology object created from the JSON representation. |
| 70 | |
| 71 | Raises: |
| 72 | ValueError: If the provided JSON representation is invalid. |
| 73 | """ |
| 74 | txt = txt if isinstance(txt, dict) else json.loads(txt) |
| 75 | return Ontology( |
| 76 | [Entity.from_json(entity) for entity in txt["entities"]], |
| 77 | [Relation.from_json(relation) for relation in txt["relations"]], |
| 78 | ) |
| 79 | |
| 80 | @staticmethod |
| 81 | def from_graph(graph: Graph): |
| 82 | """ |
| 83 | Creates an Ontology object from a given graph. |
| 84 | |
| 85 | Args: |
| 86 | graph (Graph): The graph object representing the ontology. |
| 87 | |
| 88 | Returns: |
| 89 | The Ontology object created from the graph. |
| 90 | """ |
| 91 | ontology = Ontology() |
| 92 | |
| 93 | entities = graph.query("MATCH (n) RETURN n").result_set |
| 94 | for entity in entities: |
| 95 | ontology.add_entity(Entity.from_graph(entity[0])) |
| 96 | |
| 97 | for relation in graph.query("MATCH ()-[r]->() RETURN r").result_set: |
| 98 | ontology.add_relation( |
| 99 | Relation.from_graph(relation[0], [x for xs in entities for x in xs]) |
| 100 | ) |
| 101 | |
| 102 | return ontology |
| 103 | |
| 104 | def add_entity(self, entity: Entity): |
| 105 | """ |
| 106 | Adds an entity to the ontology. |
| 107 | |
| 108 | Parameters: |
| 109 | entity: The entity object to be added. |
| 110 | """ |
| 111 | self.entities.append(entity) |
| 112 | |
| 113 | def add_relation(self, relation: Relation): |
| 114 | """ |
| 115 | Adds a relation to the ontology. |
| 116 | |
| 117 | Args: |
| 118 | relation (Relation): The relation to be added. |
| 119 | """ |
| 120 | self.relations.append(relation) |
| 121 | |
| 122 | def to_json(self): |
| 123 | """ |
| 124 | Converts the ontology object to a JSON representation. |
| 125 | |
| 126 | Returns: |
| 127 | A dictionary representing the ontology object in JSON format. |
| 128 | """ |
| 129 | return { |
| 130 | "entities": [entity.to_json() for entity in self.entities], |
| 131 | "relations": [relation.to_json() for relation in self.relations], |
| 132 | } |
| 133 | |
| 134 | def merge_with(self, o: "Ontology"): |
| 135 | """ |
| 136 | Merges the given ontology `o` with the current ontology. |
| 137 | |
| 138 | Args: |
| 139 | o (Ontology): The ontology to merge with. |
| 140 | |
| 141 | Returns: |
| 142 | The merged ontology. |
| 143 | """ |
| 144 | # Merge entities |
| 145 | for entity in o.entities: |
| 146 | if entity.label not in [n.label for n in self.entities]: |
| 147 | # Entity does not exist in self, add it |
| 148 | self.entities.append(entity) |
| 149 | logger.debug(f"Adding entity {entity.label}") |
| 150 | else: |
| 151 | # Entity exists in self, merge attributes |
| 152 | entity1 = next(n for n in self.entities if n.label == entity.label) |
| 153 | entity1.merge(entity) |
| 154 | |
| 155 | # Merge relations |
| 156 | for relation in o.relations: |
| 157 | if relation.label not in [e.label for e in self.relations]: |
| 158 | # Relation does not exist in self, add it |
| 159 | self.relations.append(relation) |
| 160 | logger.debug(f"Adding relation {relation.label}") |
| 161 | else: |
| 162 | # Relation exists in self, merge attributes |
| 163 | relation1 = next(e for e in self.relations if e.label == relation.label) |
| 164 | relation1.combine(relation) |
| 165 | |
| 166 | return self |
| 167 | |
| 168 | def discard_entities_without_relations(self): |
| 169 | """ |
| 170 | Discards entities that do not have any relations in the ontology. |
| 171 | |
| 172 | Returns: |
| 173 | The updated ontology object after discarding entities without relations. |
| 174 | """ |
| 175 | entities_to_discard = [ |
| 176 | entity.label |
| 177 | for entity in self.entities |
| 178 | if all( |
| 179 | [ |
| 180 | relation.source.label != entity.label |
| 181 | and relation.target.label != entity.label |
| 182 | for relation in self.relations |
| 183 | ] |
| 184 | ) |
| 185 | ] |
| 186 | |
| 187 | self.entities = [ |
| 188 | entity |
| 189 | for entity in self.entities |
| 190 | if entity.label not in entities_to_discard |
| 191 | ] |
| 192 | self.relations = [ |
| 193 | relation |
| 194 | for relation in self.relations |
| 195 | if relation.source.label not in entities_to_discard |
| 196 | and relation.target.label not in entities_to_discard |
| 197 | ] |
| 198 | |
| 199 | if len(entities_to_discard) > 0: |
| 200 | logger.info(f"Discarded entities: {', '.join(entities_to_discard)}") |
| 201 | |
| 202 | return self |
| 203 | |
| 204 | def discard_relations_without_entities(self): |
| 205 | """ |
| 206 | Discards relations that have entities not present in the ontology. |
| 207 | |
| 208 | Returns: |
| 209 | The current instance of the Ontology class. |
| 210 | """ |
| 211 | relations_to_discard = [ |
| 212 | relation.label |
| 213 | for relation in self.relations |
| 214 | if relation.source.label not in [entity.label for entity in self.entities] |
| 215 | or relation.target.label not in [entity.label for entity in self.entities] |
| 216 | ] |
| 217 | |
| 218 | self.relations = [ |
| 219 | relation |
| 220 | for relation in self.relations |
| 221 | if relation.label not in relations_to_discard |
| 222 | ] |
| 223 | |
| 224 | if len(relations_to_discard) > 0: |
| 225 | logger.info(f"Discarded relations: {', '.join(relations_to_discard)}") |
| 226 | |
| 227 | return self |
| 228 | |
| 229 | def validate_entities(self): |
| 230 | """ |
| 231 | Validates the entities in the ontology. |
| 232 | |
| 233 | This method checks for entities without unique attributes and logs a warning if any are found. |
| 234 | |
| 235 | Returns: |
| 236 | True if all entities have unique attributes, False otherwise. |
| 237 | """ |
| 238 | # Check for entities without unique attributes |
| 239 | entities_without_unique_attributes = [ |
| 240 | entity.label |
| 241 | for entity in self.entities |
| 242 | if len(entity.get_unique_attributes()) == 0 |
| 243 | ] |
| 244 | if len(entities_without_unique_attributes) > 0: |
| 245 | logger.warn( |
| 246 | f""" |
| 247 | *** WARNING *** |
| 248 | The following entities do not have unique attributes: |
| 249 | {', '.join(entities_without_unique_attributes)} |
| 250 | """ |
| 251 | ) |
| 252 | return False |
| 253 | return True |
| 254 | |
| 255 | def get_entity_with_label(self, label: str): |
| 256 | """ |
| 257 | Retrieves the entity with the specified label. |
| 258 | |
| 259 | Args: |
| 260 | label (str): The label of the entity to retrieve. |
| 261 | |
| 262 | Returns: |
| 263 | The entity with the specified label, or None if not found. |
| 264 | """ |
| 265 | return next((n for n in self.entities if n.label == label), None) |
| 266 | |
| 267 | def get_relations_with_label(self, label: str): |
| 268 | """ |
| 269 | Returns a list of relations with the specified label. |
| 270 | |
| 271 | Parameters: |
| 272 | label (str): The label to search for. |
| 273 | |
| 274 | Returns: |
| 275 | A list of relations with the specified label. |
| 276 | """ |
| 277 | return [e for e in self.relations if e.label == label] |
| 278 | |
| 279 | def has_entity_with_label(self, label: str): |
| 280 | """ |
| 281 | Checks if the ontology has an entity with the given label. |
| 282 | |
| 283 | Parameters: |
| 284 | label (str): The label to search for. |
| 285 | |
| 286 | Returns: |
| 287 | True if an entity with the given label exists, False otherwise. |
| 288 | """ |
| 289 | return any(n.label == label for n in self.entities) |
| 290 | |
| 291 | def has_relation_with_label(self, label: str): |
| 292 | """ |
| 293 | Checks if the ontology has a relation with the given label. |
| 294 | |
| 295 | Parameters: |
| 296 | label (str): The label of the relation to check. |
| 297 | |
| 298 | Returns: |
| 299 | True if a relation with the given label exists, False otherwise. |
| 300 | """ |
| 301 | return any(e.label == label for e in self.relations) |
| 302 | |
| 303 | def __str__(self) -> str: |
| 304 | """ |
| 305 | Returns a string representation of the Ontology object. |
| 306 | |
| 307 | The string includes a list of entities and relations in the ontology. |
| 308 | |
| 309 | Returns: |
| 310 | A string representation of the Ontology object. |
| 311 | """ |
| 312 | return "Entities:\n\f- {entities}\n\nEdges:\n\f- {relations}".format( |
| 313 | entities="\n- ".join([str(entity) for entity in self.entities]), |
| 314 | relations="\n- ".join([str(relation) for relation in self.relations]), |
| 315 | ) |
| 316 | |
| 317 | def save_to_graph(self, graph: Graph): |
| 318 | """ |
| 319 | Saves the entities and relations to the specified graph. |
| 320 | |
| 321 | Args: |
| 322 | graph (Graph): The graph to save the entities and relations to. |
| 323 | """ |
| 324 | for entity in self.entities: |
| 325 | query = entity.to_graph_query() |
| 326 | logger.debug(f"Query: {query}") |
| 327 | graph.query(query) |
| 328 | |
| 329 | for relation in self.relations: |
| 330 | query = relation.to_graph_query() |
| 331 | logger.debug(f"Query: {query}") |
| 332 | graph.query(query) |