
    9iu                        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m	Z	m
Z
mZmZ d dlmZmZmZmZ d dlmZmZmZ ddlmZmZ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$ d
dl%m&Z&m'Z'  e$jP                  e)      Z* e"       rd dl+Z+ e!       rd dl,m-Z- dZ.d*dZ/dZ0 G d d      Z1 G d de1      Z2 G d de1      Z3de1fdZ4d Z5dddddddd d!d"d#
Z6d$ Z7d% Z8d+d&Z9d' Z: G d( d)      Z;y),    N)AnyDictListOptionalUnion)create_repohf_hub_downloadmetadata_updateupload_folder)RepositoryNotFoundErrorbuild_hf_headersget_session   )custom_object_saveget_class_from_dynamic_moduleget_imports)is_pil_image)AutoProcessor)CONFIG_NAMEcached_fileis_accelerate_availableis_torch_availableis_vision_availablelogging   )handle_agent_inputshandle_agent_outputs)send_to_devicetool_config.jsonc                     ||S 	 t        | t        fddi| y# t        $ r> 	 t        | t        fddi| Y y# t        $ r t        d|  d      t        $ r Y Y yw xY wt        $ r Y yw xY w)N	repo_typespacemodel`z9` does not seem to be a valid repo identifier on the Hub.)r	   TOOL_CONFIG_FILEr   EnvironmentError	Exception)repo_idr!   
hub_kwargss      a/var/www/html/backtest/airagagent/rag_env/lib/python3.12/site-packages/transformers/tools/base.pyget_repo_typer+   7   s    !1SWS
S" 	G%5WWJW& 	k"Qwi/h#ijj 		 s*    	A+9 AA+AA+*A+zufrom transformers import launch_gradio_demo
from {module_name} import {class_name}

launch_gradio_demo({class_name})
c                       e Zd ZU dZdZeed<   dZeed<   ee   ed<   ee   ed<   d Z	d	 Z
d
 Zd Ze	 	 	 ddedee   dee   defd       Z	 	 	 	 ddededee   deeeef      dedefdZed        Zy)Toola  
    A base class for the functions used by the agent. Subclass this and implement the `__call__` method as well as the
    following class attributes:

    - **description** (`str`) -- A short description of what your tool does, the inputs it expects and the output(s) it
      will return. For instance 'This is a tool that downloads a file from a `url`. It takes the `url` as input, and
      returns the text contained in the file'.
    - **name** (`str`) -- A performative name that will be used for your tool in the prompt to the agent. For instance
      `"text-classifier"` or `"image_generator"`.
    - **inputs** (`List[str]`) -- The list of modalities expected for the inputs (in the same order as in the call).
      Modalitiies should be `"text"`, `"image"` or `"audio"`. This is only used by `launch_gradio_demo` or to make a
      nice space from your tool.
    - **outputs** (`List[str]`) -- The list of modalities returned but the tool (in the same order as the return of the
      call method). Modalitiies should be `"text"`, `"image"` or `"audio"`. This is only used by `launch_gradio_demo`
      or to make a nice space from your tool.

    You can also override the method [`~Tool.setup`] if your tool as an expensive operation to perform before being
    usable (such as loading a model). [`~Tool.setup`] will be called the first time you use your tool, but not at
    instantiation.
    zThis is a tool that ...description nameinputsoutputsc                     d| _         y )NFis_initializedselfargskwargss      r*   __init__zTool.__init__m   s
    #    c                     t        d      S )Nz-Write this method in your subclass of `Tool`.)NotImplementedr6   s      r*   __call__zTool.__call__p   s    MNNr;   c                     d| _         y)z
        Overwrite this method here for any operation that is expensive and needs to be executed before you start using
        your tool. Such as loading a big model.
        TNr4   )r7   s    r*   setupz
Tool.setups   s    
 #r;   c                    t        j                  |d       | j                  dk(  rt        d|  d| d      t	        | |      }| j
                  j                  }|j                  d      d   }| d| j
                  j                   }t         j                  j                  |d	      }t         j                  j                  |      r-t        |d
d      5 }t        j                  |      }ddd       ni }|| j                  | j                  d}t        |dd      5 }|j!                  t        j"                  |dd      dz          ddd       t         j                  j                  |d      }	t        |	dd      5 }|j!                  t$        j'                  || j
                  j                               ddd       t         j                  j                  |d      }
g }|D ]  }|j)                  t+        |              t-        t/        |            }t        |
dd      5 }|j!                  dj                  |      dz          ddd       y# 1 sw Y   hxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   yxY w)a  
        Saves the relevant code files for your tool so it can be pushed to the Hub. This will copy the code of your
        tool in `output_dir` as well as autogenerate:

        - a config file named `tool_config.json`
        - an `app.py` file so that your tool can be converted to a space
        - a `requirements.txt` containing the names of the module used by your tool (as detected when inspecting its
          code)

        You should only use this method to save tools that are defined in a separate module (not `__main__`).

        Args:
            output_dir (`str`): The folder in which you want to save your tool.
        T)exist_ok__main__z We can't save the code defining z in z{ as it's been defined in __main__. You have to put this code in a separate module so we can include it in the saved folder..r   rutf-8encodingN)
tool_classr.   r0   wr   )indent	sort_keys
zapp.py)module_name
class_namezrequirements.txt)osmakedirs
__module__
ValueErrorr   	__class__split__name__pathjoinisfileopenjsonloadr.   r0   writedumpsAPP_FILE_TEMPLATEformatextendr   listset)r7   
output_dirmodule_filesrO   last_module	full_nameconfig_fileftool_configapp_filerequirements_fileimportsmodules                r*   savez	Tool.savez   sH    	J.??j(24&ZL Ig g  *$
;nn//!'',R0"m1T^^%<%<$=>	 ggll:/AB77>>+&k39 +Q"iil+ + K%.t?O?OY]YbYbc+sW5 	NGGDJJ{1ELM	N 77<<
H5(C'2 	kaGG%,,QUQ_Q_QhQh,ij	k GGLL5GH" 	0FNN;v./	0s7|$#S7; 	/qGGDIIg&-.	/ 	/)+ +	N 	N
	k 	k	/ 	/s0   I +I#;I0)$I<I #I-0I9<JNr(   model_repo_idtokenremotec                    |r$|"t               }||vrt        d| d      ||   }g d}|j                         D 	ci c]  \  }}	||v s||	 }
}}	t        |fi |
|
d<   t	        |t
        fd|i|
ddd}|du}|t	        |t        fd|i|
ddd}|t        | d	      t        |d
      5 }t        j                  |      }ddd       |sdvrt        | d      |d   }n}|d   }t        ||fd|i|
}t        |j                        dk(  r
|d   |_        |j                  |d   k7  r,t        j                  |j                    d       |d   |_        t        |j"                        dk(  r
|d   |_        |j"                  |d   k7  r,t        j                  |j                    d       |d   |_        |rt%        |||      S  ||fd|i|S c c}	}w # 1 sw Y   xY w)aw  
        Loads a tool defined on the Hub.

        Args:
            repo_id (`str`):
                The name of the repo on the Hub where your tool is defined.
            model_repo_id (`str`, *optional*):
                If your tool uses a model and you want to use a different model than the default, you can pass a second
                repo ID or an endpoint url to this argument.
            token (`str`, *optional*):
                The token to identify you on hf.co. If unset, will use the token generated when running
                `huggingface-cli login` (stored in `~/.huggingface`).
            remote (`bool`, *optional*, defaults to `False`):
                Whether to use your tool by downloading the model or (if it is available) with an inference endpoint.
            kwargs (additional keyword arguments, *optional*):
                Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
                `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your tool, and the
                others will be passed along to its init.
        N'Could not infer a default endpoint for :, you need to pass one using the `model_repo_id` argument.)	cache_dirforce_downloadresume_downloadproxiesrevisionr!   	subfolderlocal_files_onlyr!   use_auth_tokenF)%_raise_exceptions_for_missing_entries'_raise_exceptions_for_connection_errorszY does not appear to provide a valid configuration in `tool_config.json` or `config.json`.rG   rH   custom_toolzO does not provide a mapping to custom tools in its configuration `config.json`.rJ   r   r0   z_ implements a different name in its configuration and class. Using the tool configuration name.r.   zm implements a different description in its configuration and class. Using the tool configuration description.rr   rJ   rr   )get_default_endpointsrT   itemsr+   r   r%   r   r&   r[   r\   r]   r   lenr0   loggerwarningrW   r.   
RemoteTool)clsr(   rq   rr   rs   r9   	endpointshub_kwargs_nameskvr)   resolved_config_fileis_tool_configreaderconfigr   rJ   s                    r*   from_hubzTool.from_hub   s   8 m+-/Ii' =gY G0 0  &g.M	
 (.||~Otq!>N9NadO
O #0"F:"F
;* 
 ! 
 	 

 3849 
 .T9'#.$  %$ 	$
 7<8=$   '")tu  &9 	'VYYv&F	' F*&ino  !/K K .
2:wkW\k`jk
z1$)&1JO??k&11NN&&' (& & *&1JOz%%&!+%0%?J"!![%??NN&&' (2 2 &1%?J"m5ZPP-?u???} P6	' 	's   GG5G$$G.commit_messageprivate	create_prreturnc                 p   t        |||ddd      }|j                  }t        |ddgid       t        j                         5 }| j                  |       t        j                  d| d	d
j                  t        j                  |                    t        |||||d      cddd       S # 1 sw Y   yxY w)a  
        Upload the tool to the Hub.

        Parameters:
            repo_id (`str`):
                The name of the repository you want to push your tool to. It should contain your organization name when
                pushing to a given organization.
            commit_message (`str`, *optional*, defaults to `"Upload tool"`):
                Message to commit while pushing.
            private (`bool`, *optional*):
                Whether or not the repository created should be private.
            token (`bool` or `str`, *optional*):
                The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated
                when running `huggingface-cli login` (stored in `~/.huggingface`).
            create_pr (`bool`, *optional*, defaults to `False`):
                Whether or not to create a PR with the uploaded files or directly commit.
        Tr"   gradio)r(   rr   r   rB   r!   	space_sdktagstoolr!   z!Uploading the following files to z: ,)r(   r   folder_pathrr   r   r!   N)r   r(   r
   tempfileTemporaryDirectoryrp   r   inforY   rQ   listdirr   )r7   r(   r   r   rr   r   repo_urlwork_dirs           r*   push_to_hubzTool.push_to_hub  s    2 5'DT[go
 ""&6(!3wG((* 	hIIhKK;G9BsxxPRPZPZ[cPdGeFfgh -$#!		 	 	s   AB,,B5c                 R     G d dt               }| j                  |_         ||       S )z8
        Creates a [`Tool`] from a gradio tool.
        c                        e Zd Z fdZ xZS )+Tool.from_gradio.<locals>.GradioToolWrapperc                 f    t         |           |j                  | _        |j                  | _        y N)superr:   r0   r.   )r7   _gradio_toolrU   s     r*   r:   z4Tool.from_gradio.<locals>.GradioToolWrapper.__init__Q  s)     "(--	#/#;#; r;   )rW   rS   __qualname__r:   __classcell__rU   s   @r*   GradioToolWrapperr   P  s    < <r;   r   )r-   runr>   )gradio_toolr   s     r*   from_gradiozTool.from_gradioJ  s(    	< 	< &1__" --r;   )NNF)zUpload toolNNF)rW   rS   r   __doc__r.   str__annotations__r0   r   r:   r>   r@   rp   classmethodr   boolr   r   r   staticmethodr    r;   r*   r-   r-   Q   s   * 1K0D#NI#Y$O#4/l  (,#k@k@  }k@ }	k@
 k@ k@` ,"&,0** * $	*
 dCi()* * 
*X . .r;   r-   c                   *    e Zd ZdZddZd Zd Zd Zy)r   at  
    A [`Tool`] that will make requests to an inference endpoint.

    Args:
        endpoint_url (`str`, *optional*):
            The url of the endpoint to use.
        token (`str`, *optional*):
            The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated when
            running `huggingface-cli login` (stored in `~/.huggingface`).
        tool_class (`type`, *optional*):
            The corresponding `tool_class` if this is a remote version of an existing tool. Will help determine when
            the output should be converted to another type (like images).
    Nc                 D    || _         t        ||      | _        || _        y )Nrr   )endpoint_urlEndpointClientclientrJ   )r7   r   rr   rJ   s       r*   r:   zRemoteTool.__init__i  s    ($\?$r;   c           	         |j                         }t        |      dkD  r| j                  6t        | j                  t              r| j                  j
                  }n| j                  j                  }t        j                  |      j                  }|j                         D cg c]G  \  }}|j                  t        j                  j                  t        j                  j                  fvr|I }}}|d   dk(  r|dd }t        |      t        |      kD  r0t        | j                   dt        |       dt        |       d      t!        ||      D ]
  \  }	}
|	||
<    n\t        |      dkD  rt        d      t        |      dk(  r5t#        |d         r d	| j$                  j'                  |d         iS d	|d   iS |j                         D ]/  \  }}t#        |      s| j$                  j'                  |      ||<   1 d	|iS c c}}w )
aP  
        Prepare the inputs received for the HTTP client sending data to the endpoint. Positional arguments will be
        matched with the signature of the `tool_class` if it was provided at instantation. Images will be encoded into
        bytes.

        You can override this method in your custom class of [`RemoteTool`].
        r   Nr7   r   z only accepts z arguments but z were given.z4A `RemoteTool` can only accept one positional input.r1   )copyr   rJ   
issubclassPipelineToolencoder>   inspect	signature
parametersr   kind_ParameterKindVAR_POSITIONALVAR_KEYWORDrT   zipr   r   encode_image)r7   r8   r9   r1   call_methodr   r   pr   argr0   keyvalues                r*   prepare_inputszRemoteTool.prepare_inputsn  s    t9q=*doo|<"&//"8"8K"&//":":K#--k:EE	 !* 11vvg&<&<&K&KWMcMcMoMo%pp 
 
 a=F*!+ABJt9s:.$??+>#j/9J/Z]^bZcYddpq  "%T:!6 'IC#&F4L'TQ !WXXTaQ($dkk&>&>tAw&GHH $q'** ,,. 	>JCE""kk66u=s	> &!!1s   &AHc                     |S )z
        You can override this method in your custom class of [`RemoteTool`] to apply some custom post-processing of the
        outputs of the endpoint.
        r   r7   r2   s     r*   extract_outputszRemoteTool.extract_outputs  s	    
 r;   c                    t        |i |\  }}| j                  d uxr | j                  j                  dgk(  } | j                  |i |}t	        |t
              r | j                  di |d|i}n| j                  ||      }t	        |t              r&t        |      dk(  rt	        |d   t              r|d   }t        || j                  | j                  j                  nd       }| j                  |      S )Nimageoutput_image)r   r   r   r   )r   rJ   r2   r   
isinstancedictr   rc   r   r   r   )r7   r8   r9   r   r1   r2   s         r*   r>   zRemoteTool.__call__  s    *D;F;fd2[t7N7NSZR[7[$$$d5f5fd#!dkkFFFFGkk&|kDGgt$W):z'RS*VZ?[ajG&w4??Kf0G0Glpq##G,,r;   )NNN)rW   rS   r   r   r:   r   r   r>   r   r;   r*   r   r   Z  s    %
)"V-r;   r   c                   d     e Zd ZdZeZdZeZdZ	 	 	 	 	 	 	 d	 fd	Z	 fdZ
d Zd Zd Zd Z xZS )
r   a0	  
    A [`Tool`] tailored towards Transformer models. On top of the class attributes of the base class [`Tool`], you will
    need to specify:

    - **model_class** (`type`) -- The class to use to load the model in this tool.
    - **default_checkpoint** (`str`) -- The default checkpoint that should be used when the user doesn't specify one.
    - **pre_processor_class** (`type`, *optional*, defaults to [`AutoProcessor`]) -- The class to use to load the
      pre-processor
    - **post_processor_class** (`type`, *optional*, defaults to [`AutoProcessor`]) -- The class to use to load the
      post-processor (when different from the pre-processor).

    Args:
        model (`str` or [`PreTrainedModel`], *optional*):
            The name of the checkpoint to use for the model, or the instantiated model. If unset, will default to the
            value of the class attribute `default_checkpoint`.
        pre_processor (`str` or `Any`, *optional*):
            The name of the checkpoint to use for the pre-processor, or the instantiated pre-processor (can be a
            tokenizer, an image processor, a feature extractor or a processor). Will default to the value of `model` if
            unset.
        post_processor (`str` or `Any`, *optional*):
            The name of the checkpoint to use for the post-processor, or the instantiated pre-processor (can be a
            tokenizer, an image processor, a feature extractor or a processor). Will default to the `pre_processor` if
            unset.
        device (`int`, `str` or `torch.device`, *optional*):
            The device on which to execute the model. Will default to any accelerator available (GPU, MPS etc...), the
            CPU otherwise.
        device_map (`str` or `dict`, *optional*):
            If passed along, will be used to instantiate the model.
        model_kwargs (`dict`, *optional*):
            Any keyword argument to send to the model instantiation.
        token (`str`, *optional*):
            The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated when
            running `huggingface-cli login` (stored in `~/.huggingface`).
        hub_kwargs (additional keyword arguments, *optional*):
            Any additional keyword argument to send to the methods that will load the data from the Hub.
    Nc                 r   t               st        d      t               st        d      |#| j                  t	        d      | j                  }||}|| _        || _        || _        || _        || _	        |i n|| _
        ||| j                  d<   || _        || j                  d<   t        	| 5          y )N/Please install torch in order to use this tool.z4Please install accelerate in order to use this tool.zHThis tool does not implement a default checkpoint, you need to pass one.
device_maprr   )r   ImportErrorr   default_checkpointrT   r#   pre_processorpost_processordevicer   model_kwargsr)   r   r:   )
r7   r#   r   r   r   r   r   rr   r)   rU   s
            r*   r:   zPipelineTool.__init__  s     "#OPP&(TUU=&&. !kll++E !M
*,$"."6BL!.8Dl+$#( r;   c                 r   t        | j                  t              r6 | j                  j                  | j                  fi | j
                  | _        t        | j                  t              rB | j                  j                  | j                  fi | j                  | j
                  | _        | j                  | j                  | _	        nPt        | j                  t              r6 | j                  j                  | j                  fi | j
                  | _	        | j                  Q| j                  6t        | j                  j                  j                               d   | _        nt!               | _        | j                  %| j                  j#                  | j                         t$        | M          y)z^
        Instantiates the `pre_processor`, `model` and `post_processor` if necessary.
        Nr   )r   r   r   pre_processor_classfrom_pretrainedr)   r#   model_classr   r   post_processor_classr   r   rc   hf_device_mapvaluesget_default_devicetor   r@   )r7   rU   s    r*   r@   zPipelineTool.setup  sE    d((#.!I!9!9!I!I$J\J\!p`d`o`o!pDdjj#&9))99$**mHYHYm]a]l]lmDJ&"&"4"4D++S1"K$";";"K"KDL_L_"scgcrcr"sD;;*"4::#;#;#B#B#DEaH02??"JJMM$++&r;   c                 $    | j                  |      S )zQ
        Uses the `pre_processor` to prepare the inputs for the `model`.
        )r   )r7   
raw_inputss     r*   r   zPipelineTool.encode  s     !!*--r;   c                 z    t        j                         5   | j                  di |cddd       S # 1 sw Y   yxY w)z7
        Sends the inputs through the `model`.
        Nr   )torchno_gradr#   )r7   r1   s     r*   forwardzPipelineTool.forward!  s3     ]]_ 	(4::''	( 	( 	(s   1:c                 $    | j                  |      S )zG
        Uses the `post_processor` to decode the model output.
        )r   r   s     r*   decodezPipelineTool.decode(  s     ""7++r;   c                 .   t        |i |\  }}| j                  s| j                           | j                  |i |}t	        || j
                        }| j                  |      }t	        |d      }| j                  |      }t        || j                        S )Ncpu)
r   r5   r@   r   r   r   r   r   r   r2   )r7   r8   r9   encoded_inputsr2   decoded_outputss         r*   r>   zPipelineTool.__call__.  s    *D;F;f""JJL$d5f5'D,,~. %0++g.#OT\\BBr;   )NNNNNNN)rW   rS   r   r   r   r   r   r   r   r:   r@   r   r   r   r>   r   r   s   @r*   r   r     sY    #J (K( #J4.(,Cr;   r   rJ   c                     	 ddl } |        fd}|j                  || j                  | j                  | j
                  j                        j                          y# t        $ r t        d      w xY w)z
    Launches a gradio demo for a tool. The corresponding tool class needs to properly implement the class attributes
    `inputs` and `outputs`.

    Args:
        tool_class (`type`): The class of the tool for which to launch the demo.
    r   Nz<Gradio should be installed in order to launch a gradio demo.c                       | i |S r   r   )r8   r9   r   s     r*   fnzlaunch_gradio_demo.<locals>.fnL  s    T$V$$r;   )r   r1   r2   titlearticle)r   r   	Interfacer1   r2   rW   r.   launch)rJ   grr   r   s      @r*   launch_gradio_demor  =  s|    Z <D% LL  ""!!     fh  ZXYYZs   A   A5c                     t         j                  d       t               st        d      t        j
                  j                  j                         r=t        j
                  j                  j                         rt	        j                  d      S t        j                  j                         rt	        j                  d      S t	        j                  d      S )Nu   `get_default_device` is deprecated and will be replaced with `accelerate`'s `PartialState().default_device` in version 4.36 of 🤗 Transformers. r   mpscudar   )r   r   r   r   r   backendsr  is_availableis_builtr   r  r   r;   r*   r   r   Y  s    
NN	1 KLL~~&&(U^^-?-?-H-H-J||E""		 	 	"||F##||E""r;   DocumentQuestionAnsweringToolImageCaptioningToolImageQuestionAnsweringToolImageSegmentationToolSpeechToTextToolTextSummarizationToolTextClassificationToolTextQuestionAnsweringToolTextToSpeechToolTranslationTool)
zdocument-question-answeringzimage-captioningzimage-question-answeringzimage-segmentationzspeech-to-textsummarizationztext-classificationztext-question-answeringztext-to-speechtranslationc                      t        ddd      } t        | dd      5 }t        j                  |      }d d d        |S # 1 sw Y   S xY w)Nz#huggingface-tools/default-endpointszdefault_endpoints.jsondatasetr   rF   rG   rH   )r   r[   r\   r]   )endpoints_filerj   r   s      r*   r   r   w  sJ     !FH`luvN	ncG	4 !IIaL	!!s	   =Ac                     t               }| |v S r   )r   )task_or_repo_idr   s     r*   supports_remoter  ~  s    %'Ii''r;   c                 0   | t         v rut         |    }t        j                  d      }|j                  }t	        ||      }|r2|"t               }	| |	vrt        d|  d      |	|    }t        |||      S  ||fd|i|S t        j                  | f|||d|S )a  
    Main function to quickly load a tool, be it on the Hub or in the Transformers library.

    Args:
        task_or_repo_id (`str`):
            The task for which to load the tool or a repo ID of a tool on the Hub. Tasks implemented in Transformers
            are:

            - `"document-question-answering"`
            - `"image-captioning"`
            - `"image-question-answering"`
            - `"image-segmentation"`
            - `"speech-to-text"`
            - `"summarization"`
            - `"text-classification"`
            - `"text-question-answering"`
            - `"text-to-speech"`
            - `"translation"`

        model_repo_id (`str`, *optional*):
            Use this argument to use a different model than the default one for the tool you selected.
        remote (`bool`, *optional*, defaults to `False`):
            Whether to use your tool by downloading the model or (if it is available) with an inference endpoint.
        token (`str`, *optional*):
            The token to identify you on hf.co. If unset, will use the token generated when running `huggingface-cli
            login` (stored in `~/.huggingface`).
        kwargs (additional keyword arguments, *optional*):
            Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
            `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your tool, and the others
            will be passed along to its init.
    transformersru   rv   r   rr   )rq   rr   rs   )
TASK_MAPPING	importlibimport_moduletoolsgetattrr   rT   r   r-   r   )
r  rq   rs   rr   r9   tool_class_namemain_moduletools_modulerJ   r   s
             r*   	load_toolr'    s    @ ,&&7--n="((\?;
$13	")3$A/AR S4 4  !*/ :m5ZPPmC5CFCC}}_pMQV_epioppr;   c                       fd}|S )z<
    A decorator that adds a description to a function.
    c                 8    | _         | j                  | _        | S r   )r.   rW   r0   )funcr.   s    r*   innerzadd_description.<locals>.inner  s    &MM	r;   r   )r.   r+  s   ` r*   add_descriptionr,    s    

 Lr;   c                       e Zd Zddedee   fdZed        Zed        Z	 	 	 	 ddee	ee
ee   eee      f      dee
   d	ee   d
edef
dZy)r   Nr   rr   c                 @    i t        |      ddi| _        || _        y )Nr   zContent-Typezapplication/json)r   headersr   )r7   r   rr   s      r*   r:   zEndpointClient.__init__  s$    \*7\I[\(r;   c                     t        j                         }| j                  |d       t        j                  |j                               }|j                  d      S )NPNG)ra   rG   )ioBytesIOrp   base64	b64encodegetvaluer   )r   _bytesb64s      r*   r   zEndpointClient.encode_image  sC    

6%
(v01zz'""r;   c                     t               st        d      ddlm} t	        j
                  |       }t        j                  |      }|j                  |      S )NzbThis tool returned an image but Pillow is not installed. Please install it (`pip install Pillow`).r   )Image)	r   r   PILr:  r4  	b64decoder2  r3  r[   )	raw_imager:  r8  r7  s       r*   decode_imagezEndpointClient.decode_image  sI    "$t  	y)Czz&!!r;   r1   paramsdatar   r   c                     i }|r||d<   |r||d<   t               j                  | j                  | j                  ||      }|r| j	                  |j
                        S |j                         S )Nr1   r   )r/  r\   r@  )r   postr   r/  r>  contentr\   )r7   r1   r?  r@  r   payloadresponses          r*   r>   zEndpointClient.__call__  st      &GH$*GL! =%%d&7&7T[bf%g $$X%5%566==?"r;   r   )NNNF)rW   rS   r   r   r   r:   r   r   r>  r   r   r   bytesr   r   r>   r   r;   r*   r   r     s    )S )# ) # # 
" 
" JN!% $"#sD$s)T$s)_DEF# # uo	#
 # 
#r;   r   r   )NFN)<r4  r   r   r2  r\   rQ   r   typingr   r   r   r   r   huggingface_hubr   r	   r
   r   huggingface_hub.utilsr   r   r   dynamic_module_utilsr   r   r   image_utilsr   models.autor   utilsr   r   r   r   r   r   agent_typesr   r   
get_loggerrW   r   r   accelerate.utilsr   r%   r+   r`   r-   r   r   r  r   r  r   r  r'  r,  r   r   r;   r*   <module>rQ     s  "    	  	  3 3 X X X X a a & '  C 
		H	%/ & & F. F.RT- T-nIC4 ICX4 8#" $C- <1(,3:($(
3ql
.# .#r;   