
import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch





class 			_lowerCAmelCase      (			__A ):




    @require_torch
    def   __a		(      self  )       ->   Optional[int]:
       lowerCAmelCase_      			=			'''
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
        '''

       lowerCAmelCase_      			=			'''
mname = "hf-internal-testing/tiny-random-bert"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
BertTokenizer.from_pretrained(mname)
pipe = pipeline(task="fill-mask", model=mname)
print("success")
        '''

       lowerCAmelCase_      			=			'''
import socket
def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")
socket.socket = offline_socket
        '''

       # Force fetching the files so that we can use the cache
       lowerCAmelCase_      			=			'''hf-internal-testing/tiny-random-bert'''
       BertConfig.from_pretrained(_UpperCamelCase  )
       BertModel.from_pretrained(_UpperCamelCase  )
       BertTokenizer.from_pretrained(_UpperCamelCase  )
       pipeline(task="fill-mask"       ,       model=_UpperCamelCase  )

       # baseline - just load from_pretrained with normal network
       lowerCAmelCase_      			=			[sys.executable, '''-c''', '''\n'''.join([load, run, mock]  )]

       # should succeed
       lowerCAmelCase_      			=			self.get_env()
       # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
       lowerCAmelCase_      			=			'''1'''
       lowerCAmelCase_      			=			subprocess.run(_UpperCamelCase       ,       env=_UpperCamelCase       ,       check=_UpperCamelCase       ,       capture_output=_UpperCamelCase  )
       self.assertEqual(result.returncode       ,       0       ,       result.stderr  )
       self.assertIn("success"       ,       result.stdout.decode()  )




    @require_torch
    def   __a		(      self  )       ->   List[str]:
       lowerCAmelCase_      			=			'''
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
        '''

       lowerCAmelCase_      			=			'''
mname = "hf-internal-testing/tiny-random-bert"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
BertTokenizer.from_pretrained(mname)
pipe = pipeline(task="fill-mask", model=mname)
print("success")
        '''

       lowerCAmelCase_      			=			'''
import socket
def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")
socket.socket = offline_socket
        '''

       # Force fetching the files so that we can use the cache
       lowerCAmelCase_      			=			'''hf-internal-testing/tiny-random-bert'''
       BertConfig.from_pretrained(_UpperCamelCase  )
       BertModel.from_pretrained(_UpperCamelCase  )
       BertTokenizer.from_pretrained(_UpperCamelCase  )
       pipeline(task="fill-mask"       ,       model=_UpperCamelCase  )

       # baseline - just load from_pretrained with normal network
       lowerCAmelCase_      			=			[sys.executable, '''-c''', '''\n'''.join([load, run, mock]  )]

       # should succeed
       lowerCAmelCase_      			=			self.get_env()
       lowerCAmelCase_      			=			subprocess.run(_UpperCamelCase       ,       env=_UpperCamelCase       ,       check=_UpperCamelCase       ,       capture_output=_UpperCamelCase  )
       self.assertEqual(result.returncode       ,       0       ,       result.stderr  )
       self.assertIn("success"       ,       result.stdout.decode()  )




    @require_torch
    def   __a		(      self  )       ->   Optional[Any]:
       lowerCAmelCase_      			=			'''
from transformers import BertConfig, BertModel, BertTokenizer
        '''

       lowerCAmelCase_      			=			'''
mname = "hf-internal-testing/tiny-random-bert-sharded"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
print("success")
        '''

       lowerCAmelCase_      			=			'''
import socket
def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")
socket.socket = offline_socket
        '''

       # baseline - just load from_pretrained with normal network
       lowerCAmelCase_      			=			[sys.executable, '''-c''', '''\n'''.join([load, run]  )]

       # should succeed
       lowerCAmelCase_      			=			self.get_env()
       lowerCAmelCase_      			=			subprocess.run(_UpperCamelCase       ,       env=_UpperCamelCase       ,       check=_UpperCamelCase       ,       capture_output=_UpperCamelCase  )
       self.assertEqual(result.returncode       ,       0       ,       result.stderr  )
       self.assertIn("success"       ,       result.stdout.decode()  )

       # next emulate no network
       lowerCAmelCase_      			=			[sys.executable, '''-c''', '''\n'''.join([load, mock, run]  )]

       # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
       # env["TRANSFORMERS_OFFLINE"] = "0"
       # result = subprocess.run(cmd, env=env, check=False, capture_output=True)
       # self.assertEqual(result.returncode, 1, result.stderr)

       # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
       lowerCAmelCase_      			=			'''1'''
       lowerCAmelCase_      			=			subprocess.run(_UpperCamelCase       ,       env=_UpperCamelCase       ,       check=_UpperCamelCase       ,       capture_output=_UpperCamelCase  )
       self.assertEqual(result.returncode       ,       0       ,       result.stderr  )
       self.assertIn("success"       ,       result.stdout.decode()  )




    @require_torch
    def   __a		(      self  )       ->   Optional[int]:
       lowerCAmelCase_      			=			'''
from transformers import pipeline
        '''
       lowerCAmelCase_      			=			'''
mname = "hf-internal-testing/tiny-random-bert"
pipe = pipeline(model=mname)
        '''

       lowerCAmelCase_      			=			'''
import socket
def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")
socket.socket = offline_socket
        '''
       lowerCAmelCase_      			=			self.get_env()
       lowerCAmelCase_      			=			'''1'''
       lowerCAmelCase_      			=			[sys.executable, '''-c''', '''\n'''.join([load, mock, run]  )]
       lowerCAmelCase_      			=			subprocess.run(_UpperCamelCase       ,       env=_UpperCamelCase       ,       check=_UpperCamelCase       ,       capture_output=_UpperCamelCase  )
       self.assertEqual(result.returncode       ,       1       ,       result.stderr  )
       self.assertIn(
           "You cannot infer task automatically within `pipeline` when using offline mode"       ,       result.stderr.decode().replace("\n"       ,       ""  )       ,       )




    @require_torch
    def   __a		(      self  )       ->   Optional[int]:
       lowerCAmelCase_      			=			'''
from transformers import AutoModel
        '''
       lowerCAmelCase_      			=			'''
mname = "hf-internal-testing/test_dynamic_model"
AutoModel.from_pretrained(mname, trust_remote_code=True)
print("success")
        '''

       # baseline - just load from_pretrained with normal network
       lowerCAmelCase_      			=			[sys.executable, '''-c''', '''\n'''.join([load, run]  )]

       # should succeed
       lowerCAmelCase_      			=			self.get_env()
       lowerCAmelCase_      			=			subprocess.run(_UpperCamelCase       ,       env=_UpperCamelCase       ,       check=_UpperCamelCase       ,       capture_output=_UpperCamelCase  )
       self.assertEqual(result.returncode       ,       0       ,       result.stderr  )
       self.assertIn("success"       ,       result.stdout.decode()  )

       # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
       lowerCAmelCase_      			=			'''1'''
       lowerCAmelCase_      			=			subprocess.run(_UpperCamelCase       ,       env=_UpperCamelCase       ,       check=_UpperCamelCase       ,       capture_output=_UpperCamelCase  )
       self.assertEqual(result.returncode       ,       0       ,       result.stderr  )
       self.assertIn("success"       ,       result.stdout.decode()  )





import itertools
import string
from collections.abc import Generator, Iterable






def      lowerCamelCase__       (       __lowerCAmelCase						:						Iterable[str]					,							__lowerCAmelCase						:						int       ):




			"""simple docstring"""


			lowerCAmelCase_      			=			iter(__lowerCAmelCase       )
			while True:
						lowerCAmelCase_      			=			tuple(itertools.islice(__lowerCAmelCase					,							__lowerCAmelCase       )       )
						if not chunk:
									return
						yield chunk






def      lowerCamelCase__       (       __lowerCAmelCase						:						str       ):




			"""simple docstring"""


			lowerCAmelCase_      			=			"".join([c.upper() for c in dirty if c in string.ascii_letters]       )
			lowerCAmelCase_      			=			""

			if len(__lowerCAmelCase       ) < 2:
						return dirty

			for i in range(len(__lowerCAmelCase       ) - 1       ):
						clean += dirty[i]

						if dirty[i] == dirty[i + 1]:
									clean += "X"

			clean += dirty[-1]

			if len(__lowerCAmelCase       ) & 1:
						clean += "X"

			return clean






def      lowerCamelCase__       (       __lowerCAmelCase						:						str       ):




			"""simple docstring"""


			lowerCAmelCase_      			=			"ABCDEFGHIKLMNOPQRSTUVWXYZ"
			# we're using a list instead of a '2d' array because it makes the math
			# for setting up the table and doing the actual encoding/decoding simpler
			lowerCAmelCase_      			=			[]

			# copy key chars into the table if they are in `alphabet` ignoring duplicates
			for char in key.upper():
						if char not in table and char in alphabet:
									table.append(__lowerCAmelCase       )

    # fill the rest of the table in with the remaining alphabet chars
			for char in alphabet:
						if char not in table:
									table.append(__lowerCAmelCase       )

			return table






def      lowerCamelCase__       (       __lowerCAmelCase						:						str					,							__lowerCAmelCase						:						str       ):




			"""simple docstring"""


			lowerCAmelCase_      			=			generate_table(__lowerCAmelCase       )
			lowerCAmelCase_      			=			prepare_input(__lowerCAmelCase       )
			lowerCAmelCase_      			=			""

			# https://en.wikipedia.org/wiki/Playfair_cipher#Description
			for chara, chara in chunker(__lowerCAmelCase					,							2       ):
						lowerCAmelCase_			,						lowerCAmelCase_      			=			divmod(table.index(__lowerCAmelCase       )					,							5       )
						lowerCAmelCase_			,						lowerCAmelCase_      			=			divmod(table.index(__lowerCAmelCase       )					,							5       )

						if rowa == rowa:
									ciphertext += table[rowa * 5 + (cola + 1) % 5]
									ciphertext += table[rowa * 5 + (cola + 1) % 5]
						elif cola == cola:
									ciphertext += table[((rowa + 1) % 5) * 5 + cola]
									ciphertext += table[((rowa + 1) % 5) * 5 + cola]
						else:  # rectangle
									ciphertext += table[rowa * 5 + cola]
									ciphertext += table[rowa * 5 + cola]

			return ciphertext






def      lowerCamelCase__       (       __lowerCAmelCase						:						str					,							__lowerCAmelCase						:						str       ):




			"""simple docstring"""


			lowerCAmelCase_      			=			generate_table(__lowerCAmelCase       )
			lowerCAmelCase_      			=			""

			# https://en.wikipedia.org/wiki/Playfair_cipher#Description
			for chara, chara in chunker(__lowerCAmelCase					,							2       ):
						lowerCAmelCase_			,						lowerCAmelCase_      			=			divmod(table.index(__lowerCAmelCase       )					,							5       )
						lowerCAmelCase_			,						lowerCAmelCase_      			=			divmod(table.index(__lowerCAmelCase       )					,							5       )

						if rowa == rowa:
									plaintext += table[rowa * 5 + (cola - 1) % 5]
									plaintext += table[rowa * 5 + (cola - 1) % 5]
						elif cola == cola:
									plaintext += table[((rowa - 1) % 5) * 5 + cola]
									plaintext += table[((rowa - 1) % 5) * 5 + cola]
						else:  # rectangle
									plaintext += table[rowa * 5 + cola]
									plaintext += table[rowa * 5 + cola]

			return plaintext



