


'''simple docstring'''
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 				lowerCAmelCase__	(       UpperCAmelCase    ,       UpperCAmelCase=10    ,       UpperCAmelCase=10    ,       UpperCAmelCase=False    ,       UpperCAmelCase=False     ):






       """simple docstring"""





       snake_case__					:	int          =					[]
       for i in range(image_processor_tester.num_frames     ):
              video.append(np.random.randint(255    ,       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
              snake_case__					:	List[Any]          =					[Image.fromarray(np.moveaxis(UpperCAmelCase    ,       0    ,       -1     )     ) for frame in video]

       if torchify:
              snake_case__					:	List[str]          =					[torch.from_numpy(UpperCAmelCase     ) for frame in video]

       return video



def 				lowerCAmelCase__	(       UpperCAmelCase    ,       UpperCAmelCase=False    ,       UpperCAmelCase=False    ,       UpperCAmelCase=False     ):






       """simple docstring"""





       assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

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

       return video_inputs







class 					_A						(						unittest.TestCase							):



   '''simple docstring'''






   def __init__(	self	:					Union[str, Any]					, lowerCamelCase	:					Tuple					, lowerCamelCase	:					int=7					, lowerCamelCase	:					Union[str, Any]=3					, lowerCamelCase	:					List[str]=4					, lowerCamelCase	:					Optional[Any]=18					, lowerCamelCase	:					Any=30					, lowerCamelCase	:					Tuple=400					, lowerCamelCase	:					List[str]=True					, lowerCamelCase	:					Dict=None					, lowerCamelCase	:					List[str]=True					, lowerCamelCase	:					Dict=[0.5, 0.5, 0.5]					, lowerCamelCase	:					int=[0.5, 0.5, 0.5]					, lowerCamelCase	:					Optional[int]=True					, lowerCamelCase	:					Optional[Any]=None					, )->	Optional[int]:
          snake_case__					:	List[str]          =					size if size is not None else {"""shortest_edge""": 18}
          snake_case__					:	List[Any]          =					crop_size if crop_size is not None else {"""height""": 18, """width""": 18}

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




   def   __lowerCAmelCase						(	self	:					Union[str, Any]						)->	Optional[int]:
          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						(						UpperCamelCase    ,  unittest.TestCase							):



   '''simple docstring'''






   _lowercase    						= TvltImageProcessor if is_vision_available() else None




   def   __lowerCAmelCase						(	self	:					str						)->	str:
          snake_case__					:	Union[str, Any]          =					TvltImageProcessorTester(self						)




   @property
   def   __lowerCAmelCase						(	self	:					List[Any]						)->	Optional[int]:
          return self.image_processor_tester.prepare_image_processor_dict()




   def   __lowerCAmelCase						(	self	:					Optional[Any]						)->	Dict:
          snake_case__					:	Any          =					self.image_processing_class(**self.image_processor_dict						)
          self.assertTrue(hasattr(lowerCamelCase					, """image_mean"""						)						)
          self.assertTrue(hasattr(lowerCamelCase					, """image_std"""						)						)
          self.assertTrue(hasattr(lowerCamelCase					, """do_normalize"""						)						)
          self.assertTrue(hasattr(lowerCamelCase					, """do_resize"""						)						)
          self.assertTrue(hasattr(lowerCamelCase					, """do_center_crop"""						)						)
          self.assertTrue(hasattr(lowerCamelCase					, """size"""						)						)




   def   __lowerCAmelCase						(	self	:					str						)->	Union[str, Any]:
          # Initialize image_processor
          snake_case__					:	str          =					self.image_processing_class(**self.image_processor_dict						)
          # create random PIL videos
          snake_case__					:	str          =					prepare_video_inputs(self.image_processor_tester					, equal_resolution=lowerCamelCase						)
          for video in video_inputs:
                 self.assertIsInstance(lowerCamelCase					, lowerCamelCase						)
                 self.assertIsInstance(video[0]					, Image.Image						)

          # Test not batched input
          snake_case__					:	List[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
          snake_case__					:	int          =					image_processor(lowerCamelCase					, 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   __lowerCAmelCase						(	self	:					Dict						)->	int:
          # Initialize image_processor
          snake_case__					:	Union[str, Any]          =					self.image_processing_class(**self.image_processor_dict						)
          # create random numpy tensors
          snake_case__					:	Tuple          =					prepare_video_inputs(self.image_processor_tester					, equal_resolution=lowerCamelCase					, numpify=lowerCamelCase						)
          for video in video_inputs:
                 self.assertIsInstance(lowerCamelCase					, lowerCamelCase						)
                 self.assertIsInstance(video[0]					, np.ndarray						)

          # Test not batched input
          snake_case__					:	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
          snake_case__					:	int          =					image_processor(lowerCamelCase					, 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   __lowerCAmelCase						(	self	:					Optional[Any]						)->	Union[str, Any]:
          # Initialize image_processor
          snake_case__					:	Dict          =					self.image_processing_class(**self.image_processor_dict						)
          # create random PyTorch tensors
          snake_case__					:	Optional[int]          =					prepare_video_inputs(self.image_processor_tester					, equal_resolution=lowerCamelCase					, torchify=lowerCamelCase						)
          for video in video_inputs:
                 self.assertIsInstance(lowerCamelCase					, lowerCamelCase						)
                 self.assertIsInstance(video[0]					, torch.Tensor						)

          # Test not batched input
          snake_case__					:	Tuple          =					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
          snake_case__					:	str          =					image_processor(lowerCamelCase					, 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"""],
              )					, )








'''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


lowerCAmelCase__  =     '1.5.0'

lowerCAmelCase__  =     ['vision-encoder-decoder']



def 				lowerCAmelCase__	(       UpperCAmelCase     ):






       """simple docstring"""





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

              snake_case__					:	Dict          =					version.parse(UpperCAmelCase     )
              if parsed_optimum_version < version.parse(UpperCAmelCase     ):
                     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]"""     )
       snake_case__					:	Union[str, Any]          =					[
           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}""",
       ]
       snake_case__					:	Union[str, Any]          =					subprocess.Popen(""" """.join(UpperCAmelCase     )    ,       stdout=subprocess.PIPE    ,       shell=UpperCAmelCase     )
       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__	(       UpperCAmelCase     ):






       """simple docstring"""





       snake_case__					:	str          =					args.output if args.output.is_file() else args.output.joinpath("""model.onnx"""     )
       if not args.output.parent.exists():
              args.output.parent.mkdir(parents=UpperCAmelCase     )

       # Allocate the model
       snake_case__					:	Dict          =					FeaturesManager.get_model_from_feature(
           args.feature    ,       args.model    ,       framework=args.framework    ,       cache_dir=args.cache_dir     )

       snake_case__       ,   snake_case__					:	List[Any]          =					FeaturesManager.check_supported_model_or_raise(UpperCAmelCase    ,       feature=args.feature     )
       snake_case__					:	Any          =					model_onnx_config(model.config     )

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

              snake_case__					:	Optional[Any]          =					onnx_config.get_encoder_config(encoder_model.config     )
              snake_case__					:	Any          =					onnx_config.get_decoder_config(
                  encoder_model.config    ,       decoder_model.config    ,       feature=args.feature     )

              if args.opset is None:
                     snake_case__					:	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."""     )

              snake_case__					:	Dict          =					AutoFeatureExtractor.from_pretrained(args.model     )

              snake_case__       ,   snake_case__					:	List[str]          =					export(
                  UpperCAmelCase    ,       UpperCAmelCase    ,       UpperCAmelCase    ,       args.opset    ,       args.output.parent.joinpath("""encoder_model.onnx"""     )    ,       )

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

              snake_case__					:	List[Any]          =					AutoTokenizer.from_pretrained(args.model     )

              snake_case__       ,   snake_case__					:	Dict          =					export(
                  UpperCAmelCase    ,       UpperCAmelCase    ,       UpperCAmelCase    ,       args.opset    ,       args.output.parent.joinpath("""decoder_model.onnx"""     )    ,       )

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

              snake_case__       ,   snake_case__					:	Dict          =					export(
                  UpperCAmelCase    ,       UpperCAmelCase    ,       UpperCAmelCase    ,       args.opset    ,       args.output    ,       )

              if args.atol is None:
                     snake_case__					:	int          =					onnx_config.atol_for_validation

              validate_model_outputs(UpperCAmelCase    ,       UpperCAmelCase    ,       UpperCAmelCase    ,       args.output    ,       UpperCAmelCase    ,       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."""    ,       UpperCAmelCase    ,       )



def 				lowerCAmelCase__	(       ):






       """simple docstring"""





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

       snake_case__					:	str          =					parser.parse_args()
       if args.export_with_transformers or not is_optimum_available():
              export_with_transformers(UpperCAmelCase     )
       else:
              export_with_optimum(UpperCAmelCase     )


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




