






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


_UpperCamelCase   :						Optional[int]     						= """1.5.0"""

_UpperCamelCase   :						Optional[Any]     						= ["""vision-encoder-decoder"""]




def 				a (     UpperCamelCase_							:				List[Any]		)  ->		List[str]:
 if is_optimum_available():
  from optimum.version import __version__ as optimum_version

  __A	:       List[Any]       =	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]'		)
 __A	:       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(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 				a (     UpperCamelCase_							:				int		)  ->		Optional[Any]:
 __A	:       List[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=UpperCamelCase_		)

 # Allocate the model
 __A	:       Union[str, Any]       =	FeaturesManager.get_model_from_feature(
     args.feature     ,	args.model     ,	framework=args.framework     ,	cache_dir=args.cache_dir		)

 __A    ,					__A	:       Tuple       =	FeaturesManager.check_supported_model_or_raise(UpperCamelCase_     ,	feature=args.feature		)
 __A	:       Any       =	model_onnx_config(model.config		)

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

  __A	:       Tuple       =	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[str]       =	AutoFeatureExtractor.from_pretrained(args.model		)

  __A    ,					__A	:       Optional[int]       =	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     ,	)

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

  __A    ,					__A	:       Any       =	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":
   __A	:       int       =	get_preprocessor(args.model		)
  elif args.preprocessor == "tokenizer":
   __A	:       Any       =	AutoTokenizer.from_pretrained(args.model		)
  elif args.preprocessor == "image_processor":
   __A	:       int       =	AutoImageProcessor.from_pretrained(args.model		)
  elif args.preprocessor == "feature_extractor":
   __A	:       Union[str, Any]       =	AutoFeatureExtractor.from_pretrained(args.model		)
  elif args.preprocessor == "processor":
   __A	:       List[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:
   __A	:       int       =	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	:       Union[str, Any]       =	export(
      UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	args.opset     ,	args.output     ,	)

  if args.atol is None:
   __A	:       Any       =	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 				a (     )  ->		Optional[int]:
 __A	:       Dict       =	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.'
     )     ,	)

 __A	:       Optional[Any]       =	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__":
   _UpperCamelCase   :						List[Any]     						= logging.get_logger("""transformers.onnx""")  # pylint: disable=invalid-name
   logger.setLevel(logging.INFO)
   main()













"""simple docstring"""


import csv
import json
import os

import datasets


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_UpperCamelCase   :						List[Any]     						= """\
@InProceedings{huggingface:dataset,
title = {A great new dataset},
author={huggingface, Inc.
},
year={2020}
}
"""

# TODO: Add description of the dataset here
# You can copy an official description
_UpperCamelCase   :						Any     						= """\
This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
"""

# TODO: Add a link to an official homepage for the dataset here
_UpperCamelCase   :						Dict     						= """"""

# TODO: Add the licence for the dataset here if you can find it
_UpperCamelCase   :						Tuple     						= """"""

# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_UpperCamelCase   :						str     						= {
    """first_domain""": """https://huggingface.co/great-new-dataset-first_domain.zip""",
    """second_domain""": """https://huggingface.co/great-new-dataset-second_domain.zip""",
}






class __a   (   datasets.GeneratorBasedBuilder				):
  __lowercase    :    int						=					datasets.Version('1.1.0'				)

  # This is an example of a dataset with multiple configurations.
  # If you don't want/need to define several sub-sets in your dataset,
  # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

  # If you need to make complex sub-parts in the datasets with configurable options
  # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
  # BUILDER_CONFIG_CLASS = MyBuilderConfig

  # You will be able to load one or the other configurations in the following list with
  # data = datasets.load_dataset('my_dataset', 'first_domain')
  # data = datasets.load_dataset('my_dataset', 'second_domain')
  __lowercase    :    Optional[Any]						=					[
      datasets.BuilderConfig(name='first_domain' ,version=snake_case_ ,description='This part of my dataset covers a first domain'				),
      datasets.BuilderConfig(name='second_domain' ,version=snake_case_ ,description='This part of my dataset covers a second domain'				),
  ]

  __lowercase    :    Any						=					'first_domain'  # It's not mandatory to have a default configuration. Just use one if it make sense.



  def 						A_				(self  :		Optional[Any]   )		->							List[Any]:
   # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
   if self.config.name == "first_domain":  # This is the name of the configuration selected in BUILDER_CONFIGS above
    __A	:       Dict       =	datasets.Features(
        {
            'sentence': datasets.Value('string'   ),
            'option1': datasets.Value('string'   ),
            'answer': datasets.Value('string'   )
            # These are the features of your dataset like images, labels ...
        }   )
   else:  # This is an example to show how to have different features for "first_domain" and "second_domain"
    __A	:       Optional[int]       =	datasets.Features(
        {
            'sentence': datasets.Value('string'   ),
            'option2': datasets.Value('string'   ),
            'second_domain_answer': datasets.Value('string'   )
            # These are the features of your dataset like images, labels ...
        }   )
   return datasets.DatasetInfo(
       # This is the description that will appear on the datasets page.
       description=_DESCRIPTION				,			features=lowercase_				,			homepage=_HOMEPAGE				,			license=_LICENSE				,			citation=_CITATION				,			)



  def 						A_				(self  :		Dict				,			lowercase_  :		Union[str, Any]   )		->							Union[str, Any]:
   # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
   # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name

   # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
   # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
   # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
   __A	:       Optional[int]       =	_URLS[self.config.name]
   __A	:       Any       =	dl_manager.download_and_extract(lowercase_   )
   return [
       datasets.SplitGenerator(
           name=datasets.Split.TRAIN				,			gen_kwargs={
               'filepath': os.path.join(lowercase_				,			'train.jsonl'   ),
               'split': 'train',
           }				,			),
       datasets.SplitGenerator(
           name=datasets.Split.VALIDATION				,			gen_kwargs={
               'filepath': os.path.join(lowercase_				,			'dev.jsonl'   ),
               'split': 'dev',
           }				,			),
       datasets.SplitGenerator(
           name=datasets.Split.TEST				,			gen_kwargs={
               'filepath': os.path.join(lowercase_				,			'test.jsonl'   ),
               'split': 'test'
           }				,			),
   ]



  def 						A_				(self  :		Tuple				,			lowercase_  :		Dict				,			lowercase_  :		Optional[Any]   )		->							Tuple:
   # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
   # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
   with open(lowercase_				,			encoding='utf-8'   ) as f:
    for key, row in enumerate(lowercase_   ):
     __A	:       int       =	json.loads(lowercase_   )
     if self.config.name == "first_domain":
      # Yields examples as (key, example) tuples
      yield key, {
          "sentence": data["sentence"],
          "option1": data["option1"],
          "answer": "" if split == "test" else data["answer"],
      }
     else:
      yield key, {
          "sentence": data["sentence"],
          "option2": data["option2"],
          "second_domain_answer": "" if split == "test" else data["second_domain_answer"],
      }





