



"""simple docstring"""


import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
					import tensorflow as tf

if is_torch_available():
					import torch


__A :				Union[str, Any]					    = logging.get_logger(__name__)
class       _a			:
			"""simple docstring"""



			def __init__(		self  :     str					, __UpperCamelCase  :     Tuple = None					, __UpperCamelCase  :     int = None					, __UpperCamelCase  :     Union[str, Any]=None					, __UpperCamelCase  :     int=None )->Union[str, Any]:
							if not conversation_id:
											_UpperCAmelCase      		=     uuid.uuida()
							if past_user_inputs is None:
											_UpperCAmelCase      		=     []
							if generated_responses is None:
											_UpperCAmelCase      		=     []

							_UpperCAmelCase      		=     conversation_id
							_UpperCAmelCase      		=     past_user_inputs
							_UpperCAmelCase      		=     generated_responses
							_UpperCAmelCase      		=     text



			def __eq__(		self  :     List[Any]					, __UpperCamelCase  :     Optional[int] )->Any:
							if not isinstance(_a					, _a ):
											return False
							if self.uuid == other.uuid:
											return True
							return (
							    self.new_user_input == other.new_user_input
							    and self.past_user_inputs == other.past_user_inputs
							    and self.generated_responses == other.generated_responses
							)



			def 			lowercase__    (		self  :     Dict					, __UpperCamelCase  :     Optional[Any]					, __UpperCamelCase  :     List[str] = False )->List[str]:
							if self.new_user_input:
											if overwrite:
															logger.warning(
															    F'User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten '
															    F'with: \"{text}\".' )
															_UpperCAmelCase      		=     text
											else:
															logger.warning(
															    F'User input added while unprocessed input was existing: \"{self.new_user_input}\" new input '
															    F'ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input' )
							else:
											_UpperCAmelCase      		=     text



			def 			lowercase__    (		self  :     str )->Optional[int]:
							if self.new_user_input:
											self.past_user_inputs.append(self.new_user_input )
							_UpperCAmelCase      		=     None



			def 			lowercase__    (		self  :     int					, __UpperCamelCase  :     Optional[int] )->Optional[Any]:
							self.generated_responses.append(_a )



			def 			lowercase__    (		self  :     List[Any] )->str:
							for user_input, generated_response in zip(self.past_user_inputs					, self.generated_responses ):
											yield True, user_input
											yield False, generated_response
							if self.new_user_input:
											yield True, self.new_user_input



			def __repr__(		self  :     List[str] )->Optional[int]:
							_UpperCAmelCase      		=     F'Conversation id: {self.uuid} \n'
							for is_user, text in self.iter_texts():
											_UpperCAmelCase      		=     '''user''' if is_user else '''bot'''
											output += F'{name} >> {text} \n'
							return output



@add_end_docstrings(
    __lowercase      ,				r"""\n        min_length_for_response (`int`, *optional*, defaults to 32):\n            The minimum length (in number of tokens) for a response.\n        minimum_tokens (`int`, *optional*, defaults to 10):\n            The minimum length of tokens to leave for a response.\n    """      ,				)
class       _a			(       __lowercase):
			"""simple docstring"""



			def __init__(		self  :     Tuple					, *__UpperCamelCase  :     Union[str, Any]					, **__UpperCamelCase  :     int )->List[str]:
							super().__init__(*_a					, **_a )
							if self.tokenizer.pad_token_id is None:
											_UpperCAmelCase      		=     self.tokenizer.eos_token



			def 			lowercase__    (		self  :     Any					, __UpperCamelCase  :     int=None					, __UpperCamelCase  :     List[str]=None					, __UpperCamelCase  :     Optional[Any]=None					, **__UpperCamelCase  :     Optional[int] )->Union[str, Any]:
							_UpperCAmelCase      		=     {}
							_UpperCAmelCase      		=     {}
							_UpperCAmelCase      		=     {}

							if min_length_for_response is not None:
											_UpperCAmelCase      		=     min_length_for_response
							if minimum_tokens is not None:
											_UpperCAmelCase      		=     minimum_tokens

							if "max_length" in generate_kwargs:
											_UpperCAmelCase      		=     generate_kwargs['''max_length''']
											# self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
							if clean_up_tokenization_spaces is not None:
											_UpperCAmelCase      		=     clean_up_tokenization_spaces

							if generate_kwargs:
											forward_params.update(_a )
							return preprocess_params, forward_params, postprocess_params



			def __call__(		self  :     Dict					, __UpperCamelCase  :     Optional[int]					, __UpperCamelCase  :     int=0					, **__UpperCamelCase  :     int )->int:
							_UpperCAmelCase      		=     super().__call__(_a					, num_workers=_a					, **_a )
							if isinstance(_a					, _a ) and len(_a ) == 1:
											return outputs[0]
							return outputs



			def 			lowercase__    (		self  :     Optional[int]					, __UpperCamelCase  :     Any					, __UpperCamelCase  :     Union[str, Any]=3_2 )->Dict[str, Any]:
							if not isinstance(_a					, _a ):
											raise ValueError('''ConversationalPipeline, expects Conversation as inputs''' )
							if conversation.new_user_input is None:
											raise ValueError(
											    F'Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. '
											    '''Add user inputs with the conversation\'s `add_user_input` method''' )
							if hasattr(self.tokenizer					, '''_build_conversation_input_ids''' ):
											_UpperCAmelCase      		=     self.tokenizer._build_conversation_input_ids(_a )
							else:
											# If the tokenizer cannot handle conversations, we default to only the old version
											_UpperCAmelCase      		=     self._legacy_parse_and_tokenize(_a )

							if self.framework == "pt":
											_UpperCAmelCase      		=     torch.LongTensor([input_ids] )
							elif self.framework == "tf":
											_UpperCAmelCase      		=     tf.constant([input_ids] )
							return {"input_ids": input_ids, "conversation": conversation}



			def 			lowercase__    (		self  :     Tuple					, __UpperCamelCase  :     Any					, __UpperCamelCase  :     str=1_0					, **__UpperCamelCase  :     Optional[int] )->Union[str, Any]:
							_UpperCAmelCase      		=     generate_kwargs.get('''max_length'''					, self.model.config.max_length )

							_UpperCAmelCase      		=     model_inputs['''input_ids'''].shape[1]
							if max_length - minimum_tokens < n:
											logger.warning(F'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})' )
											_UpperCAmelCase      		=     max_length - minimum_tokens
											_UpperCAmelCase      		=     model_inputs['''input_ids'''][:, -trim:]
											if "attention_mask" in model_inputs:
															_UpperCAmelCase      		=     model_inputs['''attention_mask'''][:, -trim:]
							_UpperCAmelCase      		=     model_inputs.pop('''conversation''' )
							_UpperCAmelCase      		=     max_length
							_UpperCAmelCase      		=     self.model.generate(**_a					, **_a )
							if self.model.config.is_encoder_decoder:
											_UpperCAmelCase      		=     1
							else:
											_UpperCAmelCase      		=     n
							return {"output_ids": output_ids[:, start_position:], "conversation": conversation}



			def 			lowercase__    (		self  :     Dict					, __UpperCamelCase  :     List[str]					, __UpperCamelCase  :     List[Any]=True )->Union[str, Any]:
							_UpperCAmelCase      		=     model_outputs['''output_ids''']
							_UpperCAmelCase      		=     self.tokenizer.decode(
							    output_ids[0]					, skip_special_tokens=_a					, clean_up_tokenization_spaces=_a					, )
							_UpperCAmelCase      		=     model_outputs['''conversation''']
							conversation.mark_processed()
							conversation.append_response(_a )
							return conversation



			def 			lowercase__    (		self  :     Optional[int]					, __UpperCamelCase  :     Any )->Dict:
							_UpperCAmelCase      		=     self.tokenizer.eos_token_id
							_UpperCAmelCase      		=     []
							for is_user, text in conversation.iter_texts():
											if eos_token_id is not None:
															input_ids.extend(self.tokenizer.encode(_a					, add_special_tokens=_a ) + [eos_token_id] )
											else:
															input_ids.extend(self.tokenizer.encode(_a					, add_special_tokens=_a ) )

							if len(_a ) > self.tokenizer.model_max_length:
											_UpperCAmelCase      		=     input_ids[-self.tokenizer.model_max_length :]
							return input_ids






import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402

class 							UpperCAmelCase_						(     unittest.TestCase  ):
							"""simple docstring"""







							def 							__lowercase							(     self			)       ->       List[Any]:
												_a      :       int   =						0


							def 							__lowercase							(     self			)       ->       List[str]:
												_a      :       Dict   =						AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''			)
												self.assertIsInstance(_a			,				_a			)


							def 							__lowercase							(     self			)       ->       Union[str, Any]:
												with tempfile.TemporaryDirectory() as tmpdirname:
																	_a      :       Tuple   =						Path(_a			) / '''preprocessor_config.json'''
																	_a      :       Optional[Any]   =						Path(_a			) / '''config.json'''
																	json.dump(
																	    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			,				open(_a			,				'''w'''			)			,				)
																	json.dump({'''model_type''': '''clip'''}			,				open(_a			,				'''w'''			)			)

																	_a      :       List[str]   =						AutoImageProcessor.from_pretrained(_a			)
																	self.assertIsInstance(_a			,				_a			)


							def 							__lowercase							(     self			)       ->       Optional[Any]:
												# Ensure we can load the image processor from the feature extractor config
												with tempfile.TemporaryDirectory() as tmpdirname:
																	_a      :       Optional[int]   =						Path(_a			) / '''preprocessor_config.json'''
																	_a      :       Any   =						Path(_a			) / '''config.json'''
																	json.dump(
																	    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}			,				open(_a			,				'''w'''			)			,				)
																	json.dump({'''model_type''': '''clip'''}			,				open(_a			,				'''w'''			)			)

																	_a      :       Optional[Any]   =						AutoImageProcessor.from_pretrained(_a			)
																	self.assertIsInstance(_a			,				_a			)


							def 							__lowercase							(     self			)       ->       Optional[Any]:
												with tempfile.TemporaryDirectory() as tmpdirname:
																	_a      :       Dict   =						CLIPConfig()

																	# Create a dummy config file with image_proceesor_type
																	_a      :       Tuple   =						Path(_a			) / '''preprocessor_config.json'''
																	_a      :       List[str]   =						Path(_a			) / '''config.json'''
																	json.dump(
																	    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			,				open(_a			,				'''w'''			)			,				)
																	json.dump({'''model_type''': '''clip'''}			,				open(_a			,				'''w'''			)			)

																	# remove image_processor_type to make sure config.json alone is enough to load image processor locally
																	_a      :       Tuple   =						AutoImageProcessor.from_pretrained(_a			).to_dict()

																	config_dict.pop('''image_processor_type'''			)
																	_a      :       Tuple   =						CLIPImageProcessor(**_a			)

																	# save in new folder
																	model_config.save_pretrained(_a			)
																	config.save_pretrained(_a			)

																	_a      :       List[str]   =						AutoImageProcessor.from_pretrained(_a			)

																	# make sure private variable is not incorrectly saved
																	_a      :       Optional[int]   =						json.loads(config.to_json_string()			)
																	self.assertTrue('''_processor_class''' not in dict_as_saved			)

												self.assertIsInstance(_a			,				_a			)


							def 							__lowercase							(     self			)       ->       Dict:
												with tempfile.TemporaryDirectory() as tmpdirname:
																	_a      :       Optional[int]   =						Path(_a			) / '''preprocessor_config.json'''
																	json.dump(
																	    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			,				open(_a			,				'''w'''			)			,				)

																	_a      :       List[str]   =						AutoImageProcessor.from_pretrained(_a			)
																	self.assertIsInstance(_a			,				_a			)


							def 							__lowercase							(     self			)       ->       Any:
												with self.assertRaisesRegex(
												    _a			,				'''clip-base is not a local folder and is not a valid model identifier'''			):
																	_a      :       Dict   =						AutoImageProcessor.from_pretrained('''clip-base'''			)


							def 							__lowercase							(     self			)       ->       List[Any]:
												with self.assertRaisesRegex(
												    _a			,				R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''			):
																	_a      :       List[str]   =						AutoImageProcessor.from_pretrained(_a			,				revision='''aaaaaa'''			)


							def 							__lowercase							(     self			)       ->       Dict:
												with self.assertRaisesRegex(
												    _a			,				'''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''			,				):
																	_a      :       Optional[int]   =						AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model'''			)


							def 							__lowercase							(     self			)       ->       Union[str, Any]:
												# If remote code is not set, we will time out when asking whether to load the model.
												with self.assertRaises(_a			):
																	_a      :       str   =						AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''			)
												# If remote code is disabled, we can't load this config.
												with self.assertRaises(_a			):
																	_a      :       Optional[Any]   =						AutoImageProcessor.from_pretrained(
																	    '''hf-internal-testing/test_dynamic_image_processor'''			,				trust_remote_code=_a			)

												_a      :       Union[str, Any]   =						AutoImageProcessor.from_pretrained(
												    '''hf-internal-testing/test_dynamic_image_processor'''			,				trust_remote_code=_a			)
												self.assertEqual(image_processor.__class__.__name__			,				'''NewImageProcessor'''			)

												# Test image processor can be reloaded.
												with tempfile.TemporaryDirectory() as tmp_dir:
																	image_processor.save_pretrained(_a			)
																	_a      :       Optional[Any]   =						AutoImageProcessor.from_pretrained(_a			,				trust_remote_code=_a			)
												self.assertEqual(reloaded_image_processor.__class__.__name__			,				'''NewImageProcessor'''			)


							def 							__lowercase							(     self			)       ->       Dict:
												try:
																	AutoConfig.register('''custom'''			,				_a			)
																	AutoImageProcessor.register(_a			,				_a			)
																	# Trying to register something existing in the Transformers library will raise an error
																	with self.assertRaises(_a			):
																						AutoImageProcessor.register(_a			,				_a			)

																	with tempfile.TemporaryDirectory() as tmpdirname:
																						_a      :       int   =						Path(_a			) / '''preprocessor_config.json'''
																						_a      :       int   =						Path(_a			) / '''config.json'''
																						json.dump(
																						    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}			,				open(_a			,				'''w'''			)			,				)
																						json.dump({'''model_type''': '''clip'''}			,				open(_a			,				'''w'''			)			)

																						_a      :       int   =						CustomImageProcessor.from_pretrained(_a			)

																	# Now that the config is registered, it can be used as any other config with the auto-API
																	with tempfile.TemporaryDirectory() as tmp_dir:
																						image_processor.save_pretrained(_a			)
																						_a      :       Optional[Any]   =						AutoImageProcessor.from_pretrained(_a			)
																						self.assertIsInstance(_a			,				_a			)

												finally:
																	if "custom" in CONFIG_MAPPING._extra_content:
																						del CONFIG_MAPPING._extra_content["custom"]
																	if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																						del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]




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

												class 							UpperCAmelCase_						(     __lowercase  ):
																			"""simple docstring"""







																			UpperCAmelCase__			:		Tuple             =       True

												try:
																	AutoConfig.register('''custom'''			,				_a			)
																	AutoImageProcessor.register(_a			,				_a			)
																	# If remote code is not set, the default is to use local
																	_a      :       str   =						AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''			)
																	self.assertEqual(image_processor.__class__.__name__			,				'''NewImageProcessor'''			)
																	self.assertTrue(image_processor.is_local			)

																	# If remote code is disabled, we load the local one.
																	_a      :       int   =						AutoImageProcessor.from_pretrained(
																	    '''hf-internal-testing/test_dynamic_image_processor'''			,				trust_remote_code=_a			)
																	self.assertEqual(image_processor.__class__.__name__			,				'''NewImageProcessor'''			)
																	self.assertTrue(image_processor.is_local			)

																	# If remote is enabled, we load from the Hub
																	_a      :       Dict   =						AutoImageProcessor.from_pretrained(
																	    '''hf-internal-testing/test_dynamic_image_processor'''			,				trust_remote_code=_a			)
																	self.assertEqual(image_processor.__class__.__name__			,				'''NewImageProcessor'''			)
																	self.assertTrue(not hasattr(_a			,				'''is_local'''			)			)

												finally:
																	if "custom" in CONFIG_MAPPING._extra_content:
																						del CONFIG_MAPPING._extra_content["custom"]
																	if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																						del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]



