
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      :					Union[str, Any]   	=       '1.5.0'

__lowerCAmelCase      :					int   	=       ['vision-encoder-decoder']

def a__   (	A_ ):






  '''simple docstring'''





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

    __magic_name__    					=	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]""" )
  __magic_name__    					=	[
      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}''',
  ]
  __magic_name__    					=	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 a__   (	A_ ):






  '''simple docstring'''





  __magic_name__    					=	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
  __magic_name__    					=	FeaturesManager.get_model_from_feature(
      args.feature,					args.model,					framework=args.framework,					cache_dir=args.cache_dir )

  __magic_name__					,   __magic_name__    					=	FeaturesManager.check_supported_model_or_raise(A_,					feature=args.feature )
  __magic_name__    					=	model_onnx_config(model.config )

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

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

    if args.opset is None:
      __magic_name__    					=	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.''' )

    __magic_name__    					=	AutoFeatureExtractor.from_pretrained(args.model )

    __magic_name__					,   __magic_name__    					=	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,					)

    __magic_name__    					=	AutoTokenizer.from_pretrained(args.model )

    __magic_name__					,   __magic_name__    					=	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":
      __magic_name__    					=	get_preprocessor(args.model )
    elif args.preprocessor == "tokenizer":
      __magic_name__    					=	AutoTokenizer.from_pretrained(args.model )
    elif args.preprocessor == "image_processor":
      __magic_name__    					=	AutoImageProcessor.from_pretrained(args.model )
    elif args.preprocessor == "feature_extractor":
      __magic_name__    					=	AutoFeatureExtractor.from_pretrained(args.model )
    elif args.preprocessor == "processor":
      __magic_name__    					=	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:
      __magic_name__    					=	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.''' )

    __magic_name__					,   __magic_name__    					=	export(
        A_,					A_,					A_,					args.opset,					args.output,					)

    if args.atol is None:
      __magic_name__    					=	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 a__   (	):






  '''simple docstring'''





  __magic_name__    					=	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."""
      ),					)

  __magic_name__    					=	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__":
   __lowerCAmelCase      :					Union[str, Any]   	=       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 normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


__lowerCAmelCase      :					str   	=       logging.get_logger(__name__)




class 	UpperCAmelCase_      (			_A					):


  '''simple docstring'''







  a__   	=		["""pixel_values"""]
  def __init__(			self      :			Tuple      ,							UpperCamelCase__      :			bool = True      ,							UpperCamelCase__      :			Optional[Dict[str, int]] = None      ,							UpperCamelCase__      :			PILImageResampling = PILImageResampling.BILINEAR      ,							UpperCamelCase__      :			bool = True      ,							UpperCamelCase__      :			Union[int, float] = 1 / 255      ,							UpperCamelCase__      :			bool = True      ,							UpperCamelCase__      :			Optional[Union[float, List[float]]] = None      ,							UpperCamelCase__      :			Optional[Union[float, List[float]]] = None      ,							**UpperCamelCase__      :			Optional[Any]      ,							)      ->     None:







    """simple docstring"""






    super().__init__(**UpperCamelCase__   )
    __magic_name__    					=	size if size is not None else {"""height""": 224, """width""": 224}
    __magic_name__    					=	get_size_dict(UpperCamelCase__   )
    __magic_name__    					=	do_resize
    __magic_name__    					=	do_rescale
    __magic_name__    					=	do_normalize
    __magic_name__    					=	size
    __magic_name__    					=	resample
    __magic_name__    					=	rescale_factor
    __magic_name__    					=	image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
    __magic_name__    					=	image_std if image_std is not None else IMAGENET_STANDARD_STD
  def 							_lowercase							(			self      :			Optional[Any]      ,							UpperCamelCase__      :			np.ndarray      ,							UpperCamelCase__      :			Dict[str, int]      ,							UpperCamelCase__      :			PILImageResampling = PILImageResampling.BILINEAR      ,							UpperCamelCase__      :			Optional[Union[str, ChannelDimension]] = None      ,							**UpperCamelCase__      :			Optional[int]      ,							)      ->     np.ndarray:







    """simple docstring"""






    __magic_name__    					=	get_size_dict(UpperCamelCase__   )
    if "height" not in size or "width" not in size:
      raise ValueError(F'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}'''   )
    return resize(
        UpperCamelCase__      ,							size=(size["""height"""], size["""width"""])      ,							resample=UpperCamelCase__      ,							data_format=UpperCamelCase__      ,							**UpperCamelCase__   )
  def 							_lowercase							(			self      :			Tuple      ,							UpperCamelCase__      :			np.ndarray      ,							UpperCamelCase__      :			float      ,							UpperCamelCase__      :			Optional[Union[str, ChannelDimension]] = None      ,							**UpperCamelCase__      :			Union[str, Any]   )      ->     np.ndarray:







    """simple docstring"""






    return rescale(UpperCamelCase__      ,							scale=UpperCamelCase__      ,							data_format=UpperCamelCase__      ,							**UpperCamelCase__   )
  def 							_lowercase							(			self      :			List[str]      ,							UpperCamelCase__      :			np.ndarray      ,							UpperCamelCase__      :			Union[float, List[float]]      ,							UpperCamelCase__      :			Union[float, List[float]]      ,							UpperCamelCase__      :			Optional[Union[str, ChannelDimension]] = None      ,							**UpperCamelCase__      :			Union[str, Any]      ,							)      ->     np.ndarray:







    """simple docstring"""






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





  def 							_lowercase							(			self      :			Tuple      ,							UpperCamelCase__      :			ImageInput      ,							UpperCamelCase__      :			Optional[bool] = None      ,							UpperCamelCase__      :			Dict[str, int] = None      ,							UpperCamelCase__      :			PILImageResampling = None      ,							UpperCamelCase__      :			Optional[bool] = None      ,							UpperCamelCase__      :			Optional[float] = None      ,							UpperCamelCase__      :			Optional[bool] = None      ,							UpperCamelCase__      :			Optional[Union[float, List[float]]] = None      ,							UpperCamelCase__      :			Optional[Union[float, List[float]]] = None      ,							UpperCamelCase__      :			Optional[Union[str, TensorType]] = None      ,							UpperCamelCase__      :			Union[str, ChannelDimension] = ChannelDimension.FIRST      ,							**UpperCamelCase__      :			List[str]      ,							)      ->     Optional[int]:







    """simple docstring"""






    __magic_name__    					=	do_resize if do_resize is not None else self.do_resize
    __magic_name__    					=	do_rescale if do_rescale is not None else self.do_rescale
    __magic_name__    					=	do_normalize if do_normalize is not None else self.do_normalize
    __magic_name__    					=	resample if resample is not None else self.resample
    __magic_name__    					=	rescale_factor if rescale_factor is not None else self.rescale_factor
    __magic_name__    					=	image_mean if image_mean is not None else self.image_mean
    __magic_name__    					=	image_std if image_std is not None else self.image_std

    __magic_name__    					=	size if size is not None else self.size
    __magic_name__    					=	get_size_dict(UpperCamelCase__   )

    __magic_name__    					=	make_list_of_images(UpperCamelCase__   )

    if not valid_images(UpperCamelCase__   ):
      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."""   )

    # All transformations expect numpy arrays.
    __magic_name__    					=	[to_numpy_array(UpperCamelCase__   ) for image in images]

    if do_resize:
      __magic_name__    					=	[self.resize(image=UpperCamelCase__      ,							size=UpperCamelCase__      ,							resample=UpperCamelCase__   ) for image in images]

    if do_rescale:
      __magic_name__    					=	[self.rescale(image=UpperCamelCase__      ,							scale=UpperCamelCase__   ) for image in images]

    if do_normalize:
      __magic_name__    					=	[self.normalize(image=UpperCamelCase__      ,							mean=UpperCamelCase__      ,							std=UpperCamelCase__   ) for image in images]

    __magic_name__    					=	[to_channel_dimension_format(UpperCamelCase__      ,							UpperCamelCase__   ) for image in images]

    __magic_name__    					=	{"""pixel_values""": images}
    return BatchFeature(data=UpperCamelCase__      ,							tensor_type=UpperCamelCase__   )

