
    謜i*X                        d dl Z d dlZd dlZd dlmZmZ d dlZd dlm	Z	m
Z
 ddlmZ ddlmZ ddlmZmZ ddlmZmZmZmZmZ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 jB                        e _!        e jB                  jD                  8e jB                  jD                  jG                  ddd      e jB                  _"        yy)    N)AnyTypeVar)create_repois_offline_mode   )custom_object_save)BatchFeature)is_valid_image
load_image)IMAGE_PROCESSOR_NAMEPROCESSOR_NAMEPushToHubMixin	copy_funcloggingsafe_load_json_file)cached_fileImageProcessorTypeImageProcessingMixin)boundc                       e Zd ZdZy)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/Numpy Tensors at
            initialization.
    N)__name__
__module____qualname____doc__     ^/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/transformers/image_processing_base.pyr	   r	   -   s    r   r	   c                      e Zd ZdZdZd Ze	 	 	 	 	 ddee   de	e
j                  z  de	e
j                  z  dz  deded	e	ez  dz  d
e	defd       Zdde	e
j                  z  defdZede	e
j                  z  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
j                  z  fd       Zde	fdZde	e
j                  z  fdZd Zedd       Zde	ee	   z  eee	      z  fdZy) r   z
    This is an image processor mixin used to provide saving/loading functionality for sequential and image feature
    extractors.
    Nc           
          |j                  dd       |j                  dd       |j                         D ]  \  }}	 t        | ||        y# t        $ r%}t        j                  d| d| d|         |d}~ww xY w)z'Set elements of `kwargs` as attributes.feature_extractor_typeNprocessor_classz
Can't set z with value z for )popitemssetattrAttributeErrorloggererror)selfkwargskeyvalueerrs        r   __init__zImageProcessingMixin.__init__E   s     	

+T2

$d+ ,,. 	JCc5)	 " z#l5'tfMN	s   A	A: A55A:clspretrained_model_name_or_path	cache_dirforce_downloadlocal_files_onlytokenrevisionreturnc                     ||d<   ||d<   ||d<   ||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.
            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}
        ```r0   r1   r2   r4   r3   )get_image_processor_dict	from_dict)	r.   r/   r0   r1   r2   r3   r4   r)   image_processor_dicts	            r   from_pretrainedz$ImageProcessingMixin.from_pretrainedT   st    n ({#1 %5!"%z#F7O'Cs'C'CDa'lek'l$fs}}1<V<<r   save_directorypush_to_hubc           	         t         j                  j                  |      rt        d| d      t        j                  |d       |rw|j                  dd      }|j                  d|j                  t         j                  j                        d         }t        |fd	di|j                  }| j                  |      }| j                  t        | || 
       t         j                  j                  |t              }| j                  |       t         j#                  d|        |r%| j%                  ||j'                  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.
        zProvided path (z#) should be a directory, not a fileT)exist_okcommit_messageNrepo_idr>   )configzImage processor saved in r3   )r?   r3   )ospathisfileAssertionErrormakedirsr"   splitsepr   r@   _get_files_timestamps_auto_classr   joinr   to_json_filer&   info_upload_modified_filesget)r(   r;   r<   r)   r?   r@   files_timestampsoutput_image_processor_files           r   save_pretrainedz$ImageProcessingMixin.save_pretrained   s/    77>>.) ?>2BBe!fgg
NT2#ZZ(8$?NjjN,@,@,Mb,QRG!'CDCFCKKG#99.I 't^DA ')ggll>CW&X#56/0K/LMN'' -jj) (  ,,,r   c                    |j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  d	d
      }	|j                  dt              }
|j                  dd      }|j                  dd      }d|d}|||d<   t               r|st        j	                  d       d}t        |      }t        j                  j                  |      }t        j                  j                  |      r t        j                  j                  ||
      }t        j                  j                  |      r|}d}d}n3|
}	 t        |t        ||||||||	d      }t        ||||||||||	d      }d}|t        |      }d|v r|d   }||t        |      }|t        d| d| d|
 d      |rt        j	                  d|        ||fS t        j	                  d d|        ||fS # t        $ r  t        $ r t        d| d| d|
 d      w xY w)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.
        r0   Nr1   Fproxiesr3   r2   r4   	subfolder image_processor_filename_from_pipeline
_from_autoimage processor)	file_typefrom_auto_classusing_pipelinez+Offline mode: forcing local_files_only=TrueT)
filenamer0   r1   rU   r2   r3   
user_agentr4   rV   %_raise_exceptions_for_missing_entriesz 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image_processorzloading configuration file z from cache at )r"   r   r   r&   rN   strrC   rD   isdirrL   rE   r   r   OSError	Exceptionr   )r.   r/   r)   r0   r1   rU   r3   r2   r4   rV   rX   from_pipeliner]   r`   is_localimage_processor_fileresolved_image_processor_fileresolved_processor_filer9   processor_dicts                       r   r7   z-ImageProcessingMixin.get_image_processor_dict   s   ( JJ{D1	$4e<**Y-

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

#3T: **\59#4Y
$+8J'(%5KKEF#(+,I(J%77==!>?77==67#%77<<0MOg#h 77>>78,I)&*#H#; &*51+'#1#%5)%':?+' 1<11'#1#%5)%':?1-:  $".01HIN N2'56G'H$(49M9U#67T#U '23P2Q R55R4S T++C*DEK  KK56S5TUV $V++	 KK-.B-C?SpRqr $V++Q    67T6U V99V8W X//G.HO s   :0H% %(Ir9   c                    |j                         }|j                  dd      }|j                  |j                         D ci c]!  \  }}|| j                  j
                  v s||# c}}        | di |}t        |      D ]   }t        ||      s|j                  |       " t        j                  d|        |r||fS |S c c}}w )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_kwargsFzImage processor r   )
copyr"   updater#   valid_kwargs__annotations__listhasattrr&   rN   )r.   r9   r)   rn   kvrb   r*   s           r   r8   zImageProcessingMixin.from_dict^  s    "  488:%zz*@%H##flln$ndaSM]M]MmMmHmQT$no5 45 < 	 C,

3	  	&&789"F**"" %os    C
"C
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)ro   deepcopy__dict__	__class__r   )r(   outputs     r   to_dictzImageProcessingMixin.to_dict  s0     t}}-)-)@)@%&r   	json_filec                     t        |d      5 }|j                         }ddd       t        j                        } | di |S # 1 sw Y   &xY w)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.
        utf-8encodingNr   )openreadjsonloads)r.   r~   readertextr9   s        r   from_json_filez#ImageProcessingMixin.from_json_file  sN     )g. 	!&;;=D	!#zz$/*)**	! 	!s   AAc                     | j                         }|j                         D ]3  \  }}t        |t        j                        s!|j                         ||<   5 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.
           T)indent	sort_keys
)r}   r#   
isinstancenpndarraytolistr   dumps)r(   
dictionaryr*   r+   s       r   to_json_stringz#ImageProcessingMixin.to_json_string  sb     \\^
$**, 	1JC%,"',,.
3	1 zz*Q$?$FFr   json_file_pathc                     t        |dd      5 }|j                  | j                                ddd       y# 1 sw Y   yxY w)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)r   writer   )r(   r   writers      r   rM   z!ImageProcessingMixin.to_json_file  s<     .#8 	0FLL,,./	0 	0 	0s	    8Ac                 T    | j                   j                   d| j                          S )N )r{   r   r   )r(   s    r   __repr__zImageProcessingMixin.__repr__  s(    ..))*!D,?,?,A+BCCr   c                     t        |t              s|j                  }ddlmc m} t        ||      st        | d      || _        y)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   rc   r   transformers.models.automodelsautort   
ValueErrorrK   )r.   
auto_classauto_modules      r   register_for_auto_classz,ImageProcessingMixin.register_for_auto_class  sC     *c*#,,J66{J/
|+FGHH$r   image_url_or_urlsc                     t        |t              r|D cg c]  }| j                  |       c}S t        |t              rt	        |      S t        |      r|S t        dt        |             c c}w )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.
        z=only a single or a list of entries is supported but got type=)r   rs   fetch_imagesrc   r   r
   	TypeErrortype)r(   r   xs      r   r   z!ImageProcessingMixin.fetch_images  sr     '.2CDQD%%a(DD)3//00-.$$[\`ar\s[tuvv Es   A/)NFFNmain)F)AutoImageProcessor)r   r   r   r   rK   r-   classmethodr   r   rc   rC   PathLikeboolr:   rS   tupledictr   r7   r8   r}   r   r   rM   r   r   rs   r   r   r   r   r   r   =   s   
 K  /3$!&#'`=$%`='*R[['8`= $t+`= 	`=
 `= TzD `= `= 
`= `=D.-cBKK.? .-d .-` t,,/"++,=t,	tCH~tCH~-	.t, t,l #T#s(^ # #@
c3h 
 +sR[['8 + +$G G	03+< 	0D % %*wcDIoT#Y.O wr   r[   r   zimage processor file)objectobject_classobject_files)$ro   r   rC   typingr   r   numpyr   huggingface_hubr   r   dynamic_module_utilsr   feature_extraction_utilsr	   BaseBatchFeatureimage_utilsr
   r   utilsr   r   r   r   r   r   	utils.hubr   r   
get_loggerr   r&   r   r<   r   formatr   r   r   <module>r      s      	   8 4 F 3  # 19OP  
		H	%
#  bw> bwJ $--A-M-M#N   ##++7/C/O/O/W/W/^/^ /CRh 0_ 0$$, 8r   