o
    i                     @   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
 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(dgZ)ere Z*ee+e,e	e+ e	e+ f f e-d< neg dZ*e*. D ]\Z/\Z0Z1e sdZ0e sdZ1e0e1fe*e/< qe e"e*Z2de+fddZ3							d'de
e+ej4f de	e
e+ej4f  de5de	e5 de	e6e+e+f  de	e
e5e+f  de	e+ de5fddZ7d d! Z8ed"d#G d$d% d%Z9d&d%gZ:dS )(zAutoImageProcessor class.    N)OrderedDict)TYPE_CHECKINGOptional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Qwen2VLImageProcessorIMAGE_PROCESSOR_MAPPING_NAMES))aimv2CLIPImageProcessorCLIPImageProcessorFast)aimv2_vision_modelr   )alignEfficientNetImageProcessorEfficientNetImageProcessorFast)aria)AriaImageProcessorN)beitBeitImageProcessorBeitImageProcessorFast)bitBitImageProcessorBitImageProcessorFast)blipBlipImageProcessorBlipImageProcessorFast)zblip-2r1   )bridgetower)BridgeTowerImageProcessorBridgeTowerImageProcessorFast)	chameleon)ChameleonImageProcessorChameleonImageProcessorFast)chinese_clip)ChineseCLIPImageProcessorChineseCLIPImageProcessorFast)clipr   )clipsegViTImageProcessorViTImageProcessorFast)cohere2_vision)NCohere2VisionImageProcessorFast)conditional_detr)ConditionalDetrImageProcessor!ConditionalDetrImageProcessorFast)convnextConvNextImageProcessorConvNextImageProcessorFast)
convnextv2rH   )cvtrH   )zdata2vec-visionr)   )deepseek_vl)DeepseekVLImageProcessorDeepseekVLImageProcessorFast)deepseek_vl_hybrid)DeepseekVLHybridImageProcessor"DeepseekVLHybridImageProcessorFast)deformable_detr)DeformableDetrImageProcessor DeformableDetrImageProcessorFast)deit)DeiTImageProcessorDeiTImageProcessorFast)depth_anythingDPTImageProcessorDPTImageProcessorFast)	depth_pro)DepthProImageProcessorDepthProImageProcessorFast)deta)DetaImageProcessorN)detrDetrImageProcessorDetrImageProcessorFast)dinatr?   )dinov2r-   )
dinov3_vit)NDINOv3ViTImageProcessorFast)z
donut-swin)DonutImageProcessorDonutImageProcessorFast)dptrZ   )edgetamNSam2ImageProcessorFast)efficientformer)EfficientFormerImageProcessorN)efficientloftr)EfficientLoFTRImageProcessor EfficientLoFTRImageProcessorFast)efficientnetr#   )eomt)EomtImageProcessorEomtImageProcessorFast)flava)FlavaImageProcessorFlavaImageProcessorFast)focalnetr-   )fuyu)FuyuImageProcessorN)gemma3Gemma3ImageProcessorGemma3ImageProcessorFast)gemma3nSiglipImageProcessorSiglipImageProcessorFast)gitr   )glm4v)Glm4vImageProcessorGlm4vImageProcessorFast)glpn)GLPNImageProcessorN)got_ocr2)GotOcr2ImageProcessorGotOcr2ImageProcessorFast)zgrounding-dinoGroundingDinoImageProcessorGroundingDinoImageProcessorFast)groupvitr   )hierar-   )idefics)IdeficsImageProcessorN)idefics2)Idefics2ImageProcessorIdefics2ImageProcessorFast)idefics3)Idefics3ImageProcessorIdefics3ImageProcessorFast)ijepar?   )imagegpt)ImageGPTImageProcessorImageGPTImageProcessorFast)instructblipr1   )instructblipvideo)InstructBlipVideoImageProcessorN)janus)JanusImageProcessorJanusImageProcessorFast)zkosmos-2r   )z
kosmos-2.5)Kosmos2_5ImageProcessorKosmos2_5ImageProcessorFast)
layoutlmv2)LayoutLMv2ImageProcessorLayoutLMv2ImageProcessorFast)
layoutlmv3LayoutLMv3ImageProcessorLayoutLMv3ImageProcessorFast)levit)LevitImageProcessorLevitImageProcessorFast)lfm2_vl)NLfm2VlImageProcessorFast)	lightglue)LightGlueImageProcessorN)llama4)Llama4ImageProcessorLlama4ImageProcessorFast)llava)LlavaImageProcessorLlavaImageProcessorFast)
llava_next)LlavaNextImageProcessorLlavaNextImageProcessorFast)llava_next_video)LlavaNextVideoImageProcessorN)llava_onevision)LlavaOnevisionImageProcessor LlavaOnevisionImageProcessorFast)mask2former)Mask2FormerImageProcessorMask2FormerImageProcessorFast)
maskformer)MaskFormerImageProcessorMaskFormerImageProcessorFast)
metaclip_2r   )zmgp-strr?   )mistral3PixtralImageProcessorPixtralImageProcessorFast)mlcdr   )mllama)MllamaImageProcessorN)zmm-grounding-dinor   )mobilenet_v1)MobileNetV1ImageProcessorMobileNetV1ImageProcessorFast)mobilenet_v2)MobileNetV2ImageProcessorMobileNetV2ImageProcessorFast)	mobilevitMobileViTImageProcessorMobileViTImageProcessorFast)mobilevitv2r   )natr?   )nougat)NougatImageProcessorNougatImageProcessorFast)	oneformer)OneFormerImageProcessorOneFormerImageProcessorFast)ovis2)Ovis2ImageProcessorOvis2ImageProcessorFast)owlv2)Owlv2ImageProcessorOwlv2ImageProcessorFast)owlvit)OwlViTImageProcessorOwlViTImageProcessorFast)	paligemmar   )	perceiver)PerceiverImageProcessorPerceiverImageProcessorFast)perception_lm)NPerceptionLMImageProcessorFast)phi4_multimodal)N Phi4MultimodalImageProcessorFast)
pix2struct)Pix2StructImageProcessorN)pixtralr   )
poolformer)PoolFormerImageProcessorPoolFormerImageProcessorFast)prompt_depth_anything)!PromptDepthAnythingImageProcessor%PromptDepthAnythingImageProcessorFast)pvtPvtImageProcessorPvtImageProcessorFast)pvt_v2r   )
qwen2_5_vlr   Qwen2VLImageProcessorFast)qwen2_vlr  )qwen3_vlr  )regnetrH   )resnetrH   )rt_detr)RTDetrImageProcessorRTDetrImageProcessorFast)samSamImageProcessorSamImageProcessorFast)sam2rn   )sam_hqr  )	segformerSegformerImageProcessorSegformerImageProcessorFast)seggpt)SegGptImageProcessorN)shieldgemma2r   )siglipr   )siglip2)Siglip2ImageProcessorSiglip2ImageProcessorFast)smolvlm)SmolVLMImageProcessorSmolVLMImageProcessorFast)	superglue)SuperGlueImageProcessorN)
superpoint)SuperPointImageProcessorSuperPointImageProcessorFast)swiftformerr?   )swinr?   )swin2sr)Swin2SRImageProcessorSwin2SRImageProcessorFast)swinv2r?   )ztable-transformerrc   )textnet)TextNetImageProcessorTextNetImageProcessorFast)timesformerVideoMAEImageProcessorN)timm_wrapper)TimmWrapperImageProcessorN)tvlt)TvltImageProcessorN)tvp)TvpImageProcessorTvpImageProcessorFast)udopr   )upernetr  )vanrH   )videomaer1  )vilt)ViltImageProcessorViltImageProcessorFast)vipllavar   )vitr?   )
vit_hybrid)ViTHybridImageProcessorN)vit_maer?   )vit_msnr?   )vitmatte)VitMatteImageProcessorVitMatteImageProcessorFast)xclipr   )yolos)YolosImageProcessorYolosImageProcessorFast)zoedepth)ZoeDepthImageProcessorZoeDepthImageProcessorFast
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rK|    S q;q7td}t|| r\t|| S d S )Nr   .ztransformers.models__name__transformers)r   r   itemsr   	importlibimport_modulegetattrAttributeErrorIMAGE_PROCESSOR_MAPPING_extra_contentvalueshasattr)rQ  module_name
extractorsmodule	extractormain_module rc  b/home/ubuntu/.local/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 `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.
        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   _raise_exceptions_for_gated_repo%_raise_exceptions_for_missing_entries'_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  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`.)rz  warning)
fast_classrc  rc  rd  '_warning_fast_image_processor_availableZ  s   
r  )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.)OSError)selfrc  rc  rd  __init__j  s   zAutoImageProcessor.__init__c                 O   s  | dd}|durtdt |ddurtd||d< | dd}| dd}| dd}d	|d
< d|v r?| d}n	t|rFt}nt}zt	j
|fd|i|\}	}
W n1 ty } z%zt	j
|fdti|\}	}
W n	 tyw   |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r|du r(|d}|s |tv r t r d	}td| d |s(td |r5|ds5|d7 }|rXt sXt|dd }|du rQtd| dtd d}|r|t D ]
}||v rh nq_|dd }d}td t|}n|d}t|}|du r|drtd| d|du}|dupt|tv }|r|durt|t s|df}|r|d dur|d }n|d }d |v r|!d d }nd}t"|||||}|r|r|s|d durt#|d  t$||fi |}| d!d}
|%  |j&|	fi |S |dur#|j&|	fi |S t|tv rltt| }|\}}|s@|dur@t#| |rW|sK|du rW|j|g|R i |S |durh|j|g|R i |S td"td#| d$t d%t d&t d'd('d)d* tD  
)+aI  
        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 `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.
            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_codeT
_from_autoimage_processor_filenameimage_processor_typer  auto_mapfeature_extractor_typeFeatureExtractorImageProcessorAutoFeatureExtractorFastzThe image processor of type `aS  ` is now loaded as a fast processor by default, even if the model checkpoint was saved with a slow processor. This is a breaking change and may produce slightly different outputs. To continue using the slow processor, instantiate this class with `use_fast=False`. Note that this behavior will be extended to all models in a future release.aC  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`.`zU` requires `torchvision` to be installed. Please install `torchvision` and try again.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.z\` does not have a slow version. Please set `use_fast=True` when instantiating the processor.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>q  s    z5AutoImageProcessor.from_pretrained.<locals>.<genexpr>)(ru  rv  rw  rx  getry  r   r   r   r
   get_image_processor_dict	Exceptionr   replace
isinstancer   r   from_pretrainedrX  r]  r  endswithFORCE_FAST_IMAGE_PROCESSORr   rz  warning_oncere  r   r\  removesuffixtyperZ  tuplesplitr	   r  r   register_for_auto_class	from_dictjoin)clsrf  inputsr  rn  r  r  r  r  config_dict_initial_exceptionr  image_processor_auto_mapfeature_extractor_classfeature_extractor_auto_mapimage_processor_classimage_processorsimage_processor_type_slowhas_remote_codehas_local_code	class_refupstream_repoimage_processor_tupleimage_processor_class_pyimage_processor_class_fastrc  rc  rd  r  p  s8  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)
ry  rv  rw  rx  
issubclassr   slow_image_processor_classrZ  r[  register)config_classr  r  fast_image_processor_classr  existing_slowexisting_fastrc  rc  rd  r  t  sJ   




zAutoImageProcessor.register)NNNF)rS  
__module____qualname____doc__r  classmethodr   r   r  staticmethodr  rc  rc  rc  rd  r  a  s      r  rZ  )NFNNNNF);r  rV  r}  osrv  collectionsr   typingr   r   r   configuration_utilsr   dynamic_module_utilsr   r	   image_processing_utilsr
   image_processing_utils_fastr   utilsr   r   r   r   r   r   r   r   utils.import_utilsr   auto_factoryr   configuration_autor   r   r   r   
get_loggerrS  rz  r  r   strr  __annotations__rU  
model_type
slow_classr  rZ  re  PathLikebooldictr  r  r  __all__rc  rc  rc  rd  <module>   sz   (

( 

g  P