| 1 | import json |
| 2 | import logging |
| 3 | from .attribute import Attribute |
| 4 | from falkordb import Node as GraphNode |
| 5 | import re |
| 6 | |
| 7 | logger = logging.getLogger(__name__) |
| 8 | |
| 9 | descriptionKey = "__description__" |
| 10 | |
| 11 | |
| 12 | class Entity: |
| 13 | """ |
| 14 | Represents an entity in the knowledge graph. |
| 15 | |
| 16 | Attributes: |
| 17 | label (str): The label of the entity. |
| 18 | attributes (list[Attribute]): The attributes associated with the entity. |
| 19 | description (str): The description of the entity (optional). |
| 20 | |
| 21 | Methods: |
| 22 | from_graph(entity: GraphNode) -> Entity: Creates an Entity object from a GraphNode object. |
| 23 | from_json(txt: dict | str) -> Entity: Creates an Entity object from a JSON string or dictionary. |
| 24 | to_json() -> dict: Converts the Entity object to a JSON dictionary. |
| 25 | merge(entity2: Entity) -> Entity: Overwrites attributes of self with attributes of entity2. |
| 26 | get_unique_attributes() -> list[Attribute]: Returns a list of unique attributes of the entity. |
| 27 | to_graph_query() -> str: Generates a Cypher query to merge the entity in the graph. |
| 28 | """ |
| 29 | |
| 30 | def __init__(self, label: str, attributes: list[Attribute], description: str = ""): |
| 31 | """ |
| 32 | Initialize a new Entity object. |
| 33 | |
| 34 | Args: |
| 35 | label (str): The label of the entity. |
| 36 | attributes (list[Attribute]): A list of Attribute objects associated with the entity. |
| 37 | description (str, optional): The description of the entity. Defaults to "". |
| 38 | """ |
| 39 | self.label = re.sub(r"([^a-zA-Z0-9_])", "", label) |
| 40 | self.attributes = attributes |
| 41 | self.description = description |
| 42 | |
| 43 | @staticmethod |
| 44 | def from_graph(entity: GraphNode): |
| 45 | """ |
| 46 | Converts a GraphNode object to an Entity object. |
| 47 | |
| 48 | Args: |
| 49 | entity (GraphNode): The GraphNode object to convert. |
| 50 | |
| 51 | Returns: |
| 52 | Entity: The converted Entity object. |
| 53 | |
| 54 | """ |
| 55 | logger.debug(f"Entity.from_graph: {entity}") |
| 56 | return Entity( |
| 57 | entity.labels[0], |
| 58 | [ |
| 59 | Attribute.from_string(f"{attr}:{entity.properties[attr]}") |
| 60 | for attr in entity.properties |
| 61 | if attr != descriptionKey |
| 62 | ], |
| 63 | entity.properties.get(descriptionKey, ""), |
| 64 | ) |
| 65 | |
| 66 | @staticmethod |
| 67 | def from_json(txt: dict | str): |
| 68 | """ |
| 69 | Create an Entity object from a JSON representation. |
| 70 | |
| 71 | Args: |
| 72 | txt (dict | str): The JSON representation of the Entity. It can be either a dictionary or a string. |
| 73 | |
| 74 | Returns: |
| 75 | Entity: The Entity object created from the JSON representation. |
| 76 | |
| 77 | """ |
| 78 | txt = txt if isinstance(txt, dict) else json.loads(txt) |
| 79 | return Entity( |
| 80 | txt["label"], |
| 81 | [Attribute.from_json(attr) for attr in (txt.get("attributes", []))], |
| 82 | txt.get("description", ""), |
| 83 | ) |
| 84 | |
| 85 | def to_json(self): |
| 86 | """ |
| 87 | Convert the entity object to a JSON representation. |
| 88 | |
| 89 | Returns: |
| 90 | dict: A dictionary representing the entity object in JSON format. |
| 91 | The dictionary contains the following keys: |
| 92 | - "label": The label of the entity. |
| 93 | - "attributes": A list of attribute objects converted to JSON format. |
| 94 | - "description": The description of the entity. |
| 95 | """ |
| 96 | return { |
| 97 | "label": self.label, |
| 98 | "attributes": [attr.to_json() for attr in self.attributes], |
| 99 | "description": self.description, |
| 100 | } |
| 101 | |
| 102 | def merge(self, entity2: "Entity"): |
| 103 | """Overwrite attributes of self with attributes of entity2. |
| 104 | |
| 105 | Args: |
| 106 | entity2 (Entity): The entity to merge with self. |
| 107 | |
| 108 | Raises: |
| 109 | Exception: If the entities have different labels. |
| 110 | |
| 111 | Returns: |
| 112 | Entity: The merged entity. |
| 113 | """ |
| 114 | if self.label != entity2.label: |
| 115 | raise Exception("Entities must have the same label to be combined") |
| 116 | |
| 117 | for attr in entity2.attributes: |
| 118 | if attr.name not in [a.name for a in self.attributes]: |
| 119 | logger.debug(f"Adding attribute {attr.name} to entity {self.label}") |
| 120 | self.attributes.append(attr) |
| 121 | |
| 122 | return self |
| 123 | |
| 124 | def get_unique_attributes(self): |
| 125 | """ |
| 126 | Returns a list of unique attributes for the entity. |
| 127 | |
| 128 | Returns: |
| 129 | list: A list of attributes that are marked as unique. |
| 130 | """ |
| 131 | return [attr for attr in self.attributes if attr.unique] |
| 132 | |
| 133 | def to_graph_query(self): |
| 134 | """ |
| 135 | Generates a Cypher query string for creating or updating a node in a graph database. |
| 136 | |
| 137 | Returns: |
| 138 | str: The Cypher query string. |
| 139 | """ |
| 140 | unique_attributes = ", ".join( |
| 141 | [str(attr) for attr in self.attributes if attr.unique] |
| 142 | ) |
| 143 | non_unique_attributes = ", ".join( |
| 144 | [str(attr) for attr in self.attributes if not attr.unique] |
| 145 | ) |
| 146 | if self.description: |
| 147 | non_unique_attributes += f"{', ' if len(non_unique_attributes) > 0 else ''} {descriptionKey}: '{self.description}'" |
| 148 | return f"MERGE (n:{self.label} {{{unique_attributes}}}) SET n += {{{non_unique_attributes}}} RETURN n" |
| 149 | |
| 150 | def __str__(self) -> str: |
| 151 | """ |
| 152 | Returns a string representation of the Entity object. |
| 153 | |
| 154 | The string representation includes the label of the entity and its attributes. |
| 155 | |
| 156 | Returns: |
| 157 | str: The string representation of the Entity object. |
| 158 | """ |
| 159 | return ( |
| 160 | f"(:{self.label} {{{', '.join([str(attr) for attr in self.attributes])}}})" |
| 161 | ) |