




import os
import shutil
from pathlib import Path
from typing import Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging


if is_onnx_available():
   import onnxruntime as ort


lowerCamelCase__					:  Dict      							=				logging.get_logger(__name__)

lowerCamelCase__					:  int      							=				{
    'tensor(bool)': np.bool_,
    'tensor(int8)': np.inta,
    'tensor(uint8)': np.uinta,
    'tensor(int16)': np.intaa,
    'tensor(uint16)': np.uintaa,
    'tensor(int32)': np.intaa,
    'tensor(uint32)': np.uintaa,
    'tensor(int64)': np.intaa,
    'tensor(uint64)': np.uintaa,
    'tensor(float16)': np.floataa,
    'tensor(float)': np.floataa,
    'tensor(double)': np.floataa,
}





class 			lowerCamelCase_				:


 '''simple docstring'''







 def __init__(				self    :						Optional[Any]							,							_lowerCAmelCase    :						int=None							,							**_lowerCAmelCase    :						Optional[Any]		):
       logger.info('`diffusers.OnnxRuntimeModel` is experimental and might change in the future.'		)
       SCREAMING_SNAKE_CASE_      		=     model
       SCREAMING_SNAKE_CASE_      		=     kwargs.get('model_save_dir'							,							_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     kwargs.get('latest_model_name'							,							_lowerCAmelCase		)



 def __call__(				self    :						int							,							**_lowerCAmelCase    :						Any		):
       SCREAMING_SNAKE_CASE_      		=     {k: np.array(_lowerCAmelCase		) for k, v in kwargs.items()}
       return self.model.run(_lowerCAmelCase							,							_lowerCAmelCase		)



 @staticmethod
 def  lowerCAmelCase_    (				_lowerCAmelCase    :						Union[str, Path]							,							_lowerCAmelCase    :						Tuple=None							,							_lowerCAmelCase    :						Dict=None		):
       if provider is None:
             logger.info('No onnxruntime provider specified, using CPUExecutionProvider'		)
             SCREAMING_SNAKE_CASE_      		=     'CPUExecutionProvider'

       return ort.InferenceSession(_lowerCAmelCase							,							providers=[provider]							,							sess_options=_lowerCAmelCase		)



 def  lowerCAmelCase_    (				self    :						Tuple							,							_lowerCAmelCase    :						Union[str, Path]							,							_lowerCAmelCase    :						Optional[str] = None							,							**_lowerCAmelCase    :						str		):
       SCREAMING_SNAKE_CASE_      		=     file_name if file_name is not None else ONNX_WEIGHTS_NAME

       SCREAMING_SNAKE_CASE_      		=     self.model_save_dir.joinpath(self.latest_model_name		)
       SCREAMING_SNAKE_CASE_      		=     Path(_lowerCAmelCase		).joinpath(_lowerCAmelCase		)
       try:
             shutil.copyfile(_lowerCAmelCase							,							_lowerCAmelCase		)
       except shutil.SameFileError:
             pass

       # copy external weights (for models >2GB)
       SCREAMING_SNAKE_CASE_      		=     self.model_save_dir.joinpath(_lowerCAmelCase		)
       if src_path.exists():
             SCREAMING_SNAKE_CASE_      		=     Path(_lowerCAmelCase		).joinpath(_lowerCAmelCase		)
             try:
                   shutil.copyfile(_lowerCAmelCase							,							_lowerCAmelCase		)
             except shutil.SameFileError:
                   pass



 def  lowerCAmelCase_    (				self    :						List[Any]							,							_lowerCAmelCase    :						Union[str, os.PathLike]							,							**_lowerCAmelCase    :						int							,							):
       if os.path.isfile(_lowerCAmelCase		):
             logger.error(F"Provided path ({save_directory}) should be a directory, not a file"		)
             return

       os.makedirs(_lowerCAmelCase							,							exist_ok=_lowerCAmelCase		)

       # saving model weights/files
       self._save_pretrained(_lowerCAmelCase							,							**_lowerCAmelCase		)



 @classmethod
 def  lowerCAmelCase_    (				cls    :						Optional[Any]							,							_lowerCAmelCase    :						Union[str, Path]							,							_lowerCAmelCase    :						Optional[Union[bool, str, None]] = None							,							_lowerCAmelCase    :						Optional[Union[str, None]] = None							,							_lowerCAmelCase    :						bool = False							,							_lowerCAmelCase    :						Optional[str] = None							,							_lowerCAmelCase    :						Optional[str] = None							,							_lowerCAmelCase    :						Optional[str] = None							,							_lowerCAmelCase    :						Optional["ort.SessionOptions"] = None							,							**_lowerCAmelCase    :						str							,							):
       SCREAMING_SNAKE_CASE_      		=     file_name if file_name is not None else ONNX_WEIGHTS_NAME
       # load model from local directory
       if os.path.isdir(_lowerCAmelCase		):
             SCREAMING_SNAKE_CASE_      		=     OnnxRuntimeModel.load_model(
                 os.path.join(_lowerCAmelCase							,							_lowerCAmelCase		)							,							provider=_lowerCAmelCase							,							sess_options=_lowerCAmelCase		)
             SCREAMING_SNAKE_CASE_      		=     Path(_lowerCAmelCase		)
       # load model from hub
       else:
             # download model
             SCREAMING_SNAKE_CASE_      		=     hf_hub_download(
                 repo_id=_lowerCAmelCase							,							filename=_lowerCAmelCase							,							use_auth_token=_lowerCAmelCase							,							revision=_lowerCAmelCase							,							cache_dir=_lowerCAmelCase							,							force_download=_lowerCAmelCase							,							)
             SCREAMING_SNAKE_CASE_      		=     Path(_lowerCAmelCase		).parent
             SCREAMING_SNAKE_CASE_      		=     Path(_lowerCAmelCase		).name
             SCREAMING_SNAKE_CASE_      		=     OnnxRuntimeModel.load_model(_lowerCAmelCase							,							provider=_lowerCAmelCase							,							sess_options=_lowerCAmelCase		)
       return cls(model=_lowerCAmelCase							,							**_lowerCAmelCase		)




 @classmethod
 def  lowerCAmelCase_    (				cls    :						Union[str, Any]							,							_lowerCAmelCase    :						Union[str, Path]							,							_lowerCAmelCase    :						bool = True							,							_lowerCAmelCase    :						Optional[str] = None							,							_lowerCAmelCase    :						Optional[str] = None							,							**_lowerCAmelCase    :						List[str]							,							):
       SCREAMING_SNAKE_CASE_      		=     None
       if len(str(_lowerCAmelCase		).split('@'		)		) == 2:
             SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     model_id.split('@'		)

       return cls._from_pretrained(
           model_id=_lowerCAmelCase							,							revision=_lowerCAmelCase							,							cache_dir=_lowerCAmelCase							,							force_download=_lowerCAmelCase							,							use_auth_token=_lowerCAmelCase							,							**_lowerCAmelCase							,							)

import datasets


A		: Optional[int]								=     '''\
@InProceedings{conneau2018xnli,
  author = "Conneau, Alexis
                 and Rinott, Ruty
                 and Lample, Guillaume
                 and Williams, Adina
                 and Bowman, Samuel R.
                 and Schwenk, Holger
                 and Stoyanov, Veselin",
  title = "XNLI: Evaluating Cross-lingual Sentence Representations",
  booktitle = "Proceedings of the 2018 Conference on Empirical Methods
               in Natural Language Processing",
  year = "2018",
  publisher = "Association for Computational Linguistics",
  location = "Brussels, Belgium",
}
'''

A		: Optional[int]								=     '''\
XNLI is a subset of a few thousand examples from MNLI which has been translated
into a 14 different languages (some low-ish resource). As with MNLI, the goal is
to predict textual entailment (does sentence A imply/contradict/neither sentence
B) and is a classification task (given two sentences, predict one of three
labels).
'''

A		: str								=     '''
Computes XNLI score which is just simple accuracy.
Args:
    predictions: Predicted labels.
    references: Ground truth labels.
Returns:
    \'accuracy\': accuracy
Examples:

    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> xnli_metric = datasets.load_metric("xnli")
    >>> results = xnli_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'accuracy\': 1.0}
'''




def 	UpperCamelCase__  (     SCREAMING_SNAKE_CASE_	:	List[str]		,   SCREAMING_SNAKE_CASE_	:	List[Any]       )  ->     str:
						return (preds == labels).mean()



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






			def    UpperCamelCase_				(      self  ):
									return datasets.MetricInfo(
									    description=_DESCRIPTION				,			citation=_CITATION				,			inputs_description=_KWARGS_DESCRIPTION				,			features=datasets.Features(
									        {
									            """predictions""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32"""  ),
									            """references""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32"""  ),
									        }  )				,			codebase_urls=[]				,			reference_urls=[]				,			format="""numpy"""				,			)






			def    UpperCamelCase_				(      self				,			__UpperCamelCase				,			__UpperCamelCase  ):
									return {"accuracy": simple_accuracy(__UpperCamelCase				,			__UpperCamelCase  )}