
    Ng                    X    d dl mZ d dlZd dlmZmZmZmZ erd dlZ G d d          Z	dS )    )annotationsN)TYPE_CHECKINGListOptionalUnionc                      e Zd ZdZ	 	 	 dddZedd            ZddZeddd            Zedd            Z	ddZ
edd            ZddZdS ) OntotextGraphDBGrapha  Ontotext GraphDB https://graphdb.ontotext.com/ wrapper for graph operations.

    *Security note*: Make sure that the database connection uses credentials
        that are narrowly-scoped to only include necessary permissions.
        Failure to do so may result in data corruption or loss, since the calling
        code may attempt commands that would result in deletion, mutation
        of data if appropriately prompted or reading sensitive data if such
        data is present in the database.
        The best way to guard against such negative outcomes is to (as appropriate)
        limit the permissions granted to the credentials used with this tool.

        See https://python.langchain.com/docs/security for more information.
    Nquery_endpointstrquery_ontologyOptional[str]
local_filelocal_file_formatreturnNonec                6   |r|rt          d          |s|st          d          	 ddl}ddlm} n# t          $ r t	          d          w xY w|                                 }|                    |          }|                    |            |j        |dd	          | _	        | 
                                 |r|                     ||          }	n*|                     |           |                     |          }	|	                    d
          | _        dS )a+  
        Set up the GraphDB wrapper

        :param query_endpoint: SPARQL endpoint for queries, read access

        If GraphDB is secured,
        set the environment variables 'GRAPHDB_USERNAME' and 'GRAPHDB_PASSWORD'.

        :param query_ontology: a `CONSTRUCT` query that is executed
        on the SPARQL endpoint and returns the KG schema statements
        Example:
        'CONSTRUCT {?s ?p ?o} FROM <https://example.com/ontology/> WHERE {?s ?p ?o}'
        Currently, DESCRIBE queries like
        'PREFIX onto: <https://example.com/ontology/>
        PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        DESCRIBE ?term WHERE {
            ?term rdfs:isDefinedBy onto:
        }'
        are not supported, because DESCRIBE returns
        the Symmetric Concise Bounded Description (SCBD),
        i.e. also the incoming class links.
        In case of large graphs with a million of instances, this is not efficient.
        Check https://github.com/eclipse-rdf4j/rdf4j/issues/4857

        :param local_file: a local RDF ontology file.
        Supported RDF formats:
        Turtle, RDF/XML, JSON-LD, N-Triples, Notation-3, Trig, Trix, N-Quads.
        If the rdf format can't be determined from the file extension,
        pass explicitly the rdf format in `local_file_format` param.

        :param local_file_format: Used if the rdf format can't be determined
        from the local file extension.
        One of "json-ld", "xml", "n3", "turtle", "nt", "trig", "nquads", "trix"

        Either `query_ontology` or `local_file` should be passed.
        z2Both file and query provided. Only one is allowed.z1Neither file nor query provided. One is required.r   N)sparqlstorezTCould not import rdflib python package. Please install it with `pip install rdflib`.)authnone)
identifierbind_namespacesturtleformat)
ValueErrorrdflibrdflib.plugins.storesr   ImportError	_get_authSPARQLStoreopenGraphgraph_check_connectivity_load_ontology_schema_from_file_validate_user_query _load_ontology_schema_with_query	serializeschema)
selfr
   r   r   r   r   r   r   storeontology_schema_graphs
             m/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/graphs/ontotext_graphdb_graph.py__init__zOntotextGraphDBGraph.__init__   ss   X  	Sj 	SQRRR 	Rj 	RPQQQ	MMM9999999 	 	 	?  	 ~~''T'22

>"""!V\%D&QQQ
  """ 		$($H$H!% %!!
 %%n555$($I$I% %! ,55X5FFs	   
3 AUnion[tuple, None]c                     t           j                            dd          } t           j                            dd          }| r|st          d          | |fS dS )z@
        Returns the basic authentication configuration
        GRAPHDB_USERNAMENGRAPHDB_PASSWORDzREnvironment variable 'GRAPHDB_USERNAME' is set, but 'GRAPHDB_PASSWORD' is not set.)osenvirongetr   )usernamepasswords     r-   r   zOntotextGraphDBGraph._get_authl   si    
 :>>"4d;;:>>"4d;; 	* * 9  
  ))t    c                v    	 | j                             d           dS # t          $ r t          d          w xY w)zE
        Executes a simple `ASK` query to check connectivity
        zASK { ?s ?p ?o }zCould not query the provided endpoint. Please, check, if the value of the provided query_endpoint points to the right repository. If GraphDB is secured, please, make sure that the environment variables 'GRAPHDB_USERNAME' and 'GRAPHDB_PASSWORD' are set.N)r#   queryr   r*   s    r-   r$   z(OntotextGraphDBGraph._check_connectivity~   sW    
	J/00000 	 	 	E  	s    8c                r   ddl }t          j                            |           st	          d|  d          t          j        | t          j                  st          d|  d           |j                    }	 |	                    | |           n&# t          $ r}t          d|  d	|          d}~ww xY w|S )
zM
        Parse the ontology schema statements from the provided file
        r   NzFile z does not exist.zRead permission for z is restrictedr   zInvalid file format for z : )r   r3   pathexistsFileNotFoundErroraccessR_OKPermissionErrorConjunctiveGraphparse	Exceptionr   )r   r   r   r#   es        r-   r%   z4OntotextGraphDBGraph._load_ontology_schema_from_file   s    
 	w~~j)) 	J#$HJ$H$H$HIIIyRW-- 	U!"S"S"S"STTT''))	LKK
+<K==== 	L 	L 	LG
GGGKKK	Ls   9B 
B4B//B4c                    ddl m} ddlm} t	          | t
                    st          d          	  ||           }n# |$ r}t          d|          d}~ww xY w|j        j	        dk    rt          d          dS )	zF
        Validate the query is a valid SPARQL CONSTRUCT query
        r   )ParseException)prepareQueryz*Ontology query must be provided as string.z+Ontology query is not a valid SPARQL query.NConstructQueryz9Invalid query type. Only CONSTRUCT queries are supported.)
	pyparsingrH   rdflib.plugins.sparqlrI   
isinstancer   	TypeErrorr   algebraname)r   rH   rI   parsed_queryrF   s        r-   r&   z)OntotextGraphDBGraph._validate_user_query   s    
 	-,,,,,666666.#.. 	JHIII	O'<77LL 	O 	O 	OJANNN	O $(888K   98s   > AAAr:   c                    ddl m} 	 | j                            |          }n# |$ r}t	          d|           d}~ww xY w|j        S )zQ
        Execute the query for collecting the ontology schema statements
        r   )ParserErrorz&Generated SPARQL statement is invalid
N)rdflib.exceptionsrS   r#   r:   r   )r*   r:   rS   resultsrF   s        r-   r'   z5OntotextGraphDBGraph._load_ontology_schema_with_query   sw     	211111	Lj&&u--GG 	L 	L 	LJqJJKKK	L }s   # ?:?c                    | j         S )zK
        Returns the schema of the graph database in turtle format
        )r)   r;   s    r-   
get_schemazOntotextGraphDBGraph.get_schema   s    
 {r8   List[rdflib.query.ResultRow]c                `    ddl m | j                            |          }fd|D             S )z"
        Query the graph.
        r   )	ResultRowc                4    g | ]}t          |          |S  )rM   ).0rrZ   s     r-   
<listcomp>z.OntotextGraphDBGraph.query.<locals>.<listcomp>   s(    ;;;a*Q	":":;;;;r8   )rdflib.queryrZ   r#   r:   )r*   r:   resrZ   s      @r-   r:   zOntotextGraphDBGraph.query   sF     	+*****ju%%;;;;3;;;;r8   )NNN)
r
   r   r   r   r   r   r   r   r   r   )r   r/   )r   r   )N)r   r   r   r   )r   r   r   r   )r:   r   )r   r   )r:   r   r   rX   )__name__
__module____qualname____doc__r.   staticmethodr   r$   r%   r&   r'   propertyrW   r:   r\   r8   r-   r	   r	      s        " )-$(+/LG LG LG LG LG\    \"         \"    \&       X
< 
< 
< 
< 
< 
<r8   r	   )

__future__r   r3   typingr   r   r   r   r   r	   r\   r8   r-   <module>rj      s    " " " " " " 				             MMMC< C< C< C< C< C< C< C< C< C<r8   