
    Ng                    |    d Z ddlmZ ddlmZmZmZmZmZ dZ	 G d de          Z
ddZddZ G d d          ZdS )z&Networkx wrapper for graph operations.    )annotations)AnyList
NamedTupleOptionalTuplez<|>c                  J    e Zd ZU dZded<   ded<   ded<   edd	            Zd
S )KnowledgeTriplezKnowledge triple in the graph.strsubject	predicateobject_triple_stringreturn'KnowledgeTriple'c                    |                                                     d          \  }}}|dd         }|dd         } | |||          S )z'Create a KnowledgeTriple from a string.z,    Nstripsplit)clsr   r   r   r   s        e/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/graphs/networkx_graph.pyfrom_stringzKnowledgeTriple.from_string   sX     '4&9&9&;&;&A&A$&G&G#G!""+#2#,s7Iw///    N)r   r   r   r   )__name__
__module____qualname____doc____annotations__classmethodr    r   r   r
   r
   
   sU         ((LLLNNNLLL0 0 0 [0 0 0r   r
   knowledge_strr   r   List[KnowledgeTriple]c                   |                                  } | r| dk    rg S |                     t                    }g }|D ]C}	 t                              |          }n# t
          $ r Y *w xY w|                    |           D|S )z2Parse knowledge triples from the knowledge string.NONE)r   r   KG_TRIPLE_DELIMITERr
   r   
ValueErrorappend)r#   triple_strsresults
triple_str	kg_triples        r   parse_triplesr.      s    !''))M MV33	%%&9::KG! " "
	'33J??II 	 	 	H	y!!!!Ns    A
A('A(
entity_str	List[str]c                t    |                                  dk    rg S d |                     d          D             S )z$Extract entities from entity string.r&   c                6    g | ]}|                                 S r"   )r   ).0ws     r   
<listcomp>z get_entities.<locals>.<listcomp>/   s     999a		999r   ,r   )r/   s    r   get_entitiesr7   *   s@    V##	99:#3#3C#8#89999r   c                      e Zd ZdZd*d+dZed,d
            Zd-dZd-dZd.dZ	d/d0dZ
d1dZd2dZd2dZd3dZd3dZd4dZd5d"Zd6d#Zd7d$Zd8d%Zd9d&Zd:d)ZdS );NetworkxEntityGrapha  Networkx wrapper for entity 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graphOptional[Any]r   Nonec                    	 ddl }n# t          $ r t          d          w xY w|-t          ||j                  st	          d          || _        dS |                                | _        dS )zCreate a new graph.r   NXCould not import networkx python package. Please install it with `pip install networkx`.z'Passed in graph is not of correct shape)networkxImportError
isinstanceDiGraphr(   _graph)selfr:   nxs      r   __init__zNetworkxEntityGraph.__init__A   s    	!!!!! 	 	 	A  	
 eRZ00 L !JKKKDKKK**,,DKKK    !gml_pathr   c                    	 dd l }n# t          $ r t          d          w xY w|                    |          } | |          S )Nr   r>   )r?   r@   read_gml)r   rH   rE   r:   s       r   from_gmlzNetworkxEntityGraph.from_gmlQ   sj    	!!!!! 	 	 	A  	
 H%%s5zzrG   knowledge_tripler
   c                V   | j                             |j                  s| j                             |j                   | j                             |j                  s| j                             |j                   | j                             |j        |j        |j                   dS )zAdd a triple to the graph.relationN)rC   has_noder   add_noder   add_edger   rD   rL   s     r   
add_triplezNetworkxEntityGraph.add_triple]   s     {##$4$<== 	;K  !1!9:::{##$4$<== 	;K  !1!9:::$$%/ 	 	
 	
 	
 	
 	
r   c                    | j                             |j        |j                  r'| j                             |j        |j                   dS dS )zDelete a triple from the graph.N)rC   has_edger   r   remove_edgerS   s     r   delete_triplez!NetworkxEntityGraph.delete_triplek   sW    ; 0 8:J:RSS 	XK##$4$<>N>VWWWWW	X 	Xr   List[Tuple[str, str, str]]c                L    d | j                             d          D             S )zGet all triples in the graph.c                ,    g | ]\  }}}|||d          fS rN   r"   )r3   uvds       r   r5   z3NetworkxEntityGraph.get_triples.<locals>.<listcomp>r   s)    RRR'!QAq}%RRRr   T)data)rC   edgesrD   s    r   get_tripleszNetworkxEntityGraph.get_triplesp   s)    RRT[5F5FD5F5Q5QRRRRr   r   entitydepthintr0   c                    ddl }| j                            |          sg S g }|                    | j        ||          D ];\  }}| j        |         |         d         }|                    | d| d|            <|S )z Get information about an entity.r   N)depth_limitrO    )r?   rC   rP   	dfs_edgesr)   )rD   rc   rd   rE   r+   srcsinkrO   s           r   get_entity_knowledgez(NetworkxEntityGraph.get_entity_knowledget   s     {##F++ 	Idk6uMM 	7 	7IC{3'-j9HNNc55H55t556666r   pathc                D    dd l }|                    | j        |           d S )Nr   )r?   	write_gmlrC   )rD   rm   rE   s      r   write_to_gmlz NetworkxEntityGraph.write_to_gml   s*    
T[$'''''r   c                8    | j                                          dS )zClear the graph.N)rC   clearra   s    r   rr   zNetworkxEntityGraph.clear   s    r   c                8    | j                                          dS )zClear the graph edges.N)rC   clear_edgesra   s    r   rt   zNetworkxEntityGraph.clear_edges   s    !!!!!r   nodec                :    | j                             |           dS )zAdd node in the graph.N)rC   rQ   rD   ru   s     r   rQ   zNetworkxEntityGraph.add_node   s    T"""""r   c                r    | j                             |          r| j                             |           dS dS )zRemove node from the graph.N)rC   rP   remove_noderw   s     r   ry   zNetworkxEntityGraph.remove_node   s@    ;%% 	*K##D)))))	* 	*r   boolc                6    | j                             |          S )z#Return if graph has the given node.)rC   rP   rw   s     r   rP   zNetworkxEntityGraph.has_node   s    {##D)))r   source_nodedestination_nodec                <    | j                             ||           dS )zRemove edge from the graph.N)rC   rW   rD   r|   r}   s      r   rW   zNetworkxEntityGraph.remove_edge   s!    -=>>>>>r   c                    | j                             |          r5| j                             |          r| j                             ||          S dS )z4Return if graph has an edge between the given nodes.F)rC   rP   rV   r   s      r   rV   zNetworkxEntityGraph.has_edge   sP    ;,, 	1E1EFV1W1W 	;''5EFFF5r   c                6    | j                             |          S )z,Return the neighbor nodes of the given node.)rC   	neighborsrw   s     r   get_neighborsz!NetworkxEntityGraph.get_neighbors   s    {$$T***r   c                4    | j                                         S )z!Get number of nodes in the graph.)rC   number_of_nodesra   s    r   get_number_of_nodesz'NetworkxEntityGraph.get_number_of_nodes   s    {**,,,r   c                X    ddl }t          |                    | j                            S )zDGet a list of entity names in the graph sorted by causal dependence.r   N)r?   listtopological_sortrC   )rD   rE   s     r   get_topological_sortz(NetworkxEntityGraph.get_topological_sort   s,    B''44555r   kwargsr   c                \   ddl m} 	 ddl}n<# t          $ r/}|j        dk    r	 t          d          t          d          d}~ww xY w || j                  }|                    |                    dd          	           |                    |                    d
d                     dS )z
        Provides better drawing

        Usage in a jupyter notebook:

            >>> from IPython.display import SVG
            >>> self.draw_graphviz_svg(layout="dot", filename="web.svg")
            >>> SVG('web.svg')
        r   )	to_agraphN	_graphvizzCould not import graphviz debian package. Please install it with:`sudo apt-get update``sudo apt-get install graphviz graphviz-dev`z\Could not import pygraphviz python package. Please install it with:`pip install pygraphviz`.progdot)r   rm   z	graph.svg)	networkx.drawing.nx_agraphr   
pygraphvizr@   namerC   layoutgetdraw)rD   r   r   r   er:   s         r   draw_graphvizz!NetworkxEntityGraph.draw_graphviz   s     	988888	 	 	 	v$$ "C   "0  	& 	$+&&&**VU33444

6::fk2233333s    
A*AA)N)r:   r;   r   r<   )rH   r   r   r9   )rL   r
   r   r<   )r   rY   )r   )rc   r   rd   re   r   r0   )rm   r   r   r<   )r   r<   )ru   r   r   r<   )ru   r   r   rz   )r|   r   r}   r   r   r<   )r|   r   r}   r   r   rz   )ru   r   r   r0   )r   re   )r   r0   )r   r   r   r<   )r   r   r   r   rF   r!   rK   rT   rX   rb   rl   rp   rr   rt   rQ   ry   rP   rW   rV   r   r   r   r   r"   r   r   r9   r9   2   s        ' ' ' ' '  	 	 	 [	
 
 
 
X X X X
S S S S    ( ( ( (
   " " " "# # # #* * * *
* * * *? ? ? ?   + + + +- - - -6 6 6 6%4 %4 %4 %4 %4 %4r   r9   N)r#   r   r   r$   )r/   r   r   r0   )r   
__future__r   typingr   r   r   r   r   r'   r
   r.   r7   r9   r"   r   r   <module>r      s    , , " " " " " " 9 9 9 9 9 9 9 9 9 9 9 9 9 9 0 0 0 0 0j 0 0 0     : : : :h4 h4 h4 h4 h4 h4 h4 h4 h4 h4r   