

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__					: int								=      "1.5.0"

UpperCamelCase__					: Any								=      ["vision-encoder-decoder"]


def    _UpperCAmelCase    (					_SCREAMING_SNAKE_CASE   :						Tuple    ):





    """simple docstring"""


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

        SCREAMING_SNAKE_CASE_													=  version.parse(_SCREAMING_SNAKE_CASE    )
        if parsed_optimum_version < version.parse(_SCREAMING_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_													=  [
        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_													=  subprocess.Popen(' '.join(_SCREAMING_SNAKE_CASE    )	,				stdout=subprocess.PIPE	,				shell=_SCREAMING_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    _UpperCAmelCase    (					_SCREAMING_SNAKE_CASE   :						Optional[int]    ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_													=  args.output if args.output.is_file() else args.output.joinpath('model.onnx'    )
    if not args.output.parent.exists():
        args.output.parent.mkdir(parents=_SCREAMING_SNAKE_CASE    )

    # Allocate the model
    SCREAMING_SNAKE_CASE_													=  FeaturesManager.get_model_from_feature(
        args.feature	,				args.model	,				framework=args.framework	,				cache_dir=args.cache_dir    )

    SCREAMING_SNAKE_CASE_							,     SCREAMING_SNAKE_CASE_													=  FeaturesManager.check_supported_model_or_raise(_SCREAMING_SNAKE_CASE	,				feature=args.feature    )
    SCREAMING_SNAKE_CASE_													=  model_onnx_config(model.config    )

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

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

        if args.opset is None:
            SCREAMING_SNAKE_CASE_													=  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_													=  AutoFeatureExtractor.from_pretrained(args.model    )

        SCREAMING_SNAKE_CASE_							,     SCREAMING_SNAKE_CASE_													=  export(
            _SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				args.opset	,				args.output.parent.joinpath('encoder_model.onnx'    )	,				)

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

        SCREAMING_SNAKE_CASE_													=  AutoTokenizer.from_pretrained(args.model    )

        SCREAMING_SNAKE_CASE_							,     SCREAMING_SNAKE_CASE_													=  export(
            _SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				args.opset	,				args.output.parent.joinpath('decoder_model.onnx'    )	,				)

        validate_model_outputs(
            _SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				args.output.parent.joinpath('decoder_model.onnx'    )	,				_SCREAMING_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_													=  get_preprocessor(args.model    )
        elif args.preprocessor == "tokenizer":
            SCREAMING_SNAKE_CASE_													=  AutoTokenizer.from_pretrained(args.model    )
        elif args.preprocessor == "image_processor":
            SCREAMING_SNAKE_CASE_													=  AutoImageProcessor.from_pretrained(args.model    )
        elif args.preprocessor == "feature_extractor":
            SCREAMING_SNAKE_CASE_													=  AutoFeatureExtractor.from_pretrained(args.model    )
        elif args.preprocessor == "processor":
            SCREAMING_SNAKE_CASE_													=  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_													=  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_													=  export(
            _SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				_SCREAMING_SNAKE_CASE	,				args.opset	,				args.output	,				)

        if args.atol is None:
            SCREAMING_SNAKE_CASE_													=  onnx_config.atol_for_validation

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


def    _UpperCAmelCase    (					):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_													=  ArgumentParser('Hugging Face Transformers ONNX exporter'    )
    parser.add_argument(
        '-m'	,				'--model'	,				type=_SCREAMING_SNAKE_CASE	,				required=_SCREAMING_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=_SCREAMING_SNAKE_CASE	,				default=_SCREAMING_SNAKE_CASE	,				help='ONNX opset version to export the model with.'    )
    parser.add_argument(
        '--atol'	,				type=_SCREAMING_SNAKE_CASE	,				default=_SCREAMING_SNAKE_CASE	,				help='Absolute difference tolerance when validating the model.'    )
    parser.add_argument(
        '--framework'	,				type=_SCREAMING_SNAKE_CASE	,				choices=['pt', 'tf']	,				default=_SCREAMING_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=_SCREAMING_SNAKE_CASE	,				help='Path indicating where to store generated ONNX model.'    )
    parser.add_argument('--cache_dir'	,				type=_SCREAMING_SNAKE_CASE	,				default=_SCREAMING_SNAKE_CASE	,				help='Path indicating where to store cache.'    )
    parser.add_argument(
        '--preprocessor'	,				type=_SCREAMING_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_													=  parser.parse_args()
    if args.export_with_transformers or not is_optimum_available():
        export_with_transformers(_SCREAMING_SNAKE_CASE    )
    else:
        export_with_optimum(_SCREAMING_SNAKE_CASE    )


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





import functools
from contextlib import contextmanager

import bert_score
from packaging import version

import datasets


@contextmanager
def    _UpperCAmelCase    (					):





    """simple docstring"""


    def filter_log(_SCREAMING_SNAKE_CASE   :						Dict    ):
        return False if "This IS expected if you are initializing" in record.msg else True

    SCREAMING_SNAKE_CASE_													=  datasets.utils.logging.get_logger('transformers.modeling_utils'    )
    logger.addFilter(_SCREAMING_SNAKE_CASE    )
    try:
        yield
    finally:
        logger.removeFilter(_SCREAMING_SNAKE_CASE    )


UpperCamelCase__					: List[str]								=      "\\n@inproceedings{bert-score,\n  title={BERTScore: Evaluating Text Generation with BERT},\n  author={Tianyi Zhang* and Varsha Kishore* and Felix Wu* and Kilian Q. Weinberger and Yoav Artzi},\n  booktitle={International Conference on Learning Representations},\n  year={2020},\n  url={https://openreview.net/forum?id=SkeHuCVFDr}\n}\n"

UpperCamelCase__					: Dict								=      "\\nBERTScore leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference\nsentences by cosine similarity.\nIt has been shown to correlate with human judgment on sentence-level and system-level evaluation.\nMoreover, BERTScore computes precision, recall, and F1 measure, which can be useful for evaluating different language\ngeneration tasks.\n\nSee the project's README at https://github.com/Tiiiger/bert_score#readme for more information.\n"

UpperCamelCase__					: Dict								=      "\nBERTScore Metrics with the hashcode from a source against one or more references.\n\nArgs:\n    predictions (list of str): Prediction/candidate sentences.\n    references (list of str or list of list of str): Reference sentences.\n    lang (str): Language of the sentences; required (e.g. 'en').\n    model_type (str): Bert specification, default using the suggested\n        model for the target language; has to specify at least one of\n        `model_type` or `lang`.\n    num_layers (int): The layer of representation to use,\n        default using the number of layers tuned on WMT16 correlation data.\n    verbose (bool): Turn on intermediate status update.\n    idf (bool or dict): Use idf weighting; can also be a precomputed idf_dict.\n    device (str): On which the contextual embedding model will be allocated on.\n        If this argument is None, the model lives on cuda:0 if cuda is available.\n    nthreads (int): Number of threads.\n    batch_size (int): Bert score processing batch size,\n        at least one of `model_type` or `lang`. `lang` needs to be\n        specified when `rescale_with_baseline` is True.\n    rescale_with_baseline (bool): Rescale bertscore with pre-computed baseline.\n    baseline_path (str): Customized baseline file.\n    use_fast_tokenizer (bool): `use_fast` parameter passed to HF tokenizer. New in version 0.3.10.\n\nReturns:\n    precision: Precision.\n    recall: Recall.\n    f1: F1 score.\n    hashcode: Hashcode of the library.\n\nExamples:\n\n    >>> predictions = [\"hello there\", \"general kenobi\"]\n    >>> references = [\"hello there\", \"general kenobi\"]\n    >>> bertscore = datasets.load_metric(\"bertscore\")\n    >>> results = bertscore.compute(predictions=predictions, references=references, lang=\"en\")\n    >>> print([round(v, 2) for v in results[\"f1\"]])\n    [1.0, 1.0]\n"





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION       ,	_KWARGS_DESCRIPTION    )
class  __snake_case					(      datasets.Metric    ):

  def   lowerCAmelCase__       (   self):
      return datasets.MetricInfo(
          description=_DESCRIPTION  ,						citation=_CITATION  ,						homepage='https://github.com/Tiiiger/bert_score'  ,						inputs_description=_KWARGS_DESCRIPTION  ,						features=datasets.Features(
              {
                  'predictions': datasets.Value('string'  ,						id='sequence'),
                  'references': datasets.Sequence(datasets.Value('string'  ,						id='sequence')  ,						id='references'),
              })  ,						codebase_urls=['https://github.com/Tiiiger/bert_score']  ,						reference_urls=[
              'https://github.com/Tiiiger/bert_score',
              'https://arxiv.org/abs/1904.09675',
          ]  ,						)

  def   lowerCAmelCase__       (   self  ,						_A  ,						_A  ,						_A=None  ,						_A=None  ,						_A=None  ,						_A=False  ,						_A=False  ,						_A=None  ,						_A=64  ,						_A=4  ,						_A=False  ,						_A=False  ,						_A=None  ,						_A=False  ,						):
      SCREAMING_SNAKE_CASE_													=  bert_score.utils.get_hash
      SCREAMING_SNAKE_CASE_													=  bert_score.BERTScorer

      if version.parse(bert_score.__version__) >= version.parse('0.3.10'):
          SCREAMING_SNAKE_CASE_													=  functools.partial(_A  ,						use_fast_tokenizer=_A)
          SCREAMING_SNAKE_CASE_													=  functools.partial(_A  ,						use_fast_tokenizer=_A)
      elif use_fast_tokenizer:
          raise ImportWarning(
              'To use a fast tokenizer, the module `bert-score>=0.3.10` is required, and the current version of `bert-score` doesn\'t match this condition.\n'
              'You can install it with `pip install "bert-score>=0.3.10"`.')

      if model_type is None:
          assert lang is not None, "either lang or model_type should be specified"
          SCREAMING_SNAKE_CASE_													=  bert_score.utils.langamodel[lang.lower()]

      if num_layers is None:
          SCREAMING_SNAKE_CASE_													=  bert_score.utils.modelalayers[model_type]

      SCREAMING_SNAKE_CASE_													=  get_hash(
          model=_A  ,						num_layers=_A  ,						idf=_A  ,						rescale_with_baseline=_A  ,						use_custom_baseline=baseline_path is not None  ,						)

      with filter_logging_context():
          if not hasattr(self  ,						'cached_bertscorer') or self.cached_bertscorer.hash != hashcode:
              SCREAMING_SNAKE_CASE_													=  scorer(
                  model_type=_A  ,						num_layers=_A  ,						batch_size=_A  ,						nthreads=_A  ,						all_layers=_A  ,						idf=_A  ,						device=_A  ,						lang=_A  ,						rescale_with_baseline=_A  ,						baseline_path=_A  ,						)

      ((SCREAMING_SNAKE_CASE_)							,     (SCREAMING_SNAKE_CASE_)							,     (SCREAMING_SNAKE_CASE_))													=  self.cached_bertscorer.score(
          cands=_A  ,						refs=_A  ,						verbose=_A  ,						batch_size=_A  ,						)
      SCREAMING_SNAKE_CASE_													=  {
          'precision': P.tolist(),
          'recall': R.tolist(),
          'f1': F.tolist(),
          'hashcode': hashcode,
      }
      return output_dict

  def   lowerCAmelCase__       (   self  ,						_A=None  ,						_A=None  ,						**_A):
      # References can be strings or lists of strings
      # Let's change strings to lists of strings with one element
      if references is not None:
          SCREAMING_SNAKE_CASE_													=  [[ref] if isinstance(_A  ,						_A) else ref for ref in references]
      super().add_batch(predictions=_A  ,						references=_A  ,						**_A)


  def   lowerCAmelCase__       (   self  ,						_A=None  ,						_A=None  ,						**_A):
      # References can be strings or lists of strings
      # Let's change strings to lists of strings with one element
      if isinstance(_A  ,						_A):
          SCREAMING_SNAKE_CASE_													=  [reference]
      super().add(prediction=_A  ,						reference=_A  ,						**_A)


