a
    h3`                     @   s  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 d dl	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mZmZmZ ddlmZ ed	d
dZee Z!G dd deZG dd
 d
eZ"ee"j#e"_#e"j#j$dure"j#j$j%dddde"j#_$dS )    N)AnyOptionalTypeVarUnion   )custom_object_save)BatchFeature)is_valid_image
load_image)IMAGE_PROCESSOR_NAMEPROCESSOR_NAMEPushToHubMixin	copy_funcdownload_urlis_offline_modeis_remote_urllogging)cached_filesImageProcessorTypeImageProcessingMixin)boundc                   @   s   e Zd ZdZdS )r   a  
    Holds the output of the image processor specific `__call__` methods.

    This class is derived from a python dictionary and can be used as a dictionary.

    Args:
        data (`dict`):
            Dictionary of lists/arrays/tensors returned by the __call__ method ('pixel_values', etc.).
        tensor_type (`Union[None, str, TensorType]`, *optional*):
            You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
            initialization.
    N)__name__
__module____qualname____doc__ r   r   ^/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/image_processing_base.pyr   0   s   r   c                   @   sr  e Zd ZdZdZdd ZedddZed)e	e
 eeejf eeeejf  eeeeeef  ee
d
ddZd*eeejf edddZeeeejf eeeef eeef f dddZeeeef dddZeeef dddZeeeejf dddZedddZeeejf ddd Zd!d" Zed+d$d%Zeeee eee  f d&d'd(ZdS ),r   z
    This is an image processor mixin used to provide saving/loading functionality for sequential and image feature
    extractors.
    Nc                 K   s   | dd | dd| _| D ]^\}}zt| || W q" ty~ } z,td| d| d|   |W Y d}~q"d}~0 0 q"dS )z'Set elements of `kwargs` as attributes.Zfeature_extractor_typeNprocessor_classz
Can't set z with value z for )pop_processor_classitemssetattrAttributeErrorloggererror)selfkwargskeyvalueerrr   r   r   __init__H   s    zImageProcessingMixin.__init__)r   c                 C   s
   || _ dS )z%Sets processor class as an attribute.N)r   )r%   r   r   r   r   _set_processor_classW   s    z)ImageProcessingMixin._set_processor_classFmain)clspretrained_model_name_or_path	cache_dirforce_downloadlocal_files_onlytokenrevisionreturnc           
      K   s   ||d< ||d< ||d< ||d< | dd}|durTtdt |durPtd|}|durd||d	< | j|fi |\}	}| j|	fi |S )
a  
        Instantiate a type of [`~image_processing_utils.ImageProcessingMixin`] from an image processor.

        Args:
            pretrained_model_name_or_path (`str` or `os.PathLike`):
                This can be either:

                - a string, the *model id* of a pretrained image_processor hosted inside a model repo on
                  huggingface.co.
                - a path to a *directory* containing a image processor file saved using the
                  [`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g.,
                  `./my_model_directory/`.
                - a path or url to a saved image processor JSON *file*, e.g.,
                  `./my_model_directory/preprocessor_config.json`.
            cache_dir (`str` or `os.PathLike`, *optional*):
                Path to a directory in which a downloaded pretrained model image processor should be cached if the
                standard cache should not be used.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force to (re-)download the image processor files and override the cached versions if
                they exist.
            resume_download:
                Deprecated and ignored. All downloads are now resumed by default when possible.
                Will be removed in v5 of Transformers.
            proxies (`dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
            token (`str` or `bool`, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
                the token generated when running `hf auth login` (stored in `~/.huggingface`).
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
                identifier allowed by git.


                <Tip>

                To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.

                </Tip>

            return_unused_kwargs (`bool`, *optional*, defaults to `False`):
                If `False`, then this function returns just the final image processor object. If `True`, then this
                functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary
                consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part of
                `kwargs` which has not been used to update `image_processor` and is otherwise ignored.
            subfolder (`str`, *optional*, defaults to `""`):
                In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
                specify the folder name here.
            kwargs (`dict[str, Any]`, *optional*):
                The values in kwargs of any keys which are image processor attributes will be used to override the
                loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is
                controlled by the `return_unused_kwargs` keyword parameter.

        Returns:
            A image processor of type [`~image_processing_utils.ImageProcessingMixin`].

        Examples:

        ```python
        # We can't instantiate directly the base class *ImageProcessingMixin* so let's show the examples on a
        # derived class: *CLIPImageProcessor*
        image_processor = CLIPImageProcessor.from_pretrained(
            "openai/clip-vit-base-patch32"
        )  # Download image_processing_config from huggingface.co and cache.
        image_processor = CLIPImageProcessor.from_pretrained(
            "./test/saved_model/"
        )  # E.g. image processor (or model) was saved using *save_pretrained('./test/saved_model/')*
        image_processor = CLIPImageProcessor.from_pretrained("./test/saved_model/preprocessor_config.json")
        image_processor = CLIPImageProcessor.from_pretrained(
            "openai/clip-vit-base-patch32", do_normalize=False, foo=False
        )
        assert image_processor.do_normalize is False
        image_processor, unused_kwargs = CLIPImageProcessor.from_pretrained(
            "openai/clip-vit-base-patch32", do_normalize=False, foo=False, return_unused_kwargs=True
        )
        assert image_processor.do_normalize is False
        assert unused_kwargs == {"foo": False}
        ```r/   r0   r1   r3   use_auth_tokenNrThe `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.V`token` and `use_auth_token` are both specified. Please set only the argument `token`.r2   )r   warningswarnFutureWarning
ValueErrorget_image_processor_dict	from_dict)
r-   r.   r/   r0   r1   r2   r3   r&   r5   image_processor_dictr   r   r   from_pretrained[   s&    Zz$ImageProcessingMixin.from_pretrained)save_directorypush_to_hubc           	      K   s  | dd}|dur>tdt |ddur6td||d< tj|rZt	d| dtj
|dd	 |r| d
d}| d|tjjd }| j|fi |}| |}| jdurt| || d tj|t}| | td|  |r| j|||||dd |gS )as  
        Save an image processor object to the directory `save_directory`, so that it can be re-loaded using the
        [`~image_processing_utils.ImageProcessingMixin.from_pretrained`] class method.

        Args:
            save_directory (`str` or `os.PathLike`):
                Directory where the image processor JSON file will be saved (will be created if it does not exist).
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
                repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
                namespace).
            kwargs (`dict[str, Any]`, *optional*):
                Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        r5   Nr6   r2   r7   zProvided path (z#) should be a directory, not a fileT)exist_okcommit_messagerepo_id)configzImage processor saved in )rC   r2   )r   r8   r9   r:   getr;   ospathisfileAssertionErrormakedirssplitsepZ_create_repoZ_get_files_timestamps_auto_classr   joinr   to_json_filer#   infoZ_upload_modified_files)	r%   r@   rA   r&   r5   rC   rD   Zfiles_timestampsZoutput_image_processor_filer   r   r   save_pretrained   sB    


z$ImageProcessingMixin.save_pretrained)r.   r4   c                 K   sr  | dd}| dd}| dd}| dd}| dd}| dd}| d	d}	| d
d}
| dd}| dt}| dd}| dd}|durtdt |durtd|}d|d}|dur||d< t r|	std d}	t	|}t
j|}t
j|rt
j||}t
j|r2|}d}nt|rJ|}t|}nz|}z0t||tg|||||	|||
|dd}|d }W nD ty    Y n0 ty   td| d| d| dY n0 zPt|dd}| }W d   n1 s0    Y  t|}|d|}W n& tjy:   td | d!Y n0 |rTtd"|  ntd"| d#|  ||fS )$a  
        From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
        image processor of type [`~image_processor_utils.ImageProcessingMixin`] using `from_dict`.

        Parameters:
            pretrained_model_name_or_path (`str` or `os.PathLike`):
                The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
            subfolder (`str`, *optional*, defaults to `""`):
                In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
                specify the folder name here.
            image_processor_filename (`str`, *optional*, defaults to `"config.json"`):
                The name of the file in the model directory to use for the image processor config.

        Returns:
            `tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the image processor object.
        r/   Nr0   Fresume_downloadproxiesr2   r5   r1   r3   	subfolder image_processor_filenameZ_from_pipelineZ
_from_autor6   r7   image processor)	file_typefrom_auto_classZusing_pipelinez+Offline mode: forcing local_files_only=TrueT)	filenamesr/   r0   rU   rT   r1   r2   
user_agentr3   rV   Z%_raise_exceptions_for_missing_entriesr   z Can't load image processor for 'z'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'z2' is the correct path to a directory containing a z fileutf-8encodingimage_processorz"It looks like the config file at 'z' is not a valid JSON file.zloading configuration file z from cache at )r   r   r8   r9   r:   r;   r   r#   rR   strrH   rI   isdirrP   rJ   r   r   r   r   OSError	ExceptionopenreadjsonloadsrG   JSONDecodeError)r-   r.   r&   r/   r0   rT   rU   r2   r5   r1   r3   rV   rX   Zfrom_pipeliner[   r]   is_localZimage_processor_fileZresolved_image_processor_fileZresolved_image_processor_filesreadertextr>   r   r   r   r<   
  s    





(


z-ImageProcessingMixin.get_image_processor_dict)r>   c                 K   s   |  }|dd}d|v r2d|v r2|d|d< d|v rPd|v rP|d|d< | f i |}g }| D ](\}}t||rjt||| || qj|D ]}||d qtd|  |r||fS |S dS )a  
        Instantiates a type of [`~image_processing_utils.ImageProcessingMixin`] from a Python dictionary of parameters.

        Args:
            image_processor_dict (`dict[str, Any]`):
                Dictionary that will be used to instantiate the image processor object. Such a dictionary can be
                retrieved from a pretrained checkpoint by leveraging the
                [`~image_processing_utils.ImageProcessingMixin.to_dict`] method.
            kwargs (`dict[str, Any]`):
                Additional parameters from which to initialize the image processor object.

        Returns:
            [`~image_processing_utils.ImageProcessingMixin`]: The image processor object instantiated from those
            parameters.
        return_unused_kwargsFsizeZ	crop_sizeNzImage processor )copyr   r    hasattrr!   appendr#   rR   )r-   r>   r&   rn   ra   Z	to_remover'   r(   r   r   r   r=   ~  s$    
zImageProcessingMixin.from_dict)r4   c                 C   s   t | j}| jj|d< |S )z
        Serializes this instance to a Python dictionary.

        Returns:
            `dict[str, Any]`: Dictionary of all the attributes that make up this image processor instance.
        Zimage_processor_type)rp   deepcopy__dict__	__class__r   )r%   outputr   r   r   to_dict  s    zImageProcessingMixin.to_dict)	json_filec                 C   sL   t |dd}| }W d   n1 s*0    Y  t|}| f i |S )a  
        Instantiates a image processor of type [`~image_processing_utils.ImageProcessingMixin`] from the path to a JSON
        file of parameters.

        Args:
            json_file (`str` or `os.PathLike`):
                Path to the JSON file containing the parameters.

        Returns:
            A image processor of type [`~image_processing_utils.ImageProcessingMixin`]: The image_processor object
            instantiated from that JSON file.
        r^   r_   N)rf   rg   rh   ri   )r-   rx   rl   rm   r>   r   r   r   from_json_file  s    &
z#ImageProcessingMixin.from_json_filec                 C   sb   |   }| D ] \}}t|tjr| ||< q|dd}|durN||d< tj|dddd S )z
        Serializes this instance to a JSON string.

        Returns:
            `str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
        r   Nr      T)indent	sort_keys
)	rw   r    
isinstancenpZndarraytolistr   rh   dumps)r%   
dictionaryr'   r(   r   r   r   r   to_json_string  s    z#ImageProcessingMixin.to_json_string)json_file_pathc                 C   s@   t |ddd}||   W d   n1 s20    Y  dS )z
        Save this instance to a JSON file.

        Args:
            json_file_path (`str` or `os.PathLike`):
                Path to the JSON file in which this image_processor instance's parameters will be saved.
        wr^   r_   N)rf   writer   )r%   r   writerr   r   r   rQ     s    z!ImageProcessingMixin.to_json_filec                 C   s   | j j d|   S )N )ru   r   r   r%   r   r   r   __repr__  s    zImageProcessingMixin.__repr__AutoImageProcessorc                 C   sD   t |ts|j}ddlm  m} t||s:t| d|| _dS )a{  
        Register this class with a given auto class. This should only be used for custom image processors as the ones
        in the library are already mapped with `AutoImageProcessor `.



        Args:
            auto_class (`str` or `type`, *optional*, defaults to `"AutoImageProcessor "`):
                The auto class to register this new image processor with.
        r   Nz is not a valid auto class.)	r~   rb   r   Ztransformers.models.automodelsautorq   r;   rO   )r-   Z
auto_classZauto_moduler   r   r   register_for_auto_class  s    

z,ImageProcessingMixin.register_for_auto_class)image_url_or_urlsc                    sP   t |tr fdd|D S t |tr.t|S t|r:|S tdt| dS )z
        Convert a single or a list of urls into the corresponding `PIL.Image` objects.

        If a single url is passed, the return value will be a single object. If a list is passed a list of objects is
        returned.
        c                    s   g | ]}  |qS r   )fetch_images).0xr   r   r   
<listcomp>      z5ImageProcessingMixin.fetch_images.<locals>.<listcomp>z=only a single or a list of entries is supported but got type=N)r~   listrb   r
   r	   	TypeErrortype)r%   r   r   r   r   r     s    

z!ImageProcessingMixin.fetch_images)NFFNr,   )F)r   )r   r   r   r   rO   r*   rb   r+   classmethodr   r   r   rH   PathLiker   boolr?   rS   tupledictr   r<   r=   rw   ry   r   rQ   r   r   r   r   r   r   r   r   r   @   sH        q=s,rY   r   zimage processor file)objectZobject_classZobject_files)&rp   rh   rH   r8   typingr   r   r   r   numpyr   Zdynamic_module_utilsr   Zfeature_extraction_utilsr   ZBaseBatchFeatureZimage_utilsr	   r
   utilsr   r   r   r   r   r   r   r   Z	utils.hubr   r   Z
get_loggerr   r#   r   rA   r   formatr   r   r   r   <module>   s,   (

   W