U
    4AfOn                  ]   @   s  U d Z ddlZddlZddlZddlZddlmZ ddlmZm	Z	m
Z
mZmZ ddlmZ ddlmZm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 ddl m!Z!m"Z"m#Z#m$Z$ e%e&Z'ere Z(ee)ee
e) e
e) f f e*d< nedddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjg\Z(e(+ D ]T\Z,Z-e-^Z.Z/e sdZ.e/re/d dkse sdZ/ne/d Z/e.e/fe(e,< qee!e(Z0e)dkdldmZ1dvee)ej2f e
ee)ej2f  e3e
e3 e
e	e)e)f  e
ee3e)f  e
e) e3dodpdqZ4drds Z5G dtdu duZ6dS )wzAutoImageProcessor class.    N)OrderedDict)TYPE_CHECKINGDictOptionalTupleUnion   )PretrainedConfig)get_class_from_dynamic_moduleresolve_trust_remote_code)BaseImageProcessorImageProcessingMixin)BaseImageProcessorFast)CONFIG_NAMEIMAGE_PROCESSOR_NAMEget_file_from_repois_torchvision_availableis_vision_availablelogging   )_LazyAutoMapping)CONFIG_MAPPING_NAMES
AutoConfigmodel_type_to_module_name!replace_list_option_in_docstringsIMAGE_PROCESSOR_MAPPING_NAMES)ZalignZEfficientNetImageProcessor)ZbeitZBeitImageProcessor)bitZBitImageProcessor)ZblipZBlipImageProcessor)zblip-2r    )Zbridgetower)ZBridgeTowerImageProcessor)Z	chameleon)ZChameleonImageProcessor)Zchinese_clip)ZChineseCLIPImageProcessor)ZclipZCLIPImageProcessor)ZclipsegZViTImageProcessorZViTImageProcessorFast)Zconditional_detr)ZConditionalDetrImageProcessor)ZconvnextZConvNextImageProcessor)Z
convnextv2r#   )cvtr#   )zdata2vec-visionr   )Zdeformable_detr)ZDeformableDetrImageProcessor)Zdeit)ZDeiTImageProcessor)Zdepth_anythingZDPTImageProcessor)Zdeta)ZDetaImageProcessor)ZdetrZDetrImageProcessor)Zdinatr"   )Zdinov2r   )z
donut-swin)ZDonutImageProcessor)Zdptr%   )Zefficientformer)ZEfficientFormerImageProcessor)Zefficientnetr   )Zflava)ZFlavaImageProcessor)Zfocalnetr   )Zfuyu)ZFuyuImageProcessor)gitr!   )Zglpn)ZGLPNImageProcessor)zgrounding-dino)ZGroundingDinoImageProcessor)Zgroupvitr!   )Zhierar   )Zidefics)ZIdeficsImageProcessor)Zidefics2)ZIdefics2ImageProcessor)Zimagegpt)ZImageGPTImageProcessor)Zinstructblipr    )Zinstructblipvideo)ZInstructBlipVideoImageProcessor)zkosmos-2r!   )Z
layoutlmv2)ZLayoutLMv2ImageProcessor)Z
layoutlmv3ZLayoutLMv3ImageProcessor)Zlevit)ZLevitImageProcessor)Zllavar!   )zllava-next-video)ZLlavaNextVideoImageProcessor)Z
llava_next)ZLlavaNextImageProcessor)Zmask2former)ZMask2FormerImageProcessor)Z
maskformer)ZMaskFormerImageProcessor)zmgp-strr"   )Zmobilenet_v1)ZMobileNetV1ImageProcessor)Zmobilenet_v2)ZMobileNetV2ImageProcessor)Z	mobilevitZMobileViTImageProcessor)Zmobilevitv2r)   )Znatr"   )Znougat)ZNougatImageProcessor)Z	oneformer)ZOneFormerImageProcessor)Zowlv2)ZOwlv2ImageProcessor)Zowlvit)ZOwlViTImageProcessor)Z	perceiver)ZPerceiverImageProcessor)Z
pix2struct)ZPix2StructImageProcessor)Z
poolformer)ZPoolFormerImageProcessor)ZpvtZPvtImageProcessor)Zpvt_v2r*   )Zregnetr#   )Zresnetr#   )Zrt_detrZRTDetrImageProcessor)Zsam)ZSamImageProcessor)Z	segformerZSegformerImageProcessor)Zseggpt)ZSegGptImageProcessor)Zsiglip)ZSiglipImageProcessor)Zswiftformerr"   )Zswinr"   )Zswin2sr)ZSwin2SRImageProcessor)Zswinv2r"   )ztable-transformerr&   )ZtimesformerZVideoMAEImageProcessor)Ztvlt)ZTvltImageProcessor)Ztvp)ZTvpImageProcessor)Zudopr(   )Zupernetr+   )Zvanr#   )Zvideomaer,   )Zvilt)ZViltImageProcessor)Zvipllavar!   )Zvitr"   )Z
vit_hybrid)ZViTHybridImageProcessor)Zvit_maer"   )Zvit_msnr"   )Zvitmatte)ZVitMatteImageProcessor)Zxclipr!   )Zyolos)ZYolosImageProcessor)Zzoedepth)ZZoeDepthImageProcessor)
class_namec              	   C   s   | dkrt S t D ]T\}}| |krt|}td| d}zt|| W   S  tk
rf   Y qY qX qtj	 D ].\}}|D ] }t|dd | kr|    S qqttd}t
|| rt|| S d S )Nr   .ztransformers.models__name__Ztransformers)r   r   itemsr   	importlibimport_modulegetattrAttributeErrorIMAGE_PROCESSOR_MAPPING_extra_contenthasattr)r-   module_nameZ
extractorsmodule_Z	extractorZmain_module r;   R/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/auto/image_processing_auto.pyimage_processor_class_from_name   s$    


r=   F)pretrained_model_name_or_path	cache_dirforce_downloadresume_downloadproxiestokenrevisionlocal_files_onlyc                 K   s   | dd}	|	dk	r4tdt |dk	r0td|	}t| t|||||||d	}
|
dkrdtd i S t	|
dd}t
|W  5 Q R  S Q R X dS )	a  
    Loads the image processor configuration from a pretrained model image processor configuration.

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

            - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
              huggingface.co.
            - a path to a *directory* containing a configuration file saved using the
              [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.

        cache_dir (`str` or `os.PathLike`, *optional*):
            Path to a directory in which a downloaded pretrained model configuration 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 configuration 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`, will use the token generated
            when running `huggingface-cli 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.
        local_files_only (`bool`, *optional*, defaults to `False`):
            If `True`, will only try to load the image processor configuration from local files.

    <Tip>

    Passing `token=True` is required when you want to use a private model.

    </Tip>

    Returns:
        `Dict`: The configuration of the image processor.

    Examples:

    ```python
    # Download configuration from huggingface.co and cache.
    image_processor_config = get_image_processor_config("google-bert/bert-base-uncased")
    # This model does not have a image processor config so the result will be an empty dict.
    image_processor_config = get_image_processor_config("FacebookAI/xlm-roberta-base")

    # Save a pretrained image processor locally and you can reload its config
    from transformers import AutoTokenizer

    image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
    image_processor.save_pretrained("image-processor-test")
    image_processor_config = get_image_processor_config("image-processor-test")
    ```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@   rA   rB   rC   rD   rE   zbCould not locate the image processor configuration file, will try to use the model config instead.zutf-8)encoding)popwarningswarnFutureWarning
ValueErrorr   r   loggerinfoopenjsonload)r>   r?   r@   rA   rB   rC   rD   rE   kwargsrF   Zresolved_config_filereaderr;   r;   r<   get_image_processor_config   s6    ErV   c                 C   s   t d|  d d S )NzFast image processor class zz is available for this model. Using slow image processor class. To use the fast image processor class set `use_fast=True`.)rO   warning)Z
fast_classr;   r;   r<   '_warning_fast_image_processor_available'  s    
rX   c                   @   s:   e Zd ZdZdd Zeeedd Ze	d
dd	Z
dS )AutoImageProcessora%  
    This is a generic image processor class that will be instantiated as one of the image processor classes of the
    library when created with the [`AutoImageProcessor.from_pretrained`] class method.

    This class cannot be instantiated directly using `__init__()` (throws an error).
    c                 C   s   t dd S )NzAutoImageProcessor is designed to be instantiated using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.)EnvironmentError)selfr;   r;   r<   __init__6  s    zAutoImageProcessor.__init__c                 O   sp  | dd}|dk	r@tdt |dddk	r8td||d< | dd}| dd}| dd}d	|d
< tj|f|\}}	|dd}
d}d|di kr|d d }|
dkr|dkr| dd}|dk	r|dd}
d|di kr|d d }|dd}|
dkrd|dkrdt	|t
s6tj|f|}t|dd}
t|drdd|jkrd|jd }|
dk	r|dk	r|r|
ds|
d7 }
n|s|
dr|
dd }
t|
}
|dk	}|
dk	pt|tk}t||||}|dk	rt	|ts|df}|r|r|s0|d dk	r0t|d  |rN|d dk	rN|d }n|d }t||f|}
| dd}	tj|r|
  |
j|f|S |
dk	r|
j|f|S t|tkr2tt| }|\}}|s|dk	rt| |r|s|dkr|j|f||S |dk	r*|j|f||S tdtd| dt dt dt dddd t ! D  
dS ) a  
        Instantiate one of the image processor classes of the library from a pretrained model vocabulary.

        The image processor class to instantiate is selected based on the `model_type` property of the config object
        (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's
        missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:

        List options

        Params:
            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`, will use the token generated
                when running `huggingface-cli 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.
            use_fast (`bool`, *optional*, defaults to `False`):
                Use a fast torchvision-base image processor if it is supported for a given model.
                If a fast tokenizer is not available for a given model, a normal numpy-based image processor
                is returned instead.
            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.
            trust_remote_code (`bool`, *optional*, defaults to `False`):
                Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
                should only be set to `True` for repositories you trust and in which you have read the code, as it will
                execute code present on the Hub on your local machine.
            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.

        <Tip>

        Passing `token=True` is required when you want to use a private model.

        </Tip>

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor

        >>> # Download image processor from huggingface.co and cache.
        >>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")

        >>> # If image processor files are in a directory (e.g. image processor was saved using *save_pretrained('./test/saved_model/')*)
        >>> # image_processor = AutoImageProcessor.from_pretrained("./test/saved_model/")
        ```rF   NrG   rC   rH   configuse_fasttrust_remote_codeTZ
_from_autoZimage_processor_typerY   auto_mapZfeature_extractor_typeZFeatureExtractorZImageProcessorZAutoFeatureExtractorZFastr   r   Zcode_revisionzZThis image processor cannot be instantiated. Please make sure you have `Pillow` installed.z Unrecognized image processor in z2. Should have a `image_processor_type` key in its z of z3, or one of the following `model_type` keys in its z: z, c                 s   s   | ]
}|V  qd S )Nr;   ).0cr;   r;   r<   	<genexpr>  s     z5AutoImageProcessor.from_pretrained.<locals>.<genexpr>)"rJ   rK   rL   rM   getrN   r   Zget_image_processor_dictreplace
isinstancer	   r   from_pretrainedr3   r7   r`   endswithr=   typer5   r   tuplerX   r
   ospathisdirZregister_for_auto_class	from_dictr   r   joinr   keys)clsr>   inputsrT   rF   r]   r^   r_   Zconfig_dictr:   image_processor_classZimage_processor_auto_mapZfeature_extractor_classZfeature_extractor_auto_mapZhas_remote_codeZhas_local_codeZ	class_refZimage_processor_tupleZimage_processor_class_pyZimage_processor_class_fastr;   r;   r<   rh   <  s    M



   


4z"AutoImageProcessor.from_pretrainedNFc                 C   s   |dk	r(|dk	rt dtdt |}|dkr@|dkr@t d|dk	rZt|trZt d|dk	rtt|trtt d|dk	r|dk	rt|tr|j|krt d|j d| d	| tj	krt|  \}}|dkr|}|dkr|}tj
| ||f|d
 dS )a)  
        Register a new image processor for this class.

        Args:
            config_class ([`PretrainedConfig`]):
                The configuration corresponding to the model to register.
            image_processor_class ([`ImageProcessingMixin`]): The image processor to register.
        NzHCannot specify both image_processor_class and slow_image_processor_classzThe image_processor_class argument is deprecated and will be removed in v4.42. Please use `slow_image_processor_class`, or `fast_image_processor_class` insteadzSYou need to specify either slow_image_processor_class or fast_image_processor_classzIYou passed a fast image processor in as the `slow_image_processor_class`.zIYou passed a slow image processor in as the `fast_image_processor_class`.zThe fast processor class you are passing has a `slow_image_processor_class` attribute that is not consistent with the slow processor class you passed (fast tokenizer has z and you passed z!. Fix one of those so they match!)exist_ok)rN   rK   rL   rM   
issubclassr   r   slow_image_processor_classr5   r6   register)Zconfig_classrt   rw   fast_image_processor_classru   Zexisting_slowZexisting_fastr;   r;   r<   rx     sH    
  zAutoImageProcessor.register)NNNF)r/   
__module____qualname____doc__r\   classmethodr   r   rh   staticmethodrx   r;   r;   r;   r<   rY   .  s    1    rY   )NFNNNNF)7r|   r1   rR   rl   rK   collectionsr   typingr   r   r   r   r   Zconfiguration_utilsr	   Zdynamic_module_utilsr
   r   Zimage_processing_utilsr   r   Zimage_processing_utils_fastr   utilsr   r   r   r   r   r   Zauto_factoryr   Zconfiguration_autor   r   r   r   Z
get_loggerr/   rO   r   str__annotations__r0   Z
model_typeZimage_processorsrw   ry   r5   r=   PathLikeboolrV   rX   rY   r;   r;   r;   r<   <module>   s   
(a
       d