






'''simple docstring'''



from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
      import PIL


SCREAMING_SNAKE_CASE							=						logging.get_logger(__name__)


def 				lowercase_					(     __A			:							Tuple      )							->   List[List[ImageInput]]:



 """simple docstring"""




 if isinstance(__A       ,   (list, tuple)      ) and isinstance(videos[0]       ,   (list, tuple)      ) and is_valid_image(videos[0][0]      ):
  return videos

 elif isinstance(__A       ,   (list, tuple)      ) and is_valid_image(videos[0]      ):
  return [videos]

 elif is_valid_image(__A      ):
  return [[videos]]

 raise ValueError(F'Could not make batched video from {videos}'      )





class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      UpperCamelCase_             =      ['''pixel_values''']






      def __init__(			self      :		List[Any]  ,   UpperCAmelCase      :		bool = True  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		PILImageResampling = PILImageResampling.BILINEAR  ,   UpperCAmelCase      :		bool = True  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		bool = True  ,   UpperCAmelCase      :		Union[int, float] = 1 / 255  ,   UpperCAmelCase      :		bool = True  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   **UpperCAmelCase      :		Tuple  ,   )	->	None:


       '''simple docstring'''

       super().__init__(**UpperCAmelCase		)
       lowercase       : Tuple						=size if size is not None else {'''shortest_edge''': 224}
       lowercase       : str						=get_size_dict(UpperCAmelCase  ,   default_to_square=UpperCAmelCase		)
       lowercase       : List[str]						=crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
       lowercase       : List[Any]						=get_size_dict(UpperCAmelCase  ,   param_name='''crop_size'''		)

       lowercase       : Tuple						=do_resize
       lowercase       : Any						=size
       lowercase       : Optional[Any]						=do_center_crop
       lowercase       : str						=crop_size
       lowercase       : Any						=resample
       lowercase       : List[Any]						=do_rescale
       lowercase       : Dict						=rescale_factor
       lowercase       : List[str]						=do_normalize
       lowercase       : Optional[int]						=image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       lowercase       : List[Any]						=image_std if image_std is not None else IMAGENET_STANDARD_STD






      def 					A__   (			self      :		Dict  ,   UpperCAmelCase      :		np.ndarray  ,   UpperCAmelCase      :		Dict[str, int]  ,   UpperCAmelCase      :		PILImageResampling = PILImageResampling.BILINEAR  ,   UpperCAmelCase      :		Optional[Union[str, ChannelDimension]] = None  ,   **UpperCAmelCase      :		List[str]  ,   )	->	np.ndarray:


       '''simple docstring'''

       lowercase       : str						=get_size_dict(UpperCAmelCase  ,   default_to_square=UpperCAmelCase		)
       if "shortest_edge" in size:
        lowercase       : int						=get_resize_output_image_size(UpperCAmelCase  ,   size['''shortest_edge''']  ,   default_to_square=UpperCAmelCase		)
       elif "height" in size and "width" in size:
        lowercase       : str						=(size['''height'''], size['''width'''])
       else:
        raise ValueError(f'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'		)
       return resize(UpperCAmelCase  ,   size=UpperCAmelCase  ,   resample=UpperCAmelCase  ,   data_format=UpperCAmelCase  ,   **UpperCAmelCase		)






      def 					A__   (			self      :		Any  ,   UpperCAmelCase      :		np.ndarray  ,   UpperCAmelCase      :		Dict[str, int]  ,   UpperCAmelCase      :		Optional[Union[str, ChannelDimension]] = None  ,   **UpperCAmelCase      :		Optional[Any]  ,   )	->	np.ndarray:


       '''simple docstring'''

       lowercase       : List[str]						=get_size_dict(UpperCAmelCase		)
       if "height" not in size or "width" not in size:
        raise ValueError(f'Size must have \'height\' and \'width\' as keys. Got {size.keys()}'		)
       return center_crop(UpperCAmelCase  ,   size=(size['''height'''], size['''width'''])  ,   data_format=UpperCAmelCase  ,   **UpperCAmelCase		)






      def 					A__   (			self      :		int  ,   UpperCAmelCase      :		np.ndarray  ,   UpperCAmelCase      :		Union[int, float]  ,   UpperCAmelCase      :		Optional[Union[str, ChannelDimension]] = None  ,   **UpperCAmelCase      :		Tuple  ,   )	->	List[Any]:


       '''simple docstring'''

       return rescale(UpperCAmelCase  ,   scale=UpperCAmelCase  ,   data_format=UpperCAmelCase  ,   **UpperCAmelCase		)






      def 					A__   (			self      :		Any  ,   UpperCAmelCase      :		np.ndarray  ,   UpperCAmelCase      :		Union[float, List[float]]  ,   UpperCAmelCase      :		Union[float, List[float]]  ,   UpperCAmelCase      :		Optional[Union[str, ChannelDimension]] = None  ,   **UpperCAmelCase      :		int  ,   )	->	np.ndarray:


       '''simple docstring'''

       return normalize(UpperCAmelCase  ,   mean=UpperCAmelCase  ,   std=UpperCAmelCase  ,   data_format=UpperCAmelCase  ,   **UpperCAmelCase		)






      def 					A__   (			self      :		int  ,   UpperCAmelCase      :		ImageInput  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		PILImageResampling = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		float = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   UpperCAmelCase      :		Optional[ChannelDimension] = ChannelDimension.FIRST  ,   )	->	np.ndarray:


       '''simple docstring'''

       if do_resize and size is None or resample is None:
        raise ValueError('''Size and resample must be specified if do_resize is True.'''		)

       if do_center_crop and crop_size is None:
        raise ValueError('''Crop size must be specified if do_center_crop is True.'''		)

       if do_rescale and rescale_factor is None:
        raise ValueError('''Rescale factor must be specified if do_rescale is True.'''		)

       if do_normalize and (image_mean is None or image_std is None):
        raise ValueError('''Image mean and std must be specified if do_normalize is True.'''		)

       # All transformations expect numpy arrays.
       lowercase       : Dict						=to_numpy_array(UpperCAmelCase		)

       if do_resize:
        lowercase       : Union[str, Any]						=self.resize(image=UpperCAmelCase  ,   size=UpperCAmelCase  ,   resample=UpperCAmelCase		)

       if do_center_crop:
        lowercase       : Optional[Any]						=self.center_crop(UpperCAmelCase  ,   size=UpperCAmelCase		)

       if do_rescale:
        lowercase       : Dict						=self.rescale(image=UpperCAmelCase  ,   scale=UpperCAmelCase		)

       if do_normalize:
        lowercase       : int						=self.normalize(image=UpperCAmelCase  ,   mean=UpperCAmelCase  ,   std=UpperCAmelCase		)

       lowercase       : Optional[Any]						=to_channel_dimension_format(UpperCAmelCase  ,   UpperCAmelCase		)
       return image






      def 					A__   (			self      :		List[str]  ,   UpperCAmelCase      :		ImageInput  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		PILImageResampling = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Dict[str, int] = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		float = None  ,   UpperCAmelCase      :		bool = None  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   UpperCAmelCase      :		Optional[Union[float, List[float]]] = None  ,   UpperCAmelCase      :		Optional[Union[str, TensorType]] = None  ,   UpperCAmelCase      :		ChannelDimension = ChannelDimension.FIRST  ,   **UpperCAmelCase      :		Optional[int]  ,   )	->	PIL.Image.Image:


       '''simple docstring'''

       lowercase       : Any						=do_resize if do_resize is not None else self.do_resize
       lowercase       : Union[str, Any]						=resample if resample is not None else self.resample
       lowercase       : Tuple						=do_center_crop if do_center_crop is not None else self.do_center_crop
       lowercase       : List[Any]						=do_rescale if do_rescale is not None else self.do_rescale
       lowercase       : str						=rescale_factor if rescale_factor is not None else self.rescale_factor
       lowercase       : List[str]						=do_normalize if do_normalize is not None else self.do_normalize
       lowercase       : List[str]						=image_mean if image_mean is not None else self.image_mean
       lowercase       : Optional[int]						=image_std if image_std is not None else self.image_std

       lowercase       : Optional[Any]						=size if size is not None else self.size
       lowercase       : Any						=get_size_dict(UpperCAmelCase  ,   default_to_square=UpperCAmelCase		)
       lowercase       : Union[str, Any]						=crop_size if crop_size is not None else self.crop_size
       lowercase       : Optional[int]						=get_size_dict(UpperCAmelCase  ,   param_name='''crop_size'''		)

       if not valid_images(UpperCAmelCase		):
        raise ValueError(
            '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
            '''torch.Tensor, tf.Tensor or jax.ndarray.'''		)

       lowercase       : List[str]						=make_batched(UpperCAmelCase		)

       lowercase       : Union[str, Any]						=[
           [
               self._preprocess_image(
                   image=UpperCAmelCase  ,   do_resize=UpperCAmelCase  ,   size=UpperCAmelCase  ,   resample=UpperCAmelCase  ,   do_center_crop=UpperCAmelCase  ,   crop_size=UpperCAmelCase  ,   do_rescale=UpperCAmelCase  ,   rescale_factor=UpperCAmelCase  ,   do_normalize=UpperCAmelCase  ,   image_mean=UpperCAmelCase  ,   image_std=UpperCAmelCase  ,   data_format=UpperCAmelCase  ,   )
               for img in video
           ]
           for video in videos
       ]

       lowercase       : Dict						={'''pixel_values''': videos}
       return BatchFeature(data=UpperCAmelCase  ,   tensor_type=UpperCAmelCase		)











'''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 UpperCAmelCase_       (     __A					):




      """simple docstring"""




      UpperCamelCase_             =      '''char'''
      UpperCamelCase_             =      '''bpe'''
      UpperCamelCase_             =      '''wp'''





SCREAMING_SNAKE_CASE							=						(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      UpperCamelCase_             =      ['''image_processor''', '''char_tokenizer''']
      UpperCamelCase_             =      '''ViTImageProcessor'''
      UpperCamelCase_             =      '''MgpstrTokenizer'''






      def __init__(			self      :		int  ,   UpperCAmelCase      :		Tuple=None  ,   UpperCAmelCase      :		Dict=None  ,   **UpperCAmelCase      :		Any		)	->	List[str]:


       '''simple docstring'''

       lowercase       : str						=None
       if "feature_extractor" in kwargs:
        warnings.warn(
            '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
            ''' instead.'''  ,   UpperCAmelCase  ,   )
        lowercase       : int						=kwargs.pop('''feature_extractor'''		)

       lowercase       : Optional[Any]						=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`.'''		)

       lowercase       : Any						=tokenizer
       lowercase       : Dict						=AutoTokenizer.from_pretrained('''gpt2'''		)
       lowercase       : Optional[int]						=AutoTokenizer.from_pretrained('''bert-base-uncased'''		)

       super().__init__(UpperCAmelCase  ,   UpperCAmelCase		)






      def __call__(			self      :		List[Any]  ,   UpperCAmelCase      :		Union[str, Any]=None  ,   UpperCAmelCase      :		List[str]=None  ,   UpperCAmelCase      :		Dict=None  ,   **UpperCAmelCase      :		Union[str, Any]		)	->	int:


       '''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:
        lowercase       : str						=self.image_processor(UpperCAmelCase  ,   return_tensors=UpperCAmelCase  ,   **UpperCAmelCase		)
       if text is not None:
        lowercase       : Any						=self.char_tokenizer(UpperCAmelCase  ,   return_tensors=UpperCAmelCase  ,   **UpperCAmelCase		)

       if text is None:
        return inputs
       elif images is None:
        return encodings
       else:
        lowercase       : List[str]						=encodings['''input_ids''']
        return inputs






      def 					A__   (			self      :		List[Any]  ,   UpperCAmelCase      :		Optional[Any]		)	->	Optional[Any]:


       '''simple docstring'''

       lowercase	,		lowercase	,		lowercase       : Union[str, Any]						=sequences
       lowercase       : Dict						=char_preds.size(0		)

       lowercase	,		lowercase       : Any						=self._decode_helper(UpperCAmelCase  ,   '''char'''		)
       lowercase	,		lowercase       : int						=self._decode_helper(UpperCAmelCase  ,   '''bpe'''		)
       lowercase	,		lowercase       : Optional[Any]						=self._decode_helper(UpperCAmelCase  ,   '''wp'''		)

       lowercase       : Dict						=[]
       lowercase       : List[Any]						=[]
       for i in range(UpperCAmelCase		):
        lowercase       : List[str]						=[char_scores[i], bpe_scores[i], wp_scores[i]]
        lowercase       : Union[str, Any]						=[char_strs[i], bpe_strs[i], wp_strs[i]]
        lowercase       : List[str]						=scores.index(max(UpperCAmelCase		)		)
        final_strs.append(strs[max_score_index]		)
        final_scores.append(scores[max_score_index]		)

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






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		Dict  ,   UpperCAmelCase      :		Union[str, Any]		)	->	Optional[int]:


       '''simple docstring'''

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

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

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

       return dec_strs, conf_scores






      def 					A__   (			self      :		List[str]  ,   UpperCAmelCase      :		Optional[int]		)	->	Dict:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=[seq.replace(''' '''  ,   ''''''		) for seq in self.char_tokenizer.batch_decode(UpperCAmelCase		)]
       return decode_strs






      def 					A__   (			self      :		Optional[int]  ,   UpperCAmelCase      :		Optional[Any]		)	->	str:


       '''simple docstring'''

       return self.bpe_tokenizer.batch_decode(UpperCAmelCase		)






      def 					A__   (			self      :		Tuple  ,   UpperCAmelCase      :		Dict		)	->	List[str]:


       '''simple docstring'''

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



