
"""simple docstring"""






import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
 import torch





class 				a__					(						A__       ):
     UpperCAmelCase__         =      '''char'''
     UpperCAmelCase__         =      '''bpe'''
     UpperCAmelCase__         =      '''wp'''


__SCREAMING_SNAKE_CASE							=     (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)





class 				a__					(						A__       ):
     UpperCAmelCase__         =      ['''image_processor''', '''char_tokenizer''']
     UpperCAmelCase__         =      '''ViTImageProcessor'''
     UpperCAmelCase__         =      '''MgpstrTokenizer'''



     def __init__(							self :Any      ,  _lowerCamelCase :Any=None      ,  _lowerCamelCase :Tuple=None      ,  **_lowerCamelCase :Dict   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[Any]   	=None
      if "feature_extractor" in kwargs:
       warnings.warn(
           'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
           ' instead.'      ,  _lowerCamelCase      ,  )
       UpperCamelCase_     :					Any   	=kwargs.pop('feature_extractor'   )

      UpperCamelCase_     :					str   	=image_processor if image_processor is not None else feature_extractor
      if image_processor is None:
       raise ValueError('You need to specify an `image_processor`.'   )
      if tokenizer is None:
       raise ValueError('You need to specify a `tokenizer`.'   )

      UpperCamelCase_     :					Optional[int]   	=tokenizer
      UpperCamelCase_     :					List[str]   	=AutoTokenizer.from_pretrained('gpt2'   )
      UpperCamelCase_     :					List[Any]   	=AutoTokenizer.from_pretrained('bert-base-uncased'   )

      super().__init__(_lowerCamelCase      ,  _lowerCamelCase   )



     def __call__(							self :Tuple      ,  _lowerCamelCase :Optional[int]=None      ,  _lowerCamelCase :str=None      ,  _lowerCamelCase :int=None      ,  **_lowerCamelCase :Any   ):







      '''simple docstring'''



      if images is None and text is None:
       raise ValueError('You need to specify either an `images` or `text` input to process.'   )

      if images is not None:
       UpperCamelCase_     :					str   	=self.image_processor(_lowerCamelCase      ,  return_tensors=_lowerCamelCase      ,  **_lowerCamelCase   )
      if text is not None:
       UpperCamelCase_     :					Optional[Any]   	=self.char_tokenizer(_lowerCamelCase      ,  return_tensors=_lowerCamelCase      ,  **_lowerCamelCase   )

      if text is None:
       return inputs
      elif images is None:
       return encodings
      else:
       UpperCamelCase_     :					int   	=encodings['input_ids']
       return inputs



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







      '''simple docstring'''



      UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_     :					List[str]   	=sequences
      UpperCamelCase_     :					Optional[Any]   	=char_preds.size(0   )

      UpperCamelCase_	,     UpperCamelCase_     :					str   	=self._decode_helper(_lowerCamelCase      ,  'char'   )
      UpperCamelCase_	,     UpperCamelCase_     :					Any   	=self._decode_helper(_lowerCamelCase      ,  'bpe'   )
      UpperCamelCase_	,     UpperCamelCase_     :					List[Any]   	=self._decode_helper(_lowerCamelCase      ,  'wp'   )

      UpperCamelCase_     :					Tuple   	=[]
      UpperCamelCase_     :					Any   	=[]
      for i in range(_lowerCamelCase   ):
       UpperCamelCase_     :					Dict   	=[char_scores[i], bpe_scores[i], wp_scores[i]]
       UpperCamelCase_     :					Any   	=[char_strs[i], bpe_strs[i], wp_strs[i]]
       UpperCamelCase_     :					int   	=scores.index(max(_lowerCamelCase   )   )
       final_strs.append(strs[max_score_index]   )
       final_scores.append(scores[max_score_index]   )

      UpperCamelCase_     :					List[Any]   	={}
      UpperCamelCase_     :					List[str]   	=final_strs
      UpperCamelCase_     :					str   	=final_scores
      UpperCamelCase_     :					Tuple   	=char_strs
      UpperCamelCase_     :					int   	=bpe_strs
      UpperCamelCase_     :					Tuple   	=wp_strs
      return out



     def  lowerCamelCase_						(							self :Dict      ,  _lowerCamelCase :str      ,  _lowerCamelCase :int   ):







      '''simple docstring'''



      if format == DecodeType.CHARACTER:
       UpperCamelCase_     :					Optional[int]   	=self.char_decode
       UpperCamelCase_     :					int   	=1
       UpperCamelCase_     :					List[Any]   	='[s]'
      elif format == DecodeType.BPE:
       UpperCamelCase_     :					Optional[Any]   	=self.bpe_decode
       UpperCamelCase_     :					List[Any]   	=2
       UpperCamelCase_     :					List[str]   	='#'
      elif format == DecodeType.WORDPIECE:
       UpperCamelCase_     :					int   	=self.wp_decode
       UpperCamelCase_     :					Union[str, Any]   	=102
       UpperCamelCase_     :					List[str]   	='[SEP]'
      else:
       raise ValueError(f'''Format {format} is not supported.'''   )

      UpperCamelCase_	,     UpperCamelCase_     :					Union[str, Any]   	=[], []
      UpperCamelCase_     :					Optional[int]   	=pred_logits.size(0   )
      UpperCamelCase_     :					Optional[Any]   	=pred_logits.size(1   )
      UpperCamelCase_	,     UpperCamelCase_     :					List[Any]   	=pred_logits.topk(1      ,  dim=-1      ,  largest=_lowerCamelCase      ,  sorted=_lowerCamelCase   )
      UpperCamelCase_     :					Tuple   	=preds_index.view(-1      ,  _lowerCamelCase   )[:, 1:]
      UpperCamelCase_     :					Optional[int]   	=decoder(_lowerCamelCase   )
      UpperCamelCase_	,     UpperCamelCase_     :					int   	=torch.nn.functional.softmax(_lowerCamelCase      ,  dim=2   ).max(dim=2   )
      UpperCamelCase_     :					Any   	=preds_max_prob[:, 1:]

      for index in range(_lowerCamelCase   ):
       UpperCamelCase_     :					Union[str, Any]   	=preds_str[index].find(_lowerCamelCase   )
       UpperCamelCase_     :					List[Any]   	=preds_str[index][:pred_eos]
       UpperCamelCase_     :					Union[str, Any]   	=preds_index[index].cpu().tolist()
       UpperCamelCase_     :					Optional[int]   	=pred_index.index(_lowerCamelCase   ) if eos_token in pred_index else -1
       UpperCamelCase_     :					List[str]   	=preds_max_prob[index][: pred_eos_index + 1]
       UpperCamelCase_     :					int   	=pred_max_prob.cumprod(dim=0   )[-1] if pred_max_prob.nelement() != 0 else 0.0
       dec_strs.append(_lowerCamelCase   )
       conf_scores.append(_lowerCamelCase   )

      return dec_strs, conf_scores



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







      '''simple docstring'''



      UpperCamelCase_     :					int   	=[seq.replace(' '      ,  ''   ) for seq in self.char_tokenizer.batch_decode(_lowerCamelCase   )]
      return decode_strs



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







      '''simple docstring'''



      return self.bpe_tokenizer.batch_decode(_lowerCamelCase   )




     def  lowerCamelCase_						(							self :List[Any]      ,  _lowerCamelCase :int   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=[seq.replace(' '      ,  ''   ) for seq in self.wp_tokenizer.batch_decode(_lowerCamelCase   )]
      return decode_strs


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