import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory

from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
    convert,
    ensure_valid_input,
    generate_identified_filename,
    infer_shapes,
    quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow




class    a__				:






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]  ,    a		:		List[str]  ,    a		:		Tuple  ,    a		:		Dict   ):





         """simple docstring"""



         return None




class    a__				:






     def        SCREAMING_SNAKE_CASE__       (			self		:		Union[str, Any]  ,    a		:		Optional[Any]  ,    a		:		str  ,    a		:		str  ,    a		:		List[Any]   ):





         """simple docstring"""



         return None




class    a__				(       unittest.TestCase			):
     lowerCamelCase  :					List[str]							=[
         # (model_name, model_kwargs)
         ("bert-base-cased", {}),
         ("gpt2", {"use_cache": False}),  # We don't support exporting GPT2 past keys anymore
     ]






     @require_tf
     @slow
     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



         for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
             self._test_export(a  ,    '''tf'''  ,    12  ,    **a   )






     @require_torch
     @slow
     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]   ):





         """simple docstring"""



         for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
             self._test_export(a  ,    '''pt'''  ,    12  ,    **a   )






     @require_torch
     @slow
     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



         from transformers import BertModel

         __lowerCamelCase          =  ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words''']
         with NamedTemporaryFile(mode='''w+t'''   ) as vocab_file:
             vocab_file.write('''\n'''.join(a   )   )
             vocab_file.flush()
             __lowerCamelCase          =  BertTokenizerFast(vocab_file.name   )

         with TemporaryDirectory() as bert_save_dir:
             __lowerCamelCase          =  BertModel(BertConfig(vocab_size=len(a   )   )   )
             model.save_pretrained(a   )
             self._test_export(a  ,    '''pt'''  ,    12  ,    a   )






     @require_tf
     @slow
     def        SCREAMING_SNAKE_CASE__       (			self		:		int   ):





         """simple docstring"""



         for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
             __lowerCamelCase          =  self._test_export(a  ,    '''tf'''  ,    12  ,    **a   )
             __lowerCamelCase          =  quantize(Path(a   )   )

             # Ensure the actual quantized model is not bigger than the original one
             if quantized_path.stat().st_size >= Path(a   ).stat().st_size:
                 self.fail('''Quantized model is bigger than initial ONNX model'''   )






     @require_torch
     @slow
     def        SCREAMING_SNAKE_CASE__       (			self		:		int   ):





         """simple docstring"""



         for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
             __lowerCamelCase          =  self._test_export(a  ,    '''pt'''  ,    12  ,    **a   )
             __lowerCamelCase          =  quantize(a   )

             # Ensure the actual quantized model is not bigger than the original one
             if quantized_path.stat().st_size >= Path(a   ).stat().st_size:
                 self.fail('''Quantized model is bigger than initial ONNX model'''   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]  ,    a		:		Dict  ,    a		:		Optional[Any]  ,    a		:		int  ,    a		:		Any=None  ,    **a		:		int   ):





         """simple docstring"""



         try:
             # Compute path
             with TemporaryDirectory() as tempdir:
                 __lowerCamelCase          =  Path(a   ).joinpath('''model.onnx'''   )

             # Remove folder if exists
             if path.parent.exists():
                 path.parent.rmdir()

             # Export
             convert(a  ,    a  ,    a  ,    a  ,    a  ,    **a   )

             return path
         except Exception as e:
             self.fail(a   )






     @require_torch
     @require_tokenizers
     @slow
     def        SCREAMING_SNAKE_CASE__       (			self		:		Any   ):





         """simple docstring"""



         from transformers import BertModel

         __lowerCamelCase          =  BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random'''   )   )
         __lowerCamelCase          =  BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random'''   )
         self._test_infer_dynamic_axis(a  ,    a  ,    '''pt'''   )






     @require_tf
     @require_tokenizers
     @slow
     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]   ):





         """simple docstring"""



         from transformers import TFBertModel

         __lowerCamelCase          =  TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random'''   )   )
         __lowerCamelCase          =  BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random'''   )
         self._test_infer_dynamic_axis(a  ,    a  ,    '''tf'''   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Any  ,    a		:		Tuple  ,    a		:		List[Any]  ,    a		:		List[str]   ):





         """simple docstring"""



         __lowerCamelCase          =  FeatureExtractionPipeline(a  ,    a   )

         __lowerCamelCase          =  ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1''']
         __lowerCamelCase     ,  __lowerCamelCase     ,  __lowerCamelCase     ,  __lowerCamelCase          =  infer_shapes(a  ,    a   )

         # Assert all variables are present
         self.assertEqual(len(a   )  ,    len(a   )   )
         self.assertTrue(all(var_name in shapes for var_name in variable_names   )   )
         self.assertSequenceEqual(variable_names[:3]  ,    a   )
         self.assertSequenceEqual(variable_names[3:]  ,    a   )

         # Assert inputs are {0: batch, 1: sequence}
         for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
             self.assertDictEqual(shapes[var_name]  ,    {0: '''batch''', 1: '''sequence'''}   )

         # Assert outputs are {0: batch, 1: sequence} and {0: batch}
         self.assertDictEqual(shapes['''output_0''']  ,    {0: '''batch''', 1: '''sequence'''}   )
         self.assertDictEqual(shapes['''output_1''']  ,    {0: '''batch'''}   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		int   ):





         """simple docstring"""



         __lowerCamelCase          =  ['''input_ids''', '''attention_mask''', '''token_type_ids''']
         __lowerCamelCase          =  {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]}
         __lowerCamelCase     ,  __lowerCamelCase          =  ensure_valid_input(FuncContiguousArgs()  ,    a  ,    a   )

         # Should have exactly the same number of args (all are valid)
         self.assertEqual(len(a   )  ,    3   )

         # Should have exactly the same input names
         self.assertEqual(set(a   )  ,    set(a   )   )

         # Parameter should be reordered according to their respective place in the function:
         # (input_ids, token_type_ids, attention_mask)
         self.assertEqual(a  ,    (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask'''])   )

         # Generated args are interleaved with another args (for instance parameter "past" in GPT2)
         __lowerCamelCase     ,  __lowerCamelCase          =  ensure_valid_input(FuncNonContiguousArgs()  ,    a  ,    a   )

         # Should have exactly the one arg (all before the one not provided "some_other_args")
         self.assertEqual(len(a   )  ,    1   )
         self.assertEqual(len(a   )  ,    1   )

         # Should have only "input_ids"
         self.assertEqual(inputs_args[0]  ,    tokens['''input_ids''']   )
         self.assertEqual(ordered_input_names[0]  ,    '''input_ids'''   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  generate_identified_filename(Path('''/home/something/my_fake_model.onnx'''   )  ,    '''-test'''   )
         self.assertEqual('''/home/something/my_fake_model-test.onnx'''  ,    generated.as_posix()   )

'''simple docstring'''




def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    )     ->   float:
    if principal <= 0:
        raise Exception('''Principal borrowed must be > 0'''    )
    if rate_per_annum < 0:
        raise Exception('''Rate of interest must be >= 0'''    )
    if years_to_repay <= 0 or not isinstance(UpperCamelCase__    ,  UpperCamelCase__    ):
        raise Exception('''Years to repay must be an integer > 0'''    )

    # Yearly rate is divided by 12 to get monthly rate
    __lowerCamelCase          =  rate_per_annum / 12

    # Years to repay is multiplied by 12 to get number of payments as payment is monthly
    __lowerCamelCase          =  years_to_repay * 12

    return (
        principal
        * rate_per_month
        * (1 + rate_per_month) ** number_of_payments
        / ((1 + rate_per_month) ** number_of_payments - 1)
    )


if __name__ == "__main__":
  import doctest

  doctest.testmod()
