
"""simple docstring"""







import subprocess
import sys

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







class 							__magic_name__     (		lowercase__   ):





					@require_torch
					def 							lowerCAmelCase      (				self   :							Tuple    ):
												# this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
												# `transformers` is loaded, and it's too late for inside pytest - so we are changing it
												# while running an external program

												# python one-liner segments

												# this must be loaded before socket.socket is monkey-patched
												__snake_case     			=       "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        "

												__snake_case     			=       "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n        "

												__snake_case     			=       "\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\")\nsocket.socket = offline_socket\n        "

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

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

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





					@require_torch
					def 							lowerCAmelCase      (				self   :							List[Any]    ):
												# python one-liner segments
												# this must be loaded before socket.socket is monkey-patched
												__snake_case     			=       "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        "

												__snake_case     			=       "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n        "

												__snake_case     			=       "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\")\nsocket.socket = offline_socket\n        "

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

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

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





					@require_torch
					def 							lowerCAmelCase      (				self   :							str    ):
												# this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
												# `transformers` is loaded, and it's too late for inside pytest - so we are changing it
												# while running an external program

												# python one-liner segments

												# this must be loaded before socket.socket is monkey-patched
												__snake_case     			=       "\nfrom transformers import BertConfig, BertModel, BertTokenizer\n        "

												__snake_case     			=       "\nmname = \"hf-internal-testing/tiny-random-bert-sharded\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint(\"success\")\n        "

												__snake_case     			=       "\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n        "

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

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

												# next emulate no network
												__snake_case     			=       [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
												__snake_case     			=       "1"
												__snake_case     			=       subprocess.run(snake_case_							,						env=snake_case_							,						check=snake_case_							,						capture_output=snake_case_    )
												self.assertEqual(result.returncode							,						0							,						result.stderr    )
												self.assertIn("success"							,						result.stdout.decode()    )





					@require_torch
					def 							lowerCAmelCase      (				self   :							str    ):
												__snake_case     			=       "\nfrom transformers import pipeline\n        "
												__snake_case     			=       "\nmname = \"hf-internal-testing/tiny-random-bert\"\npipe = pipeline(model=mname)\n        "

												__snake_case     			=       "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n        "
												__snake_case     			=       self.get_env()
												__snake_case     			=       "1"
												__snake_case     			=       [sys.executable, "-c", "\n".join([load, mock, run]    )]
												__snake_case     			=       subprocess.run(snake_case_							,						env=snake_case_							,						check=snake_case_							,						capture_output=snake_case_    )
												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 							lowerCAmelCase      (				self   :							List[str]    ):
												__snake_case     			=       "\nfrom transformers import AutoModel\n        "
												__snake_case     			=       "\nmname = \"hf-internal-testing/test_dynamic_model\"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint(\"success\")\n        "

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

												# should succeed
												__snake_case     			=       self.get_env()
												__snake_case     			=       subprocess.run(snake_case_							,						env=snake_case_							,						check=snake_case_							,						capture_output=snake_case_    )
												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
												__snake_case     			=       "1"
												__snake_case     			=       subprocess.run(snake_case_							,						env=snake_case_							,						check=snake_case_							,						capture_output=snake_case_    )
												self.assertEqual(result.returncode							,						0							,						result.stderr    )
												self.assertIn("success"							,						result.stdout.decode()    )


"""simple docstring"""







from pathlib import Path
from typing import List

from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import get_tests_dir, is_tool_test
from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image


_SCREAMING_SNAKE_CASE	       =      ["""text""", """image""", """audio"""]
def   __UpperCamelCase   (					SCREAMING_SNAKE_CASE )  ->     List[Any]:







							"""simple docstring"""


							__snake_case     			=       []

							for input_type in input_types:
														if input_type == "text":
																					inputs.append("Text input" )
														elif input_type == "image":
																					inputs.append(
																					    Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" ).resize((5_12, 5_12) ) )
														elif input_type == "audio":
																					inputs.append(torch.ones(30_00 ) )
														elif isinstance(SCREAMING_SNAKE_CASE							,    SCREAMING_SNAKE_CASE ):
																					inputs.append(create_inputs(SCREAMING_SNAKE_CASE ) )
														else:
																					raise ValueError(F'''Invalid type requested: {input_type}''' )

							return inputs
def   __UpperCamelCase   (					SCREAMING_SNAKE_CASE )  ->     Optional[Any]:







							"""simple docstring"""


							__snake_case     			=       []

							for output in outputs:
														if isinstance(SCREAMING_SNAKE_CASE							,    (str, AgentText) ):
																					output_types.append("text" )
														elif isinstance(SCREAMING_SNAKE_CASE							,    (Image.Image, AgentImage) ):
																					output_types.append("image" )
														elif isinstance(SCREAMING_SNAKE_CASE							,    (torch.Tensor, AgentAudio) ):
																					output_types.append("audio" )
														else:
																					raise ValueError(F'''Invalid output: {output}''' )

							return output_types







@is_tool_test
class 							__magic_name__     :





					def 							lowerCAmelCase      (				self   :							Optional[int]    ):
												self.assertTrue(hasattr(self.tool							,						"inputs"    )    )
												self.assertTrue(hasattr(self.tool							,						"outputs"    )    )

												__snake_case     			=       self.tool.inputs
												for _input in inputs:
																			if isinstance(_input							,						snake_case_    ):
																										for __input in _input:
																																	self.assertTrue(__input in authorized_types    )
																			else:
																										self.assertTrue(_input in authorized_types    )

												__snake_case     			=       self.tool.outputs
												for _output in outputs:
																			self.assertTrue(_output in authorized_types    )





					def 							lowerCAmelCase      (				self   :							int    ):
												__snake_case     			=       create_inputs(self.tool.inputs    )
												__snake_case     			=       self.tool(*snake_case_    )

												# There is a single output
												if len(self.tool.outputs    ) == 1:
																			__snake_case     			=       [outputs]

												self.assertListEqual(output_types(snake_case_    )							,						self.tool.outputs    )





					def 							lowerCAmelCase      (				self   :							Union[str, Any]    ):
												self.assertTrue(hasattr(self.tool							,						"description"    )    )
												self.assertTrue(hasattr(self.tool							,						"default_checkpoint"    )    )
												self.assertTrue(self.tool.description.startswith("This is a tool that"    )    )





					def 							lowerCAmelCase      (				self   :							Any    ):
												__snake_case     			=       create_inputs(self.tool.inputs    )
												__snake_case     			=       self.tool(*snake_case_    )

												if not isinstance(snake_case_							,						snake_case_    ):
																			__snake_case     			=       [outputs]

												self.assertEqual(len(snake_case_    )							,						len(self.tool.outputs    )    )

												for output, output_type in zip(snake_case_							,						self.tool.outputs    ):
																			__snake_case     			=       AGENT_TYPE_MAPPING[output_type]
																			self.assertTrue(isinstance(snake_case_							,						snake_case_    )    )





					def 							lowerCAmelCase      (				self   :							Tuple    ):
												__snake_case     			=       create_inputs(self.tool.inputs    )

												__snake_case     			=       []

												for _input, input_type in zip(snake_case_							,						self.tool.inputs    ):
																			if isinstance(snake_case_							,						snake_case_    ):
																										_inputs.append([AGENT_TYPE_MAPPING[_input_type](_input    ) for _input_type in input_type]    )
																			else:
																										_inputs.append(AGENT_TYPE_MAPPING[input_type](_input    )    )

        # Should not raise an error
												__snake_case     			=       self.tool(*snake_case_    )

												if not isinstance(snake_case_							,						snake_case_    ):
																			__snake_case     			=       [outputs]

												self.assertEqual(len(snake_case_    )							,						len(self.tool.outputs    )    )
