




"""simple docstring"""







import os
import pathlib
import tempfile
import uuid

import numpy as np

from ..utils import is_soundfile_availble, is_torch_available, is_vision_available, logging


SCREAMING_SNAKE_CASE_      =					logging.get_logger(__name__)

if is_vision_available():
		import PIL.Image
		from PIL import Image
		from PIL.Image import Image as ImageType
else:
		SCREAMING_SNAKE_CASE_      =					object

if is_torch_available():
		import torch

if is_soundfile_availble():
		import soundfile as sf

class 							snake_case_ :







			"""simple docstring"""




			def __init__(		self					,				lowerCamelCase_)							->      List[Any]:
							UpperCamelCase										=  value







			def __str__(		self)							->      Any:
							return self.to_string()







			def      UpperCAmelCase__ (		self)							->      Dict:
							logger.error(
							    '''This is a raw AgentType of unknown type. Display in notebooks and string conversion will be unreliable''')
							return self._value







			def      UpperCAmelCase__ (		self)							->      str:
							logger.error(
							    '''This is a raw AgentType of unknown type. Display in notebooks and string conversion will be unreliable''')
							return str(self._value)

class 							snake_case_ (				__SCREAMING_SNAKE_CASE  ,   __SCREAMING_SNAKE_CASE ):







			"""simple docstring"""




			def      UpperCAmelCase__ (		self)							->      int:
							return self._value







			def      UpperCAmelCase__ (		self)							->      int:
							return self._value

class 							snake_case_ (				__SCREAMING_SNAKE_CASE  ,   __SCREAMING_SNAKE_CASE ):







			"""simple docstring"""




			def __init__(		self					,				lowerCamelCase_)							->      Optional[int]:
							super().__init__(UpperCamelCase__)

							if not is_vision_available():
											raise ImportError('''PIL must be installed in order to handle images.''')

							UpperCamelCase										=  None
							UpperCamelCase										=  None
							UpperCamelCase										=  None

							if isinstance(UpperCamelCase__					,				UpperCamelCase__):
											UpperCamelCase										=  value
							elif isinstance(UpperCamelCase__					,				(str, pathlib.Path)):
											UpperCamelCase										=  value
							elif isinstance(UpperCamelCase__					,				torch.Tensor):
											UpperCamelCase										=  value
							else:
											raise ValueError(F'Unsupported type for {self.__class__.__name__}: {type(UpperCamelCase__)}')







			def      UpperCAmelCase__ (		self					,				lowerCamelCase_=None					,				lowerCamelCase_=None)							->      List[Any]:
							from IPython.display import Image, display

							display(Image(self.to_string()))







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







							if self._raw is not None:
											return self._raw

							if self._path is not None:
											UpperCamelCase										=  Image.open(self._path)
											return self._raw







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







							if self._path is not None:
											return self._path

							if self._raw is not None:
											UpperCamelCase										=  tempfile.mkdtemp()
											UpperCamelCase										=  os.path.join(UpperCamelCase__					,				str(uuid.uuida()) + '''.png''')
											self._raw.save(self._path)

											return self._path

							if self._tensor is not None:
											UpperCamelCase										=  self._tensor.cpu().detach().numpy()

											# There is likely simpler than load into image into save
											UpperCamelCase										=  Image.fromarray((array * 2_5_5).astype(np.uinta))

											UpperCamelCase										=  tempfile.mkdtemp()
											UpperCamelCase										=  os.path.join(UpperCamelCase__					,				str(uuid.uuida()) + '''.png''')

											img.save(self._path)

											return self._path

class 							snake_case_ (				__SCREAMING_SNAKE_CASE ):







			"""simple docstring"""




			def __init__(		self					,				lowerCamelCase_					,				lowerCamelCase_=1_6_0_0_0)							->      Any:
							super().__init__(UpperCamelCase__)

							if not is_soundfile_availble():
											raise ImportError('''soundfile must be installed in order to handle audio.''')

							UpperCamelCase										=  None
							UpperCamelCase										=  None

							UpperCamelCase										=  samplerate

							if isinstance(UpperCamelCase__					,				(str, pathlib.Path)):
											UpperCamelCase										=  value
							elif isinstance(UpperCamelCase__					,				torch.Tensor):
											UpperCamelCase										=  value
							else:
											raise ValueError(F'Unsupported audio type: {type(UpperCamelCase__)}')







			def      UpperCAmelCase__ (		self					,				lowerCamelCase_=None					,				lowerCamelCase_=None)							->      Tuple:
							from IPython.display import Audio, display

							display(Audio(self.to_string()					,				rate=self.samplerate))







			def      UpperCAmelCase__ (		self)							->      Tuple:







							if self._tensor is not None:
											return self._tensor

							if self._path is not None:
											UpperCamelCase										=  sf.read(self._path)
											UpperCamelCase										=  torch.tensor(UpperCamelCase__)
											return self._tensor







			def      UpperCAmelCase__ (		self)							->      Any:







							if self._path is not None:
											return self._path

							if self._tensor is not None:
											UpperCamelCase										=  tempfile.mkdtemp()
											UpperCamelCase										=  os.path.join(UpperCamelCase__					,				str(uuid.uuida()) + '''.wav''')
											sf.write(self._path					,				self._tensor					,				samplerate=self.samplerate)
											return self._path
SCREAMING_SNAKE_CASE_      =					{'text': AgentText, 'image': AgentImage, 'audio': AgentAudio}
SCREAMING_SNAKE_CASE_      =					{str: AgentText}

if is_vision_available():
		SCREAMING_SNAKE_CASE_      =					AgentImage





def     __snake_case   (							*_lowercase ,**_lowercase						):


				"""simple docstring"""







				UpperCamelCase										=  [(arg.to_raw() if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__						) else arg) for arg in args]
				UpperCamelCase										=  {k: (v.to_raw() if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__						) else v) for k, v in kwargs.items()}
				return args, kwargs





def     __snake_case   (							_lowercase ,_lowercase=None						):


				"""simple docstring"""







				if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__						):
								UpperCamelCase										=  {}
								for i, (k, v) in enumerate(outputs.items()						):
												if output_types is not None:
																# If the class has defined outputs, we can map directly according to the class definition
																if output_types[i] in AGENT_TYPE_MAPPING:
																				UpperCamelCase										=  AGENT_TYPE_MAPPING[output_types[i]](SCREAMING_SNAKE_CASE__						)
																else:
																				UpperCamelCase										=  AgentType(SCREAMING_SNAKE_CASE__						)

												else:
																# If the class does not have defined output, then we map according to the type
																for _k, _v in INSTANCE_TYPE_MAPPING.items():
																				if isinstance(SCREAMING_SNAKE_CASE__ ,_k						):
																								UpperCamelCase										=  _v(SCREAMING_SNAKE_CASE__						)
																if k not in decoded_outputs:
																				UpperCamelCase										=  AgentType[v]

				elif isinstance(SCREAMING_SNAKE_CASE__ ,(list, tuple)						):
								UpperCamelCase										=  type(SCREAMING_SNAKE_CASE__						)()
								for i, v in enumerate(SCREAMING_SNAKE_CASE__						):
												if output_types is not None:
																# If the class has defined outputs, we can map directly according to the class definition
																if output_types[i] in AGENT_TYPE_MAPPING:
																				decoded_outputs.append(AGENT_TYPE_MAPPING[output_types[i]](SCREAMING_SNAKE_CASE__						)						)
																else:
																				decoded_outputs.append(AgentType(SCREAMING_SNAKE_CASE__						)						)
												else:
																# If the class does not have defined output, then we map according to the type
																UpperCamelCase										=  False
																for _k, _v in INSTANCE_TYPE_MAPPING.items():
																				if isinstance(SCREAMING_SNAKE_CASE__ ,_k						):
																								decoded_outputs.append(_v(SCREAMING_SNAKE_CASE__						)						)
																								UpperCamelCase										=  True

																if not found:
																				decoded_outputs.append(AgentType(SCREAMING_SNAKE_CASE__						)						)

				else:
								if output_types[0] in AGENT_TYPE_MAPPING:
												# If the class has defined outputs, we can map directly according to the class definition
												UpperCamelCase										=  AGENT_TYPE_MAPPING[output_types[0]](SCREAMING_SNAKE_CASE__						)

								else:
												# If the class does not have defined output, then we map according to the type
												for _k, _v in INSTANCE_TYPE_MAPPING.items():
																if isinstance(SCREAMING_SNAKE_CASE__ ,_k						):
																				return _v(SCREAMING_SNAKE_CASE__						)
												return AgentType(SCREAMING_SNAKE_CASE__						)

				return decoded_outputs





"""simple docstring"""







from __future__ import annotations

import unittest

from transformers import CTRLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers.models.ctrl.modeling_tf_ctrl import (
      TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFCTRLForSequenceClassification,
      TFCTRLLMHeadModel,
      TFCTRLModel,
  )

class 							snake_case_ (				lowerCamelCase_ ):







   """simple docstring"""




   def __init__(		self					,				lowerCamelCase_					,				)							->      Any:
       UpperCamelCase										=  parent
       UpperCamelCase										=  1_3
       UpperCamelCase										=  7
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  True
       UpperCamelCase										=  9_9
       UpperCamelCase										=  3_2
       UpperCamelCase										=  2
       UpperCamelCase										=  4
       UpperCamelCase										=  3_7
       UpperCamelCase										=  '''gelu'''
       UpperCamelCase										=  0.1
       UpperCamelCase										=  0.1
       UpperCamelCase										=  5_1_2
       UpperCamelCase										=  1_6
       UpperCamelCase										=  2
       UpperCamelCase										=  0.02
       UpperCamelCase										=  3
       UpperCamelCase										=  4
       UpperCamelCase										=  None
       UpperCamelCase										=  self.vocab_size - 1







   def      UpperCAmelCase__ (		self)							->      int:
       UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]					,				self.vocab_size)

       UpperCamelCase										=  None
       if self.use_input_mask:
           UpperCamelCase										=  random_attention_mask([self.batch_size, self.seq_length])

       UpperCamelCase										=  None
       if self.use_token_type_ids:
           UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]					,				self.type_vocab_size)

       UpperCamelCase										=  None
       if self.use_mc_token_ids:
           UpperCamelCase										=  ids_tensor([self.batch_size, self.num_choices]					,				self.seq_length)

       UpperCamelCase										=  None
       UpperCamelCase										=  None
       UpperCamelCase										=  None
       if self.use_labels:
           UpperCamelCase										=  ids_tensor([self.batch_size]					,				self.type_sequence_label_size)
           UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]					,				self.num_labels)
           UpperCamelCase										=  ids_tensor([self.batch_size]					,				self.num_choices)

       UpperCamelCase										=  CTRLConfig(
           vocab_size=self.vocab_size					,				n_embd=self.hidden_size					,				n_layer=self.num_hidden_layers					,				n_head=self.num_attention_heads					,				n_positions=self.max_position_embeddings					,				pad_token_id=self.pad_token_id					,				)

       UpperCamelCase										=  ids_tensor([self.num_hidden_layers, self.num_attention_heads]					,				2)

       return (
           config,
           input_ids,
           input_mask,
           head_mask,
           token_type_ids,
           mc_token_ids,
           sequence_labels,
           token_labels,
           choice_labels,
       )







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				*lowerCamelCase_)							->      Optional[Any]:
       UpperCamelCase										=  TFCTRLModel(config=lowerCamelCase_)
       UpperCamelCase										=  {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
       UpperCamelCase										=  model(lowerCamelCase_)

       UpperCamelCase										=  [input_ids, None, input_mask]  # None is the input for 'past'
       UpperCamelCase										=  model(lowerCamelCase_)

       UpperCamelCase										=  model(lowerCamelCase_)

       self.parent.assertEqual(result.last_hidden_state.shape					,				(self.batch_size, self.seq_length, self.hidden_size))







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				*lowerCamelCase_)							->      int:
       UpperCamelCase										=  TFCTRLLMHeadModel(config=lowerCamelCase_)
       UpperCamelCase										=  {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
       UpperCamelCase										=  model(lowerCamelCase_)
       self.parent.assertEqual(result.logits.shape					,				(self.batch_size, self.seq_length, self.vocab_size))







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				*lowerCamelCase_)							->      List[str]:
       UpperCamelCase										=  self.num_labels
       UpperCamelCase										=  ids_tensor([self.batch_size]					,				self.type_sequence_label_size)
       UpperCamelCase										=  {
           '''input_ids''': input_ids,
           '''token_type_ids''': token_type_ids,
           '''labels''': sequence_labels,
       }
       UpperCamelCase										=  TFCTRLForSequenceClassification(lowerCamelCase_)
       UpperCamelCase										=  model(lowerCamelCase_)
       self.parent.assertEqual(result.logits.shape					,				(self.batch_size, self.num_labels))







   def      UpperCAmelCase__ (		self)							->      str:
       UpperCamelCase										=  self.prepare_config_and_inputs()

       (
           (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  (
           UpperCamelCase
       )					,  
       )										=  config_and_inputs

       UpperCamelCase										=  {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
       return config, inputs_dict

@require_tf
class 							snake_case_ (				lowerCamelCase_  ,   lowerCamelCase_  ,   unittest.TestCase ):







   """simple docstring"""




   A_										=					(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
   A_										=					(TFCTRLLMHeadModel,) if is_tf_available() else ()
   A_										=					(
       {
           '''feature-extraction''': TFCTRLModel,
           '''text-classification''': TFCTRLForSequenceClassification,
           '''text-generation''': TFCTRLLMHeadModel,
           '''zero-shot''': TFCTRLForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   A_										=					False
   A_										=					False







   def      UpperCAmelCase__ (		self					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_					,				lowerCamelCase_)							->      int:
       if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
           # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
           # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
           # config could not be created.
           return True

       return False







   def      UpperCAmelCase__ (		self)							->      int:
       UpperCamelCase										=  TFCTRLModelTester(self)
       UpperCamelCase										=  ConfigTester(self					,				config_class=lowerCamelCase_					,				n_embd=3_7)







   def      UpperCAmelCase__ (		self)							->      int:
       self.config_tester.run_common_tests()







   def      UpperCAmelCase__ (		self)							->      Union[str, Any]:
       UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_model(*lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      List[Any]:
       UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_lm_head(*lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      List[Any]:
       UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_for_sequence_classification(*lowerCamelCase_)







   def      UpperCAmelCase__ (		self)							->      List[str]:
       UpperCamelCase					,  UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase										=  [TFCTRLLMHeadModel]
       UpperCamelCase										=  [TFCTRLForSequenceClassification]

       for model_class in self.all_model_classes:
           UpperCamelCase										=  model_class(lowerCamelCase_)
           model.build()  # may be needed for the get_bias() call below
           assert isinstance(model.get_input_embeddings()					,				tf.keras.layers.Layer)

           if model_class in list_lm_models:
               UpperCamelCase										=  model.get_output_embeddings()
               assert isinstance(lowerCamelCase_					,				tf.keras.layers.Layer)
               UpperCamelCase										=  model.get_bias()
               assert isinstance(lowerCamelCase_					,				lowerCamelCase_)
               for k, v in name.items():
                   assert isinstance(lowerCamelCase_					,				tf.Variable)
           elif model_class in list_other_models_with_output_ebd:
               UpperCamelCase										=  model.get_output_embeddings()
               assert isinstance(lowerCamelCase_					,				tf.keras.layers.Layer)
               UpperCamelCase										=  model.get_bias()
               assert name is None
           else:
               UpperCamelCase										=  model.get_output_embeddings()
               assert x is None
               UpperCamelCase										=  model.get_bias()
               assert name is None







   @slow
   def      UpperCAmelCase__ (		self)							->      List[Any]:
       for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase										=  TFCTRLModel.from_pretrained(lowerCamelCase_)
           self.assertIsNotNone(lowerCamelCase_)

@require_tf
class 							snake_case_ (				unittest.TestCase ):







   """simple docstring"""




   @slow
   def      UpperCAmelCase__ (		self)							->      str:
       UpperCamelCase										=  TFCTRLLMHeadModel.from_pretrained('''ctrl''')
       UpperCamelCase										=  tf.convert_to_tensor([[1_1_8_5_9, 0, 1_6_1_1, 8]]					,				dtype=tf.intaa)  # Legal the president is
       UpperCamelCase										=  [
           1_1_8_5_9,
           0,
           1_6_1_1,
           8,
           5,
           1_5_0,
           2_6_4_4_9,
           2,
           1_9,
           3_4_8,
           4_6_9,
           3,
           2_5_9_5,
           4_8,
           2_0_7_4_0,
           2_4_6_5_3_3,
           2_4_6_5_3_3,
           1_9,
           3_0,
           5,
       ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

       UpperCamelCase										=  model.generate(lowerCamelCase_					,				do_sample=lowerCamelCase_)
       self.assertListEqual(output_ids[0].numpy().tolist()					,				lowerCamelCase_)