

import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
		import tensorflow as tf

		from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

lowercase			:				List[Any]   =     logging.get_logger(__name__)







class 					__lowercase  (						enum.Enum				):





							"""simple docstring"""

							UpperCAmelCase_						:		List[str]								=	0
							UpperCAmelCase_						:		int								=	1







@add_end_docstrings(_SCREAMING_SNAKE_CASE				)
class 					__lowercase  (						_SCREAMING_SNAKE_CASE				):





							"""simple docstring"""

							UpperCAmelCase_						:		Dict								=	'''generated'''




							def __init__(					self    ,						*__UpperCAmelCase    ,						**__UpperCAmelCase						)		->       str:
														super().__init__(*__UpperCAmelCase    ,						**__UpperCAmelCase						)

														self.check_model_type(
														    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
														    if self.framework == '''tf'''
														    else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING						)




							def       snake_case			(					self    ,						__UpperCAmelCase=None    ,						__UpperCAmelCase=None    ,						__UpperCAmelCase=None    ,						__UpperCAmelCase=None    ,						__UpperCAmelCase=None    ,						__UpperCAmelCase=None    ,						**__UpperCAmelCase    ,						)		->       Any:
														A      :					Optional[int]      		=					{}
														if truncation is not None:
																					A      :					Optional[int]      		=					truncation

														A      :					str      		=					generate_kwargs

														A      :					List[Any]      		=					{}
														if return_tensors is not None and return_type is None:
																					A      :					Union[str, Any]      		=					ReturnType.TENSORS if return_tensors else ReturnType.TEXT
														if return_type is not None:
																					A      :					int      		=					return_type

														if clean_up_tokenization_spaces is not None:
																					A      :					Any      		=					clean_up_tokenization_spaces

														if stop_sequence is not None:
																					A      :					Tuple      		=					self.tokenizer.encode(__UpperCAmelCase    ,						add_special_tokens=__UpperCAmelCase						)
																					if len(__UpperCAmelCase						) > 1:
																												warnings.warn(
																												    '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of'''
																												    ''' the stop sequence will be used as the stop sequence string in the interim.'''						)
																					A      :					Union[str, Any]      		=					stop_sequence_ids[0]

														return preprocess_params, forward_params, postprocess_params




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase						)		->       Any:
														return True




							def       snake_case			(					self    ,						*__UpperCAmelCase    ,						__UpperCAmelCase						)		->       Union[str, Any]:
														A      :					Optional[Any]      		=					self.model.config.prefix if self.model.config.prefix is not None else ''''''
														if isinstance(args[0]    ,						__UpperCAmelCase						):
																					if self.tokenizer.pad_token_id is None:
																												raise ValueError('''Please make sure that the tokenizer has a pad_token_id when using a batch input'''						)
																					A      :					Dict      		=					([prefix + arg for arg in args[0]],)
																					A      :					Tuple      		=					True

														elif isinstance(args[0]    ,						__UpperCAmelCase						):
																					A      :					Union[str, Any]      		=					(prefix + args[0],)
																					A      :					Union[str, Any]      		=					False
														else:
																					raise ValueError(
																					    f' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`'						)
														A      :					List[Any]      		=					self.tokenizer(*__UpperCAmelCase    ,						padding=__UpperCAmelCase    ,						truncation=__UpperCAmelCase    ,						return_tensors=self.framework						)
														# This is produced by tokenizers but is an invalid generate kwargs
														if "token_type_ids" in inputs:
																					del inputs["token_type_ids"]
														return inputs




							def __call__(					self    ,						*__UpperCAmelCase    ,						**__UpperCAmelCase						)		->       List[str]:
														A      :					Optional[int]      		=					super().__call__(*__UpperCAmelCase    ,						**__UpperCAmelCase						)
														if (
														    isinstance(args[0]    ,						__UpperCAmelCase						)
														    and all(isinstance(__UpperCAmelCase    ,						__UpperCAmelCase						) for el in args[0]						)
														    and all(len(__UpperCAmelCase						) == 1 for res in result						)
														):
																					return [res[0] for res in result]
														return result




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase=TruncationStrategy.DO_NOT_TRUNCATE    ,						**__UpperCAmelCase						)		->       Optional[int]:
														A      :					int      		=					self._parse_and_tokenize(__UpperCAmelCase    ,						truncation=__UpperCAmelCase    ,						**__UpperCAmelCase						)
														return inputs




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						**__UpperCAmelCase						)		->       List[str]:
														if self.framework == "pt":
																					A		,		A      :					str      		=					model_inputs['''input_ids'''].shape
														elif self.framework == "tf":
																					A		,		A      :					Optional[Any]      		=					tf.shape(model_inputs['''input_ids''']						).numpy()

														A      :					Union[str, Any]      		=					generate_kwargs.get('''min_length'''    ,						self.model.config.min_length						)
														A      :					int      		=					generate_kwargs.get('''max_length'''    ,						self.model.config.max_length						)
														self.check_inputs(__UpperCAmelCase    ,						generate_kwargs['''min_length''']    ,						generate_kwargs['''max_length''']						)
														A      :					Any      		=					self.model.generate(**__UpperCAmelCase    ,						**__UpperCAmelCase						)
														A      :					Dict      		=					output_ids.shape[0]
														if self.framework == "pt":
																					A      :					Optional[Any]      		=					output_ids.reshape(__UpperCAmelCase    ,						out_b // in_b    ,						*output_ids.shape[1:]						)
														elif self.framework == "tf":
																					A      :					int      		=					tf.reshape(__UpperCAmelCase    ,						(in_b, out_b // in_b, *output_ids.shape[1:])						)
														return {"output_ids": output_ids}






							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase=ReturnType.TEXT    ,						__UpperCAmelCase=False						)		->       List[Any]:
														A      :					str      		=					[]
														for output_ids in model_outputs["output_ids"][0]:
																					if return_type == ReturnType.TENSORS:
																												A      :					Dict      		=					{f'{self.return_name}_token_ids': output_ids}
																					elif return_type == ReturnType.TEXT:
																												A      :					List[str]      		=					{
																												    f'{self.return_name}_text': self.tokenizer.decode(
																												        __UpperCAmelCase    ,						skip_special_tokens=__UpperCAmelCase    ,						clean_up_tokenization_spaces=__UpperCAmelCase    ,						)
																												}
																					records.append(__UpperCAmelCase						)
														return records







@add_end_docstrings(_SCREAMING_SNAKE_CASE				)
class 					__lowercase  (						_SCREAMING_SNAKE_CASE				):





							"""simple docstring"""

							UpperCAmelCase_						:		Optional[int]								=	'''summary'''




							def __call__(					self    ,						*__UpperCAmelCase    ,						**__UpperCAmelCase						)		->       Optional[Any]:
														return super().__call__(*__UpperCAmelCase    ,						**__UpperCAmelCase						)






							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase						)		->       bool:
														if max_length < min_length:
																					logger.warning(f'Your min_length={min_length} must be inferior than your max_length={max_length}.'						)

														if input_length < max_length:
																					logger.warning(
																					    f'Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is '
																					    '''a summarization task, where outputs shorter than the input are typically wanted, you might '''
																					    f'consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})'						)







@add_end_docstrings(_SCREAMING_SNAKE_CASE				)
class 					__lowercase  (						_SCREAMING_SNAKE_CASE				):





							"""simple docstring"""

							UpperCAmelCase_						:		Optional[Any]								=	'''translation'''




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase						)		->       int:
														if input_length > 0.9 * max_length:
																					logger.warning(
																					    f'Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider '
																					    '''increasing your max_length manually, e.g. translator(\'...\', max_length=400)'''						)
														return True




							def       snake_case			(					self    ,						*__UpperCAmelCase    ,						__UpperCAmelCase=TruncationStrategy.DO_NOT_TRUNCATE    ,						__UpperCAmelCase=None    ,						__UpperCAmelCase=None						)		->       Optional[int]:
														if getattr(self.tokenizer    ,						'''_build_translation_inputs'''    ,						__UpperCAmelCase						):
																					return self.tokenizer._build_translation_inputs(
																					    *__UpperCAmelCase    ,						return_tensors=self.framework    ,						truncation=__UpperCAmelCase    ,						src_lang=__UpperCAmelCase    ,						tgt_lang=__UpperCAmelCase						)
														else:
																					return super()._parse_and_tokenize(*__UpperCAmelCase    ,						truncation=__UpperCAmelCase						)




							def       snake_case			(					self    ,						__UpperCAmelCase=None    ,						__UpperCAmelCase=None    ,						**__UpperCAmelCase						)		->       Optional[Any]:
														A		,		A		,		A      :					int      		=					super()._sanitize_parameters(**__UpperCAmelCase						)
														if src_lang is not None:
																					A      :					Union[str, Any]      		=					src_lang
														if tgt_lang is not None:
																					A      :					Any      		=					tgt_lang
														if src_lang is None and tgt_lang is None:
																					# Backward compatibility, direct arguments use is preferred.
																					A      :					Any      		=					kwargs.get('''task'''    ,						self.task						)
																					A      :					int      		=					task.split('''_'''						)
																					if task and len(__UpperCAmelCase						) == 4:
																												# translation, XX, to YY
																												A      :					str      		=					items[1]
																												A      :					Optional[Any]      		=					items[3]
														return preprocess_params, forward_params, postprocess_params






							def __call__(					self    ,						*__UpperCAmelCase    ,						**__UpperCAmelCase						)		->       List[str]:
														return super().__call__(*__UpperCAmelCase    ,						**__UpperCAmelCase						)









import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union

# Build the list of all image processors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...image_processing_utils import ImageProcessingMixin
from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)


lowercase			:				Dict   =     logging.get_logger(__name__)

lowercase			:				Dict   =     OrderedDict(
    [
        ("align", "EfficientNetImageProcessor"),
        ("beit", "BeitImageProcessor"),
        ("bit", "BitImageProcessor"),
        ("blip", "BlipImageProcessor"),
        ("blip-2", "BlipImageProcessor"),
        ("bridgetower", "BridgeTowerImageProcessor"),
        ("chinese_clip", "ChineseCLIPImageProcessor"),
        ("clip", "CLIPImageProcessor"),
        ("clipseg", "ViTImageProcessor"),
        ("conditional_detr", "ConditionalDetrImageProcessor"),
        ("convnext", "ConvNextImageProcessor"),
        ("convnextv2", "ConvNextImageProcessor"),
        ("cvt", "ConvNextImageProcessor"),
        ("data2vec-vision", "BeitImageProcessor"),
        ("deformable_detr", "DeformableDetrImageProcessor"),
        ("deit", "DeiTImageProcessor"),
        ("deta", "DetaImageProcessor"),
        ("detr", "DetrImageProcessor"),
        ("dinat", "ViTImageProcessor"),
        ("donut-swin", "DonutImageProcessor"),
        ("dpt", "DPTImageProcessor"),
        ("efficientformer", "EfficientFormerImageProcessor"),
        ("efficientnet", "EfficientNetImageProcessor"),
        ("flava", "FlavaImageProcessor"),
        ("focalnet", "BitImageProcessor"),
        ("git", "CLIPImageProcessor"),
        ("glpn", "GLPNImageProcessor"),
        ("groupvit", "CLIPImageProcessor"),
        ("imagegpt", "ImageGPTImageProcessor"),
        ("instructblip", "BlipImageProcessor"),
        ("layoutlmv2", "LayoutLMv2ImageProcessor"),
        ("layoutlmv3", "LayoutLMv3ImageProcessor"),
        ("levit", "LevitImageProcessor"),
        ("mask2former", "Mask2FormerImageProcessor"),
        ("maskformer", "MaskFormerImageProcessor"),
        ("mgp-str", "ViTImageProcessor"),
        ("mobilenet_v1", "MobileNetV1ImageProcessor"),
        ("mobilenet_v2", "MobileNetV2ImageProcessor"),
        ("mobilevit", "MobileViTImageProcessor"),
        ("mobilevit", "MobileViTImageProcessor"),
        ("mobilevitv2", "MobileViTImageProcessor"),
        ("nat", "ViTImageProcessor"),
        ("oneformer", "OneFormerImageProcessor"),
        ("owlvit", "OwlViTImageProcessor"),
        ("perceiver", "PerceiverImageProcessor"),
        ("pix2struct", "Pix2StructImageProcessor"),
        ("poolformer", "PoolFormerImageProcessor"),
        ("regnet", "ConvNextImageProcessor"),
        ("resnet", "ConvNextImageProcessor"),
        ("sam", "SamImageProcessor"),
        ("segformer", "SegformerImageProcessor"),
        ("swiftformer", "ViTImageProcessor"),
        ("swin", "ViTImageProcessor"),
        ("swin2sr", "Swin2SRImageProcessor"),
        ("swinv2", "ViTImageProcessor"),
        ("table-transformer", "DetrImageProcessor"),
        ("timesformer", "VideoMAEImageProcessor"),
        ("tvlt", "TvltImageProcessor"),
        ("upernet", "SegformerImageProcessor"),
        ("van", "ConvNextImageProcessor"),
        ("videomae", "VideoMAEImageProcessor"),
        ("vilt", "ViltImageProcessor"),
        ("vit", "ViTImageProcessor"),
        ("vit_hybrid", "ViTHybridImageProcessor"),
        ("vit_mae", "ViTImageProcessor"),
        ("vit_msn", "ViTImageProcessor"),
        ("xclip", "CLIPImageProcessor"),
        ("yolos", "YolosImageProcessor"),
    ]
)

lowercase			:				Tuple   =     _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)






def        snake_case__		(    lowerCamelCase_		):
							for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
														if class_name in extractors:
																					A      :					Optional[Any]      		=					model_type_to_module_name(lowerCamelCase_		)

																					A      :					Optional[int]      		=					importlib.import_module(F'.{module_name}'     ,				'''transformers.models'''		)
																					try:
																												return getattr(lowerCamelCase_     ,				lowerCamelCase_		)
																					except AttributeError:
																												continue

							for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items():
														if getattr(lowerCamelCase_     ,				'''__name__'''     ,				lowerCamelCase_		) == class_name:
																					return extractor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
							A      :					Any      		=					importlib.import_module('''transformers'''		)
							if hasattr(lowerCamelCase_     ,				lowerCamelCase_		):
														return getattr(lowerCamelCase_     ,				lowerCamelCase_		)

							return None






def        snake_case__		(    lowerCamelCase_     ,				lowerCamelCase_ = None     ,				lowerCamelCase_ = False     ,				lowerCamelCase_ = False     ,				lowerCamelCase_ = None     ,				lowerCamelCase_ = None     ,				lowerCamelCase_ = None     ,				lowerCamelCase_ = False     ,				**lowerCamelCase_     ,				):
							A      :					Optional[Any]      		=					get_file_from_repo(
							    lowerCamelCase_     ,				lowerCamelCase_     ,				cache_dir=lowerCamelCase_     ,				force_download=lowerCamelCase_     ,				resume_download=lowerCamelCase_     ,				proxies=lowerCamelCase_     ,				use_auth_token=lowerCamelCase_     ,				revision=lowerCamelCase_     ,				local_files_only=lowerCamelCase_     ,				)
							if resolved_config_file is None:
														logger.info(
														    '''Could not locate the image processor configuration file, will try to use the model config instead.'''		)
														return {}

							with open(lowerCamelCase_     ,				encoding='''utf-8'''		) as reader:
														return json.load(lowerCamelCase_		)







class 					__lowercase  :





							"""simple docstring"""

							def __init__(					self						)		->       int:
														raise EnvironmentError(
														    '''AutoImageProcessor is designed to be instantiated '''
														    '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.'''						)




							@classmethod
							@replace_list_option_in_docstrings(__UpperCAmelCase						)
							def       snake_case			(					cls    ,						__UpperCAmelCase    ,						**__UpperCAmelCase						)		->       Tuple:
														A      :					Tuple      		=					kwargs.pop('''config'''    ,						__UpperCAmelCase						)
														A      :					Union[str, Any]      		=					kwargs.pop('''trust_remote_code'''    ,						__UpperCAmelCase						)
														A      :					str      		=					True

														A		,		A      :					str      		=					ImageProcessingMixin.get_image_processor_dict(__UpperCAmelCase    ,						**__UpperCAmelCase						)
														A      :					List[Any]      		=					config_dict.get('''image_processor_type'''    ,						__UpperCAmelCase						)
														A      :					List[Any]      		=					None
														if "AutoImageProcessor" in config_dict.get('''auto_map'''    ,						{}						):
																					A      :					List[str]      		=					config_dict['''auto_map''']['''AutoImageProcessor''']

														# If we still don't have the image processor class, check if we're loading from a previous feature extractor config
														# and if so, infer the image processor class from there.
														if image_processor_class is None and image_processor_auto_map is None:
																					A      :					List[str]      		=					config_dict.pop('''feature_extractor_type'''    ,						__UpperCAmelCase						)
																					if feature_extractor_class is not None:
																												logger.warning(
																												    '''Could not find image processor class in the image processor config or the model config. Loading'''
																												    ''' based on pattern matching with the model\'s feature extractor configuration.'''						)
																												A      :					Tuple      		=					feature_extractor_class.replace('''FeatureExtractor'''    ,						'''ImageProcessor'''						)
																					if "AutoFeatureExtractor" in config_dict.get('''auto_map'''    ,						{}						):
																												A      :					Any      		=					config_dict['''auto_map''']['''AutoFeatureExtractor''']
																												A      :					int      		=					feature_extractor_auto_map.replace('''FeatureExtractor'''    ,						'''ImageProcessor'''						)
																												logger.warning(
																												    '''Could not find image processor auto map in the image processor config or the model config.'''
																												    ''' Loading based on pattern matching with the model\'s feature extractor configuration.'''						)

        # If we don't find the image processor class in the image processor config, let's try the model config.
														if image_processor_class is None and image_processor_auto_map is None:
																					if not isinstance(__UpperCAmelCase    ,						__UpperCAmelCase						):
																												A      :					List[str]      		=					AutoConfig.from_pretrained(__UpperCAmelCase    ,						**__UpperCAmelCase						)
																					# It could be in `config.image_processor_type``
																					A      :					Any      		=					getattr(__UpperCAmelCase    ,						'''image_processor_type'''    ,						__UpperCAmelCase						)
																					if hasattr(__UpperCAmelCase    ,						'''auto_map'''						) and "AutoImageProcessor" in config.auto_map:
																												A      :					List[Any]      		=					config.auto_map['''AutoImageProcessor''']

														if image_processor_class is not None:
																					A      :					str      		=					image_processor_class_from_name(__UpperCAmelCase						)

														A      :					int      		=					image_processor_auto_map is not None
														A      :					List[str]      		=					image_processor_class is not None or type(__UpperCAmelCase						) in IMAGE_PROCESSOR_MAPPING
														A      :					Optional[Any]      		=					resolve_trust_remote_code(
														    __UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase						)

														if has_remote_code and trust_remote_code:
																					A      :					Tuple      		=					get_class_from_dynamic_module(
																					    __UpperCAmelCase    ,						__UpperCAmelCase    ,						**__UpperCAmelCase						)
																					A      :					Optional[Any]      		=					kwargs.pop('''code_revision'''    ,						__UpperCAmelCase						)
																					if os.path.isdir(__UpperCAmelCase						):
																												image_processor_class.register_for_auto_class()
																					return image_processor_class.from_dict(__UpperCAmelCase    ,						**__UpperCAmelCase						)
														elif image_processor_class is not None:
																					return image_processor_class.from_dict(__UpperCAmelCase    ,						**__UpperCAmelCase						)
														# Last try: we use the IMAGE_PROCESSOR_MAPPING.
														elif type(__UpperCAmelCase						) in IMAGE_PROCESSOR_MAPPING:
																					A      :					Tuple      		=					IMAGE_PROCESSOR_MAPPING[type(__UpperCAmelCase						)]
																					return image_processor_class.from_dict(__UpperCAmelCase    ,						**__UpperCAmelCase						)

														raise ValueError(
														    f'Unrecognized image processor in {pretrained_model_name_or_path}. Should have a '
														    f'`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following '
														    f'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys()						)}'						)






							@staticmethod
							def       snake_case			(					__UpperCAmelCase    ,						__UpperCAmelCase						)		->       Any:
														IMAGE_PROCESSOR_MAPPING.register(__UpperCAmelCase    ,						__UpperCAmelCase						)






