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


_a   :      Optional[Any]       =				"""1.5.0"""

_a   :      Optional[Any]       =				["""vision-encoder-decoder"""]
def 					a__ ( a :					Any		):

  """simple docstring"""







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

    _snake_case  :    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]"		)
  _snake_case  :    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}',
  ]
  _snake_case  :    str            = 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 :					Dict		):

  """simple docstring"""







  _snake_case  :    Tuple            = 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
  _snake_case  :    Optional[Any]            = FeaturesManager.get_model_from_feature(
      args.feature							,  args.model							,  framework=args.framework							,  cache_dir=args.cache_dir		)

  _snake_case      ,       _snake_case  :    Optional[Any]            = FeaturesManager.check_supported_model_or_raise(a							,  feature=args.feature		)
  _snake_case  :    Union[str, Any]            = model_onnx_config(model.config		)

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

    _snake_case  :    Any            = onnx_config.get_encoder_config(encoder_model.config		)
    _snake_case  :    str            = onnx_config.get_decoder_config(
        encoder_model.config							,  decoder_model.config							,  feature=args.feature		)

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

    _snake_case  :    Any            = AutoFeatureExtractor.from_pretrained(args.model		)

    _snake_case      ,       _snake_case  :    str            = 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							,  )

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

    _snake_case      ,       _snake_case  :    List[Any]            = 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":
      _snake_case  :    int            = get_preprocessor(args.model		)
    elif args.preprocessor == "tokenizer":
      _snake_case  :    str            = AutoTokenizer.from_pretrained(args.model		)
    elif args.preprocessor == "image_processor":
      _snake_case  :    Dict            = AutoImageProcessor.from_pretrained(args.model		)
    elif args.preprocessor == "feature_extractor":
      _snake_case  :    Optional[Any]            = 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  :    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.'		)

    _snake_case      ,       _snake_case  :    Tuple            = export(
        a							,  a							,  a							,  args.opset							,  args.output							,  )

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

  """simple docstring"""







  _snake_case  :    List[Any]            = 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."
      )							,  )

  _snake_case  :    str            = 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__":
    _a   :      int       =				logging.get_logger("""transformers.onnx""")  # pylint: disable=invalid-name
    logger.setLevel(logging.INFO)
    main()



"""simple docstring"""
import unittest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    SummarizationPipeline,
    TFPreTrainedModel,
    pipeline,
)
from transformers.testing_utils import get_gpu_count, is_pipeline_test, require_tf, require_torch, slow, torch_device
from transformers.tokenization_utils import TruncationStrategy

from .test_pipelines_common import ANY


_a   :      List[Any]       =				-1 if torch_device == """cpu""" else 0






@is_pipeline_test
class   _UpperCAmelCase					(       unittest.TestCase):
    __lowercase				:			List[str]	=       MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
    __lowercase				:			str	=       TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_  ):
      _snake_case  :    int            = SummarizationPipeline(model=snake_case_    ,     tokenizer=snake_case_  )
      return summarizer, ["(CNN)The Palestinian Authority officially became", "Some other text"]
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_  ):
      _snake_case  :    str            = summarizer.model

      _snake_case  :    Optional[int]            = summarizer("(CNN)The Palestinian Authority officially became"  )
      self.assertEqual(snake_case_    ,     [{"summary_text": ANY(snake_case_  )}]  )

      _snake_case  :    List[str]            = summarizer(
          "(CNN)The Palestinian Authority officially became "    ,     num_beams=2    ,     min_length=2    ,     max_length=5    ,     )
      self.assertEqual(snake_case_    ,     [{"summary_text": ANY(snake_case_  )}]  )

      # Some models (Switch Transformers, LED, T5, LongT5, etc) can handle long sequences.
      _snake_case  :    Tuple            = [
          "SwitchTransformersConfig",
          "T5Config",
          "LongT5Config",
          "LEDConfig",
          "PegasusXConfig",
          "FSMTConfig",
          "M2M100Config",
          "ProphetNetConfig",  # positional embeddings up to a fixed maximum size (otherwise clamping the values)
      ]
      if model.config.__class__.__name__ not in model_can_handle_longer_seq:
        # Too long and exception is expected.
        # For TF models, if the weights are initialized in GPU context, we won't get expected index error from
        # the embedding layer.
        if not (
            isinstance(snake_case_    ,     snake_case_  )
            and get_gpu_count() > 0
            and len(summarizer.model.trainable_weights  ) > 0
        ):
          with self.assertRaises(snake_case_  ):
            _snake_case  :    Tuple            = summarizer("This " * 10_00  )
      _snake_case  :    Any            = summarizer("This " * 10_00    ,     truncation=TruncationStrategy.ONLY_FIRST  )
    @require_torch
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[Any]            = pipeline(task="summarization"    ,     model="sshleifer/tiny-mbart"    ,     framework="pt"  )
      _snake_case  :    List[Any]            = summarizer("This is a small test"  )
      self.assertEqual(
          snake_case_    ,     [
              {
                  "summary_text": "เข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไป"
              }
          ]    ,     )
    @require_tf
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Dict            = pipeline(task="summarization"    ,     model="sshleifer/tiny-mbart"    ,     framework="tf"  )
      _snake_case  :    Union[str, Any]            = summarizer("This is a small test"  )
      self.assertEqual(
          snake_case_    ,     [
              {
                  "summary_text": "เข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไป"
              }
          ]    ,     )


    @require_torch
    @slow
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Tuple            = pipeline(task="summarization"    ,     device=snake_case_  )
      _snake_case  :    Any            = (
          " (CNN)The Palestinian Authority officially became the 123rd member of the International Criminal Court on"
          " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The"
          " formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based."
          " The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted its"
          " jurisdiction over alleged crimes committed \"in the occupied Palestinian territory, including East"
          " Jerusalem, since June 13, 2014.\" Later that month, the ICC opened a preliminary examination into the"
          " situation in Palestinian territories, paving the way for possible war crimes investigations against"
          " Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and"
          " the United States, neither of which is an ICC member, opposed the Palestinians' efforts to join the"
          " body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony, said it was a"
          " move toward greater justice. \"As Palestine formally becomes a State Party to the Rome Statute today, the"
          " world is also a step closer to ending a long era of impunity and injustice,\" he said, according to an"
          " ICC news release. \"Indeed, today brings us closer to our shared goals of justice and peace.\" Judge"
          " Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the"
          " Palestinians. \"As the Rome Statute today enters into force for the State of Palestine, Palestine"
          " acquires all the rights as well as responsibilities that come with being a State Party to the Statute."
          " These are substantive commitments, which cannot be taken lightly,\" she said. Rights group Human Rights"
          " Watch welcomed the development. \"Governments seeking to penalize Palestine for joining the ICC should"
          " immediately end their pressure, and countries that support universal acceptance of the court's treaty"
          " should speak out to welcome its membership,\" said Balkees Jarrah, international justice counsel for the"
          " group. \"What's objectionable is the attempts to undermine international justice, not Palestine's"
          " decision to join a treaty to which over 100 countries around the world are members.\" In January, when"
          " the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an"
          " outrage, saying the court was overstepping its boundaries. The United States also said it \"strongly\""
          " disagreed with the court's decision. \"As we have said repeatedly, we do not believe that Palestine is a"
          " state and therefore we do not believe that it is eligible to join the ICC,\" the State Department said in"
          " a statement. It urged the warring sides to resolve their differences through direct negotiations. \"We"
          " will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,\""
          " it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the"
          " territories as \"Palestine.\" While a preliminary examination is not a formal investigation, it allows the"
          " court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou"
          " Bensouda said her office would \"conduct its analysis in full independence and impartiality.\" The war"
          " between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry"
          " will include alleged war crimes committed since June. The International Criminal Court was set up in"
          " 2002 to prosecute genocide, crimes against humanity and war crimes. CNN's Vasco Cotovio, Kareem Khadder"
          " and Faith Karimi contributed to this report."
      )
      _snake_case  :    int            = (
          " The Palestinian Authority becomes the 123rd member of the International Criminal Court . The move gives"
          " the court jurisdiction over alleged crimes in Palestinian territories . Israel and the United States"
          " opposed the Palestinians' efforts to join the court . Rights group Human Rights Watch welcomes the move,"
          " says governments seeking to penalize Palestine should end pressure ."
      )
      _snake_case  :    Union[str, Any]            = summarizer(snake_case_  )
      self.assertEqual(result[0]["summary_text"]    ,     snake_case_  )

