o
    Zh                     @   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 dd	l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  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z' e(e)Z*ere Z+ee,ee
e, e
e, f f e-d< neg dZ+e+. D ]%\Z/Z0e0^Z1Z2e sdZ1e2re2d du se sdZ2ne2d Z2e1e2fe+e/< qe"e$e+Z3de,fddZ4							d&dee,ej5f de
ee,ej5f  de6de
e6 de
e	e,e,f  de
ee6e,f  de
e, de6fddZ7dd  Z8e d!d"G d#d$ d$Z9d%d$gZ:dS )'zAutoImageProcessor class.    N)OrderedDict)TYPE_CHECKINGDictOptionalTupleUnion   )PretrainedConfig)get_class_from_dynamic_moduleresolve_trust_remote_code)ImageProcessingMixin)BaseImageProcessorFast)CONFIG_NAMEIMAGE_PROCESSOR_NAMEcached_fileis_timm_config_dictis_timm_local_checkpointis_torchvision_availableis_vision_availablelogging)requires   )_LazyAutoMapping)CONFIG_MAPPING_NAMES
AutoConfigmodel_type_to_module_name!replace_list_option_in_docstringsIMAGE_PROCESSOR_MAPPING_NAMES)s)alignZEfficientNetImageProcessorZEfficientNetImageProcessorFast)ZariaZAriaImageProcessor)ZbeitZBeitImageProcessorZBeitImageProcessorFast)bitZBitImageProcessorZBitImageProcessorFast)ZblipZBlipImageProcessorZBlipImageProcessorFast)zblip-2r#   )Zbridgetower)ZBridgeTowerImageProcessorZBridgeTowerImageProcessorFast)Z	chameleon)ZChameleonImageProcessor)Zchinese_clip)ZChineseCLIPImageProcessorZChineseCLIPImageProcessorFast)ZclipZCLIPImageProcessorZCLIPImageProcessorFast)ZclipsegZViTImageProcessorZViTImageProcessorFast)Zconditional_detr)ZConditionalDetrImageProcessorZ!ConditionalDetrImageProcessorFast)ZconvnextZConvNextImageProcessorZConvNextImageProcessorFast)Z
convnextv2r&   )cvtr&   )zdata2vec-visionr    )Zdeformable_detr)ZDeformableDetrImageProcessorZ DeformableDetrImageProcessorFast)Zdeit)ZDeiTImageProcessorZDeiTImageProcessorFast)Zdepth_anythingZDPTImageProcessor)Z	depth_pro)ZDepthProImageProcessorZDepthProImageProcessorFast)Zdeta)ZDetaImageProcessor)Zdetr)DetrImageProcessorZDetrImageProcessorFast)Zdinatr%   )Zdinov2r"   )z
donut-swin)ZDonutImageProcessorZDonutImageProcessorFast)Zdptr(   )Zefficientformer)ZEfficientFormerImageProcessor)Zefficientnetr   )Zflava)ZFlavaImageProcessorZFlavaImageProcessorFast)Zfocalnetr"   )Zfuyu)ZFuyuImageProcessor)Zgemma3ZGemma3ImageProcessorZGemma3ImageProcessorFast)gitr$   )Zglpn)ZGLPNImageProcessor)Zgot_ocr2)ZGotOcr2ImageProcessorZGotOcr2ImageProcessorFast)zgrounding-dino)ZGroundingDinoImageProcessorZGroundingDinoImageProcessorFast)Zgroupvitr$   )Zhierar"   )Zidefics)ZIdeficsImageProcessor)Zidefics2)ZIdefics2ImageProcessor)Zidefics3)ZIdefics3ImageProcessor)Zijepar%   )Zimagegpt)ZImageGPTImageProcessor)Zinstructblipr#   )Zinstructblipvideo)ZInstructBlipVideoImageProcessor)ZjanusZJanusImageProcessor)zkosmos-2r$   )Z
layoutlmv2)ZLayoutLMv2ImageProcessorZLayoutLMv2ImageProcessorFast)Z
layoutlmv3ZLayoutLMv3ImageProcessorZLayoutLMv3ImageProcessorFast)Zlevit)ZLevitImageProcessorZLevitImageProcessorFast)Zllama4)ZLlama4ImageProcessorZLlama4ImageProcessorFast)Zllava)ZLlavaImageProcessorZLlavaImageProcessorFast)Z
llava_next)ZLlavaNextImageProcessorZLlavaNextImageProcessorFast)Zllava_next_video)ZLlavaNextVideoImageProcessor)Zllava_onevision)ZLlavaOnevisionImageProcessorZ LlavaOnevisionImageProcessorFast)Zmask2former)ZMask2FormerImageProcessor)Z
maskformer)ZMaskFormerImageProcessor)zmgp-strr%   )Zmistral3ZPixtralImageProcessorZPixtralImageProcessorFast)Zmlcdr$   )Zmllama)ZMllamaImageProcessor)Zmobilenet_v1)ZMobileNetV1ImageProcessorZMobileNetV1ImageProcessorFast)Zmobilenet_v2)ZMobileNetV2ImageProcessorZMobileNetV2ImageProcessorFast)Z	mobilevitZMobileViTImageProcessor)Zmobilevitv2r.   )Znatr%   )Znougat)ZNougatImageProcessor)Z	oneformer)ZOneFormerImageProcessor)Zowlv2)ZOwlv2ImageProcessor)Zowlvit)ZOwlViTImageProcessorZOwlViTImageProcessorFast)Z	paligemmaZSiglipImageProcessorZSiglipImageProcessorFast)Z	perceiver)ZPerceiverImageProcessorZPerceiverImageProcessorFast)Zphi4_multimodal)Z Phi4MultimodalImageProcessorFast)Z
pix2struct)ZPix2StructImageProcessor)Zpixtralr-   )Z
poolformer)ZPoolFormerImageProcessorZPoolFormerImageProcessorFast)Zprompt_depth_anything)Z!PromptDepthAnythingImageProcessor)ZpvtZPvtImageProcessorZPvtImageProcessorFast)Zpvt_v2r0   )Z
qwen2_5_vlZQwen2VLImageProcessorZQwen2VLImageProcessorFast)Zqwen2_vlr1   )Zregnetr&   )Zresnetr&   )Zrt_detr)ZRTDetrImageProcessorZRTDetrImageProcessorFast)ZsamZSamImageProcessor)Zsam_hqr2   )Z	segformerZSegformerImageProcessor)Zseggpt)ZSegGptImageProcessor)Zshieldgemma2r*   )Zsiglipr/   )Zsiglip2)ZSiglip2ImageProcessorZSiglip2ImageProcessorFast)Z	superglue)ZSuperGlueImageProcessor)Zswiftformerr%   )Zswinr%   )Zswin2sr)ZSwin2SRImageProcessorZSwin2SRImageProcessorFast)Zswinv2r%   )ztable-transformer)r)   )ZtimesformerZVideoMAEImageProcessor)Ztimm_wrapper)ZTimmWrapperImageProcessor)Ztvlt)ZTvltImageProcessor)Ztvp)ZTvpImageProcessor)Zudopr,   )Zupernetr3   )Zvanr&   )Zvideomaer4   )Zvilt)ZViltImageProcessorZViltImageProcessorFast)Zvipllavar$   )Zvitr%   )Z
vit_hybrid)ZViTHybridImageProcessor)Zvit_maer%   )Zvit_msnr%   )Zvitmatte)ZVitMatteImageProcessorZVitMatteImageProcessorFast)Zxclipr$   )Zyolos)ZYolosImageProcessorZYolosImageProcessorFast)Zzoedepth)ZZoeDepthImageProcessor
class_namec              	   C   s   | dkrt S t D ]'\}}| |v r1t|}td| d}zt|| W   S  ty0   Y q
w q
tj	 D ]\}}|D ]}t|dd | krM|    S q=q7td}t
|| r^t|| S d S )Nr   .ztransformers.models__name__Ztransformers)r   r   itemsr   	importlibimport_modulegetattrAttributeErrorIMAGE_PROCESSOR_MAPPING_extra_contenthasattr)r5   module_nameZ
extractorsmodule_Z	extractorZmain_module rC   ]/var/www/auris/lib/python3.10/site-packages/transformers/models/auto/image_processing_auto.py#get_image_processor_class_from_name   s,   	


rE   Fpretrained_model_name_or_path	cache_dirforce_downloadresume_downloadproxiestokenrevisionlocal_files_onlyc                 K   s   | dd}	|	durtdt |durtd|	}t| t|||||||dddd}
|
du r5td i S t	|
dd	}t
|W  d   S 1 sKw   Y  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`.F)
rG   rH   rI   rJ   rK   rL   rM   Z _raise_exceptions_for_gated_repoZ%_raise_exceptions_for_missing_entriesZ'_raise_exceptions_for_connection_errorszbCould 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)rF   rG   rH   rI   rJ   rK   rL   rM   kwargsrN   Zresolved_config_filereaderrC   rC   rD   get_image_processor_config   s>   E$r^   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`.)rW   warning)Z
fast_classrC   rC   rD   '_warning_fast_image_processor_availableD  s   
r`   )Zvision)backendsc                   @   sB   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)NzAutoImageProcessor is designed to be instantiated using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.)EnvironmentError)selfrC   rC   rD   __init__T  s   zAutoImageProcessor.__init__c                 O   s  | dd}|dur tdt |dddurtd||d< | dd}| dd}| dd}d	|d
< d|v r@| d}n	t|rGt}nt}zt	j
|fd|i|\}	}
W n1 ty } z%zt	j
|fdti|\}	}
W n	 tyx   |w t|	s|W Y d}~nd}~ww |	dd}d}d|	di v r|	d d }|du r|du r|	 dd}|dur|dd}d|	di v r|	d d }|dd}|du r|du rt|tstj|fd|i|}t|dd}t|drd|jv r|jd }d}|durb|du r|d}|std |r t s td d}|rP|ds-|d7 }t D ]\}
}||v r< nq1|dd }d}td t|}n|dr\|dd n|}t|}|du}|duppt|tv }t||||}|durt|ts|df}|r|r|s|d durt |d  |r|d dur|d }n|d }t!||fi |}| dd}
t"j#$|r|%  |j&|	fi |S |dur|j&|	fi |S t|tv r*tt| }|\}}|s|durt | |r|s	|du r|j|g|R i |S |dur&|j|g|R i |S tdtd| dt dt d t d!d"'d#d$ t( D  
)%aQ  
        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 image processor 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.
            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.
            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/")
        ```rN   NrO   rK   rP   configuse_fasttrust_remote_codeTZ
_from_autoimage_processor_filenameimage_processor_typerb   auto_mapZfeature_extractor_typeZFeatureExtractorZImageProcessorZAutoFeatureExtractorZFastaC  Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.zcUsing `use_fast=True` but `torchvision` is not available. Falling back to the slow image processor.Fzz`use_fast` is set to `True` but the image processor class does not have a fast version.  Falling back to the slow version.r   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 )NrC   ).0crC   rC   rD   	<genexpr>K  s    z5AutoImageProcessor.from_pretrained.<locals>.<genexpr>))rR   rS   rT   rU   getrV   r   r   r   r   Zget_image_processor_dict	Exceptionr   replace
isinstancer	   r   from_pretrainedr;   r?   rk   endswithrW   Zwarning_oncer   r   r8   rE   typer=   r   tupler`   r
   ospathisdirZregister_for_auto_class	from_dictjoinkeys)clsrF   Zinputsr\   rN   rf   rg   rh   ri   Zconfig_dictrB   Zinitial_exceptionrj   Zimage_processor_auto_mapZfeature_extractor_classZfeature_extractor_auto_mapimage_processor_classimage_processorsZhas_remote_codeZhas_local_codeZ	class_refZimage_processor_tupleZimage_processor_class_pyZimage_processor_class_fastrC   rC   rD   rt   Z  s  O









z"AutoImageProcessor.from_pretrainedNFc                 C   s   |dur|durt dtdt |}|du r |du r t d|dur-t|tr-t d|dur:t|ts:t d|durX|durXt|trX|j|krXt d|j d| d	| tjv rot|  \}}|du ri|}|du ro|}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`.zNThe `fast_image_processor_class` should inherit from `BaseImageProcessorFast`.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)
rV   rS   rT   rU   
issubclassr   slow_image_processor_classr=   r>   register)Zconfig_classr   r   fast_image_processor_classr   Zexisting_slowZexisting_fastrC   rC   rD   r   N  sJ   




zAutoImageProcessor.register)NNNF)r7   
__module____qualname____doc__re   classmethodr   r   rt   staticmethodr   rC   rC   rC   rD   rb   K  s     srb   r=   )NFNNNNF);r   r9   rZ   rx   rS   collectionsr   typingr   r   r   r   r   Zconfiguration_utilsr	   Zdynamic_module_utilsr
   r   Zimage_processing_utilsr   Zimage_processing_utils_fastr   utilsr   r   r   r   r   r   r   r   Zutils.import_utilsr   Zauto_factoryr   Zconfiguration_autor   r   r   r   Z
get_loggerr7   rW   r   str__annotations__r8   Z
model_typer   r   r   r=   rE   PathLikeboolr^   r`   rb   __all__rC   rC   rC   rD   <module>   sz   (

(x

g  @