Ë
    kQêjñ0  ã                   óš   — d dl Z d dlmZmZmZmZmZ d dlmZ ddl	m
Z
mZmZ  G d„ d«      Z e«       Zded	efd
„Z e«       Zd„ Zd	efd„Zy)é    N)ÚDictÚOptionalÚSetÚTupleÚType)ÚTypeAdapteré   )ÚEmbeddingFunctionÚEmbeddingFunctionConfigÚUntrustedEmbeddingFunctionc                   ó  — e Zd ZdZed„ «       Zd„ Zddee   fd„Z	d„ Z
ded	ee   fd
„Zdeeeef      d	eedf   fd„Zdeded	efd„Zddedee   d	dfd„Zded	dfd„Zdedee   d	efd„Zded	dfd„Zdd„Zd„ Zdeded	dfd„Zded	efd„Zy)ÚEmbeddingFunctionRegistryaR  
    This is a singleton class used to register embedding functions
    and fetch them by name. It also handles serializing and deserializing.
    You can implement your own embedding function by subclassing EmbeddingFunction
    or TextEmbeddingFunction and registering it with the registry.

    NOTE: Here TEXT is a type alias for Union[str, List[str], pa.Array,
          pa.ChunkedArray, np.ndarray]

    Examples
    --------
    >>> registry = EmbeddingFunctionRegistry.get_instance()
    >>> @registry.register("my-embedding-function")
    ... class MyEmbeddingFunction(EmbeddingFunction):
    ...     def ndims(self) -> int:
    ...         return 128
    ...
    ...     def compute_query_embeddings(self, query: str, *args, **kwargs):
    ...         return self.compute_source_embeddings(query, *args, **kwargs)
    ...
    ...     def compute_source_embeddings(self, texts, *args, **kwargs):
    ...         return [np.random.rand(self.ndims()) for _ in range(len(texts))]
    ...
    >>> registry.get("my-embedding-function")
    <class 'lancedb.embeddings.registry.MyEmbeddingFunction'>
    c                 ó   — t         S ©N)Ú__REGISTRY__)Úclss    ú`/home/oem/CyberBrain26-unified/.venv/lib/python3.12/site-packages/lancedb/embeddings/registry.pyÚget_instancez&EmbeddingFunctionRegistry.get_instance,   s   € äÐó    c                 ó\   — i | _         i | _        t        «       | _        t        «       | _        y r   )Ú
_functionsÚ
_variablesÚsetÚ_allowed_remote_codeÚ_allowed_endpoints©Úselfs    r   Ú__init__z"EmbeddingFunctionRegistry.__init__0   s$   € ØˆŒØˆŒä=@»UˆÔ!Ü,/«EˆÕr   NÚaliasc                 ó   ‡ ‡— ˆˆ fd„}|S )a"  
        This creates a decorator that can be used to register
        an EmbeddingFunction.

        Parameters
        ----------
        alias : Optional[str]
            a human friendly name for the embedding function. If not
            provided, the class name will be used.
        c                 óè   •— t        | t        «      st        d«      ‚‰xs | j                  }|‰j                  v r!‰r‰j                  |   | urt        |› d�«      ‚| ‰j                  |<   || _        | S )Nz'Must be a subclass of EmbeddingFunctionz was already registered)Ú
issubclassr
   Ú	TypeErrorÚ__name__r   ÚKeyErrorÚ%__embedding_function_registry_alias__)r   Úkeyr   r   s     €€r   Ú	decoratorz5EmbeddingFunctionRegistry.register.<locals>.decoratorE   sw   ø€ Ü˜cÔ#4Ô5ÜÐ IÓJÐJØÒ'˜3Ÿ<™<ˆCØ�d—o‘oÑ%Ù˜TŸ_™_¨SÑ1¸Ñ<ä # Ð&=Ð>Ó?Ð?Ø#&ˆD�O‰O˜CÑ ð 9<ˆCÔ5ØˆJr   © )r   r   r(   s   `` r   Úregisterz"EmbeddingFunctionRegistry.register7   s   ù€ õ	ð Ðr   c                 ó   — i | _         y)z9
        Reset the registry to its initial state
        N©r   r   s    r   ÚresetzEmbeddingFunctionRegistry.resetU   s   € ð ˆ�r   ÚnameÚreturnc                 ó    — | j                   |   S )a  
        Fetch an embedding function class by name

        Parameters
        ----------
        name : str
            The name of the embedding function to fetch
            Either the alias or the class name if no alias was provided
            during registration
        r,   ©r   r.   s     r   ÚgetzEmbeddingFunctionRegistry.get[   s   € ð �‰˜tÑ$Ð$r   Úmetadatar   c                 ó  — |€i S |j                  d|j                  d«      «      }|€i S t        j                  |j                  d«      «      }|D �ci c]0  }|d   t	        |d   |d   | j                  |d   |d   «      ¬«      “Œ2 c}S c c}w )	aQ  
        Parse the metadata from an arrow table and
        return a mapping of the vector column to the
        embedding function and source column

        Parameters
        ----------
        metadata : Optional[Dict[bytes, bytes]]
            The metadata from an arrow table. Note that
            the keys and values are bytes (pyarrow api)

        Returns
        -------
        functions : dict
            A mapping of vector column name to embedding function.
            An empty dict is returned if input is None or does not
            contain b"embedding_functions".
        s   embedding_functionsÚembedding_functionsúutf-8Úvector_columnÚsource_columnr.   Úmodel)r7   r8   Úfunction)r2   ÚjsonÚloadsÚdecoder   Ú_restore)r   r3   Ú
serializedÚraw_listÚobjs        r   Úparse_functionsz)EmbeddingFunctionRegistry.parse_functionsh   s®   € ð* ÐØˆIà—\‘\Ø" H§L¡LÐ1FÓ$Gó
ˆ
ð ÐØˆIÜ—:‘:˜j×/Ñ/°Ó8Ó9ˆð  ö
ð ð �Ñ Ô"9Ø! /Ñ2Ø! /Ñ2ØŸ™ s¨6¡{°C¸±LÓAô#ñ ò
ð 	
ùò 
s   Á5B
Úargsc                 ó*  ‡ — ‰ j                  |«      }|j                  |«      } |j                  d	i |¤Ž}g }|j                  «       }|�y ‰ j                  |Ž }d|v }	|	r"t        t        «      j                  |d   «      }
n|j                  «       }
|
xr ||d<   |
r'|s%|	r#|\  }}|j                  d|› d|›d|›d|›d�	«       |j                  ˆ fd„|j                  «       D «       «       |rt        |t        |«      ¬«      }n |d	i |¤Ž}||_        |S )
zã
        Create an embedding function from table metadata. Anyone who can write
        the table controls `args`, so settings that run model code or send data
        elsewhere must already be trusted by this process.
        Útrust_remote_codezruns code from model 'z' at revision z9. If you trust it, call get_registry().allow_remote_code(z, revision=ú)c              3   ó^   •K  — | ]$  }t        |«      ‰j                  vrd |› d|›d�–— Œ& y­w)zsends data to endpoint 'z7'. If you trust it, call get_registry().allow_endpoint(rF   N)Ú_normalize_urlr   )Ú.0Úurlr   s     €r   ú	<genexpr>z5EmbeddingFunctionRegistry._restore.<locals>.<genexpr>²   sC   øè ø€ ò 
ð Ü˜cÓ"¨$×*AÑ*AÑAð ' s eð ,-Ø-0¨G°1ô6ñ
ùs   ƒ*-)Úfunction_nameÚreasonsr)   )r2   Ú_resolve_variablesÚmodel_constructÚremote_code_modelÚ_remote_code_allowedr   ÚboolÚvalidate_pythonÚ!_legacy_trust_remote_code_defaultÚappendÚextendÚ	endpointsr   ÚtupleÚ_original_args)r   r.   rC   r   ÚresolvedÚproberM   r9   ÚallowedÚexplicitÚ	requestedÚ
model_nameÚrevisionÚfuncs   `             r   r>   z"EmbeddingFunctionRegistry._restore�   sL  ø€ ð �h‰h�t‹nˆØ×)Ñ)¨$Ó/ˆà#�×#Ñ#Ñ/ hÑ/ˆàˆØ×'Ñ'Ó)ˆØÐØ/�d×/Ñ/°Ð7ˆGØ*¨hÐ6ˆHÙÜ'¬Ó-×=Ñ=ØÐ0Ñ1ó‘	ð  ×AÑAÓC�	à,5Ò,A¸'ˆHÐ(Ñ)ñ ¡©XØ',Ñ$�
˜HØ—‘Ø,¨Z¨L¸Ø�lð #8Ø8B°~ð F Ø (˜|¨1ð.ôð 	�‰ó 
ð —‘Ó(ô
ô 	
ñ Ü-Ø"¬E°'«Nô‰Dñ ‘?˜‘?ˆDØ"ˆÔØˆr   r9   r`   c                 óZ   — | j                   j                  ||€t        f«       y|f«       y)ao  
        Trust the code in a model repository when an embedding function that
        loads it is restored from table metadata.

        Table metadata cannot enable `trust_remote_code` by itself, since anyone
        who can write to the table could then run code in this process. Embedding
        functions created in this process with `trust_remote_code=True` are
        allowed automatically.

        Parameters
        ----------
        model : str
            The model name, such as `"nomic-ai/nomic-embed-text-v1.5"`.
        revision : Optional[str]
            The revision the table's embedding function must pin. Pinning a
            commit hash is recommended, since the code at a branch or tag can
            change after you review it. If None, any revision is trusted,
            including pull request refs that anyone can push to the repository.
        N)r   ÚaddÚ_ANY_REVISION©r   r9   r`   s      r   Úallow_remote_codez+EmbeddingFunctionRegistry.allow_remote_codeÂ   s0   € ð( 	×!Ñ!×%Ñ%Ø XÐ%5”MÐDõ	
Ø;CÐDõ	
r   rJ   c                 óL   — | j                   j                  t        |«      «       y)a  
        Trust a custom endpoint, such as an OpenAI `base_url` or Ollama `host`,
        when an embedding function that uses it is restored from table metadata.

        Table metadata cannot pick an endpoint by itself, since it could send
        your data and API keys to a server you don't control. Embedding functions
        created in this process are allowed to use their endpoints automatically.

        Parameters
        ----------
        url : str
            The endpoint URL. Trailing slashes are ignored.
        N)r   rc   rH   )r   rJ   s     r   Úallow_endpointz(EmbeddingFunctionRegistry.allow_endpointÚ   s   € ð 	×Ñ×#Ñ#¤N°3Ó$7Õ8r   c                 óN   — |t         f| j                  v xs ||f| j                  v S r   )rd   r   re   s      r   rQ   z.EmbeddingFunctionRegistry._remote_code_allowedê   s<   € Ø”}Ð%¨×)BÑ)BÐBò 'ØØðG
ð ×&Ñ&ðG'ð 	'r   ra   c                 óÄ   — |j                  «       }|�(t        |dd«      r| j                  j                  |«       |j	                  «       D ]  }| j                  |«       Œ y )NrE   F)rP   Úgetattrr   rc   rW   rh   )r   ra   r9   rJ   s       r   Ú_trustz EmbeddingFunctionRegistry._trustð   s\   € Ø×&Ñ&Ó(ˆØÐ¤¨Ð/BÀEÔ!Jð ×%Ñ%×)Ñ)¨%Ô0Ø—>‘>Ó#ò 	%ˆCØ×Ñ Õ$ñ	%r   c                 óì   — |j                   }t        |t        «      r|j                  }n!t	        |d|j
                  j                  «      }|j                  «       }|||j                  |j                  dœS )z¥
        Convert the given embedding function and source / vector column configs
        into a config dictionary that can be serialized into arrow metadata
        r&   )r.   r9   r8   r7   )
r:   Ú
isinstancer   rL   rk   Ú	__class__r$   Úsafe_model_dumpr8   r7   )r   Úconfra   r.   Ú	json_datas        r   Úfunction_to_metadataz.EmbeddingFunctionRegistry.function_to_metadataù   sq   € ð
 �}‰}ˆÜ�dÔ6Ô7Ø×%Ñ%‰DäØÐ=¸t¿~¹~×?VÑ?VóˆDð ×(Ñ(Ó*ˆ	àØØ!×/Ñ/Ø!×/Ñ/ñ	
ð 	
r   c                 ó¾   — |�t        |«      dk(  ry|D �cg c]  }| j                  |«      ‘Œ }}t        j                  |d¬«      j	                  d«      }d|iS c c}w )zŸ
        Convert a list of embedding functions and source / vector configs
        into a config dictionary that can be serialized into arrow metadata
        Nr   é   )Úindentr6   r5   )Úlenrs   r;   ÚdumpsÚencode)r   Ú	func_listra   rr   r3   s        r   Úget_table_metadataz,EmbeddingFunctionRegistry.get_table_metadata  sd   € ð
 Ð¤ I£°!Ò 3ØØAJÖK¸�T×.Ñ.¨tÕ4ÐKˆ	ÐKô —:‘:˜i°Ô2×9Ñ9¸'ÓBˆØ% xÐ0Ð0ùò	 Ls   –AÚvaluec                 ó@   — d|v rt        d«      ‚|| j                  |<   y)aS  
        Set a variable. These can be accessed in embedding configuration using
        the syntax `$var:variable_name`. If they are not set, an error will be
        thrown letting you know which variable is missing. If you want to supply
        a default value, you can add an additional part in the configuration
        like so: `$var:variable_name:default_value`. Default values can be
        used for runtime configurations that are not sensitive, such as
        whether to use a GPU for inference.

        The name must not contain a colon. Default values can contain colons.
        ú:z$Variable names cannot contain colonsN)Ú
ValueErrorr   )r   r.   r|   s      r   Úset_varz!EmbeddingFunctionRegistry.set_var  s%   € ð �$‰;ÜÐCÓDÐDØ %ˆ�‰˜Òr   c                 ó    — | j                   |   S )z!
        Get a variable.
        )r   r1   s     r   Úget_varz!EmbeddingFunctionRegistry.get_var*  s   € ð �‰˜tÑ$Ð$r   r   )rq   r   )r$   Ú
__module__Ú__qualname__Ú__doc__Úclassmethodr   r   r   Ústrr*   r-   r   r
   r2   r   ÚbytesrB   Údictr>   rf   rh   rR   rQ   rl   rs   r{   r€   r‚   r)   r   r   r   r      s3  „ ñð6 ñó ðò2ñ˜h s™mó ò<ð%˜ð % Ð%6Ñ 7ó %ð%
Ø   e¨U lÑ!3Ñ4ð%
à	ˆcÐ,Ð,Ñ	-ó%
ðN1˜Sð 1¨ð 1Ð1Bó 1ñf
 sð 
°h¸s±mð 
Ètó 
ð09 #ð 9¨$ó 9ð '¨#ð '¸À#¹ð 'È4ó 'ð%Ð,ð %°ó %ó
ò(1ð&˜Cð &¨ð &°ó &ð %˜Cð % Cô %r   r   rJ   r/   c                 ó$   — | j                  d«      S )Nú/)Úrstrip)rJ   s    r   rH   rH   4  s   € Ø�:‰:�c‹?Ðr   c                 óH   — t         j                  «       j                  | «      S r   )r   r   r*   )r.   s    r   r*   r*   =  s   € Ü×$Ñ$Ó&×/Ñ/°Ó5Ð5r   c                  ó*   — t         j                  «       S )a8  
    Utility function to get the global instance of the registry

    Returns
    -------
    EmbeddingFunctionRegistry
        The global registry instance

    Examples
    --------
    from lancedb.embeddings import get_registry

    registry = get_registry()
    openai = registry.get("openai").create()
    )r   r   r)   r   r   Úget_registryr�   A  s   € ô  ×$Ñ$Ó&Ð&r   )r;   Útypingr   r   r   r   r   Úpydanticr   Úbaser
   r   r   r   Úobjectrd   r‡   rH   r   r*   r�   r)   r   r   ú<module>r”      sb   ðó ß 3Õ 3å  ÷ñ ÷^%ñ ^%ñB	 “€ð˜ð  ó ñ
 )Ó*€ò6ð'Ð/ô 'r   