






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_		:    int   							=     logging.get_logger(__name__)

class 		_snake_case	:






			def __init__(							self		,       a = None		,       a = None		,       a=None		,       a=None)   ->							Optional[int]:
						if not conversation_id:
									SCREAMING_SNAKE_CASE							=			uuid.uuida()
						if past_user_inputs is None:
									SCREAMING_SNAKE_CASE							=			[]
						if generated_responses is None:
									SCREAMING_SNAKE_CASE							=			[]

						SCREAMING_SNAKE_CASE							=			conversation_id
						SCREAMING_SNAKE_CASE							=			past_user_inputs
						SCREAMING_SNAKE_CASE							=			generated_responses
						SCREAMING_SNAKE_CASE							=			text






			def __eq__(							self		,       a)   ->							List[Any]:
						if not isinstance(lowerCamelCase__		,       lowerCamelCase__):
									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  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a = False)   ->							Dict:
						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}\".''')
												SCREAMING_SNAKE_CASE							=			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:
									SCREAMING_SNAKE_CASE							=			text






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Union[str, Any]:
						if self.new_user_input:
									self.past_user_inputs.append(self.new_user_input)
						SCREAMING_SNAKE_CASE							=			None






			def  SCREAMING_SNAKE_CASE__     (							self		,       a)   ->							Optional[Any]:
						self.generated_responses.append(lowerCamelCase__)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Union[str, Any]:
						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]:
						SCREAMING_SNAKE_CASE							=			f'''Conversation id: {self.uuid} \n'''
						for is_user, text in self.iter_texts():
									SCREAMING_SNAKE_CASE							=			'user' if is_user else 'bot'
									output += f'''{name} >> {text} \n'''
						return output



@add_end_docstrings(
    A__ ,     R'''
        min_length_for_response (`int`, *optional*, defaults to 32):
            The minimum length (in number of tokens) for a response.
        minimum_tokens (`int`, *optional*, defaults to 10):
            The minimum length of tokens to leave for a response.
    ''' ,     )
class 		_snake_case	(	A__       ):






			def __init__(							self		,       *a		,       **a)   ->							List[Any]:
						super().__init__(*lowerCamelCase__		,       **lowerCamelCase__)
						if self.tokenizer.pad_token_id is None:
									SCREAMING_SNAKE_CASE							=			self.tokenizer.eos_token






			def  SCREAMING_SNAKE_CASE__     (							self		,       a=None		,       a=None		,       a=None		,       **a)   ->							List[str]:
						SCREAMING_SNAKE_CASE							=			{}
						SCREAMING_SNAKE_CASE							=			{}
						SCREAMING_SNAKE_CASE							=			{}

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

						if "max_length" in generate_kwargs:
									SCREAMING_SNAKE_CASE							=			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:
									SCREAMING_SNAKE_CASE							=			clean_up_tokenization_spaces

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






			def __call__(							self		,       a		,       a=0		,       **a)   ->							Optional[int]:
						SCREAMING_SNAKE_CASE							=			super().__call__(lowerCamelCase__		,       num_workers=lowerCamelCase__		,       **lowerCamelCase__)
						if isinstance(lowerCamelCase__		,       lowerCamelCase__) and len(lowerCamelCase__) == 1:
									return outputs[0]
						return outputs






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a=32)   ->							Dict[str, Any]:
						if not isinstance(lowerCamelCase__		,       lowerCamelCase__):
									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'):
									SCREAMING_SNAKE_CASE							=			self.tokenizer._build_conversation_input_ids(lowerCamelCase__)
						else:
									# If the tokenizer cannot handle conversations, we default to only the old version
									SCREAMING_SNAKE_CASE							=			self._legacy_parse_and_tokenize(lowerCamelCase__)

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






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a=10		,       **a)   ->							str:
						SCREAMING_SNAKE_CASE							=			generate_kwargs.get('max_length'		,       self.model.config.max_length)

						SCREAMING_SNAKE_CASE							=			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})''')
									SCREAMING_SNAKE_CASE							=			max_length - minimum_tokens
									SCREAMING_SNAKE_CASE							=			model_inputs['input_ids'][:, -trim:]
									if "attention_mask" in model_inputs:
												SCREAMING_SNAKE_CASE							=			model_inputs['attention_mask'][:, -trim:]
						SCREAMING_SNAKE_CASE							=			model_inputs.pop('conversation')
						SCREAMING_SNAKE_CASE							=			max_length
						SCREAMING_SNAKE_CASE							=			self.model.generate(**lowerCamelCase__		,       **lowerCamelCase__)
						if self.model.config.is_encoder_decoder:
									SCREAMING_SNAKE_CASE							=			1
						else:
									SCREAMING_SNAKE_CASE							=			n
						return {"output_ids": output_ids[:, start_position:], "conversation": conversation}






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a=True)   ->							Union[str, Any]:
						SCREAMING_SNAKE_CASE							=			model_outputs['output_ids']
						SCREAMING_SNAKE_CASE							=			self.tokenizer.decode(
						    output_ids[0]		,       skip_special_tokens=lowerCamelCase__		,       clean_up_tokenization_spaces=lowerCamelCase__		,       )
						SCREAMING_SNAKE_CASE							=			model_outputs['conversation']
						conversation.mark_processed()
						conversation.append_response(lowerCamelCase__)
						return conversation







			def  SCREAMING_SNAKE_CASE__     (							self		,       a)   ->							Dict:
						SCREAMING_SNAKE_CASE							=			self.tokenizer.eos_token_id
						SCREAMING_SNAKE_CASE							=			[]
						for is_user, text in conversation.iter_texts():
									if eos_token_id is not None:
												input_ids.extend(self.tokenizer.encode(lowerCamelCase__		,       add_special_tokens=lowerCamelCase__) + [eos_token_id])
									else:
												input_ids.extend(self.tokenizer.encode(lowerCamelCase__		,       add_special_tokens=lowerCamelCase__))

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










import importlib.metadata
import operator
import re
import sys
from typing import Optional

from packaging import version


__A								=       {
    "<": operator.lt,
    "<=": operator.le,
    "==": operator.eq,
    "!=": operator.ne,
    ">=": operator.ge,
    ">": operator.gt,
}







def      lowerCamelCase_						(			UpperCamelCase__							: List[str]					,	UpperCamelCase__							: Dict					,	UpperCamelCase__							: Dict					,	UpperCamelCase__							: Any					,	UpperCamelCase__							: Dict					,	UpperCamelCase__							: int )	->			List[Any]:





				"""simple docstring"""


				if got_ver is None or want_ver is None:
								raise ValueError(
								    F"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider"""
								    F""" reinstalling {pkg}.""" )
				if not ops[op](version.parse(UpperCamelCase__ )					,	version.parse(UpperCamelCase__ ) ):
								raise ImportError(
								    F"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" )







def      lowerCamelCase_						(			UpperCamelCase__							: str					,	UpperCamelCase__							: Optional[str] = None )	->			None:





				"""simple docstring"""


				__lowerCamelCase									=       F"""\n{hint}""" if hint is not None else ''

				# non-versioned check
				if re.match(R'^[\w_\-\d]+$'					,	UpperCamelCase__ ):
								__lowerCamelCase			,		__lowerCamelCase			,		__lowerCamelCase									=       requirement, None, None
				else:
								__lowerCamelCase									=       re.findall(R'^([^!=<>\s]+)([\s!=<>]{1,2}.+)'					,	UpperCamelCase__ )
								if not match:
												raise ValueError(
												    'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but'
												    F""" got {requirement}""" )
								__lowerCamelCase			,		__lowerCamelCase									=       match[0]
								__lowerCamelCase									=       want_full.split(',' )  # there could be multiple requirements
								__lowerCamelCase									=       {}
								for w in want_range:
												__lowerCamelCase									=       re.findall(R'^([\s!=<>]{1,2})(.+)'					,	UpperCamelCase__ )
												if not match:
																raise ValueError(
																    'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,'
																    F""" but got {requirement}""" )
												__lowerCamelCase			,		__lowerCamelCase									=       match[0]
												__lowerCamelCase									=       want_ver
												if op not in ops:
																raise ValueError(F"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" )

    # special case
				if pkg == "python":
								__lowerCamelCase									=       '.'.join([str(UpperCamelCase__ ) for x in sys.version_info[:3]] )
								for op, want_ver in wanted.items():
												_compare_versions(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__ )
								return

				# check if any version is installed
				try:
								__lowerCamelCase									=       importlib.metadata.version(UpperCamelCase__ )
				except importlib.metadata.PackageNotFoundError:
								raise importlib.metadata.PackageNotFoundError(
								    F"""The '{requirement}' distribution was not found and is required by this application. {hint}""" )

				# check that the right version is installed if version number or a range was provided
				if want_ver is not None:
								for op, want_ver in wanted.items():
												_compare_versions(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__ )







def      lowerCamelCase_						(			UpperCamelCase__							: Optional[int] )	->			Optional[int]:





				"""simple docstring"""


				__lowerCamelCase									=       'Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main'
				return require_version(UpperCamelCase__					,	UpperCamelCase__ )


