
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


lowercase_											=	"""1.5.0"""

lowercase_											=	["""vision-encoder-decoder"""]


def     a__			(    snake_case    ):





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

    __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						version.parse(snake_case    )
    if parsed_optimum_version < version.parse(snake_case    ):
      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]'''    )
  __SCREAMING_SNAKE_CASE     :					List[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}''',
  ]
  __SCREAMING_SNAKE_CASE     :					Tuple			=						subprocess.Popen(''' '''.join(snake_case    )   ,	stdout=subprocess.PIPE   ,	shell=snake_case    )
  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__			(    snake_case    ):





  """simple docstring"""
  __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						args.output if args.output.is_file() else args.output.joinpath('''model.onnx'''    )
  if not args.output.parent.exists():
    args.output.parent.mkdir(parents=snake_case    )

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

  __SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE     :					Optional[Any]			=						FeaturesManager.check_supported_model_or_raise(snake_case   ,	feature=args.feature    )
  __SCREAMING_SNAKE_CASE     :					List[str]			=						model_onnx_config(model.config    )

  if model_kind in ENCODER_DECODER_MODELS:
    __SCREAMING_SNAKE_CASE     :					Any			=						model.get_encoder()
    __SCREAMING_SNAKE_CASE     :					Optional[int]			=						model.get_decoder()

    __SCREAMING_SNAKE_CASE     :					str			=						onnx_config.get_encoder_config(encoder_model.config    )
    __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						onnx_config.get_decoder_config(
        encoder_model.config   ,	decoder_model.config   ,	feature=args.feature    )

    if args.opset is None:
      __SCREAMING_SNAKE_CASE     :					List[str]			=						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.'''    )

    __SCREAMING_SNAKE_CASE     :					str			=						AutoFeatureExtractor.from_pretrained(args.model    )

    __SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE     :					Optional[Any]			=						export(
        snake_case   ,	snake_case   ,	snake_case   ,	args.opset   ,	args.output.parent.joinpath('''encoder_model.onnx'''    )   ,	)

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

    __SCREAMING_SNAKE_CASE     :					str			=						AutoTokenizer.from_pretrained(args.model    )

    __SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE     :					List[str]			=						export(
        snake_case   ,	snake_case   ,	snake_case   ,	args.opset   ,	args.output.parent.joinpath('''decoder_model.onnx'''    )   ,	)

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

    __SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE     :					Optional[Any]			=						export(
        snake_case   ,	snake_case   ,	snake_case   ,	args.opset   ,	args.output   ,	)

    if args.atol is None:
      __SCREAMING_SNAKE_CASE     :					Optional[int]			=						onnx_config.atol_for_validation

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


def     a__			(    ):





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

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


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


import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
lowercase_											=	"""src/transformers"""

# Matches is_xxx_available()
lowercase_											=	re.compile(R"""is\_([a-z_]*)_available()""")
# Matches from xxx import bla
lowercase_											=	re.compile(R"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""")
lowercase_											=	re.compile(R"""^\s+if\s+not\s+\(?is\_[a-z_]*\_available\(\)""")


lowercase_											=	"""
{0} = None
"""

lowercase_											=	"""
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
"""


lowercase_											=	"""
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
"""


def     a__			(    snake_case    ):





  """simple docstring"""
  if _re_test_backend.search(snake_case    ) is None:
    return None
  __SCREAMING_SNAKE_CASE     :					Optional[int]			=						[b[0] for b in _re_backend.findall(snake_case    )]
  backends.sort()
  return "_and_".join(snake_case    )


def     a__			(    ):





  """simple docstring"""
  with open(os.path.join(snake_case   ,	'''__init__.py'''    )   ,	'''r'''   ,	encoding='''utf-8'''   ,	newline='''\n'''    ) as f:
    __SCREAMING_SNAKE_CASE     :					Tuple			=						f.readlines()

  # Get to the point we do the actual imports for type checking
  __SCREAMING_SNAKE_CASE     :					Any			=						0
  while not lines[line_index].startswith('''if TYPE_CHECKING'''    ):
    line_index += 1

  __SCREAMING_SNAKE_CASE     :					Tuple			=						{}
  # Go through the end of the file
  while line_index < len(snake_case    ):
    # If the line is an if is_backend_available, we grab all objects associated.
    __SCREAMING_SNAKE_CASE     :					int			=						find_backend(lines[line_index]    )
    if backend is not None:
      while not lines[line_index].startswith('''    else:'''    ):
        line_index += 1
      line_index += 1

      __SCREAMING_SNAKE_CASE     :					Any			=						[]
      # Until we unindent, add backend objects to the list
      while len(lines[line_index]    ) <= 1 or lines[line_index].startswith(''' ''' * 8    ):
        __SCREAMING_SNAKE_CASE     :					Dict			=						lines[line_index]
        __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						_re_single_line_import.search(snake_case    )
        if single_line_import_search is not None:
          objects.extend(single_line_import_search.groups()[0].split(''', '''    )    )
        elif line.startswith(''' ''' * 12    ):
          objects.append(line[12:-2]    )
        line_index += 1

      __SCREAMING_SNAKE_CASE     :					List[str]			=						objects
    else:
      line_index += 1

  return backend_specific_objects


def     a__			(    snake_case   ,	snake_case    ):





  """simple docstring"""
  if name.isupper():
    return DUMMY_CONSTANT.format(snake_case    )
  elif name.islower():
    return DUMMY_FUNCTION.format(snake_case   ,	snake_case    )
  else:
    return DUMMY_CLASS.format(snake_case   ,	snake_case    )


def     a__			(    snake_case=None    ):





  """simple docstring"""
  if backend_specific_objects is None:
    __SCREAMING_SNAKE_CASE     :					List[Any]			=						read_init()
  # For special correspondence backend to module name as used in the function requires_modulename
  __SCREAMING_SNAKE_CASE     :					Optional[int]			=						{}

  for backend, objects in backend_specific_objects.items():
    __SCREAMING_SNAKE_CASE     :					Tuple			=						'''[''' + ''', '''.join(F'''"{b}"''' for b in backend.split('''_and_'''    )    ) + ''']'''
    __SCREAMING_SNAKE_CASE     :					Optional[int]			=						'''# This file is autogenerated by the command `make fix-copies`, do not edit.\n'''
    dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
    dummy_file += "\n".join([create_dummy_object(snake_case   ,	snake_case    ) for o in objects]    )
    __SCREAMING_SNAKE_CASE     :					List[Any]			=						dummy_file

  return dummy_files


def     a__			(    snake_case=False    ):





  """simple docstring"""
  __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						create_dummy_files()
  # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
  __SCREAMING_SNAKE_CASE     :					str			=						{'''torch''': '''pt'''}

  # Locate actual dummy modules and read their content.
  __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						os.path.join(snake_case   ,	'''utils'''    )
  __SCREAMING_SNAKE_CASE     :					List[Any]			=						{
      backend: os.path.join(snake_case   ,	F'''dummy_{short_names.get(snake_case   ,	snake_case    )}_objects.py'''    )
      for backend in dummy_files.keys()
  }

  __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						{}
  for backend, file_path in dummy_file_paths.items():
    if os.path.isfile(snake_case    ):
      with open(snake_case   ,	'''r'''   ,	encoding='''utf-8'''   ,	newline='''\n'''    ) as f:
        __SCREAMING_SNAKE_CASE     :					Optional[Any]			=						f.read()
    else:
      __SCREAMING_SNAKE_CASE     :					Any			=						''''''

  for backend in dummy_files.keys():
    if dummy_files[backend] != actual_dummies[backend]:
      if overwrite:
        print(
            F'''Updating transformers.utils.dummy_{short_names.get(snake_case   ,	snake_case    )}_objects.py as the main '''
            '''__init__ has new objects.'''    )
        with open(dummy_file_paths[backend]   ,	'''w'''   ,	encoding='''utf-8'''   ,	newline='''\n'''    ) as f:
          f.write(dummy_files[backend]    )
      else:
        raise ValueError(
            '''The main __init__ has objects that are not present in '''
            F'''transformers.utils.dummy_{short_names.get(snake_case   ,	snake_case    )}_objects.py. Run `make fix-copies` '''
            '''to fix this.'''    )


if __name__ == "__main__":
   lowercase_											=	argparse.ArgumentParser()
   parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
   lowercase_											=	parser.parse_args()

   check_dummies(args.fix_and_overwrite)
