




import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


_lowerCamelCase			:	Tuple							 =     """hf-internal-testing/tiny-random-bert"""
_lowerCamelCase			:	str							 =     os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
_lowerCamelCase			:	Union[str, Any]							 =     """9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""


class        UpperCamelCase_					(				unittest.TestCase  ):

    '''simple docstring'''






    def  SCREAMING_SNAKE_CASE							(    self   :			Any)		->Any:





           '''simple docstring'''

           A__   				=					cached_file(UpperCAmelCase__      ,				UpperCAmelCase__)
           # Should have downloaded the file in here
           self.assertTrue(os.path.isdir(UpperCAmelCase__))
           # Cache should contain at least those three subfolders:
           for subfolder in ["blobs", "refs", "snapshots"]:
                  self.assertTrue(os.path.isdir(os.path.join(UpperCAmelCase__      ,				UpperCAmelCase__)))
           with open(os.path.join(UpperCAmelCase__      ,				'''refs'''      ,				'''main''')) as f:
                  A__   				=					f.read()
           self.assertEqual(UpperCAmelCase__      ,				os.path.join(UpperCAmelCase__      ,				'''snapshots'''      ,				UpperCAmelCase__      ,				UpperCAmelCase__))
           self.assertTrue(os.path.isfile(UpperCAmelCase__))

           # File is cached at the same place the second time.
           A__   				=					cached_file(UpperCAmelCase__      ,				UpperCAmelCase__)
           self.assertEqual(UpperCAmelCase__      ,				UpperCAmelCase__)

           # Using a specific revision to test the full commit hash.
           A__   				=					cached_file(UpperCAmelCase__      ,				UpperCAmelCase__      ,				revision='''9b8c223''')
           self.assertEqual(UpperCAmelCase__      ,				os.path.join(UpperCAmelCase__      ,				'''snapshots'''      ,				UpperCAmelCase__      ,				UpperCAmelCase__))


    def  SCREAMING_SNAKE_CASE							(    self   :			Any)		->List[Any]:





           '''simple docstring'''

           with self.assertRaisesRegex(UpperCAmelCase__      ,				'''is not a valid model identifier'''):
                  A__   				=					cached_file('''tiny-random-bert'''      ,				UpperCAmelCase__)

           with self.assertRaisesRegex(UpperCAmelCase__      ,				'''is not a valid git identifier'''):
                  A__   				=					cached_file(UpperCAmelCase__      ,				UpperCAmelCase__      ,				revision='''aaaa''')

           with self.assertRaisesRegex(UpperCAmelCase__      ,				'''does not appear to have a file named'''):
                  A__   				=					cached_file(UpperCAmelCase__      ,				'''conf''')


    def  SCREAMING_SNAKE_CASE							(    self   :			Union[str, Any])		->List[str]:





           '''simple docstring'''

           with self.assertRaisesRegex(UpperCAmelCase__      ,				'''does not appear to have a file named'''):
                  A__   				=					cached_file(UpperCAmelCase__      ,				'''conf''')

           with open(os.path.join(UpperCAmelCase__      ,				'''refs'''      ,				'''main''')) as f:
                  A__   				=					f.read()
           self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase__      ,				'''.no_exist'''      ,				UpperCAmelCase__      ,				'''conf''')))

           A__   				=					cached_file(UpperCAmelCase__      ,				'''conf'''      ,				_raise_exceptions_for_missing_entries=UpperCAmelCase__)
           self.assertIsNone(UpperCAmelCase__)

           A__   				=					cached_file(UpperCAmelCase__      ,				'''conf'''      ,				local_files_only=UpperCAmelCase__      ,				_raise_exceptions_for_missing_entries=UpperCAmelCase__)
           self.assertIsNone(UpperCAmelCase__)

           A__   				=					mock.Mock()
           A__   				=					500
           A__   				=					{}
           A__   				=					HTTPError
           A__   				=					{}

           # Under the mock environment we get a 500 error when trying to reach the tokenizer.
           with mock.patch('''requests.Session.request'''      ,				return_value=UpperCAmelCase__) as mock_head:
                  A__   				=					cached_file(UpperCAmelCase__      ,				'''conf'''      ,				_raise_exceptions_for_connection_errors=UpperCAmelCase__)
                  self.assertIsNone(UpperCAmelCase__)
                  # This check we did call the fake head request
                  mock_head.assert_called()


    def  SCREAMING_SNAKE_CASE							(    self   :			str)		->int:





           '''simple docstring'''

           self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only'''      ,				UpperCAmelCase__))
           self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only'''      ,				UpperCAmelCase__))
           self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only'''      ,				UpperCAmelCase__))


    def  SCREAMING_SNAKE_CASE							(    self   :			int)		->Optional[int]:





           '''simple docstring'''

           self.assertIsNone(get_file_from_repo('''bert-base-cased'''      ,				'''ahah.txt'''))

           # The function raises if the repository does not exist.
           with self.assertRaisesRegex(UpperCAmelCase__      ,				'''is not a valid model identifier'''):
                  get_file_from_repo('''bert-base-case'''      ,				UpperCAmelCase__)

           # The function raises if the revision does not exist.
           with self.assertRaisesRegex(UpperCAmelCase__      ,				'''is not a valid git identifier'''):
                  get_file_from_repo('''bert-base-cased'''      ,				UpperCAmelCase__      ,				revision='''ahaha''')

           A__   				=					get_file_from_repo('''bert-base-cased'''      ,				UpperCAmelCase__)
           # The name is the cached name which is not very easy to test, so instead we load the content.
           A__   				=					json.loads(open(UpperCAmelCase__      ,				'''r''').read())
           self.assertEqual(config['''hidden_size''']      ,				768)





    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[Any])		->int:





           '''simple docstring'''

           with tempfile.TemporaryDirectory() as tmp_dir:
                  A__   				=					Path(UpperCAmelCase__) / '''a.txt'''
                  filename.touch()
                  self.assertEqual(get_file_from_repo(UpperCAmelCase__      ,				'''a.txt''')      ,				str(UpperCAmelCase__))

                  self.assertIsNone(get_file_from_repo(UpperCAmelCase__      ,				'''b.txt'''))








# Logistic Regression from scratch

# In[62]:

# In[63]:

# importing all the required libraries

import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets







def SCREAMING_SNAKE_CASE       ( lowercase_		)     -> Dict:



       """simple docstring"""

       return 1 / (1 + np.exp(-z		))







def SCREAMING_SNAKE_CASE       ( lowercase_				,       lowercase_		)     -> Optional[int]:



       """simple docstring"""

       return (-y * np.log(lowercase_		) - (1 - y) * np.log(1 - h		)).mean()







def SCREAMING_SNAKE_CASE       ( lowercase_				,       lowercase_				,       lowercase_		)     -> int:



       """simple docstring"""

       A__   				=					np.dot(lowercase_				,       lowercase_		)
       return np.sum(y * scores - np.log(1 + np.exp(lowercase_		)		)		)







def SCREAMING_SNAKE_CASE       ( lowercase_				,       lowercase_				,       lowercase_				,       lowercase_=70_000		)     -> Dict:



       """simple docstring"""

       A__   				=					np.zeros(x.shape[1]		)

       for iterations in range(lowercase_		):
              A__   				=					np.dot(lowercase_				,       lowercase_		)
              A__   				=					sigmoid_function(lowercase_		)
              A__   				=					np.dot(x.T				,       h - y		) / y.size
              A__   				=					theta - alpha * gradient  # updating the weights
              A__   				=					np.dot(lowercase_				,       lowercase_		)
              A__   				=					sigmoid_function(lowercase_		)
              A__   				=					cost_function(lowercase_				,       lowercase_		)
              if iterations % 100 == 0:
                     print(f"""loss: {j} \t"""		)  # printing the loss after every 100 iterations
       return theta


# In[68]:

if __name__ == "__main__":
  _lowerCamelCase			:	str							 =     datasets.load_iris()
  _lowerCamelCase			:	Any							 =     iris.data[:, :2]
  _lowerCamelCase			:	Dict							 =     (iris.target != 0) * 1

  _lowerCamelCase			:	Union[str, Any]							 =     0.1
  _lowerCamelCase			:	Tuple							 =     logistic_reg(alpha, x, y, max_iterations=70000)
  print("""theta: """, theta)  # printing the theta i.e our weights vector







  def SCREAMING_SNAKE_CASE       ( lowercase_		)     -> List[Any]:



         """simple docstring"""

         return sigmoid_function(
             np.dot(lowercase_				,       lowercase_		)		)  # predicting the value of probability from the logistic regression algorithm

  plt.figure(figsize=(10, 6))
  plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="""b""", label="""0""")
  plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="""r""", label="""1""")
  ((_lowerCamelCase) ,    (_lowerCamelCase))			:	int							 =     (x[:, 0].min(), x[:, 0].max())
  ((_lowerCamelCase) ,    (_lowerCamelCase))			:	Union[str, Any]							 =     (x[:, 1].min(), x[:, 1].max())
  ((_lowerCamelCase) ,    (_lowerCamelCase))			:	List[Any]							 =     np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max))
  _lowerCamelCase			:	str							 =     np.c_[xxa.ravel(), xxa.ravel()]
  _lowerCamelCase			:	Tuple							 =     predict_prob(grid).reshape(xxa.shape)
  plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors="""black""")

  plt.legend()
  plt.show()


