
     `isa                        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
          Z ej        e           Z! G d de          Z G d d
e          Z" ee"j#                  e"_#        e"j#        j$        .e"j#        j$        %                    ddd          e"j#        _$        dS 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_fileImageProcessorTypeImageProcessingMixin)boundc                       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__     v/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/transformers/image_processing_base.pyr	   r	   0   s           r   r	   c                   z   e Zd ZdZdZd ZdefdZe	 	 	 	 	 d"de	e
         d	eeej        f         d
eeeej        f                  dededeeeef                  dede
fd            Zd#deeej        f         defdZed	eeej        f         deeeef         eeef         f         fd            Zedeeef         fd            Zdeeef         fdZedeeej        f         fd            ZdefdZdeeej        f         fdZd Zed$d            Zd eeee         eee                  f         f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           
      .   |                     dd           |                     dd          | _        |                                D ]N\  }}	 t          | ||           # t          $ r*}t
                              d| d| d|             |d}~ww xY wdS )z'Set elements of `kwargs` as attributes.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errs        r    __init__zImageProcessingMixin.__init__H   s     	

+T222 &

+<d C C ,,.. 	 	JCc5))))!   M#MM5MMtMMNNN		 	s   A
B(%BBr$   c                     || _         dS )z%Sets processor class as an attribute.N)r&   )r,   r$   s     r    _set_processor_classz)ImageProcessingMixin._set_processor_classW   s     /r   Fmainclspretrained_model_name_or_path	cache_dirforce_downloadlocal_files_onlytokenrevisionreturnc                     ||d<   ||d<   ||d<   ||d<   |                     dd          }|-t          j        dt                     |t	          d          |}|||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}
        ```r7   r8   r9   r;   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`.r:   )r%   warningswarnFutureWarning
ValueErrorget_image_processor_dict	from_dict)
r5   r6   r7   r8   r9   r:   r;   r-   r>   image_processor_dicts
             r    from_pretrainedz$ImageProcessingMixin.from_pretrained[   s    t ({#1 %5!"%z$4d;;%M E     l   #E#F7O'Cs'CDa'l'lek'l'l$fs}1<<V<<<r   save_directorypush_to_hubc           	      ~   |                     dd          }|Ct          j        dt                     |                    d          t          d          ||d<   t          j                            |          rt          d| d          t          j
        |d	           |rw|                     d
d          }|                     d|                    t          j        j                  d                   } | j        |fi |}|                     |          }| j        t!          | ||            t          j                            |t$                    }|                     |           t(                              d|            |r-|                     |||||                    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.
        r>   Nr?   r:   r@   zProvided path (z#) should be a directory, not a fileT)exist_okcommit_messagerepo_id)configzImage processor saved in )rM   r:   )r%   rA   rB   rC   getrD   ospathisfileAssertionErrormakedirssplitsep_create_repo_get_files_timestamps_auto_classr   joinr   to_json_filer*   info_upload_modified_files)	r,   rI   rJ   r-   r>   rM   rN   files_timestampsoutput_image_processor_files	            r    save_pretrainedz$ImageProcessingMixin.save_pretrained   s     $4d;;%M E   zz'"". l   -F7O7>>.)) 	h !f>!f!f!fggg
NT2222 	J#ZZ(8$??NjjN,@,@,M,Mb,QRRG'd'::6::G#99.II 't^DAAAA ')gll>CW&X&X#5666M0KMMNNN 	'' -jj)) (    ,,,r   c                    |                     dd          |                     dd          |                     dd          |                     dd          |                     dd          |                     dd          }|                     d	d          |                     d
d          |                     dd          |                     dt                    }|                     dd          }|                     dd          }|-t          j        dt                     t          d          |d|d||d<   t                      rst                              d           dt                    t          j                                      }t          j                                      r t          j                            |          }t          j                                      r}	d}n}t                    r}t!                    }	n\|}	 fd|t"          fD             }
|
d         }	n1# t$          $ r  t&          $ r t%          d d d| d          w xY w	 t)          |	d          5 }|                                }ddd           n# 1 swxY w Y   t-          j        |          }|                    d|          }n&# t,          j        $ r t%          d |	 d!          w xY w|rt                              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.
        r7   Nr8   Fresume_downloadproxiesr:   r>   r9   r;   	subfolder image_processor_filename_from_pipeline
_from_autor?   r@   image processor)	file_typefrom_auto_classusing_pipelinez+Offline mode: forcing local_files_only=TrueTc                 P    g | ]"}t          |	
d           x	  #S )F)filenamer7   r8   re   rd   r9   r:   
user_agentr;   rf   %_raise_exceptions_for_missing_entriesr   ).0rp   r7   r8   r9   r6   re   resolved_filerd   r;   rf   r:   rq   s     r    
<listcomp>zAImageProcessingMixin.get_image_processor_dict.<locals>.<listcomp>M  sp     2 2 2 )49%-&/+9$+,;-="''1%-&/BG* * *   !  "     r   r   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   rA   rB   rC   rD   r   r*   r^   strrR   rS   isdirr\   rT   r   r   r   OSError	ExceptionopenreadjsonloadsrQ   JSONDecodeError)r5   r6   r-   r>   rh   from_pipelinerm   is_localimage_processor_fileresolved_image_processor_fileresolved_image_processor_filesreadertextrG   r7   r8   r9   re   rt   rd   r;   rf   r:   rq   s    `            @@@@@@@@@@r    rE   z-ImageProcessingMixin.get_image_processor_dict
  so   ( JJ{D11	$4e<< **%6==**Y--

7D))$4d;;!::&8%@@::j$//JJ{B//	#)::.HJ^#_#_ 

#3T:: **\599%M E     l   #E#4YY
$+8J'( 	$%5 	$KKEFFF#(+,I(J(J%7==!>??7==677 	i#%7<<0MOg#h#h 7>>788 +	,I)HH899 (	#@ ,89V,W,W))#; #2 2 2 2 2 2 2 2 2 2 2 2 2 2%9>$J2 2 2.* 1Oq0Q--       O7T O O9VO O 0HO O O  
	3gFFF %&{{}}% % % % % % % % % % % % % % %#':d#3#3 #7#;#;<MOc#d#d  # 	 	 	o5Rooo  	
  	KKU6SUUVVVVKKr.BrrSprr   $V++s<   5'I .JK7  K5K7 KK7 K	-K7 7#LrG   c                 
   |                                 }|                    dd          }d|v rd|v r|                    d          |d<   d|v rd|v r|                    d          |d<    | di |}g }|                                D ];\  }}t          ||          r&t	          |||           |                    |           <|D ]}|                    |d           t                              d|            |r||fS |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size	crop_sizeNzImage processor r   )copyr%   r'   hasattrr(   appendr*   r^   )r5   rG   r-   r   ry   	to_remover.   r/   s           r    rF   zImageProcessingMixin.from_dict  sR   "  488::%zz*@%HH
 V*> > >+1::f+=+= (&  [4H%H%H06

;0G0G -#55 455 	 ,,.. 	& 	&JC,, &e444  %%% 	" 	"CJJsD!!!!888999 	#"F**""r   c                 V    t          j        | 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.
        image_processor_type)r   deepcopy__dict__	__class__r   )r,   outputs     r    to_dictzImageProcessingMixin.to_dict  s*     t}--)-)@%&r   	json_filec                     t          |d          5 }|                                }ddd           n# 1 swxY w Y   t          j        |          } | d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.
        rv   rw   Nr   )r~   r   r   r   )r5   r   r   r   rG   s        r    from_json_filez#ImageProcessingMixin.from_json_file  s     )g... 	!&;;==D	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	!#z$//s**)***s   377c                 .   |                                  }|                                D ]6\  }}t          |t          j                  r|                                ||<   7|                    dd          }|||d<   t          j        |dd          dz   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
)	r   r'   
isinstancenpndarraytolistr%   r   dumps)r,   
dictionaryr.   r/   r&   s        r    to_json_stringz#ImageProcessingMixin.to_json_string  s     \\^^
$**,, 	1 	1JC%,, 1"',,..
3 &>>*<dCC',<J()z*Q$???$FFr   json_file_pathc                     t          |dd          5 }|                    |                                            ddd           dS # 1 swxY w 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.
        wrv   rw   N)r~   writer   )r,   r   writers      r    r]   z!ImageProcessingMixin.to_json_file  s     .#888 	0FLL,,..///	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0s   (AAAc                 H    | j         j         d|                                  S )N )r   r   r   )r,   s    r    __repr__zImageProcessingMixin.__repr__  s'    .)CCD,?,?,A,ACCCr   AutoImageProcessorc                     t          |t                    s|j        }ddlmc 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   rz   r   transformers.models.automodelsautor   rD   r[   )r5   
auto_classauto_modules      r    register_for_auto_classz,ImageProcessingMixin.register_for_auto_class  sn     *c** 	-#,J666666666{J// 	I
GGGHHH$r   image_url_or_urlsc                      t          |t                    r fd|D             S t          |t                    rt          |          S t	          |          r|S t          dt          |                     )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                 :    g | ]}                     |          S r   )fetch_images)rs   xr,   s     r    ru   z5ImageProcessingMixin.fetch_images.<locals>.<listcomp>  s'    DDDQD%%a((DDDr   z=only a single or a list of entries is supported but got type=)r   listrz   r   r
   	TypeErrortype)r,   r   s   ` r    r   z!ImageProcessingMixin.fetch_images
  s     '.. 	wDDDD2CDDDD)3// 	w/000-.. 	w$$u\`ar\s\suuvvvr   )NFFNr4   )F)r   )r   r   r   r   r[   r1   rz   r3   classmethodr   r   r   rR   PathLiker   boolrH   rb   tupledictr   rE   rF   r   r   r   r]   r   r   r   r   r   r   r    r   r   @   s        
 K  0C 0 0 0 0  8<$!&,0o= o=$%o=',S"+-='>o= E#r{"234o= 	o=
 o= c4i()o= o= 
o= o= o= [o=b;- ;-eC4D.E ;-TX ;- ;- ;- ;-z x,,1#r{2B,Cx,	tCH~tCH~-	.x, x, x, [x,t *#T#s(^ *# *# *# [*#X
c3h 
 
 
 
 +uS"+-='> + + + [+$G G G G G*	05bk1A+B 	0 	0 	0 	0D D D % % % [%*weCcDcO4S.T w w w w w wr   rk   r   zimage processor file)objectobject_classobject_files)&r   r   rR   rA   typingr   r   r   r   numpyr   dynamic_module_utilsr   feature_extraction_utilsr	   BaseBatchFeatureimage_utilsr
   r   utilsr   r   r   r   r   r   r   r   	utils.hubr   r   
get_loggerr   r*   r   rJ   r   formatr   r   r    <module>r      s      				  0 0 0 0 0 0 0 0 0 0 0 0     4 4 4 4 4 4 F F F F F F 3 3 3 3 3 3 3 3	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 # " " " " " W19OPPP  
	H	%	%
    #    Xw Xw Xw Xw Xw> Xw Xw Xwv $-9-A-M#N#N   #+7/C/O/W/^/^ /CRh 0_ 0 0$,,, 87r   