


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


UpperCAmelCase						:       Optional[Any]        =					"1.5.0"

UpperCAmelCase						:       str        =					["vision-encoder-decoder"]







def 			_SCREAMING_SNAKE_CASE    (       a  )				->				List[Any]:





					if is_optimum_available():
										from optimum.version import __version__ as optimum_version

										__A     :						Dict          =    version.parse(_A  )
										if parsed_optimum_version < version.parse(_A  ):
															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]'  )
					__A     :						List[str]          =    [
					    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}""",
					]
					__A     :						int          =    subprocess.Popen(' '.join(_A  ) ,						stdout=subprocess.PIPE ,						shell=_A  )
					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 			_SCREAMING_SNAKE_CASE    (       a  )				->				Dict:
					__A     :						Dict          =    args.output if args.output.is_file() else args.output.joinpath('model.onnx'  )
					if not args.output.parent.exists():
										args.output.parent.mkdir(parents=_A  )

					# Allocate the model
					__A     :						Optional[int]          =    FeaturesManager.get_model_from_feature(
					    args.feature ,						args.model ,						framework=args.framework ,						cache_dir=args.cache_dir  )

					__A   ,    __A     :						Dict          =    FeaturesManager.check_supported_model_or_raise(_A ,						feature=args.feature  )
					__A     :						Tuple          =    model_onnx_config(model.config  )

					if model_kind in ENCODER_DECODER_MODELS:
										__A     :						Union[str, Any]          =    model.get_encoder()
										__A     :						Any          =    model.get_decoder()

										__A     :						Any          =    onnx_config.get_encoder_config(encoder_model.config  )
										__A     :						Tuple          =    onnx_config.get_decoder_config(
										    encoder_model.config ,						decoder_model.config ,						feature=args.feature  )

										if args.opset is None:
															__A     :						List[Any]          =    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."""  )

										__A     :						List[Any]          =    AutoFeatureExtractor.from_pretrained(args.model  )

										__A   ,    __A     :						Dict          =    export(
										    _A ,						_A ,						_A ,						args.opset ,						args.output.parent.joinpath('encoder_model.onnx'  ) ,						)

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

										__A     :						List[str]          =    AutoTokenizer.from_pretrained(args.model  )

										__A   ,    __A     :						Dict          =    export(
										    _A ,						_A ,						_A ,						args.opset ,						args.output.parent.joinpath('decoder_model.onnx'  ) ,						)

										validate_model_outputs(
										    _A ,						_A ,						_A ,						args.output.parent.joinpath('decoder_model.onnx'  ) ,						_A ,						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":
															__A     :						Optional[Any]          =    get_preprocessor(args.model  )
										elif args.preprocessor == "tokenizer":
															__A     :						Any          =    AutoTokenizer.from_pretrained(args.model  )
										elif args.preprocessor == "image_processor":
															__A     :						Union[str, Any]          =    AutoImageProcessor.from_pretrained(args.model  )
										elif args.preprocessor == "feature_extractor":
															__A     :						List[str]          =    AutoFeatureExtractor.from_pretrained(args.model  )
										elif args.preprocessor == "processor":
															__A     :						Dict          =    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:
															__A     :						List[str]          =    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."""  )

										__A   ,    __A     :						int          =    export(
										    _A ,						_A ,						_A ,						args.opset ,						args.output ,						)

										if args.atol is None:
															__A     :						Optional[Any]          =    onnx_config.atol_for_validation

										validate_model_outputs(_A ,						_A ,						_A ,						args.output ,						_A ,						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.' ,						_A ,						)







def 			_SCREAMING_SNAKE_CASE    (       )				->				int:
					__A     :						str          =    ArgumentParser('Hugging Face Transformers ONNX exporter'  )
					parser.add_argument(
					    '-m' ,						'--model' ,						type=_A ,						required=_A ,						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=_A ,						default=_A ,						help='ONNX opset version to export the model with.'  )
					parser.add_argument(
					    '--atol' ,						type=_A ,						default=_A ,						help='Absolute difference tolerance when validating the model.'  )
					parser.add_argument(
					    '--framework' ,						type=_A ,						choices=['pt', 'tf'] ,						default=_A ,						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=_A ,						help='Path indicating where to store generated ONNX model.'  )
					parser.add_argument('--cache_dir' ,						type=_A ,						default=_A ,						help='Path indicating where to store cache.'  )
					parser.add_argument(
					    '--preprocessor' ,						type=_A ,						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.'
					    ) ,						)

					__A     :						Dict          =    parser.parse_args()
					if args.export_with_transformers or not is_optimum_available():
										export_with_transformers(_A  )
					else:
										export_with_optimum(_A  )


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











import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
				import torch

if is_vision_available():
				from PIL import Image

				from transformers import TvltImageProcessor







def 			_SCREAMING_SNAKE_CASE    (       a ,						a=10 ,						a=10 ,						a=False ,						a=False  )				->				Union[str, Any]:
					__A     :						str          =    []
					for i in range(image_processor_tester.num_frames  ):
										video.append(np.random.randint(2_55 ,						size=(image_processor_tester.num_channels, width, height) ,						dtype=np.uinta  )  )

					if not numpify and not torchify:
										# PIL expects the channel dimension as last dimension
										__A     :						Union[str, Any]          =    [Image.fromarray(np.moveaxis(a ,						0 ,						-1  )  ) for frame in video]

					if torchify:
										__A     :						Dict          =    [torch.from_numpy(a  ) for frame in video]

					return video







def 			_SCREAMING_SNAKE_CASE    (       a ,						a=False ,						a=False ,						a=False  )				->				Union[str, Any]:
					assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

					__A     :						List[Any]          =    []
					for i in range(image_processor_tester.batch_size  ):
										if equal_resolution:
															__A     :						int          =    image_processor_tester.max_resolution
										else:
															__A   ,    __A     :						Tuple          =    np.random.choice(
															    np.arange(image_processor_tester.min_resolution ,						image_processor_tester.max_resolution  ) ,						2  )
															__A     :						Optional[int]          =    prepare_video(
															    image_processor_tester=a ,						width=a ,						height=a ,						numpify=a ,						torchify=a ,						)
										video_inputs.append(a  )

					return video_inputs





class 						_A( unittest.TestCase       ):


				"""simple docstring"""


				def __init__(      self					, _A					, _A=7					, _A=3					, _A=4					, _A=18					, _A=30					, _A=400					, _A=True					, _A=None					, _A=True					, _A=[0.5, 0.5, 0.5]					, _A=[0.5, 0.5, 0.5]					, _A=True					, _A=None					, ):
									__A     :						List[str]          =    size if size is not None else {'shortest_edge': 18}
									__A     :						Tuple          =    crop_size if crop_size is not None else {'height': 18, 'width': 18}

									__A     :						Dict          =    parent
									__A     :						str          =    batch_size
									__A     :						int          =    num_channels
									__A     :						Optional[Any]          =    num_frames
									__A     :						Any          =    image_size
									__A     :						List[str]          =    min_resolution
									__A     :						List[Any]          =    max_resolution
									__A     :						Tuple          =    do_resize
									__A     :						List[str]          =    size
									__A     :						str          =    do_normalize
									__A     :						str          =    image_mean
									__A     :						int          =    image_std
									__A     :						Optional[Any]          =    do_center_crop
									__A     :						Union[str, Any]          =    crop_size





				def  UpperCAmelCase_		(      self					):
									return {
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_normalize": self.do_normalize,
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "do_center_crop": self.do_center_crop,
									    "crop_size": self.crop_size,
									}





@require_torch
@require_vision
class 						_A( snake_case__    ,			unittest.TestCase       ):


				"""simple docstring"""


				UpperCamelCase   :  Optional[Any]    =     TvltImageProcessor if is_vision_available() else None



				def  UpperCAmelCase_		(      self					):
									__A     :						str          =    TvltImageProcessorTester(self					)



				@property
				def  UpperCAmelCase_		(      self					):
									return self.image_processor_tester.prepare_image_processor_dict()



				def  UpperCAmelCase_		(      self					):
									__A     :						Union[str, Any]          =    self.image_processing_class(**self.image_processor_dict					)
									self.assertTrue(hasattr(_A					, 'image_mean'					)					)
									self.assertTrue(hasattr(_A					, 'image_std'					)					)
									self.assertTrue(hasattr(_A					, 'do_normalize'					)					)
									self.assertTrue(hasattr(_A					, 'do_resize'					)					)
									self.assertTrue(hasattr(_A					, 'do_center_crop'					)					)
									self.assertTrue(hasattr(_A					, 'size'					)					)



				def  UpperCAmelCase_		(      self					):
									# Initialize image_processor
									__A     :						List[str]          =    self.image_processing_class(**self.image_processor_dict					)
									# create random PIL videos
									__A     :						List[str]          =    prepare_video_inputs(self.image_processor_tester					, equal_resolution=_A					)
									for video in video_inputs:
														self.assertIsInstance(_A					, _A					)
														self.assertIsInstance(video[0]					, Image.Image					)

									# Test not batched input
									__A     :						str          =    image_processor(video_inputs[0]					, return_tensors='pt'					).pixel_values
									self.assertEqual(
									    encoded_videos.shape					, (
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['height'],
									        self.image_processor_tester.crop_size['width'],
									    )					, )

									# Test batched
									__A     :						List[Any]          =    image_processor(_A					, return_tensors='pt'					).pixel_values
									self.assertEqual(
									    encoded_videos.shape					, (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['height'],
									        self.image_processor_tester.crop_size['width'],
									    )					, )



				def  UpperCAmelCase_		(      self					):
									# Initialize image_processor
									__A     :						Any          =    self.image_processing_class(**self.image_processor_dict					)
									# create random numpy tensors
									__A     :						Dict          =    prepare_video_inputs(self.image_processor_tester					, equal_resolution=_A					, numpify=_A					)
									for video in video_inputs:
														self.assertIsInstance(_A					, _A					)
														self.assertIsInstance(video[0]					, np.ndarray					)

									# Test not batched input
									__A     :						Dict          =    image_processor(video_inputs[0]					, return_tensors='pt'					).pixel_values
									self.assertEqual(
									    encoded_videos.shape					, (
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['height'],
									        self.image_processor_tester.crop_size['width'],
									    )					, )

									# Test batched
									__A     :						Optional[int]          =    image_processor(_A					, return_tensors='pt'					).pixel_values
									self.assertEqual(
									    encoded_videos.shape					, (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['height'],
									        self.image_processor_tester.crop_size['width'],
									    )					, )





				def  UpperCAmelCase_		(      self					):
									# Initialize image_processor
									__A     :						Any          =    self.image_processing_class(**self.image_processor_dict					)
									# create random PyTorch tensors
									__A     :						Dict          =    prepare_video_inputs(self.image_processor_tester					, equal_resolution=_A					, torchify=_A					)
									for video in video_inputs:
														self.assertIsInstance(_A					, _A					)
														self.assertIsInstance(video[0]					, torch.Tensor					)

									# Test not batched input
									__A     :						Optional[Any]          =    image_processor(video_inputs[0]					, return_tensors='pt'					).pixel_values
									self.assertEqual(
									    encoded_videos.shape					, (
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['height'],
									        self.image_processor_tester.crop_size['width'],
									    )					, )

									# Test batched
									__A     :						int          =    image_processor(_A					, return_tensors='pt'					).pixel_values
									self.assertEqual(
									    encoded_videos.shape					, (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['height'],
									        self.image_processor_tester.crop_size['width'],
									    )					, )




