o
    h]                     @   s2  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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 d dlmZmZ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% d	dl&m'Z' d	dl(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 e05e6Z7e. rd dl8Z8e- rd dl9m:Z: d dl;m<Z< dZ=d>ddZ>dZ?d?de@fddZAddddZBG dd dZCdZDeDfd eCd!eEd"eEfd#d$ZFe	d%d& ZGG d'd( d(eCZHd)eCfd*d+ZId,d-d.d/d0d1d2d3ZJd@d4d5ZKd6d7 ZLG d8d9 d9ZMG d:d; d;ZNd<ed"eCfd=d ZOdS )A    N)	lru_cachewraps)Path)AnyCallableDictListOptionalUnion)create_repoget_collectionhf_hub_downloadmetadata_updateupload_folder)RepositoryNotFoundErrorbuild_hf_headersget_session)_deprecate_method)version   )custom_object_saveget_class_from_dynamic_moduleget_imports)AutoProcessor)CONFIG_NAMETypeHintParsingExceptioncached_fileget_json_schemais_accelerate_availableis_torch_availableis_vision_availablelogging   )	ImageTypehandle_agent_inputshandle_agent_outputs)PartialState)send_to_devicetool_config.jsonc                 K   s   |d ur|S zt | tfddi| W dS  tyD   zt | tfddi| W Y dS  ty9   td|  d tyC   Y Y dS w  tyM   Y dS 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_kwargs r2   m/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/agents/tools.pyget_repo_typeC   s"   r4   zufrom transformers import launch_gradio_demo
from {module_name} import {class_name}

launch_gradio_demo({class_name})
Tdo_validate_forwardc                    s&   | j t fdd}|| _ | S )Nc                    s4   | g|R i | t | ts| j d d S d S )Nr5   )
isinstancePipelineToolvalidate_argumentsselfargskwargsr5   original_initr2   r3   new_init`   s   
z%validate_after_init.<locals>.new_init)__init__r   )clsr5   r@   r2   r>   r3   validate_after_init]   s
   rC   stringintegernumber)strintfloatc                       sJ  e Zd ZU dZeed< eed< eeeeeeef f f ed< eed< e	dddd	d
 Z
e	ddd fddZd.defddZdd Zdd Zdd Zdd Ze	d/dedee fddZ				d0ded ed!ee deeeef  d"ed#efd$d%Ze	d1d&ededed'ee dee f
d(d)Zed*d+ Zed,d- Z  ZS )2Toolak  
    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** (`Dict[str, Dict[str, Union[str, type]]]`) -- The dict of modalities expected for the inputs.
      It has one `type`key and a `description`key.
      This is used by `launch_gradio_demo` or to make a nice space from your tool, and also can be used in the generated
      description for your tool.
    - **output_type** (`type`) -- The type of the tool output. This is used by `launch_gradio_demo`
      or to make a nice space from your tool, and also can be used in the generated description for 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.
    namedescriptioninputsoutput_typez4.51.0zzSwitch to smolagents instead, with the same functionalities and similar API (https://huggingface.co/docs/smolagents/index))r   messagec                 O   s
   d| _ d S )NFis_initializedr:   r2   r2   r3   rA         
zTool.__init__c                    s"   t  jdi | t| dd d S )NFr6   r2   )super__init_subclass__rC   )rB   r=   	__class__r2   r3   rT      s   zTool.__init_subclass__Tr5   c           
   	   C   s^  t t tt d}g d}| D ],\}}t| |d }|d u r%td| dt||s;td| d|j dt| dq| j D ]>\}}t|tsRJ d	| d
d|v rZd|v siJ d	| dt	|
  d|d |vrtd	| d|d  d| dqAt| dd |v sJ |rt| tst| j}	t|	j
 t| j
 kstdd S d S d S )N)rL   rK   rM   rN   )rD   rE   rF   imageaudioanybooleanzYou must set an attribute .z
Attribute z should have type z, got z	 instead.zInput 'z' should be a dictionary.typerL   z6' should have keys 'type' and 'description', has only z	': type 'z/' is not an authorized value, should be one of rN   zTool's 'forward' method should take 'self' as its first argument, then its next arguments should match the keys of tool attribute 'inputs'.)rG   dictitemsgetattr	TypeErrorr7   __name__r\   rM   listkeysr/   r8   inspect	signatureforwardset
parameters)
r;   r5   required_attributesauthorized_typesattrexpected_type
attr_value
input_nameinput_contentre   r2   r2   r3   r9      sH   

zTool.validate_argumentsc                 O   s   t dS )Nz-Write this method in your subclass of `Tool`.)NotImplementedr:   r2   r2   r3   rf         zTool.forwardc                 O   s.   t |i |\}}| j|i |}t|| jS N)r$   rf   r%   rN   )r;   r<   r=   outputsr2   r2   r3   __call__   s   zTool.__call__c                 C   s
   d| _ dS )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.
        TNrP   r;   r2   r2   r3   setup   rR   z
Tool.setupc                 C   s  t j|dd | jdkrtd|  d| dt| |}| jj}|dd }| d| jj }t j	|d	}t j
|rZt|d
dd}t|}W d   n1 sTw   Y  ni }|| j| j| jt| jd}t|ddd}|tj|dddd  W d   n1 sw   Y  t j	|d}	t|	ddd}|tj|| jjd W d   n1 sw   Y  t j	|d}
g }|D ]	}|t| qtt|}t|
ddd}|d	|d  W d   dS 1 sw   Y  dS )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(   rutf-8encodingN)
tool_classrL   rK   rM   rN   wr   )indent	sort_keys
zapp.py)module_name
class_namezrequirements.txt)osmakedirs
__module__
ValueErrorr   rV   splitra   pathjoinisfileopenjsonloadrL   rK   rM   rG   rN   writedumpsAPP_FILE_TEMPLATEformatextendr   rb   rg   )r;   
output_dirmodule_filesr   last_module	full_nameconfig_fileftool_configapp_filerequirements_fileimportsmoduler2   r2   r3   save   sJ   

"z	Tool.saveNr0   tokenc                    s  g d  fdd|  D }t|fi ||d< t|tfd|i|dddd}|du}|du rCt|tfd|i|dddd}|du rNt| d	t|d
d}t|}W d   n1 sdw   Y  |s{d|vrvt| d|d }	n|}	|	d }
t	|
|fd|i|}
t
|
jdkr|	d |
_|
j|	d krt|
j d |	d |
_t
|
jdkr|	d |
_|
j|	d krt|
j d |	d |
_|
j|	d kr|	d |
_|
j|	d kr|	d |
_t|
jtst|
j|
_|
di |S )a  
        Loads a tool defined on the Hub.

        <Tip warning={true}>

        Loading a tool from the Hub means that you'll download the tool and execute it locally.
        ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
        installing a package using pip/npm/apt.

        </Tip>

        Args:
            repo_id (`str`):
                The name of the repo on the Hub where your tool is defined.
            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.
        )	cache_dirforce_downloadresume_downloadproxiesrevisionr)   	subfolderlocal_files_onlyc                    s   i | ]\}}| v r||qS r2   r2   .0kvhub_kwargs_namesr2   r3   
<dictcomp>-  s    z!Tool.from_hub.<locals>.<dictcomp>r)   r   F) _raise_exceptions_for_gated_repo%_raise_exceptions_for_missing_entries'_raise_exceptions_for_connection_errorsNzY does not appear to provide a valid configuration in `tool_config.json` or `config.json`.r{   r|   custom_toolzO does not provide a mapping to custom tools in its configuration `config.json`.r~   r   rK   z_ implements a different name in its configuration and class. Using the tool configuration name.rL   zm implements a different description in its configuration and class. Using the tool configuration description.rM   rN   r2   )r^   r4   r   r-   r   r.   r   r   r   r   lenrK   loggerwarningra   rL   rM   rN   r7   r]   astliteral_eval)rB   r0   r   r=   r1   resolved_config_fileis_tool_configreaderconfigr   r~   r2   r   r3   from_hub  s   

	
	








zTool.from_hubUpload toolFcommit_messageprivate	create_prreturnc                 C   s   t |||dddd}|j}t|ddgidd t (}| | td| d	d
t	
|  t|||||ddW  d   S 1 sFw   Y  dS )a  
        Upload the tool to the Hub.

        For this method to work properly, your tool must have been defined in a separate module (not `__main__`).
        For instance:
        ```
        from my_tool_module import MyTool
        my_tool = MyTool()
        my_tool.push_to_hub("my-username/my-space")
        ```

        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 to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
            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)r0   r   r   rw   r)   	space_sdktagstool)r)   z!Uploading the following files to z: ,)r0   r   folder_pathr   r   r)   N)r   r0   r   tempfileTemporaryDirectoryr   r   infor   r   listdirr   )r;   r0   r   r   r   r   repo_urlwork_dirr2   r2   r3   push_to_hubu  s,   !

"$zTool.push_to_hubspace_idapi_namec                    sF   ddl m m ddlm G  fdddt}|| ||||dS )a1  
        Creates a [`Tool`] from a Space given its id on the Hub.

        Args:
            space_id (`str`):
                The id of the Space on the Hub.
            name (`str`):
                The name of the tool.
            description (`str`):
                The description of the tool.
            api_name (`str`, *optional*):
                The specific api_name to use, if the space has several tabs. If not precised, will default to the first available api.
            token (`str`, *optional*):
                Add your token to access private spaces or increase your GPU quotas.
        Returns:
            [`Tool`]:
                The Space, as a tool.

        Examples:
        ```
        image_generator = Tool.from_space(
            space_id="black-forest-labs/FLUX.1-schnell",
            name="image-generator",
            description="Generate an image from a prompt"
        )
        image = image_generator("Generate an image of a cool surfer in Tahiti")
        ```
        ```
        face_swapper = Tool.from_space(
            "tuan2308/face-swap",
            "face_swapper",
            "Tool that puts the face shown on the first image on the second image. You can give it paths to images.",
        )
        image = face_swapper('./aymeric.jpeg', './ruth.jpg')
        ```
        r   )Clienthandle_file)is_http_url_likec                       sR   e Zd Z		ddedededee dee f
 fddZfd	d
Zdd ZdS )z)Tool.from_space.<locals>.SpaceToolWrapperNr   rK   rL   r   r   c                    s   ||d| _ || _|| _| j jdddd }|d u r,t| d }td| d || _z|| }W n t	yD   t	d	|d
w i | _
|d D ] }|d sl|d d }	|	dkr^d}	|	|d d d| j
|d < qL|d d d }
|
dkr~d| _d S |
dkrd| _d S d| _d S )N)hf_tokenr]   F)return_format
print_infonamed_endpointsr   zXSince `api_name` was not defined, it was automatically set to the first available API: `z`.z"Could not find specified api_name=z among available api names.rh   parameter_has_defaultr\   objectrY   python_typerL   r\   rL   parameter_namereturns	componentImagerW   AudiorX   )clientrK   rL   view_apirb   rc   r   r   r   KeyErrorrM   rN   )r;   r   rK   rL   r   r   space_descriptionspace_description_api	parameterparameter_typeoutput_component)r   r2   r3   rA     s>   




z2Tool.from_space.<locals>.SpaceToolWrapper.__init__c                    sd   t |trtjddd}||j |j}t |ttfr(t| r(t|	 s,|r0 |}|S )Nz.pngF)suffixdelete)
r7   r#   r   NamedTemporaryFiler   rK   rG   r   existsis_file)r;   arg	temp_file)r   r   r2   r3    sanitize_argument_for_prediction  s   
(zJTool.from_space.<locals>.SpaceToolWrapper.sanitize_argument_for_predictionc                 _   s   t |}t|D ]\}}| |||< q| D ]\}}| |||< q| jj|d| ji|}t|ts:t|t r>|d S |S )Nr   r   )	rb   	enumerater   r^   r   predictr   r7   tuple)r;   r<   r=   ir   arg_nameoutputr2   r2   r3   rf     s   z1Tool.from_space.<locals>.SpaceToolWrapper.forwardNN)ra   r   __qualname__rG   r	   rA   r   rf   r2   r   r   r   r2   r3   SpaceToolWrapper  s     ,r   )r   r   )gradio_clientr   r   gradio_client.utilsr   rJ   )r   rK   rL   r   r   r   r2   r   r3   
from_space  s   (GzTool.from_spacec                    s$   ddl  G  fdddt}|| S )z8
        Creates a [`Tool`] from a gradio tool.
        r   Nc                       s   e Zd Z fddZdS )z+Tool.from_gradio.<locals>.GradioToolWrapperc                    sP   |j | _ |j| _d| _|| _t |jj }dd |D | _	| jj| _
d S )NrD   c                 S   s"   i | ]\}}|t |j d dqS ) r   )CONVERSION_DICT
annotation)r   keyvaluer2   r2   r3   r   0  s    zHTool.from_gradio.<locals>.GradioToolWrapper.__init__.<locals>.<dictcomp>)rK   rL   rN   _gradio_toolrb   re   runrh   r^   rM   rf   )r;   r  	func_argsrd   r2   r3   rA   *  s   z4Tool.from_gradio.<locals>.GradioToolWrapper.__init__N)ra   r   r   rA   r2   r  r2   r3   GradioToolWrapper)  s    r  )rd   rJ   )gradio_toolr  r2   r  r3   from_gradio"  s   zTool.from_gradioc                 C   s   G dd dt }|| S )z;
        Creates a [`Tool`] from a langchain tool.
        c                   @   s   e Zd Zdd Zdd ZdS )z1Tool.from_langchain.<locals>.LangChainToolWrapperc                 S   sZ   |j  | _ |j| _|j | _| j D ]}d|v r |d d|d< qd| _|| _	d S )Ntitler   rL   rD   )
rK   lowerrL   r<   copyrM   valuespoprN   langchain_tool)r;   _langchain_toolro   r2   r2   r3   rA   >  s   


z:Tool.from_langchain.<locals>.LangChainToolWrapper.__init__c                 _   sJ   |  }t|D ]\}}|t| jk rtt| j}|||< q| j|S rr   )r  r   r   rM   nextiterr  r  )r;   r<   r=   
tool_inputindexargument	input_keyr2   r2   r3   rf   I  s   z9Tool.from_langchain.<locals>.LangChainToolWrapper.forwardN)ra   r   r   rA   rf   r2   r2   r2   r3   LangChainToolWrapper=  s    r  )rJ   )r  r  r2   r2   r3   from_langchain7  s   zTool.from_langchainTrr   )r   NNFr   )ra   r   r   __doc__rG   __annotations__r   r
   r\   r   rA   rT   boolr9   rf   rt   rv   r   classmethodr	   r   r   staticmethodr   r
  r  __classcell__r2   r2   rU   r3   rJ   m   s|   
  
$<q
9s
rJ   z
- {{ tool.name }}: {{ tool.description }}
    Takes inputs: {{tool.inputs}}
    Returns an output of type: {{tool.output_type}}
r   description_templater   c                 C   s   t |}|j| d}|S )Nr   )compile_jinja_templaterender)r   r!  compiled_templaterenderedr2   r2   r3   get_tool_description_with_args[  s
   r'  c                    s   zdd l }ddlm  ddlm} W n ty   tdw t|jtdk r2td|j d fdd	}|d
d
d}||j	d< |
| S )Nr   TemplateError)ImmutableSandboxedEnvironmentz)template requires jinja2 to be installed.z3.1.0zAtemplate requires jinja2>=3.1.0 to be installed. Your version is r[   c                    s    | rr   r2   )rO   r(  r2   r3   raise_exceptiono  rq   z/compile_jinja_template.<locals>.raise_exceptionT)trim_blockslstrip_blocksr+  )jinja2jinja2.exceptionsr)  jinja2.sandboxr*  ImportErrorr   parse__version__globalsfrom_string)templater.  r*  r+  	jinja_envr2   r(  r3   r#  c  s   

r#  c                       s   e Zd ZdZeZdZeZdZdZ	dZ
deiZeZ							d fdd	Z fdd	Zd
d Zdd Zdd Zdd Z  ZS )r8   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.
    NzThis is a pipeline toolpipelinepromptc           	         s   t  stdt std|d u r| jd u rtd| j}|d u r$|}|| _|| _|| _|| _|| _	|d u r9i n|| _
|d urE|| j
d< || _|| jd< t   d S )Nz/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_mapr   )r   r1  r   default_checkpointr   r+   pre_processorpost_processordevicer:  model_kwargsr1   rS   rA   )	r;   r+   r<  r=  r>  r:  r?  r   r1   rU   r2   r3   rA     s*   


zPipelineTool.__init__c                    s   t | jtr| jj| jfi | j| _t | jtr)| jj| jfi | j| j| _| j	du r3| j| _	nt | j	trF| j
j| j	fi | j| _	| jdu ra| jdur\t| jj d | _nt j| _| jdu rm| j| j t   dS )z^
        Instantiates the `pre_processor`, `model` and `post_processor` if necessary.
        Nr   )r7   r<  rG   pre_processor_classfrom_pretrainedr1   r+   model_classr?  r=  post_processor_classr>  r:  rb   hf_device_mapr  r&   default_devicetorS   rv   ru   rU   r2   r3   rv     s    





zPipelineTool.setupc                 C   
   |  |S )zQ
        Uses the `pre_processor` to prepare the inputs for the `model`.
        )r<  )r;   
raw_inputsr2   r2   r3   encode     
zPipelineTool.encodec                 C   s<   t   | jdi |W  d   S 1 sw   Y  dS )z7
        Sends the inputs through the `model`.
        Nr2   )torchno_gradr+   )r;   rM   r2   r2   r3   rf     s   
$zPipelineTool.forwardc                 C   rG  )zG
        Uses the `post_processor` to decode the model output.
        )r=  )r;   rs   r2   r2   r3   decode  rJ  zPipelineTool.decodec                 O   s   t |i |\}}| js|   | j|i |}dd | D }dd | D }t|| j}| i ||}t|d}| |}t	|| j
S )Nc                 S   s"   i | ]\}}t |tjr||qS r2   r7   rK  Tensorr   r2   r2   r3   r         " z)PipelineTool.__call__.<locals>.<dictcomp>c                 S   s"   i | ]\}}t |tjs||qS r2   rN  r   r2   r2   r3   r     rP  cpu)r$   rQ   rv   rI  r^   r'   r>  rf   rM  r%   rN   )r;   r<   r=   encoded_inputstensor_inputsnon_tensor_inputsrs   decoded_outputsr2   r2   r3   rt     s   

zPipelineTool.__call__)NNNNNNN)ra   r   r   r  r   r@  rB  rC  r;  rL   rK   rG   rM   rN   rA   rv   rI  rf   rM  rt   r   r2   r2   rU   r3   r8   w  s.    %%r8   r~   c                    s   zddl }W n ty   tdw |    fdd}|j|j|j|j|jd}g }| j D ]\}}||d  }||d}|| q/|| j }	|	|d}
|j	|||
| j
 jd	  dS )
z
    Launches a gradio demo for a tool. The corresponding tool class needs to properly implement the class attributes
    `inputs` and `output_type`.

    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                     s    | i |S rr   r2   )r<   r=   r"  r2   r3   fn  s   zlaunch_gradio_demo.<locals>.fn)rW   rX   rD   rE   rF   r\   )label)rV  rM   rs   r  article)r   r1  r   r   TextboxrM   r^   appendrN   	Interfacera   rL   launch)r~   grrV  TYPE_TO_COMPONENT_CLASS_MAPPINGgradio_inputsrn   input_detailsinput_gradio_component_classnew_componentoutput_gradio_componentclassgradio_outputr2   r"  r3   launch_gradio_demo  s8   



re  DocumentQuestionAnsweringToolImageQuestionAnsweringToolSpeechToTextToolTextToSpeechToolTranslationToolPythonInterpreterToolDuckDuckGoSearchTool)document_question_answeringimage_question_answeringspeech_to_texttext_to_speechtranslationpython_interpreter
web_searchc                 K   sh   | t v rt |  }td}|j}t||}||fd|i|S td| d tj| f||d|S )a  
    Main function to quickly load a tool, be it on the Hub or in the Transformers library.

    <Tip warning={true}>

    Loading a tool means that you'll download the tool and execute it locally.
    ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
    installing a package using pip/npm/apt.

    </Tip>

    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_question_answering"`
            - `"speech_to_text"`
            - `"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.
        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.
    transformersr   z(You're loading a tool from the Hub from a  . Please make sure this is a source that you trust as the code within that tool will be executed on your machine. Always verify the code of the tools that you load. We recommend specifying a `revision` to ensure you're loading the code that you have checked.)model_repo_idr   )	TOOL_MAPPING	importlibimport_moduleagentsr_   r   warning_oncerJ   r   )task_or_repo_idru  r   r=   tool_class_namemain_moduletools_moduler~   r2   r2   r3   	load_toolB  s   !


r  c                    s    fdd}|S )z<
    A decorator that adds a description to a function.
    c                    s    | _ | j| _| S rr   )rL   ra   rK   )funcrL   r2   r3   innerx  s   zadd_description.<locals>.innerr2   )rL   r  r2   r  r3   add_descriptions  s   r  c                   @   s   e Zd Zddedee fddZedd Zed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dZdS )EndpointClientNendpoint_urlr   c                 C   s"   i t |dddi| _|| _d S )Nr   zContent-Typezapplication/json)r   headersr  )r;   r  r   r2   r2   r3   rA     s   
zEndpointClient.__init__c                 C   s.   t  }| j|dd t| }|dS )NPNG)r   r{   )ioBytesIOr   base64	b64encodegetvaluerM  )rW   _bytesb64r2   r2   r3   encode_image  s   
zEndpointClient.encode_imagec                 C   s8   t  stdddlm} t| }t|}||S )NzbThis tool returned an image but Pillow is not installed. Please install it (`pip install Pillow`).r   )r   )	r    r1  PILr   r  	b64decoder  r  r   )	raw_imager   r  r  r2   r2   r3   decode_image  s   


zEndpointClient.decode_imageFrM   paramsdataoutput_imager   c                 C   sL   i }|r||d< |r||d< t  j| j| j||d}|r"| |jS | S )NrM   rh   )r  r   r  )r   postr  r  r  contentr   )r;   rM   r  r  r  payloadresponser2   r2   r3   rt     s   zEndpointClient.__call__rr   )NNNF)ra   r   r   rG   r	   rA   r  r  r  r
   r   r   bytesr  r   rt   r2   r2   r2   r3   r    s*    

r  c                   @   s(   e Zd ZdZddedee fddZdS )ToolCollectionai  
    Tool collections enable loading all Spaces from a collection in order to be added to the agent's toolbox.

    > [!NOTE]
    > Only Spaces will be fetched, so you can feel free to add models and datasets to your collection if you'd
    > like for this collection to showcase them.

    Args:
        collection_slug (str):
            The collection slug referencing the collection.
        token (str, *optional*):
            The authentication token if the collection is private.

    Example:

    ```py
    >>> from transformers import ToolCollection, ReactCodeAgent

    >>> image_tool_collection = ToolCollection(collection_slug="huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f")
    >>> agent = ReactCodeAgent(tools=[*image_tool_collection.tools], add_base_tools=True)

    >>> agent.run("Please draw me a picture of rivers and lakes.")
    ```
    Ncollection_slugr   c                 C   s8   t ||d| _dd | jjD | _dd | jD | _d S )Nr  c                 S   s   h | ]
}|j d kr|jqS )r*   )	item_typeitem_id)r   itemr2   r2   r3   	<setcomp>  s    z*ToolCollection.__init__.<locals>.<setcomp>c                 S   s   h | ]}t |qS r2   )rJ   r   )r   r0   r2   r2   r3   r    s    )r   _collectionr^   _hub_repo_idstools)r;   r  r   r2   r2   r3   rA     s   zToolCollection.__init__rr   )ra   r   r   r  rG   r	   rA   r2   r2   r2   r3   r    s    r  tool_functionc                    s   t d  d vrtd d   d}G  fdddt}t}tdtjjgt|j	
  }|j|d	}||j_||_| S )
a&  
    Converts a function into an instance of a Tool subclass.

    Args:
        tool_function: Your function. Should have type hints for each input and a type hint for the output.
        Should also have a docstring description including an 'Args:' part where each argument is described.
    functionr   zKTool return type not found: make sure your function has a return type hint!rK   rJ   c                       sH   e Zd Z d Z d Z d d Z d d ZefddZd	S )
ztool.<locals>.SpecificToolrK   rL   rh   
propertiesr   r\   c                    s    |i |S rr   r2   r:   )r  r2   r3   rf     s   z"tool.<locals>.SpecificTool.forwardN)	ra   r   r   rK   rL   rM   rN   r   rf   r2   rh   r  r2   r3   SpecificTool  s    r  r;   )rh   )r   r   
capitalizerJ   rd   re   	ParameterPOSITIONAL_OR_KEYWORDrb   rh   r  replacerf   __signature__ra   )r  r   r  original_signaturenew_parametersnew_signaturer2   r  r3   r     s   

rr   r  r   )Pr   r  rw  rd   r  r   r   r   	functoolsr   r   pathlibr   typingr   r   r   r   r	   r
   huggingface_hubr   r   r   r   r   huggingface_hub.utilsr   r   r   "huggingface_hub.utils._deprecationr   	packagingr   dynamic_module_utilsr   r   r   models.autor   utilsr   r   r   r   r   r   r    r!   agent_typesr#   r$   r%   
get_loggerra   r   rK  
accelerater&   accelerate.utilsr'   r-   r4   r   r  rC   r   rJ   !DEFAULT_TOOL_DESCRIPTION_TEMPLATErG   r'  r#  r8   re  rv  r  r  r  r  r   r2   r2   r2   r3   <module>   sl    (


   j
 -
14 