
"""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


__SCREAMING_SNAKE_CASE							=     logging.get_logger(__name__)





class 				a__					:



     def __init__(							self :List[Any]      ,  _lowerCamelCase :str = None      ,  _lowerCamelCase :uuid.UUID = None      ,  _lowerCamelCase :Dict=None      ,  _lowerCamelCase :int=None   ):







      '''simple docstring'''



      if not conversation_id:
       UpperCamelCase_     :					int   	=uuid.uuida()
      if past_user_inputs is None:
       UpperCamelCase_     :					Union[str, Any]   	=[]
      if generated_responses is None:
       UpperCamelCase_     :					List[Any]   	=[]

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



     def __eq__(							self :List[Any]      ,  _lowerCamelCase :List[str]   ):







      '''simple docstring'''



      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  lowerCamelCase_						(							self :Any      ,  _lowerCamelCase :str      ,  _lowerCamelCase :bool = 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_     :					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:
       UpperCamelCase_     :					Tuple   	=text



     def  lowerCamelCase_						(							self :Dict   ):







      '''simple docstring'''



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



     def  lowerCamelCase_						(							self :Any      ,  _lowerCamelCase :str   ):







      '''simple docstring'''



      self.generated_responses.append(_lowerCamelCase   )



     def  lowerCamelCase_						(							self :Optional[int]   ):







      '''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 :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Any   	=f'''Conversation id: {self.uuid} \n'''
      for is_user, text in self.iter_texts():
       UpperCamelCase_     :					Optional[int]   	='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 				a__					(						A__       ):



     def __init__(							self :List[str]      ,  *_lowerCamelCase :Optional[Any]      ,  **_lowerCamelCase :Optional[Any]   ):







      '''simple docstring'''



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



     def  lowerCamelCase_						(							self :Any      ,  _lowerCamelCase :Dict=None      ,  _lowerCamelCase :Dict=None      ,  _lowerCamelCase :Any=None      ,  **_lowerCamelCase :str   ):







      '''simple docstring'''



      UpperCamelCase_     :					Dict   	={}
      UpperCamelCase_     :					List[Any]   	={}
      UpperCamelCase_     :					Optional[int]   	={}

      if min_length_for_response is not None:
       UpperCamelCase_     :					int   	=min_length_for_response
      if minimum_tokens is not None:
       UpperCamelCase_     :					Optional[Any]   	=minimum_tokens

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

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



     def __call__(							self :Any      ,  _lowerCamelCase :Union[Conversation, List[Conversation]]      ,  _lowerCamelCase :List[Any]=0      ,  **_lowerCamelCase :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[Any]   	=super().__call__(_lowerCamelCase      ,  num_workers=_lowerCamelCase      ,  **_lowerCamelCase   )
      if isinstance(_lowerCamelCase      ,  _lowerCamelCase   ) and len(_lowerCamelCase   ) == 1:
       return outputs[0]
      return outputs



     def  lowerCamelCase_						(							self :str      ,  _lowerCamelCase :Conversation      ,  _lowerCamelCase :Dict=32   ):







      '''simple docstring'''



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

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



     def  lowerCamelCase_						(							self :Tuple      ,  _lowerCamelCase :int      ,  _lowerCamelCase :Tuple=10      ,  **_lowerCamelCase :Tuple   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[Any]   	=generate_kwargs.get('max_length'      ,  self.model.config.max_length   )

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



     def  lowerCamelCase_						(							self :Dict      ,  _lowerCamelCase :Tuple      ,  _lowerCamelCase :int=True   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[Any]   	=model_outputs['output_ids']
      UpperCamelCase_     :					Tuple   	=self.tokenizer.decode(
          output_ids[0]      ,  skip_special_tokens=_lowerCamelCase      ,  clean_up_tokenization_spaces=_lowerCamelCase      ,  )
      UpperCamelCase_     :					Any   	=model_outputs['conversation']
      conversation.mark_processed()
      conversation.append_response(_lowerCamelCase   )
      return conversation




     def  lowerCamelCase_						(							self :Union[str, Any]      ,  _lowerCamelCase :Conversation   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[str]   	=self.tokenizer.eos_token_id
      UpperCamelCase_     :					Any   	=[]
      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:
       UpperCamelCase_     :					Union[str, Any]   	=input_ids[-self.tokenizer.model_max_length :]
      return input_ids


"""simple docstring"""






# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile




def       A_  (				__lowercase						,	__lowercase						,	__lowercase						,	__lowercase	):
 UpperCamelCase_     :					Tuple   	=multiprocessing.Manager()
 UpperCamelCase_     :					Dict   	=manager.list()

 UpperCamelCase_     :					Union[str, Any]   	=multiprocessing.Process(target=__lowercase						,	args=(check_program, result, timeout)	)
 p.start()
 p.join(timeout=timeout + 1	)
 if p.is_alive():
  p.kill()

 if not result:
  result.append('timed out'	)

 return {
     "task_id": task_id,
     "passed": result[0] == "passed",
     "result": result[0],
     "completion_id": completion_id,
 }




def       A_  (				__lowercase						,	__lowercase						,	__lowercase	):
 with create_tempdir():
  # These system calls are needed when cleaning up tempdir.
  import os
  import shutil

  UpperCamelCase_     :					Tuple   	=shutil.rmtree
  UpperCamelCase_     :					List[str]   	=os.rmdir
  UpperCamelCase_     :					Any   	=os.chdir

  # Disable functionalities that can make destructive changes to the test.
  reliability_guard()

  # Run program.
  try:
   UpperCamelCase_     :					List[str]   	={}
   with swallow_io():
    with time_limit(__lowercase	):
     exec(__lowercase						,	__lowercase	)
   result.append('passed'	)
  except TimeoutException:
   result.append('timed out'	)
  except BaseException as e:
   result.append(F'''failed: {e}'''	)

  # Needed for cleaning up.
  UpperCamelCase_     :					Optional[Any]   	=rmtree
  UpperCamelCase_     :					str   	=rmdir
  UpperCamelCase_     :					Dict   	=chdir




@contextlib.contextmanager
def       A_  (				__lowercase	):
 def signal_handler(__lowercase						,	__lowercase	):
  raise TimeoutException('Timed out!'	)

 signal.setitimer(signal.ITIMER_REAL						,	__lowercase	)
 signal.signal(signal.SIGALRM						,	__lowercase	)
 try:
  yield
 finally:
  signal.setitimer(signal.ITIMER_REAL						,	0	)




@contextlib.contextmanager
def       A_  (				):
 UpperCamelCase_     :					str   	=WriteOnlyStringIO()
 with contextlib.redirect_stdout(__lowercase	):
  with contextlib.redirect_stderr(__lowercase	):
   with redirect_stdin(__lowercase	):
    yield




@contextlib.contextmanager
def       A_  (				):
 with tempfile.TemporaryDirectory() as dirname:
  with chdir(__lowercase	):
   yield dirname





class 				a__					(						A__       ):
     pass





class 				a__					(						io.StringIO       ):



     def  lowerCamelCase_						(							self :Any      ,  *_lowerCamelCase :Any      ,  **_lowerCamelCase :Tuple   ):







      '''simple docstring'''



      raise OSError



     def  lowerCamelCase_						(							self :Union[str, Any]      ,  *_lowerCamelCase :Any      ,  **_lowerCamelCase :Tuple   ):







      '''simple docstring'''



      raise OSError



     def  lowerCamelCase_						(							self :Tuple      ,  *_lowerCamelCase :str      ,  **_lowerCamelCase :List[str]   ):







      '''simple docstring'''



      raise OSError




     def  lowerCamelCase_						(							self :List[str]      ,  *_lowerCamelCase :Optional[int]      ,  **_lowerCamelCase :str   ):







      '''simple docstring'''



      return False





class 				a__					(						contextlib._RedirectStream       ):  # type: ignore
     UpperCAmelCase__         =      '''stdin'''




@contextlib.contextmanager
def       A_  (				__lowercase	):
 if root == ".":
  yield
  return
 UpperCamelCase_     :					List[str]   	=os.getcwd()
 os.chdir(__lowercase	)
 try:
  yield
 except BaseException as exc:
  raise exc
 finally:
  os.chdir(__lowercase	)





def       A_  (				__lowercase=None	):

 if maximum_memory_bytes is not None:
  import resource

  resource.setrlimit(resource.RLIMIT_AS						,	(maximum_memory_bytes, maximum_memory_bytes)	)
  resource.setrlimit(resource.RLIMIT_DATA						,	(maximum_memory_bytes, maximum_memory_bytes)	)
  if not platform.uname().system == "Darwin":
   resource.setrlimit(resource.RLIMIT_STACK						,	(maximum_memory_bytes, maximum_memory_bytes)	)

 faulthandler.disable()

 import builtins

 UpperCamelCase_     :					Any   	=None
 UpperCamelCase_     :					Any   	=None

 import os

 UpperCamelCase_     :					Union[str, Any]   	='1'

 UpperCamelCase_     :					Union[str, Any]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					Dict   	=None
 UpperCamelCase_     :					List[Any]   	=None
 UpperCamelCase_     :					Any   	=None
 UpperCamelCase_     :					str   	=None
 UpperCamelCase_     :					Optional[int]   	=None
 UpperCamelCase_     :					Union[str, Any]   	=None
 UpperCamelCase_     :					str   	=None
 UpperCamelCase_     :					str   	=None
 UpperCamelCase_     :					List[Any]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					str   	=None
 UpperCamelCase_     :					List[str]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					int   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					Tuple   	=None
 UpperCamelCase_     :					List[Any]   	=None
 UpperCamelCase_     :					Tuple   	=None
 UpperCamelCase_     :					Dict   	=None
 UpperCamelCase_     :					Optional[int]   	=None
 UpperCamelCase_     :					str   	=None
 UpperCamelCase_     :					Union[str, Any]   	=None
 UpperCamelCase_     :					int   	=None

 import shutil

 UpperCamelCase_     :					List[str]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					Dict   	=None

 import subprocess

 UpperCamelCase_     :					Optional[int]   	=None  # type: ignore

 UpperCamelCase_     :					Union[str, Any]   	=None

 import sys

 UpperCamelCase_     :					Union[str, Any]   	=None
 UpperCamelCase_     :					Tuple   	=None
 UpperCamelCase_     :					Union[str, Any]   	=None
 UpperCamelCase_     :					Dict   	=None
 UpperCamelCase_     :					Any   	=None
