



"""simple docstring"""
import subprocess
import sys
import warnings
from argparse import ArgumentParser
from pathlib import Path

from packaging import version

from .. import AutoFeatureExtractor, AutoImageProcessor, AutoProcessor, AutoTokenizer
from ..utils import logging
from ..utils.import_utils import is_optimum_available
from .convert import export, validate_model_outputs
from .features import FeaturesManager
from .utils import get_preprocessor


__SCREAMING_SNAKE_CASE     :  Optional[Any]										=					'''1.5.0'''

__SCREAMING_SNAKE_CASE     :  Optional[Any]										=					['''vision-encoder-decoder''']



def 				lowerCAmelCase_(      lowercase_   :							Optional[Any]							)		->				Union[str, Any]:
				if is_optimum_available():
								from optimum.version import __version__ as optimum_version

								_lowerCamelCase					     = version.parse(lowercase_							)
								if parsed_optimum_version < version.parse(lowercase_							):
												raise RuntimeError(
												    F"""transformers.onnx requires optimum >= {MIN_OPTIMUM_VERSION} but {optimum_version} is installed. You """
												    '''can upgrade optimum by running: pip install -U optimum[exporters]'''							)
				else:
								raise RuntimeError(
								    '''transformers.onnx requires optimum to run, you can install the library by running: pip install '''
								    '''optimum[exporters]'''							)
				_lowerCamelCase					     = [
				    sys.executable,
				    '''-m''',
				    '''optimum.exporters.onnx''',
				    F"""--model {args.model}""",
				    F"""--task {args.feature}""",
				    F"""--framework {args.framework}""" if args.framework is not None else '''''',
				    F"""{args.output}""",
				]
				_lowerCamelCase					     = subprocess.Popen(''' '''.join(lowercase_							)  ,      stdout=subprocess.PIPE  ,      shell=lowercase_							)
				proc.wait()

				logger.info(
				    '''The export was done by optimum.exporters.onnx. We recommend using to use this package directly in future, as '''
				    '''transformers.onnx is deprecated, and will be removed in v5. You can find more information here: '''
				    '''https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model.'''							)



def 				lowerCAmelCase_(      lowercase_   :							Union[str, Any]							)		->				Optional[int]:
				_lowerCamelCase					     = args.output if args.output.is_file() else args.output.joinpath('''model.onnx'''							)
				if not args.output.parent.exists():
								args.output.parent.mkdir(parents=lowercase_							)

				# Allocate the model
				_lowerCamelCase					     = FeaturesManager.get_model_from_feature(
				    args.feature  ,      args.model  ,      framework=args.framework  ,      cache_dir=args.cache_dir							)

				_lowerCamelCase     ,   _lowerCamelCase					     = FeaturesManager.check_supported_model_or_raise(lowercase_  ,      feature=args.feature							)
				_lowerCamelCase					     = model_onnx_config(model.config							)

				if model_kind in ENCODER_DECODER_MODELS:
								_lowerCamelCase					     = model.get_encoder()
								_lowerCamelCase					     = model.get_decoder()

								_lowerCamelCase					     = onnx_config.get_encoder_config(encoder_model.config							)
								_lowerCamelCase					     = onnx_config.get_decoder_config(
								    encoder_model.config  ,      decoder_model.config  ,      feature=args.feature							)

								if args.opset is None:
												_lowerCamelCase					     = max(encoder_onnx_config.default_onnx_opset  ,      decoder_onnx_config.default_onnx_opset							)

								if args.opset < min(encoder_onnx_config.default_onnx_opset  ,      decoder_onnx_config.default_onnx_opset							):
												raise ValueError(
												    F"""Opset {args.opset} is not sufficient to export {model_kind}. At least """
												    F""" {min(encoder_onnx_config.default_onnx_opset  ,      decoder_onnx_config.default_onnx_opset							)} is required."""							)

								_lowerCamelCase					     = AutoFeatureExtractor.from_pretrained(args.model							)

								_lowerCamelCase     ,   _lowerCamelCase					     = export(
								    lowercase_  ,      lowercase_  ,      lowercase_  ,      args.opset  ,      args.output.parent.joinpath('''encoder_model.onnx'''							)  ,      )

								validate_model_outputs(
								    lowercase_  ,      lowercase_  ,      lowercase_  ,      args.output.parent.joinpath('''encoder_model.onnx'''							)  ,      lowercase_  ,      args.atol if args.atol else encoder_onnx_config.atol_for_validation  ,      )

								_lowerCamelCase					     = AutoTokenizer.from_pretrained(args.model							)

								_lowerCamelCase     ,   _lowerCamelCase					     = export(
								    lowercase_  ,      lowercase_  ,      lowercase_  ,      args.opset  ,      args.output.parent.joinpath('''decoder_model.onnx'''							)  ,      )

								validate_model_outputs(
								    lowercase_  ,      lowercase_  ,      lowercase_  ,      args.output.parent.joinpath('''decoder_model.onnx'''							)  ,      lowercase_  ,      args.atol if args.atol else decoder_onnx_config.atol_for_validation  ,      )
								logger.info(
								    F"""All good, model saved at: {args.output.parent.joinpath("encoder_model.onnx"							).as_posix()},"""
								    F""" {args.output.parent.joinpath("decoder_model.onnx"							).as_posix()}"""							)

				else:
								# Instantiate the appropriate preprocessor
								if args.preprocessor == "auto":
												_lowerCamelCase					     = get_preprocessor(args.model							)
								elif args.preprocessor == "tokenizer":
												_lowerCamelCase					     = AutoTokenizer.from_pretrained(args.model							)
								elif args.preprocessor == "image_processor":
												_lowerCamelCase					     = AutoImageProcessor.from_pretrained(args.model							)
								elif args.preprocessor == "feature_extractor":
												_lowerCamelCase					     = AutoFeatureExtractor.from_pretrained(args.model							)
								elif args.preprocessor == "processor":
												_lowerCamelCase					     = AutoProcessor.from_pretrained(args.model							)
								else:
												raise ValueError(F"""Unknown preprocessor type '{args.preprocessor}'"""							)

								# Ensure the requested opset is sufficient
								if args.opset is None:
												_lowerCamelCase					     = onnx_config.default_onnx_opset

								if args.opset < onnx_config.default_onnx_opset:
												raise ValueError(
												    F"""Opset {args.opset} is not sufficient to export {model_kind}. """
												    F"""At least  {onnx_config.default_onnx_opset} is required."""							)

								_lowerCamelCase     ,   _lowerCamelCase					     = export(
								    lowercase_  ,      lowercase_  ,      lowercase_  ,      args.opset  ,      args.output  ,      )

								if args.atol is None:
												_lowerCamelCase					     = onnx_config.atol_for_validation

								validate_model_outputs(lowercase_  ,      lowercase_  ,      lowercase_  ,      args.output  ,      lowercase_  ,      args.atol							)
								logger.info(F"""All good, model saved at: {args.output.as_posix()}"""							)
								warnings.warn(
								    '''The export was done by transformers.onnx which is deprecated and will be removed in v5. We recommend'''
								    ''' using optimum.exporters.onnx in future. You can find more information here:'''
								    ''' https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model.'''  ,      lowercase_  ,      )



def 				lowerCAmelCase_(      )		->				int:
				_lowerCamelCase					     = ArgumentParser('''Hugging Face Transformers ONNX exporter'''							)
				parser.add_argument(
				    '''-m'''  ,      '''--model'''  ,      type=lowercase_  ,      required=lowercase_  ,      help='''Model ID on huggingface.co or path on disk to load model from.'''							)
				parser.add_argument(
				    '''--feature'''  ,      default='''default'''  ,      help='''The type of features to export the model with.'''  ,      )
				parser.add_argument('''--opset'''  ,      type=lowercase_  ,      default=lowercase_  ,      help='''ONNX opset version to export the model with.'''							)
				parser.add_argument(
				    '''--atol'''  ,      type=lowercase_  ,      default=lowercase_  ,      help='''Absolute difference tolerance when validating the model.'''							)
				parser.add_argument(
				    '''--framework'''  ,      type=lowercase_  ,      choices=['''pt''', '''tf''']  ,      default=lowercase_  ,      help=(
				        '''The framework to use for the ONNX export.'''
				        ''' If not provided, will attempt to use the local checkpoint\'s original framework'''
				        ''' or what is available in the environment.'''
				    )  ,      )
				parser.add_argument('''output'''  ,      type=lowercase_  ,      help='''Path indicating where to store generated ONNX model.'''							)
				parser.add_argument('''--cache_dir'''  ,      type=lowercase_  ,      default=lowercase_  ,      help='''Path indicating where to store cache.'''							)
				parser.add_argument(
				    '''--preprocessor'''  ,      type=lowercase_  ,      choices=['''auto''', '''tokenizer''', '''feature_extractor''', '''image_processor''', '''processor''']  ,      default='''auto'''  ,      help='''Which type of preprocessor to use. \'auto\' tries to automatically detect it.'''  ,      )
				parser.add_argument(
				    '''--export_with_transformers'''  ,      action='''store_true'''  ,      help=(
				        '''Whether to use transformers.onnx instead of optimum.exporters.onnx to perform the ONNX export. It can be '''
				        '''useful when exporting a model supported in transformers but not in optimum, otherwise it is not '''
				        '''recommended.'''
				    )  ,      )

				_lowerCamelCase					     = parser.parse_args()
				if args.export_with_transformers or not is_optimum_available():
								export_with_transformers(lowercase_							)
				else:
								export_with_optimum(lowercase_							)


if __name__ == "__main__":
			__SCREAMING_SNAKE_CASE     :  int										=					logging.get_logger('''transformers.onnx''')  # pylint: disable=invalid-name
			logger.setLevel(logging.INFO)
			main()



from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    get_resize_output_image_size,
    normalize,
    pad,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging
from ...utils.import_utils import is_vision_available


SCREAMING_SNAKE_CASE_						=					logging.get_logger(__name__)


if is_vision_available():
					import PIL

class  a     (		UpperCAmelCase ):
						_lowercase			  =	["pixel_values"]


						def __init__(				self  ,    A_ = True  ,    A_ = None  ,    A_ = PILImageResampling.BILINEAR  ,    A_ = True  ,    A_ = False  ,    A_ = True  ,    A_ = True  ,    A_ = 1 / 255  ,    A_ = True  ,    A_ = None  ,    A_ = None  ,    **A_  ,    ):







										'''simple docstring'''


										super().__init__(**A_		)

										_UpperCAmelCase				:						str       						=			size if size is not None else {"height": 2560, "width": 1920}
										if isinstance(A_  ,    (tuple, list)		):
														# The previous feature extractor size parameter was in (width, height) format
														_UpperCAmelCase				:						List[Any]       						=			size[::-1]
										_UpperCAmelCase				:						Dict       						=			get_size_dict(A_		)

										_UpperCAmelCase				:						int       						=			do_resize
										_UpperCAmelCase				:						Dict       						=			size
										_UpperCAmelCase				:						List[Any]       						=			resample
										_UpperCAmelCase				:						Union[str, Any]       						=			do_thumbnail
										_UpperCAmelCase				:						Optional[int]       						=			do_align_long_axis
										_UpperCAmelCase				:						Optional[Any]       						=			do_pad
										_UpperCAmelCase				:						int       						=			do_rescale
										_UpperCAmelCase				:						List[Any]       						=			rescale_factor
										_UpperCAmelCase				:						Union[str, Any]       						=			do_normalize
										_UpperCAmelCase				:						Any       						=			image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
										_UpperCAmelCase				:						Dict       						=			image_std if image_std is not None else IMAGENET_STANDARD_STD


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_  ,    A_ = None		):







										'''simple docstring'''


										_UpperCAmelCase						,							_UpperCAmelCase				:						List[str]       						=			get_image_size(A_		)
										_UpperCAmelCase						,							_UpperCAmelCase				:						Any       						=			size["height"], size["width"]

										if (output_width < output_height and input_width > input_height) or (
										    output_width > output_height and input_width < input_height
										):
														_UpperCAmelCase				:						Optional[int]       						=			np.rotaa(A_  ,    3		)

										if data_format is not None:
														_UpperCAmelCase				:						List[str]       						=			to_channel_dimension_format(A_  ,    A_		)

										return image


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_  ,    A_ = False  ,    A_ = None  ,    ):







										'''simple docstring'''


										_UpperCAmelCase						,							_UpperCAmelCase				:						Optional[Any]       						=			size["height"], size["width"]
										_UpperCAmelCase						,							_UpperCAmelCase				:						List[Any]       						=			get_image_size(A_		)

										_UpperCAmelCase				:						Optional[Any]       						=			output_width - input_width
										_UpperCAmelCase				:						Any       						=			output_height - input_height

										if random_padding:
														_UpperCAmelCase				:						List[str]       						=			np.random.randint(low=0  ,    high=delta_height + 1		)
														_UpperCAmelCase				:						Optional[int]       						=			np.random.randint(low=0  ,    high=delta_width + 1		)
										else:
														_UpperCAmelCase				:						Union[str, Any]       						=			delta_height // 2
														_UpperCAmelCase				:						str       						=			delta_width // 2

										_UpperCAmelCase				:						Optional[Any]       						=			delta_height - pad_top
										_UpperCAmelCase				:						List[Any]       						=			delta_width - pad_left

										_UpperCAmelCase				:						Optional[Any]       						=			((pad_top, pad_bottom), (pad_left, pad_right))
										return pad(A_  ,    A_  ,    data_format=A_		)


						def 				_UpperCAmelCase (				self  ,    *A_  ,    **A_		):







										'''simple docstring'''


										logger.info("pad is deprecated and will be removed in version 4.27. Please use pad_image instead."		)
										return self.pad_image(*A_  ,    **A_		)


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_  ,    A_ = PILImageResampling.BICUBIC  ,    A_ = None  ,    **A_  ,    ):







										'''simple docstring'''


										_UpperCAmelCase						,							_UpperCAmelCase				:						Union[str, Any]       						=			get_image_size(A_		)
										_UpperCAmelCase						,							_UpperCAmelCase				:						Union[str, Any]       						=			size["height"], size["width"]

										# We always resize to the smallest of either the input or output size.
										_UpperCAmelCase				:						Dict       						=			min(A_  ,    A_		)
										_UpperCAmelCase				:						Tuple       						=			min(A_  ,    A_		)

										if height == input_height and width == input_width:
														return image

										if input_height > input_width:
														_UpperCAmelCase				:						Any       						=			int(input_width * height / input_height		)
										elif input_width > input_height:
														_UpperCAmelCase				:						Any       						=			int(input_height * width / input_width		)

										return resize(
										    A_  ,    size=(height, width)  ,    resample=A_  ,    reducing_gap=2.0  ,    data_format=A_  ,    **A_		)


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_  ,    A_ = PILImageResampling.BICUBIC  ,    A_ = None  ,    **A_  ,    ):







										'''simple docstring'''


										_UpperCAmelCase				:						Any       						=			get_size_dict(A_		)
										_UpperCAmelCase				:						List[str]       						=			min(size["height"]  ,    size["width"]		)
										_UpperCAmelCase				:						Optional[Any]       						=			get_resize_output_image_size(A_  ,    size=A_  ,    default_to_square=A_		)
										_UpperCAmelCase				:						str       						=			resize(A_  ,    size=A_  ,    resample=A_  ,    data_format=A_  ,    **A_		)
										return resized_image


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_  ,    A_ = None  ,    **A_  ,    ):







										'''simple docstring'''


										return rescale(A_  ,    scale=A_  ,    data_format=A_  ,    **A_		)


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_  ,    A_  ,    A_ = None  ,    **A_  ,    ):







										'''simple docstring'''


										return normalize(A_  ,    mean=A_  ,    std=A_  ,    data_format=A_  ,    **A_		)





						def 				_UpperCAmelCase (				self  ,    A_  ,    A_ = None  ,    A_ = None  ,    A_ = None  ,    A_ = None  ,    A_ = None  ,    A_ = None  ,    A_ = False  ,    A_ = None  ,    A_ = None  ,    A_ = None  ,    A_ = None  ,    A_ = None  ,    A_ = None  ,    A_ = ChannelDimension.FIRST  ,    **A_  ,    ):







										'''simple docstring'''


										_UpperCAmelCase				:						str       						=			do_resize if do_resize is not None else self.do_resize
										_UpperCAmelCase				:						str       						=			size if size is not None else self.size
										if isinstance(A_  ,    (tuple, list)		):
														# Previous feature extractor had size in (width, height) format
														_UpperCAmelCase				:						List[Any]       						=			size[::-1]
										_UpperCAmelCase				:						Union[str, Any]       						=			get_size_dict(A_		)
										_UpperCAmelCase				:						Dict       						=			resample if resample is not None else self.resample
										_UpperCAmelCase				:						str       						=			do_thumbnail if do_thumbnail is not None else self.do_thumbnail
										_UpperCAmelCase				:						Optional[Any]       						=			do_align_long_axis if do_align_long_axis is not None else self.do_align_long_axis
										_UpperCAmelCase				:						List[str]       						=			do_pad if do_pad is not None else self.do_pad
										_UpperCAmelCase				:						Optional[Any]       						=			do_rescale if do_rescale is not None else self.do_rescale
										_UpperCAmelCase				:						int       						=			rescale_factor if rescale_factor is not None else self.rescale_factor
										_UpperCAmelCase				:						List[str]       						=			do_normalize if do_normalize is not None else self.do_normalize
										_UpperCAmelCase				:						Any       						=			image_mean if image_mean is not None else self.image_mean
										_UpperCAmelCase				:						List[Any]       						=			image_std if image_std is not None else self.image_std

										_UpperCAmelCase				:						str       						=			make_list_of_images(A_		)

										if not valid_images(A_		):
														raise ValueError(
														    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
														    "torch.Tensor, tf.Tensor or jax.ndarray."		)

										if do_resize and size is None:
														raise ValueError("Size must be specified if do_resize is True."		)

										if do_rescale and rescale_factor is None:
														raise ValueError("Rescale factor must be specified if do_rescale is True."		)

										if do_pad and size is None:
														raise ValueError("Size must be specified if do_pad is True."		)

										if do_normalize and (image_mean is None or image_std is None):
														raise ValueError("Image mean and std must be specified if do_normalize is True."		)

										# All transformations expect numpy arrays.
										_UpperCAmelCase				:						Union[str, Any]       						=			[to_numpy_array(A_		) for image in images]

										if do_align_long_axis:
														_UpperCAmelCase				:						Tuple       						=			[self.align_long_axis(A_  ,    size=A_		) for image in images]

										if do_resize:
														_UpperCAmelCase				:						Optional[int]       						=			[self.resize(image=A_  ,    size=A_  ,    resample=A_		) for image in images]

										if do_thumbnail:
														_UpperCAmelCase				:						Optional[Any]       						=			[self.thumbnail(image=A_  ,    size=A_		) for image in images]

										if do_pad:
														_UpperCAmelCase				:						List[Any]       						=			[self.pad_image(image=A_  ,    size=A_  ,    random_padding=A_		) for image in images]

										if do_rescale:
														_UpperCAmelCase				:						Tuple       						=			[self.rescale(image=A_  ,    scale=A_		) for image in images]

										if do_normalize:
														_UpperCAmelCase				:						int       						=			[self.normalize(image=A_  ,    mean=A_  ,    std=A_		) for image in images]

										_UpperCAmelCase				:						str       						=			[to_channel_dimension_format(A_  ,    A_		) for image in images]

										_UpperCAmelCase				:						Dict       						=			{"pixel_values": images}
										return BatchFeature(data=A_  ,    tensor_type=A_		)


