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



class 			UpperCAmelCase  :





       '''simple docstring'''



       def __init__(						self	,   __lowerCAmelCase = None	,   __lowerCAmelCase = None	,   __lowerCAmelCase=None	,   __lowerCAmelCase=None )  ->  List[Any]:
        if not conversation_id:
         lowercase__				:    Any  =					uuid.uuida()
        if past_user_inputs is None:
         lowercase__				:    int  =					[]
        if generated_responses is None:
         lowercase__				:    int  =					[]

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

       def __eq__(						self	,   __lowerCAmelCase )  ->  Tuple:
        if not isinstance(SCREAMING_SNAKE_CASE__	,   SCREAMING_SNAKE_CASE__ ):
         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 _lowerCAmelCase(						self	,   __lowerCAmelCase	,   __lowerCAmelCase = False )  ->  Optional[Any]:
        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}\".""" )
          lowercase__				:    Optional[int]  =					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:
         lowercase__				:    Optional[Any]  =					text

       def _lowerCAmelCase(						self )  ->  List[str]:
        if self.new_user_input:
         self.past_user_inputs.append(self.new_user_input )
        lowercase__				:    List[Any]  =					None

       def _lowerCAmelCase(						self	,   __lowerCAmelCase )  ->  Dict:
        self.generated_responses.append(SCREAMING_SNAKE_CASE__ )

       def _lowerCAmelCase(						self )  ->  Optional[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 )  ->  Dict:
        lowercase__				:    str  =					F"""Conversation id: {self.uuid} \n"""
        for is_user, text in self.iter_texts():
         lowercase__				:    List[str]  =					'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 			UpperCAmelCase  (						lowercase__					):





       '''simple docstring'''



       def __init__(						self	,   *__lowerCAmelCase	,   **__lowerCAmelCase )  ->  Optional[Any]:
        super().__init__(*SCREAMING_SNAKE_CASE__	,   **SCREAMING_SNAKE_CASE__ )
        if self.tokenizer.pad_token_id is None:
         lowercase__				:    Dict  =					self.tokenizer.eos_token

       def _lowerCAmelCase(						self	,   __lowerCAmelCase=None	,   __lowerCAmelCase=None	,   __lowerCAmelCase=None	,   **__lowerCAmelCase )  ->  Union[str, Any]:
        lowercase__				:    Optional[int]  =					{}
        lowercase__				:    Optional[Any]  =					{}
        lowercase__				:    Dict  =					{}

        if min_length_for_response is not None:
         lowercase__				:    Optional[int]  =					min_length_for_response
        if minimum_tokens is not None:
         lowercase__				:    Union[str, Any]  =					minimum_tokens

        if "max_length" in generate_kwargs:
         lowercase__				:    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:
         lowercase__				:    List[Any]  =					clean_up_tokenization_spaces

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

       def __call__(						self	,   __lowerCAmelCase	,   __lowerCAmelCase=0	,   **__lowerCAmelCase )  ->  List[str]:
        lowercase__				:    Dict  =					super().__call__(SCREAMING_SNAKE_CASE__	,   num_workers=SCREAMING_SNAKE_CASE__	,   **SCREAMING_SNAKE_CASE__ )
        if isinstance(SCREAMING_SNAKE_CASE__	,   SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) == 1:
         return outputs[0]
        return outputs

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

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

       def _lowerCAmelCase(						self	,   __lowerCAmelCase	,   __lowerCAmelCase=10	,   **__lowerCAmelCase )  ->  Any:
        lowercase__				:    Union[str, Any]  =					generate_kwargs.get('''max_length'''	,   self.model.config.max_length )

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

       def _lowerCAmelCase(						self	,   __lowerCAmelCase	,   __lowerCAmelCase=True )  ->  Optional[Any]:
        lowercase__				:    Optional[int]  =					model_outputs['output_ids']
        lowercase__				:    List[Any]  =					self.tokenizer.decode(
            output_ids[0]	,   skip_special_tokens=SCREAMING_SNAKE_CASE__	,   clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__	,   )
        lowercase__				:    Optional[int]  =					model_outputs['conversation']
        conversation.mark_processed()
        conversation.append_response(SCREAMING_SNAKE_CASE__ )
        return conversation


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

        if len(SCREAMING_SNAKE_CASE__ ) > self.tokenizer.model_max_length:
         lowercase__				:    str  =					input_ids[-self.tokenizer.model_max_length :]
        return input_ids





UpperCAmelCase_      : Optional[int]  					=       [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
UpperCAmelCase_      : str  					=       [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
UpperCAmelCase_      : str  					=       {
    0: 'Sunday',
    1: 'Monday',
    2: 'Tuesday',
    3: 'Wednesday',
    4: 'Thursday',
    5: 'Friday',
    6: 'Saturday',
}







def        SCREAMING_SNAKE_CASE_						(			__A :			int  ,    __A :			int  ,    __A :			int				)	->		str:

       """simple docstring"""

       assert len(str(__A				)				) > 2, "year should be in YYYY format"
       assert 1 <= month <= 12, "month should be between 1 to 12"
       assert 1 <= day <= 31, "day should be between 1 to 31"

       # Doomsday algorithm:
       a_					:		List[str]							=  year // 1_00
       a_					:		Optional[int]							=  (5 * (century % 4) + 2) % 7
       a_					:		List[str]							=  year % 1_00
       a_					:		str							=  centurian % 12
       a_					:		List[str]							=  (
           (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor
       ) % 7
       a_					:		Any							=  (
           DOOMSDAY_NOT_LEAP[month - 1]
           if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0)
           else DOOMSDAY_LEAP[month - 1]
       )
       a_					:		Any							=  (dooms_day + day - day_anchor) % 7
       return WEEK_DAY_NAMES[week_day]


if __name__ == "__main__":
   import doctest

   doctest.testmod()


