

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


SCREAMING_SNAKE_CASE_        =      logging.get_logger(__name__)

class 				a  :


						def __init__(       self						,					A_ = None						,					A_ = None						,					A_=None						,					A_=None	):







										'''simple docstring'''


										if not conversation_id:
														_UpperCAmelCase       :		int 		=    uuid.uuida()
										if past_user_inputs is None:
														_UpperCAmelCase       :		int 		=    []
										if generated_responses is None:
														_UpperCAmelCase       :		str 		=    []

										_UpperCAmelCase       :		uuid.UUID 		=    conversation_id
										_UpperCAmelCase       :		List[str] 		=    past_user_inputs
										_UpperCAmelCase       :		List[str] 		=    generated_responses
										_UpperCAmelCase       :		Optional[str] 		=    text


						def __eq__(       self						,					A_	):







										'''simple docstring'''


										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        _UpperCAmelCase				(       self						,					A_						,					A_ = False	):







										'''simple docstring'''


										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       :		List[str] 		=    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       :		str 		=    text


						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										if self.new_user_input:
														self.past_user_inputs.append(self.new_user_input	)
										_UpperCAmelCase       :		int 		=    None


						def        _UpperCAmelCase				(       self						,					A_	):







										'''simple docstring'''


										self.generated_responses.append(A_	)


						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										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	):







										'''simple docstring'''


										_UpperCAmelCase       :		int 		=    f'Conversation id: {self.uuid} \n'
										for is_user, text in self.iter_texts():
														_UpperCAmelCase       :		str 		=    "user" if is_user else "bot"
														output += f'{name} >> {text} \n'
										return output







@add_end_docstrings(
    UpperCAmelCase							, 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  (	UpperCAmelCase				):


						def __init__(       self						,					*A_						,					**A_	):







										'''simple docstring'''


										super().__init__(*A_						,					**A_	)
										if self.tokenizer.pad_token_id is None:
														_UpperCAmelCase       :		List[str] 		=    self.tokenizer.eos_token


						def        _UpperCAmelCase				(       self						,					A_=None						,					A_=None						,					A_=None						,					**A_	):







										'''simple docstring'''


										_UpperCAmelCase       :		Union[str, Any] 		=    {}
										_UpperCAmelCase       :		str 		=    {}
										_UpperCAmelCase       :		Union[str, Any] 		=    {}

										if min_length_for_response is not None:
														_UpperCAmelCase       :		Any 		=    min_length_for_response
										if minimum_tokens is not None:
														_UpperCAmelCase       :		List[str] 		=    minimum_tokens

										if "max_length" in generate_kwargs:
														_UpperCAmelCase       :		Optional[Any] 		=    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       :		Tuple 		=    clean_up_tokenization_spaces

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


						def __call__(       self						,					A_						,					A_=0						,					**A_	):







										'''simple docstring'''


										_UpperCAmelCase       :		List[str] 		=    super().__call__(A_						,					num_workers=A_						,					**A_	)
										if isinstance(A_						,					A_	) and len(A_	) == 1:
														return outputs[0]
										return outputs


						def        _UpperCAmelCase				(       self						,					A_						,					A_=32	):







										'''simple docstring'''


										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       :		Union[str, Any] 		=    self.tokenizer._build_conversation_input_ids(A_	)
										else:
														# If the tokenizer cannot handle conversations, we default to only the old version
														_UpperCAmelCase       :		Optional[Any] 		=    self._legacy_parse_and_tokenize(A_	)

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


						def        _UpperCAmelCase				(       self						,					A_						,					A_=10						,					**A_	):







										'''simple docstring'''


										_UpperCAmelCase       :		List[str] 		=    generate_kwargs.get("max_length"						,					self.model.config.max_length	)

										_UpperCAmelCase       :		Optional[int] 		=    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       :		str 		=    max_length - minimum_tokens
														_UpperCAmelCase       :		List[str] 		=    model_inputs["input_ids"][:, -trim:]
														if "attention_mask" in model_inputs:
																		_UpperCAmelCase       :		Union[str, Any] 		=    model_inputs["attention_mask"][:, -trim:]
										_UpperCAmelCase       :		Any 		=    model_inputs.pop("conversation"	)
										_UpperCAmelCase       :		Union[str, Any] 		=    max_length
										_UpperCAmelCase       :		List[Any] 		=    self.model.generate(**A_						,					**A_	)
										if self.model.config.is_encoder_decoder:
														_UpperCAmelCase       :		Union[str, Any] 		=    1
										else:
														_UpperCAmelCase       :		Optional[int] 		=    n
										return {"output_ids": output_ids[:, start_position:], "conversation": conversation}


						def        _UpperCAmelCase				(       self						,					A_						,					A_=True	):







										'''simple docstring'''


										_UpperCAmelCase       :		Any 		=    model_outputs["output_ids"]
										_UpperCAmelCase       :		List[Any] 		=    self.tokenizer.decode(
										    output_ids[0]						,					skip_special_tokens=A_						,					clean_up_tokenization_spaces=A_						,					)
										_UpperCAmelCase       :		Optional[Any] 		=    model_outputs["conversation"]
										conversation.mark_processed()
										conversation.append_response(A_	)
										return conversation





						def        _UpperCAmelCase				(       self						,					A_	):







										'''simple docstring'''


										_UpperCAmelCase       :		List[str] 		=    self.tokenizer.eos_token_id
										_UpperCAmelCase       :		Optional[int] 		=    []
										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       :		List[Any] 		=    input_ids[-self.tokenizer.model_max_length :]
										return input_ids





import unittest

from transformers import load_tool

from .test_tools_common import ToolTesterMixin


SCREAMING_SNAKE_CASE_        =      '\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n'

class 				a  (	unittest.TestCase							, UpperCAmelCase				):


						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		Tuple 		=    load_tool("text-question-answering"	)
										self.tool.setup()
										_UpperCAmelCase       :		str 		=    load_tool("text-question-answering"						,					remote=A_	)


						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		List[str] 		=    self.tool(A_						,					"What did Hugging Face do in April 2021?"	)
										self.assertEqual(A_						,					"launched the BigScience Research Workshop"	)


						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		Optional[Any] 		=    self.remote_tool(A_						,					"What did Hugging Face do in April 2021?"	)
										self.assertEqual(A_						,					"launched the BigScience Research Workshop"	)


						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		int 		=    self.tool(text=A_						,					question="What did Hugging Face do in April 2021?"	)
										self.assertEqual(A_						,					"launched the BigScience Research Workshop"	)





						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		List[Any] 		=    self.remote_tool(text=A_						,					question="What did Hugging Face do in April 2021?"	)
										self.assertEqual(A_						,					"launched the BigScience Research Workshop"	)


