
    Q
i7                     v   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZmZmZmZmZmZmZmZ d dlmZ d dlmZ d d	lmZ d d
lmZ  ed          ZdefdZ de!fdZ"dedeeef         fdZ#de$de$ddfdZ%dedefdZ&dedefdZ'd)dedee         defdZ(ed             Z)d*dee         dee         fdZ*d*dee         dee         fdZ+deg eeeef         f         deg df         fdZ,d e!de!fd!Z-d e!de!fd"Z.d e!de!fd#Z/d$ed%edee         fd&Z0d'edefd(Z1dS )+    N)contextmanager)Enum)wrapstime)AnyCallable	CoroutineDictOptionalSequenceTypeVarcast)warn)	BaseModel)Redis)ULIDTreturnc                  8    t          t                                S )z>Generate a unique identifier to group related Redis documents.)strr        C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\redisvl/utils/utils.pycreate_ulidr      s    tvv;;r   c                      t                      S )z=Generate a unix epoch timestamp to assign to Redis documents.r   r   r   r   current_timestampr      s    66Mr   modelc                     fd|                      dd          }|                                D ]\  }} |          ||<   |S )z
    Custom serialization function that converts a Pydantic model to a dict,
    serializing Enum fields to their values, and handling nested models and lists.
    c                    t          | t                    r| j                                        S t          | t                    r7|                     dd          }fd|                                D             S t          | t                    r fd|                                 D             S t          | t                    rfd| D             S | S )NTFexclude_noneexclude_defaultsc                 .    i | ]\  }}| |          S r   r   .0keyvalueserialize_items      r   
<dictcomp>z9model_to_dict.<locals>.serialize_item.<locals>.<dictcomp>,   s)    UUU:3C..UUUr   c                 .    i | ]\  }}| |          S r   r   r%   s      r   r*   z9model_to_dict.<locals>.serialize_item.<locals>.<dictcomp>.   s)    NNN:3C..NNNr   c                 &    g | ]} |          S r   r   )r&   elementr)   s     r   
<listcomp>z9model_to_dict.<locals>.serialize_item.<locals>.<listcomp>0   s#    @@@NN7++@@@r   )	
isinstancer   r(   lowerr   
model_dumpitemsdictlist)itemnested_datar)   s     r   r)   z%model_to_dict.<locals>.serialize_item&   s    dD!! 	:##%%%i(( 		//te/TTKUUUUARARATATUUUUd## 	NNNNNNNNd## 	@@@@4@@@@Kr   TFr!   )r1   r2   )r   serialized_datar'   r(   r)   s       @r   model_to_dictr8       sr         &&D5&QQO%++-- 5 5
U-~e44r   v1v2c                 @    | |k    rt          d|  d| d          dS )z(Check the equality of vector dimensions.z6Invalid vector dimensions! Vector has dims defined as z!Vector field has dims defined as z@Vector dims must be equal in order to perform similarity search.N)
ValueError)r9   r:   s     r   validate_vector_dimsr=   ;   s=    	RxxLLL444N
 
 	
 xr   datac                 *    t          j        |           S )z Serlize the input into a string.)jsondumpsr>   s    r   	serializerC   E       :dr   c                 *    t          j        |           S )z$Deserialize the input from a string.)r@   loadsrB   s    r   deserializerG   J   rD   r   argumentreplacementc                 8     d  d|r	d| dz   fd}|S )a`  
    Decorator to warn if a deprecated argument is passed.

    When the wrapped function is called, the decorator will warn if the
    deprecated argument is passed as an argument or keyword argument.

    NOTE: The @deprecated_argument decorator should not fall "outside"
    of the @classmethod decorator, but instead should come between
    it and the method definition. For example:

        class MyClass:
            @classmethod
            @deprecated_argument("old_arg", "new_arg")
            @other_decorator
            def test_method(cls, old_arg=None, new_arg=None):
                pass
    z	Argument z= is deprecated and will be removed in the next major release.z Use z	 instead.c                 (    t           t          t          f          rV j        t	                    fd            }t           t                    rt          |          S t          |          S t	                      fd            }|S )Nc                      |v rt          t          d           nAt          j                  } |j        | i |}|j        v rt          t          d            | i |S N   )
stacklevelr   DeprecationWarninginspect	signaturebind	arguments)argskwargssig
bound_argsrH   message
underlyings       r   inner_wrappedz=deprecated_argument.<locals>.decorator.<locals>.inner_wrappedj   s    v%%"4CCCCC!+J77C!)4!:6!:!:J:#777W&8QGGGG!z426222r   c                      |v rt          t          d           nAt          j                  } |j        | i |}|j        v rt          t          d            | i |S rM   rP   )rV   rW   rX   rY   rH   funcrZ   s       r   inner_normalz<deprecated_argument.<locals>.decorator.<locals>.inner_normal{   s    v%%"4CCCCC!+D11C!)4!:6!:!:J:#777W&8QGGGGtT,V,,,r   )r/   classmethodstaticmethod__func__r   )r^   r\   r_   r[   rH   rZ   s   `  @r   	decoratorz&deprecated_argument.<locals>.decoratore   s    d[,788 	 J:3 3 3 3 3 3 3 $,, 3"=111#M222 4[[- - - - - - [-  r   r   )rH   rI   rc   rZ   s   `  @r   deprecated_argumentrd   O   s\    $ b(aaaG 21;1111!  !  !  !  !  ! F r   c               #      K   t          j                    5  t          j        d           dV  ddd           dS # 1 swxY w Y   dS )zH
    Assert that a function does not emit any warnings when called.
    errorN)warningscatch_warningssimplefilterr   r   r   assert_no_warningsrj      s      
 
	 	"	"  g&&&                 s   <A A namec                       fd}|S )z
    Decorator to mark a function as deprecated.

    When the wrapped function is called, the decorator will log a deprecation
    warning.
    c                 n     p j         }d| drz  t                      fd            }|S )Nz	Function > is deprecated and will be removed in the next major release. c                  B    t          t          d            | i |S )N   categoryrO   r   rQ   )rV   rW   r^   warning_messages     r   wrapperz7deprecated_function.<locals>.decorator.<locals>.wrapper   s.    +=!LLLL4((((r   )__name__r   )r^   fn_nameru   rt   rk   rI   s   `  @r   rc   z&deprecated_function.<locals>.decorator   su    '$-2 2 2 2 	  	+{*O	t	) 	) 	) 	) 	) 
	) r   r   rk   rI   rc   s   `` r   deprecated_functionry      s*           r   c                       fd}|S )a  
    Decorator to mark a class as deprecated.

    When the decorated class is instantiated, the decorator will emit a
    deprecation warning.

    Args:
        name: Optional custom name for the class in the warning message.
              If not provided, uses the class's __name__.
        replacement: Optional message describing what to use instead.

    Example:
        @deprecated_class(replacement="Use NewClass instead.")
        class OldClass:
            pass
    c                     p| j         }d| drz  | j        t                    fd            }|| _        | S )NzClass rn   c                 N    t          t          d            | g|R i | d S )NrN   rq   rs   )selfrV   rW   original_initrt   s      r   new_initz5deprecated_class.<locals>.decorator.<locals>.new_init   s?    +=!LLLLM$000000000r   )rv   __init__r   )cls
class_namer   r~   rt   rk   rI   s      @@r   rc   z#deprecated_class.<locals>.decorator   s    )S\
2Z 2 2 2 	  	+{*O	}			1 	1 	1 	1 	1 
		1  
r   r   rx   s   `` r   deprecated_classr      s*    $     & r   fnc                       fd}|S )Nc                      t           t          t           dd           d S 	 t          j                    } n# t          $ r d } Y nt
          $ r Y d S w xY w	 | |                                 s0t          d S t          j                    } t          j        |            | 	                                           }| 
                    |           d S # t          t          t          f$ r}Y d }~d S d }~wt
          $ r Y d S w xY w)N	_getframe)sysgetattrasyncioget_running_loopRuntimeError	Exception
is_runningnew_event_loopset_event_loopcreate_taskrun_until_completeAttributeError	TypeError)looptasker   s      r   ru   zsync_wrapper.<locals>.wrapper   s2   ;'#{D99AF	+--DD 	 	 	DDD 	 	 	FF		|4??#4#4|?F-//&t,,,##BBDD))D##D)))))ni8 	 	 	 FFFFF 	 	 	FF	s4   6 A	AAC 4AC C=,C=<C=r   )r   ru   s   ` r   sync_wrapperr      s$    " " " " "H Nr   r(   c                 .    t          d| z
  dz  d          S )zL
    Normalize a cosine distance to a similarity score between 0 and 1.
    rN   r   maxr(   s    r   norm_cosine_distancer      s     E	Q"""r   c                 .    t          dd| z  z
  d          S )zb
    Denormalize a similarity score between 0 and 1 to a cosine distance between
    0 and 2.
    rN   r   r   r   s    r   denorm_cosine_distancer     s    
 q1u9}a   r   c                     dd| z   z  S )z$
    Normalize the L2 distance.
       r   r   s    r   norm_l2_distancer     s     E	?r   redis_clientpatternc                 f    ddl m}  |t          |                     |                              S )a  
    Scan the Redis database for keys matching a specific pattern.

    Args:
        redis (Redis): The Redis client instance.
        pattern (str): The pattern to match keys against.

    Returns:
        List[str]: A dictionary containing the keys and their values.
    r   )convert_bytes)match)redisvl.redis.utilsr   r4   	scan_iter)r   r   r   s      r   scan_by_patternr     s?     211111=l4474CCDDEEEr   module_pathc                     |                      d          }|d         }|t          j        v r%t          |          dk    rt          j        |         S  G d d          } ||           S )a  
    Lazily import a module or object from a module only when it's actually used.

    This function helps reduce startup time and avoid unnecessary dependencies
    by only importing modules when they are actually needed.

    Args:
        module_path (str): The import path, e.g., "numpy" or "numpy.array"

    Returns:
        Any: The imported module or object, or a proxy that will import it when used

    Examples:
        >>> np = lazy_import("numpy")
        >>> # numpy is not imported yet
        >>> array = np.array([1, 2, 3])  # numpy is imported here

        >>> array_func = lazy_import("numpy.array")
        >>> # numpy is not imported yet
        >>> arr = array_func([1, 2, 3])  # numpy is imported here
    .r   r   c                   D    e Zd ZdefdZd ZdedefdZdededefd	Zd
S )lazy_import.<locals>.LazyModuler   c                 V    || _         d | _        |                    d          | _        d S )Nr   )_module_path_modulesplit_parts)r}   r   s     r   r   z(lazy_import.<locals>.LazyModule.__init__H  s*     +DDL%++C00DKKKr   c                 b   | j         | j         S 	 | j        d         }t          j        |          }t	          | j                  dk    r	|| _         |S |}| j        dd         D ]%}	 t          ||          }# t          $ r Y  dS w xY w|| _         |S # t          $ r}|| _        Y d}~dS d}~ww xY w)z+Import the module or attribute on first useNr   r   )	r   r   	importlibimport_modulelenr   r   ImportError_import_error)r}   base_module_namemoduleobjpartr   s         r   _import_modulez.lazy_import.<locals>.LazyModule._import_moduleM  s    |'|##';q> "01ABB t{##q((#)DL!M  KO $ $D$%c400) $ $ $#ttt$  #
   %&"tttttsB   AB B &A76B 7
BB BB 
B.B))B.rk   r   c                 n   | j         j|                                 }|Td| j        v rt          d| j         d| j                   t          d| j        d          d| j        d          d          t          | j         |          rt          | j         |          S t          d| j         d| d          )	Nr   Failed to lazily import : zmodule 'r   ' has no attribute 'r   ')
r   r   __dict__r   r   r   r   r   hasattrr   )r}   rk   r   s      r   __getattr__z+lazy_import.<locals>.LazyModule.__getattr__l  s    |#,,.. >&$-77)`t7H``DL^``  
 -\t{1~\\4;WX>\\\  
 t|T** 3t|T222 !I4,II$III  r   rV   rW   c           	      d   | j         r|                                 }|\d| j        v rt          d| j         d| j                   t          d| j         d| j        d          d| j        d          d	          t          | j                   r | j         |i |S t          | j         d
          )Nr   r   r   zFailed to find z
: module 'r   r   r   r   z is not callable)	r   r   r   r   r   r   r   callabler   )r}   rV   rW   r   s       r   __call__z(lazy_import.<locals>.LazyModule.__call__  s    |#,,.. >&$-77)`t7H``DL^``  
 * Ad.?  A  A4;WX>  A  Aosoz{|o}  A  A  A  
 %% 5#t|T4V444 t0BBBCCCr   N)	rv   
__module____qualname__r   r   r   r   r   r   r   r   r   
LazyModuler   G  s        	1 	1 	1 	1 	1
	 	 	>	C 	C 	 	 	 	6	D# 	D 	D 	D 	D 	D 	D 	D 	Dr   r   )r   r   modulesr   )r   partstop_module_namer   s       r   lazy_importr   )  s    , c""EAhO #+%%#e**//{?++WD WD WD WD WD WD WD WDr :k"""r   )N)NN)2r   r   rR   r@   loggingr   rg   
contextlibr   enumr   	functoolsr   r   typingr   r	   r
   r   r   r   r   r   r   pydanticr   redisr   ulidr   r   r   r   floatr   r8   intr=   rC   rG   rd   rj   ry   r   r   r   r   r   r   r   r   r   r   <module>r      s           



  % % % % % %                   T T T T T T T T T T T T T T T T T T T T                        GCLLS    
5    
 tCH~    6
S 
c 
d 
 
 
 
C C    
c c    
9 9# 9HSM 9X 9 9 9 9x    hsm #    6% %8C= %hsm % % % %P%Xb)CcM"::; %T@R % % % %P# #% # # # #!% !E ! ! ! !E e    FFF c]F F F F&w#S w#S w# w# w# w# w# w#r   