o
    S"g>P                     @   sN  d dl Z d dlmZ d dlZd dlmZmZmZmZm	Z	m
Z
mZ d dlmZ d dlmZmZmZ d dlmZ d dlmZmZmZ d dlmZmZ d d	lmZ d d
lmZ d dlmZ d dl m!Z!m"Z" d dl#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.m/Z/m0Z0 dZ1e2e3Z4G dd deZ5edddG dd deZ6e6Z7dS )    N)BytesIO)AnyCallableDictListOptionalSequenceUnion)
deprecated)AsyncInferenceClientInferenceClient
model_info)	ModelInfo)DEFAULT_EMBED_BATCH_SIZEBaseEmbedding	Embedding)FieldPrivateAttr)CallbackManager)Pooling)MultiModalEmbedding)get_cache_dirinfer_torch_device)#DEFAULT_HUGGINGFACE_EMBEDDING_MODELformat_queryformat_text!get_query_instruct_for_model_name get_text_instruct_for_model_name)	ImageType)SentenceTransformer)retrystop_after_attemptwait_exponentiali   c                #       s  e Zd ZU dZeedddZeed< edddZ	e
ed	< ed
ddZee ed< edddZee ed< edddZee ed< e Zeed< e Zeed< e Ze
ed< e Zeee  ed< eddddddddeddddddfdedee dedee dee dee d	e
dee dee dedee de
dee d ee d!e
d"eee  f  fd#d$Zed%efd&d'Zeed(e d)d*d+d,dd-	dKd.ee!ee"f  d/ee d%eee#  fd0d1Z$	dKd.ee!ee"f  d/ee d%eee#  fd2d3Z%d4ed%ee# fd5d6Z&d4ed%ee# fd7d8Z'd9ed%ee# fd:d;Z(d9ed%ee# fd<d=Z)d>ee d%eee#  fd?d@Z*dAe+d%ee# fdBdCZ,dAe+d%ee# fdDdEZ-dFee+ d%eee#  fdGdHZ.dFee+ d%eee#  fdIdJZ/  Z0S )LHuggingFaceEmbeddinga  
    HuggingFace class for text and image embeddings.

    Args:
        model_name (str, optional): If it is a filepath on disc, it loads the model from that path.
            If it is not a path, it first tries to download a pre-trained SentenceTransformer model.
            If that fails, tries to construct a model from the Hugging Face Hub with that name.
            Defaults to DEFAULT_HUGGINGFACE_EMBEDDING_MODEL.
        max_length (Optional[int], optional): Max sequence length to set in Model's config. If None,
            it will use the Model's default max_seq_length. Defaults to None.
        query_instruction (Optional[str], optional): Instruction to prepend to query text.
            Defaults to None.
        text_instruction (Optional[str], optional): Instruction to prepend to text.
            Defaults to None.
        normalize (bool, optional): Whether to normalize returned vectors.
            Defaults to True.
        embed_batch_size (int, optional): The batch size used for the computation.
            Defaults to DEFAULT_EMBED_BATCH_SIZE.
        cache_folder (Optional[str], optional): Path to store models. Defaults to None.
        trust_remote_code (bool, optional): Whether or not to allow for custom models defined on the
            Hub in their own modeling files. This option should only be set to True for repositories
            you trust and in which you have read the code, as it will execute code present on the Hub
            on your local machine. Defaults to False.
        device (Optional[str], optional): Device (like "cuda", "cpu", "mps", "npu", ...) that should
            be used for computation. If None, checks if a GPU can be used. Defaults to None.
        callback_manager (Optional[CallbackManager], optional): Callback Manager. Defaults to None.
        parallel_process (bool, optional): If True it will start a multi-process pool to process the
            encoding with several independent processes. Great for vast amount of texts.
            Defaults to False.
        target_devices (Optional[List[str]], optional): PyTorch target devices, e.g.
            ["cuda:0", "cuda:1", ...], ["npu:0", "npu:1", ...], or ["cpu", "cpu", "cpu", "cpu"].
            If target_devices is None and CUDA/NPU is available, then all available CUDA/NPU devices
            will be used. If target_devices is None and CUDA/NPU is not available, then 4 CPU devices
            will be used. This parameter will only be used if `parallel_process = True`.
            Defaults to None.
        num_workers (int, optional): The number of workers to use for async embedding calls.
            Defaults to None.
        **model_kwargs: Other model kwargs to use
        tokenizer_name (Optional[str], optional): "Deprecated"
        pooling (str, optional): "Deprecated"
        model (Optional[Any], optional): "Deprecated"
        tokenizer (Optional[Any], optional): "Deprecated"

    Examples:
        `pip install llama-index-embeddings-huggingface`

        ```python
        from llama_index.core import Settings
        from llama_index.embeddings.huggingface import HuggingFaceEmbedding

        # Set up the HuggingFaceEmbedding class with the required model to use with llamaindex core.
        embed_model  = HuggingFaceEmbedding(model_name = "BAAI/bge-small-en")
        Settings.embed_model = embed_model

        # Or if you want to Embed some text separately
        embeddings = embed_model.get_text_embedding("I want to Embed this text!")

        ```

    zMaximum length of input.r   )defaultdescriptiongt
max_lengthTzNormalize embeddings or not.r$   r%   	normalizez%Instruction to prepend to query text.N)r%   r$   query_instructionzInstruction to prepend to text.text_instructionz$Cache folder for Hugging Face files.cache_folder_model_device_parallel_process_target_devicesr
   F
model_nametokenizer_namepoolingmodel	tokenizerembed_batch_sizetrust_remote_codedevicecallback_managerparallel_processtarget_devicesc              	      s   |pt  }|p	t }d|fd|	fd|fd|ffD ]\}}|dkr't| dq|d u r0tdt|f||||p;t||p@t|dd	|}|rN||_n|j}t j|
||||||d
 || _	|| _
|| _|| _d S )Nr4   r5   r3   r2   r
   z4 is deprecated. Please remove it from the arguments.z+The `model_name` argument must be provided.)querytext)r8   r,   r7   prompts)r6   r9   r1   r'   r)   r*   r+   )r   r   
ValueErrorr   r   r   max_seq_lengthsuper__init__r.   r-   r/   r0   )selfr1   r2   r3   r'   r*   r+   r)   r4   r5   r6   r,   r7   r8   r9   r:   r;   model_kwargsvariablevalue	__class__ i/mnt/skqttb/ctump_chatbot/chatbot/lib/python3.10/site-packages/llama_index/embeddings/huggingface/base.pyrB   w   sX   

	
zHuggingFaceEmbedding.__init__returnc                 C      dS )Nr#   rI   clsrI   rI   rJ   
class_name      zHuggingFaceEmbedding.class_name         
   )
multiplierminmax)stopwaitreraiseinputsprompt_namec              
   C   s   z1| j r!| jj| jd}| jj||| j|| jd}| jj|d n| jj|| j|| jd}|	 W S  t
yF } z	td|  d}~ww )a/  
        Generates embeddings with retry mechanism.

        Args:
            inputs: List of texts or images to embed
            prompt_name: Optional prompt type

        Returns:
            List of embedding vectors

        Raises:
            Exception: If embedding fails after retries
        )r;   )pool
batch_sizer\   normalize_embeddings)r]   )r^   r\   r_   zEmbedding attempt failed: N)r/   r-   start_multi_process_poolr0   encode_multi_processr6   r)   stop_multi_process_poolencodetolist	Exceptionloggerwarning)rC   r[   r\   r]   emberI   rI   rJ   _embed_with_retry   s2   
z&HuggingFaceEmbedding._embed_with_retryc                 C   s   |  ||S )a  
        Generates Embeddings with input validation and retry mechanism.

        Args:
            sentences: Texts or Sentences to embed
            prompt_name: The name of the prompt to use for encoding

        Returns:
            List of embedding vectors

        Raises:
            ValueError: If any input text is invalid
            Exception: If embedding fails after retries
        )rj   )rC   r[   r\   rI   rI   rJ   _embed   s   zHuggingFaceEmbedding._embedr<   c                 C      | j |gddd S )z
        Generates Embeddings for Query.

        Args:
            query (str): Query text/sentence

        Returns:
            List[float]: numpy array of embeddings
        r<   r\   r   rk   rC   r<   rI   rI   rJ   _get_query_embedding     
z)HuggingFaceEmbedding._get_query_embeddingc                       t | j|I dH S )z
        Generates Embeddings for Query Asynchronously.

        Args:
            query (str): Query text/sentence

        Returns:
            List[float]: numpy array of embeddings
        N)asyncio	to_threadrp   ro   rI   rI   rJ   _aget_query_embedding     
z*HuggingFaceEmbedding._aget_query_embeddingr=   c                    rr   )z
        Generates Embeddings for text Asynchronously.

        Args:
            text (str): Text/Sentence

        Returns:
            List[float]: numpy array of embeddings
        N)rs   rt   _get_text_embeddingrC   r=   rI   rI   rJ   _aget_text_embedding  rv   z)HuggingFaceEmbedding._aget_text_embeddingc                 C   rl   )z
        Generates Embeddings for text.

        Args:
            text (str): Text/sentences

        Returns:
            List[float]: numpy array of embeddings
        r=   rm   r   rn   rx   rI   rI   rJ   rw   (  rq   z(HuggingFaceEmbedding._get_text_embeddingtextsc                 C   s   | j |ddS )z
        Generates Embeddings for text.

        Args:
            texts (List[str]): Texts / Sentences

        Returns:
            List[List[float]]: numpy array of embeddings
        r=   rm   rn   rC   rz   rI   rI   rJ   _get_text_embeddings4  s   
z)HuggingFaceEmbedding._get_text_embeddingsimg_file_pathc                 C   s   |  |gd S )z Generate embedding for an image.r   rn   rC   r}   rI   rI   rJ   _get_image_embedding@  s   z)HuggingFaceEmbedding._get_image_embeddingc                       |  |S )z/Generate embedding for an image asynchronously.)r   r~   rI   rI   rJ   _aget_image_embeddingD  s   
z*HuggingFaceEmbedding._aget_image_embeddingimg_file_pathsc                 C   s
   |  |S )z(Generate embeddings for multiple images.rn   rC   r   rI   rI   rJ   _get_image_embeddingsH  s   
z*HuggingFaceEmbedding._get_image_embeddingsc                    r   )z7Generate embeddings for multiple images asynchronously.)r   r   rI   rI   rJ   _aget_image_embeddingsN  s   
z+HuggingFaceEmbedding._aget_image_embeddings)N)1__name__
__module____qualname____doc__r   DEFAULT_HUGGINGFACE_LENGTHr'   int__annotations__r)   boolr*   r   strr+   r,   r   r-   r   r.   r/   r0   r   r   r   r   r   rB   classmethodrO   r    r!   r"   r	   r   floatrj   rk   rp   ru   ry   rw   r|   r   r   r   r   r   __classcell__rI   rI   rG   rJ   r#   &   s   
 =	

D
.




r#   zDeprecated in favor of `HuggingFaceInferenceAPIEmbedding` from `llama-index-embeddings-huggingface-api` which should be used instead.always)actionc                       s2  e Zd ZU dZeejddZee e	d< edddZ
ee e	d< edddZee e	d	< edd
dZee e	d< edddZeeedf e	d< edddZee e	d< edddZeeef e	d< edddZeeef e	d< edddZee e	d< e Zde	d< e Zde	d< e Zde	d< deeef fddZdeddf fd d!Zdeddfd"d#Zdedd$fd%d&Ze defd'd(Z!d)ede"fd*d+Z#d,e$e de%e" fd-d.Z&d/ede"fd0d1Z'd)ede"fd2d3Z(d,e%e de%e" fd4d5Z)d/ede"fd6d7Z*d)ede"fd8d9Z+d,e%e de%e" fd:d;Z,  Z-S )< HuggingFaceInferenceAPIEmbeddingz
    Wrapper on the Hugging Face's Inference API for embeddings.

    Overview of the design:
    - Uses the feature extraction task: https://huggingface.co/tasks/feature-extraction
    z?Pooling strategy. If None, the model's default pooling is used.r(   r3   Nz.Instruction to prepend during query embedding.r*   z-Instruction to prepend during text embedding.r+   z8Hugging Face model name. If None, the task will be used.r1   u   Hugging Face token. Will default to the locally saved token. Pass token=False if you don’t want to send your token to the server.tokenzThe maximum number of seconds to wait for a response from the server. Loading a new model in Inference API can take up to several minutes. Defaults to None, meaning it will loop until the server is available.timeoutzAdditional headers to send to the server. By default only the authorization and user-agent headers are sent. Values in this dictionary will override the default values.headersz)Additional cookies to send to the server.cookieszhOptional task to pick Hugging Face's recommended model, used when model_name is left as default of None.taskr   _sync_clientr   _async_clientzCallable[..., ModelInfo]_get_model_inforK   c                 C   s   | j | j| j| j| jdS )zAExtract the Hugging Face InferenceClient construction parameters.)r4   r   r   r   r   )r1   r   r   r   r   rC   rI   rI   rJ   _get_inference_client_kwargs  s   z=HuggingFaceInferenceAPIEmbedding._get_inference_client_kwargskwargsc                    s   | ddu r+| dd}tj|d|d< td|d  d| d t|d d	d
 t jdi | tdi |  | _	t
di |  | _t| _dS )z\
        Initialize.

        Args:
            kwargs: See the class-level Fields.
        r1   Nr    )r   z'Using Hugging Face's recommended model z given task .T)flushrI   )getr   get_recommended_modelrf   debugprintrA   rB   r   r   r   r   r   r   )rC   r   r   rG   rI   rJ   rB     s   
z)HuggingFaceInferenceAPIEmbedding.__init__c              
   C   sn   | j jdd}z| j|| vrtd| jdW dS  ty6 } ztd|dt|  d|d}~ww )	z
        Confirm the contained model_name is deployed on the Inference API service.

        Args:
            task: Hugging Face task to check within. A list of all tasks can be
                found here: https://huggingface.co/tasks
        all)
frameworksz1The Inference API service doesn't have the model z
 deployed.zInput task z not in possible tasks r   N)r   list_deployed_modelsr1   r?   KeyErrorlistkeys)rC   r   
all_modelsexcrI   rI   rJ   validate_supported  s"   z3HuggingFaceInferenceAPIEmbedding.validate_supportedr   c                 K   s   | j | jfi |S )z4Get metadata on the current model from Hugging Face.)r   r1   )rC   r   rI   rI   rJ   get_model_info  s   z/HuggingFaceInferenceAPIEmbedding.get_model_infoc                 C   rL   )Nr   rI   rM   rI   rI   rJ   rO     rP   z+HuggingFaceInferenceAPIEmbedding.class_namer=   c              
      s   | j |I d H }t|jdkr| S |jdd}t|jdkr&| S z| | W S  tyD } z
td| j	 d|d }~ww )NrR   r   )axiszPooling is required for zG because it returned a > 1-D value, please specify pooling as not None.)
r   feature_extractionlenshaperd   squeezer3   	TypeErrorr?   r1   )rC   r=   	embeddingr   rI   rI   rJ   _async_embed_single  s"   z4HuggingFaceInferenceAPIEmbedding._async_embed_singlerz   c                    s$    fdd|D }t j| I dH S )z
        Embed a sequence of text, in parallel and asynchronously.

        NOTE: this uses an externally created asyncio event loop.
        c                    s   g | ]}  |qS rI   )r   .0r=   r   rI   rJ   
<listcomp>  s    zFHuggingFaceInferenceAPIEmbedding._async_embed_bulk.<locals>.<listcomp>N)rs   gatherrC   rz   tasksrI   r   rJ   _async_embed_bulk  s   z2HuggingFaceInferenceAPIEmbedding._async_embed_bulkr<   c                 C      t | |S )z~
        Embed the input query synchronously.

        NOTE: a new asyncio event loop is created internally for this.
        )rs   runru   ro   rI   rI   rJ   rp        z5HuggingFaceInferenceAPIEmbedding._get_query_embeddingc                 C   r   )z}
        Embed the text query synchronously.

        NOTE: a new asyncio event loop is created internally for this.
        )rs   r   ry   rx   rI   rI   rJ   rw     r   z4HuggingFaceInferenceAPIEmbedding._get_text_embeddingc                    sR   t   z fdd|D } t | W    n   w dd |D S )z
        Embed the input sequence of text synchronously and in parallel.

        NOTE: a new asyncio event loop is created internally for this.
        c                    s   g | ]
}  |qS rI   )create_taskry   r   looprC   rI   rJ   r     s    zIHuggingFaceInferenceAPIEmbedding._get_text_embeddings.<locals>.<listcomp>c                 S   s   g | ]}|  qS rI   )result)r   r   rI   rI   rJ   r     s    )rs   new_event_looprun_until_completerY   closer   rI   r   rJ   r|     s   z5HuggingFaceInferenceAPIEmbedding._get_text_embeddingsc                        | j t|| j| jdI d H S N)r=   )r   r   r1   r*   ro   rI   rI   rJ   ru   
     z6HuggingFaceInferenceAPIEmbedding._aget_query_embeddingc                    r   r   )r   r   r1   r+   rx   rI   rI   rJ   ry     r   z5HuggingFaceInferenceAPIEmbedding._aget_text_embeddingc                    s"    j  fdd|D dI d H S )Nc                    s   g | ]
}t | j jqS rI   )r   r1   r+   r   r   rI   rJ   r     s    zJHuggingFaceInferenceAPIEmbedding._aget_text_embeddings.<locals>.<listcomp>)rz   )r   r{   rI   r   rJ   _aget_text_embeddings  s   
z6HuggingFaceInferenceAPIEmbedding._aget_text_embeddings).r   r   r   r   r   r   CLSr3   r   r   r*   r   r+   r1   r   r	   r   r   r   r   r   r   r   r   r   r   r   r   r   rB   r   r   r   rO   r   r   r   r   r   rp   rw   r|   ru   ry   r   r   rI   rI   rG   rJ   r   U  sh   
 
	"r   )8rs   ior   loggingtypingr   r   r   r   r   r   r	   r
   huggingface_hubr   r   r   huggingface_hub.hf_apir   %llama_index.core.base.embeddings.baser   r   r    llama_index.core.bridge.pydanticr   r   llama_index.core.callbacksr   *llama_index.embeddings.huggingface.poolingr   ,llama_index.core.embeddings.multi_modal_baser   llama_index.core.utilsr   r   (llama_index.embeddings.huggingface.utilsr   r   r   r   r   llama_index.core.schemar   sentence_transformersr   tenacityr    r!   r"   r   	getLoggerr   rf   r#   r   !HuggingFaceInferenceAPIEmbeddingsrI   rI   rI   rJ   <module>   s:    $
  1 E