
    ?hKY                        d 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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ZddlZddlmZ ddlmZmZmZ ddlmZ d	Zd
Z dZ! G d de	      Z" G d dee"      Z#dee$ef   de$fdZ%dee$ef   de$fdZ&de$de'fdZ(de$de'fdZ)	 dLdee$ejT                  f   dee$   de+fdZ,dee$e+f   de+fdZ-de$de.fd Z/de$de.fd!Z0d"ee$ejT                  f   de$fd#Z1d$ede2fd%Z3de$de$fd&Z4d'e+d(e+de.fd)Z5d*e2d+e2de.fd,Z6d*e2d+e2de.fd-Z7dMd.ed/ede$fd0Z8d1e$de$fd2Z9d3eeee$ef         ddfd4Z:	 dNd5ed6e$d7e;d8e.ddf
d9Z<de$de.fd:Z=d;e$de$fd<Z>d5e$de$fd=Z?d>e$de@fd?ZAd@e$de.fdAZBd@e$dBe$de.fdCZCdDeeeef   edf   deeef   fdEZDdFedeee$ef      fdGZEdHej                  dIe$deee$ef      fdJZGdHej                  dIe$deeee$ef         fdKZHy)Oz
Helper functions!
    N)EnumEnumMeta)BufferedReader)UnionSequenceAnyOptionalListDictTuplecast)JSONDecodeError)SchemaValidationExceptionUnexpectedStatusCodeException ResponseCannotBeDecodedException)NUMBERSz*https://pypi.org/pypi/weaviate-client/json   zv1.16.0c                       e Zd ZdedefdZy)MetaEnumitemreturnc                     	 |j                   | j                  j                         v S # t        $ r || j                  j                         v cY S w xY wN)name__members__keysAttributeError)clsr   s     K/home/chris/cleankitchens-env/lib/python3.12/site-packages/weaviate/util.py__contains__zMetaEnum.__contains__$   sJ    	299 4 4 666 	23??//111	2s   %( %AAN)__name__
__module____qualname__r   boolr         r   r   r   #   s    2 2 2r&   r   c                       e Zd Zy)BaseEnumN)r!   r"   r#   r%   r&   r   r(   r(   -   s    r&   r(   )	metaclassimage_or_image_pathr   c                    t        | t              rSt        j                  j	                  |       st        d| z         t        | d      5 }|j                         }ddd       n,t        | t              r| j                         }nt        d      t        j                        j                  d      S # 1 sw Y   -xY w)a  
    Encode a image in a Weaviate understandable format from a binary read file or by providing
    the image path.

    Parameters
    ----------
    image_or_image_path : str, io.BufferedReader
        The binary read file or the path to the file.

    Returns
    -------
    str
        Encoded image.

    Raises
    ------
    ValueError
        If the argument is str and does not point to an existing file.
    TypeError
        If the argument is of a wrong data type.
    No file found at location brNzV"image_or_image_path" should be a image path or a binary read file (io.BufferedReader)utf-8
isinstancestrospathisfile
ValueErroropenreadr   	TypeErrorbase64	b64encodedecode)r*   filecontents      r   image_encoder_b64r>   1   s    . %s+ww~~129<OOPP%t, 	"iikG	" 	" 
'	8%**,#
 	
 G$++G44	" 	"   
B44B=file_or_file_pathc                    t        | t              rSt        j                  j	                  |       st        d| z         t        | d      5 }|j                         }ddd       n,t        | t              r| j                         }nt        d      t        j                        j                  d      S # 1 sw Y   -xY w)a  
    Encode a file in a Weaviate understandable format from a binary read file or by providing
    the file path.

    Parameters
    ----------
    file_or_file_path : str, io.BufferedReader
        The binary read file or the path to the file.

    Returns
    -------
    str
        Encoded file.

    Raises
    ------
    ValueError
        If the argument is str and does not point to an existing file.
    TypeError
        If the argument is of a wrong data type.
    r,   r-   NzS"file_or_file_path" should be a file path or a binary read file (io.BufferedReader)r.   r/   )r@   r<   r=   s      r   file_encoder_b64rB   X   s    . #S)ww~~/09<MMNN#T* 	"diikG	" 	" 
%~	6#((*d
 	
 G$++G44	" 	"r?   encoded_imagec                 J    t        j                  | j                  d            S )z
    Decode image from a Weaviate format image.

    Parameters
    ----------
    encoded_image : str
        The encoded image.

    Returns
    -------
    bytes
        Decoded image as a binary string.
    r.   r9   	b64decodeencode)rC   s    r   image_decoder_b64rH   ~   s      M009::r&   encoded_filec                 J    t        j                  | j                  d            S )aL  
    Decode file from a Weaviate format image.

    Parameters
    ----------
    encoded_file : str
        The encoded file.

    Returns
    -------
    bytes
        Decoded file as a binary string. Use this in your file
        handling code to convert it into a specific file type of choice.
        E.g., PIL for images.
    r.   rE   )rI   s    r   file_decoder_b64rK      s     " L//899r&   to_uuid
class_namec                 .   t        | t              r 	 t        t        j                  |             }n1t        | t        j                        rt        |       }nt        d      |dd| iS ddt        |       d| iS # t        $ r t	        d      dw xY w)a6  
    Generates a beacon with the given uuid and class name (only for Weaviate >= 1.14.0).

    Parameters
    ----------
    to_uuid : str or uuid.UUID
        The UUID for which to create a local beacon.
    class_name : Optional[str], optional
        The class name of the `to_uuid` object. Used with Weaviate >= 1.14.0.
        For Weaviate < 1.14.0 use None value.

    Returns
    -------
    dict
        The local beacon.

    Raises
    ------
    TypeError
        If 'to_uuid' is not of type str.
    ValueError
        If the 'to_uuid' is not valid.
    z"Uuid does not have the proper formNz0Expected to_object_uuid of type str or uuid.UUIDbeaconzweaviate://localhost//)r0   r1   uuid_libUUIDr5   r8   _capitalize_first_letter)rL   rM   uuids      r   generate_local_beaconrU      s    8 '3	Mx}}W-.D 
GX]]	+7|JKK1$899)*B:*N)OqQUPVW   	MABL	Ms   A> >Bobject_c                 8   | t        d      t        | t              r| S t        | t              rt	        j
                  |       rPt        j                  |       }|j                  dk(  rt        t        |j                               S t        d| z         t        j                  j                  |       st        d| z         t        | d      5 }t        t        t        j                   |            cddd       S t        d      # 1 sw Y   t        d      xY w)a  
    Takes an object that should describe a dict
    e.g. a schema or an object and tries to retrieve the dict.

    Parameters
    ----------
    object_ : str or dict
        The object from which to retrieve the dict.
        Can be a python dict, or the path to a json file or a url of a json file.

    Returns
    -------
    dict
        The object as a dict.

    Raises
    ------
    TypeError
        If 'object_' is neither a string nor a dict.
    ValueError
        If no dict can be retrieved from object.
    Nzargument is None   zCould not download file r,   rziArgument is not of the supported types. Supported types are url or file path as string or schema as dict.)r8   r0   dictr1   
validatorsurlrequestsgetstatus_coder   jsonr5   r2   r3   r4   r6   load)rV   responser<   s      r   _get_dict_from_objectrc      s    2 *++'4 '3>>'"||G,H##s*D(--/227'ABBww~~g&9GCDD'3 	/4diio.	/ 	/
	8 	/
	8 s   #DDr\   c                 $   t        | t              sy| j                  d      sy| dd } | j                  d      }t	        |      dvry|d   dk7  rt        j                  |d         sy	 t        j                  |d	          y
# t        $ r Y yw xY w)aR  
    Checks if the input follows a normal Weaviate 'beacon' like this:
    'weaviate://localhost/ClassName/28f3f61b-b524-45e0-9bbe-2c1550bf73d2'

    Parameters
    ----------
    url : str
        The URL to be validated.

    Returns
    -------
    bool
        True if the 'url' is a Weaviate object URL.
        False otherwise.
    Fzweaviate://   NrP      r   r   	localhostT)
r0   r1   
startswithsplitlenr[   domainrQ   rR   r5   )r\   rk   s     r   is_weaviate_object_urlrn     s    " c3>>-(
bc(CIIcNE
5zQx;  q*eBi    s   *B 	BBc                     | j                  d      }t        |      dk7  ry|d   j                  d      }t        |      dvry	 t        j                  |d          |d   d	k(  syy
# t        $ r Y yw xY w)a  
    Validates an url like 'http://localhost:8080/v1/objects/1c9cd584-88fe-5010-83d0-017cb3fcb446'
    or '/v1/objects/1c9cd584-88fe-5010-83d0-017cb3fcb446' references a object. It only validates
    the path format and UUID, not the host or the protocol.

    Parameters
    ----------
    url : str
        The URL to be validated.

    Returns
    -------
    bool
        True if the 'url' is a valid path to an object.
        False otherwise.
    z/v1/rg   F   rP   rf   ri   r   objectsT)rk   rl   rQ   rR   r5   )r\   v1_splitrk   s      r   is_object_urlrs   '  s    $ yy H
8}QKc"E
5zeBi  8y 	  s   A& &	A21A2rT   c                    t        | t        j                        rt        |       S t        | t              s t	        dt        t        |             z         t        |       }t        |       }| }|s|r| j                  d      d   }	 t        t        j                  |            }|S # t        $ r t        d      dw xY w)a  
    Validate and extract the UUID.

    Parameters
    ----------
    uuid : str or uuid.UUID
        The UUID to be validated and extracted.
        Should be in the form of an UUID or in form of an URL (weaviate 'beacon' or 'href').
        E.g.
        'http://localhost:8080/v1/objects/fc7eb129-f138-457f-b727-1b29db191a67'
        or
        'weaviate://localhost/28f3f61b-b524-45e0-9bbe-2c1550bf73d2'
        or
        'fc7eb129-f138-457f-b727-1b29db191a67'

    Returns
    -------
    str
        The extracted UUID.

    Raises
    ------
    TypeError
        If 'uuid' is not of type str.
    ValueError
        If 'uuid' is not valid or cannot be extracted.
    z2'uuid' must be of type str or uuid.UUID, but was: rP   ri   z:Not valid 'uuid' or 'uuid' can not be extracted from valueN)
r0   rQ   rR   r1   r8   typern   rs   rk   r5   )rT   _is_weaviate_url_is_object_url_uuids       r   get_valid_uuidry   L  s    : $&4ydC LsSWX\S]^__-d3"4(NE>

3#aHMM%() L  aUV\``as   B' 'B=vectorc                    t        | t              r| S 	 | j                         j                         S # t        $ rI 	 | j                         j                         j                         cY S # t        $ r t        d      dw xY ww xY w)a  
    Get weaviate compatible format of the embedding vector.

    Parameters
    ----------
    vector: Sequence
        The embedding of an object. Used only for class objects that do not have a vectorization
        module. Supported types are `list`, `numpy.ndarray`, `torch.Tensor` and `tf.Tensor`.

    Returns
    -------
    list
        The embedding as a list.

    Raises
    ------
    TypeError
        If 'vector' is not of a supported type.
    zThe type of the 'vector' argument is not supported!
Supported types are `list`, 'numpy.ndarray`, `torch.Tensor` and `tf.Tensor`N)r0   listsqueezetolistr   numpyr8   )rz   s    r   
get_vectorr   {  s    * &$~~&&(( 	<<>))+2244 	^ 		s    2 	B+A*'B*B  Bc                 0    | dd j                  d      d   S )a  
    Get the domain from a weaviate URL.

    Parameters
    ----------
    url : str
        The weaviate URL.
        Of this form: 'weaviate://localhost/objects/28f3f61b-b524-45e0-9bbe-2c1550bf73d2'

    Returns
    -------
    str
        The domain.
    re   NrP   r   )rk   r\   s    r   get_domain_from_weaviate_urlr     s      rs8>>#q!!r&   
sub_schemaschemac                 X    |j                  dg       }d| v r| d   }n| g}t        ||      S )a  
    Check for a subset in a schema.

    Parameters
    ----------
    sub_schema : dict
        The smaller schema that should be contained in the 'schema'.
    schema : dict
        The schema for which to check if 'sub_schema' is a part of. Must have the 'classes' key.

    Returns
    -------
    bool
        True is 'sub_schema' is a subset of the 'schema'.
        False otherwise.
    classes)r^   _compare_class_sets)r   r   schema_classessub_schema_classess       r   _is_sub_schemar     s=    $ ZZ	2.NJ'	2(\1>BBr&   sub_setset_c                     | D ]R  }d}|D ]E  }d|vrt        d      t        |d         t        |d         k(  s0t        |d   |d         sCd} n |rR y y)a_  
    Check for a subset in a set of classes.

    Parameters
    ----------
    sub_set : list
        The smaller set that should be contained in the 'set'.
    set_ : list
        The set for which to check if 'sub_set' is a part of.

    Returns
    -------
    bool
        True is 'sub_set' is a subset of the 'set'.
        False otherwise.
    Fclassz9The sub schema class/es MUST have a 'class' keyword each!
propertiesT)r   rS   _compare_properties)r   r   sub_set_classfound	set_classs        r   r   r     s    $ !  
	Im+/O  (g(>?C['"D  '}\'BIlD[\ E
	  r&   c                 J    | D ]  }d}|D ]  }|d   |d   k(  sd} n |r y y)ab  
    Check for a subset in a set of properties.

    Parameters
    ----------
    sub_set : list
        The smaller set that should be contained in the 'set'.
    set_ : list
        The set for which to check if 'sub_set' is a part of.

    Returns
    -------
    bool
        True is 'sub_set' is a subset of the 'set'.
        False otherwise.
    Fr   Tr%   )r   r   sub_set_propertyr   set_propertys        r   r   r     sO    $ $   	L'<+??	  r&   
identifier	namespacec           	          t        t        j                  t        j                  t        |      t        |       z               S )a  
    Generate an UUIDv5, may be used to consistently generate the same UUID for a specific
    identifier and namespace.

    Parameters
    ----------
    identifier : Any
        The identifier/object that should be used as basis for the UUID.
    namespace : Any, optional
        Allows to namespace the identifier, by default ""

    Returns
    -------
    str
        The UUID as a string.
    )r1   rQ   uuid5NAMESPACE_DNS)r   r   s     r   generate_uuid5r     s-    $ x~~h44c)ns:6VWXXr&   stringc                 p    t        |       dk(  r| j                         S | d   j                         | dd z   S )z
    Capitalize only the first letter of the `string`.

    Parameters
    ----------
    string : str
        The string to be capitalized.

    Returns
    -------
    str
        The capitalized string.
    rp   r   N)rl   
capitalize)r   s    r   rS   rS   $  s=     6{a  ""!9!F12J..r&   resultsc                 j    | y| D ]+  }d|v sd|d   v sd|d   d   v st        |d   d          - y)z
    Check batch results for errors.

    Parameters
    ----------
    results : dict
        The Weaviate batch creation return value.
    Nresulterrorserror)print)r   r   s     r   check_batch_resultr   8  sS      2v(fX.>">&*844fX&x012r&   valuearg_name	data_typeinclude_zeroc                     t        | |      rt        | t              rt        d| d| d      |r| dk  rt        d| d      y| dk  rt        d| d      y)a6  
    Check if the `value` of the `arg_name` is a positive number.

    Parameters
    ----------
    value : Union[int, float]
        The value to check.
    arg_name : str
        The name of the variable from the original function call. Used for error message.
    data_type : type
        The data type to check for.
    include_zero : bool
        Wether zero counts as positive or not. By default False.

    Raises
    ------
    TypeError
        If the `value` is not of type `data_type`.
    ValueError
        If the `value` has a non positive value.
    'z' must be of type .r   z8' must be positive, i.e. greater or equal to zero (>=0).z0' must be positive, i.e. greater that zero (>0).N)r0   r$   r8   r5   )r   r   r   r   s       r   _check_positive_numr   L  sy    2 eY':eT+B!H:%7	{!DEE19q
*bcdd  A:q
*Z[\\ r&   c                 v    d| j                         v xs& d| j                         v xs d| j                         v S )Nzweaviate.iozsemi.technologyzweaviate.cloud)lowerr   s    r   is_weaviate_domainr   o  s;    $ 	+		+	+syy{*r&   sc                 &    | j                  dd      S )N
 )replace)r   s    r   strip_newlinesr   w  s    99T3r&   c                 R    t        |       } t        j                  dd|       } d|  dS )z
    Ensures string is sanitized for GraphQL.

    Parameters
    ----------
    value : str
        The value to be converted.

    Returns
    -------
    str
        The sanitized string.
    z(?<!\\)((?:\\{2})*)"z\1\"")r   resub)r   s    r   _sanitize_strr   {  s3     5!EFF%E ugQ<r&   ver_strc                     | j                  d      dk(  r| dz   } d}t        j                  ||       }|r)t        t	        t
        |j                                     }|S t        d|  d      )a)  
    Parse a version string into a float.

    Parameters
    ----------
    ver_str : str
        The version string to parse. (e.g. "v1.18.2" or "1.18.0")

    Returns
    -------
    tuple :
        The parsed version as a tuple with len(2). (e.g. (1, 18)) Note: Ignores the patch version.
    r   r   z.0zv?(\d+)\.(\d+)z1Unable to parse a version from the input string: z>. Is it in the format '(v)x.y.z' (e.g. 'v1.18.2' or '1.18.0')?)countr   matchtuplemapintgroupsr5   )r   patternr   ver_tups       r   parse_version_stringr     ss     }}SQD.GHHWg&EC01?y  IG  H
 	
r&   current_version_strc                 @    t        |       }t        t              }||kD  S )aZ  
    Check if the user should be gently nudged to upgrade their Weaviate server version.

    Parameters
    ----------
    current_version_str : str
        The version of the Weaviate server that the client is connected to. (e.g. "v1.18.2" or "1.18.0")

    Returns
    -------
    bool :
    True if the user should be nudged to upgrade.

    )r   MINIMUM_NO_WARNING_VERSION)r   current_versionminimum_versions      r   is_weaviate_too_oldr     s%      ++>?O*+EFO_,,r&   latest_version_strc                     	 t        |       }t        |      \  }}t        |t        z
  d      }||f}||kD  S # t        $ r Y yw xY w)a!  
    Check if the user should be gently nudged to upgrade their Weaviate client version.

    Parameters
    ----------
    current_version_str : str
        The version of the Weaviate client that is being used (e.g. "v1.18.2" or "1.18.0")
    latest_version_str : str
        The latest version of the Weaviate client to compare against (e.g. "v1.18.2" or "1.18.0")

    Returns
    -------
    bool :
    True if the user should be nudged to upgrade.
    False if the user is using a valid version or if the version could not be parsed.

    r   F)r   maxMAXIMUM_MINOR_VERSION_DELTAr5   )r   r   r   latest_majorlatest_minorminimum_minorr   s          r   is_weaviate_client_too_oldr     s[    &./BC%9:L%M"lL+FFJ'700 s   47 	AAtimeout_configc                    dt         t        t        t        t        f   df   dt        fd}t	        | t
              st	        | t              r(t	        | t              s| J | dk  rt        d      | | fS t	        | t              st        d      t        |       dk7  rt        d	       || d
         r1 || d         r&t	        | d
   t              rt	        | d   t              rt        d      | d
   dk  s| d   dk  rt        d      | S )a  
    Validate and return TimeOut configuration.

    Parameters
    ----------
    timeout_config : tuple(NUMBERS, NUMBERS) or NUMBERS or None, optional
            Set the timeout configuration for all requests to the Weaviate server. It can be a
            number or, a tuple of two numbers: (connect timeout, read timeout).
            If only one number is passed then both connect and read timeout will be set to
            that value.

    Raises
    ------
    TypeError
        If arguments are of a wrong data type.
    ValueError
        If 'timeout_config' is not a tuple of 2.
    ValueError
        If 'timeout_config' is/contains negative number/s.
    numNr   c                 F    t        | t              xs t        | t              S r   )r0   floatr   )r   s    r   check_numberz/_get_valid_timeout_config.<locals>.check_number  s    #u%=C)==r&   g        z1'timeout_config' cannot be non-positive number/s!z='timeout_config' should be a (or tuple of) positive number/s!rg   z%'timeout_config' must be of length 2!r   rp   z)'timeout_config' must be tuple of numbers)r   r   r   r$   r0   r   r   r5   r   r8   rl   )r   r   s     r   _get_valid_timeout_configr     s   0>%w/?)@$ FG >D > 	>5)Z-LV`W )))S PQQ~--ne,WXX
>a@AA*+^A=N0O>!$d+
>!;Ld0SCDDaC>!#4#;LMMr&   json_responsec                 0    | y t        | t              sJ | S r   )r0   rZ   )r   s    r   _type_request_responser     s!    mT***r&   rb   locationc                     | y d| j                   cxk  rdk  r$n n!	 t        t        | j                               }|S t        ||       # t        $ r t        ||       w xY wNrX   i,  )r_   r   rZ   r`   r   r   r   rb   r   r   s      r   _decode_json_response_dictr     sm     
h""(S(	G x}}7M   ((
;;  	G28XFF	G   A	 	Ac                     | y d| j                   cxk  rdk  r$n n!	 | j                         }t        t        |      S t        ||       # t        $ r t        ||       w xY wr   )r_   r`   r   r|   r   r   r   r   s      r   _decode_json_response_listr   &  sm     
h""(S(	G$MMOMm,, ((
;;  	G28XFF	Gr   r   ) )F)I__doc__r9   r`   r2   r   rT   rQ   enumr   r   ior   typingr   r   r   r	   r
   r   r   r   r]   r[   requests.exceptionsr   weaviate.exceptionsr   r   r   weaviate.typesr   PYPI_PACKAGE_URLr   r   r   r(   r1   r>   rB   bytesrH   rK   rR   rZ   rU   rc   r$   rn   rs   ry   r|   r   r   r   r   r   r   rS   r   ru   r   r   r   r   r   r   r   r   r   r   Responser   r   r%   r&   r   <module>r      s     	 	    J J J   / 
 #?   2x 2	tx 	$55n1D+E $5# $5N#5c>.A(B #5s #5L;S ;U ;$:3 :5 :, !%*3%&** 
*Z05d#3 0 0f     F"s "t "J,sHMM12 ,s ,^#x #D #L"c "c "&Ct CT Cd C4! !T !d !H T d :Ys Ys YC Y*/S /S /(2d4S>*+2	2* FK ] ] ]*. ]>B ]	 ]FC D  c  c    *
# 
% 
:-S -T -*C S UY :-% 017D@A-
7G-`# (4S>2J <<+.<d38n< <<+.<d4S>"#<r&   