




from typing import Dict, List, Optional, Tuple, 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,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
   import torch


lowerCamelCase__ :   int					=							logging.get_logger(__name__)





class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE					):


 '''simple docstring'''







 lowercase_				    =    ["pixel_values"]



 def __init__(							self  :		Tuple				,				_lowerCAmelCase  :		bool = True				,				_lowerCAmelCase  :		Optional[Dict[str, int]] = None				,				_lowerCAmelCase  :		PILImageResampling = PILImageResampling.BILINEAR				,				_lowerCAmelCase  :		bool = True				,				_lowerCAmelCase  :		Dict[str, int] = None				,				_lowerCAmelCase  :		bool = True				,				_lowerCAmelCase  :		Union[int, float] = 1 / 255				,				_lowerCAmelCase  :		bool = True				,				_lowerCAmelCase  :		Optional[Union[float, List[float]]] = None				,				_lowerCAmelCase  :		Optional[Union[float, List[float]]] = None				,				**_lowerCAmelCase  :		Optional[Any]				,				):
       super().__init__(**_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			size if size is not None else {'shortest_edge': 256}
       SCREAMING_SNAKE_CASE_							=			get_size_dict(_lowerCAmelCase				,				default_to_square=_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			crop_size if crop_size is not None else {'height': 224, 'width': 224}
       SCREAMING_SNAKE_CASE_							=			get_size_dict(_lowerCAmelCase				,				param_name='crop_size'						)
       SCREAMING_SNAKE_CASE_							=			do_resize
       SCREAMING_SNAKE_CASE_							=			size
       SCREAMING_SNAKE_CASE_							=			resample
       SCREAMING_SNAKE_CASE_							=			do_center_crop
       SCREAMING_SNAKE_CASE_							=			crop_size
       SCREAMING_SNAKE_CASE_							=			do_rescale
       SCREAMING_SNAKE_CASE_							=			rescale_factor
       SCREAMING_SNAKE_CASE_							=			do_normalize
       SCREAMING_SNAKE_CASE_							=			image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       SCREAMING_SNAKE_CASE_							=			image_std if image_std is not None else IMAGENET_STANDARD_STD



 def       lowerCAmelCase_  (							self  :		List[str]				,				_lowerCAmelCase  :		np.ndarray				,				_lowerCAmelCase  :		Dict[str, int]				,				_lowerCAmelCase  :		PILImageResampling = PILImageResampling.BICUBIC				,				_lowerCAmelCase  :		Optional[Union[str, ChannelDimension]] = None				,				**_lowerCAmelCase  :		str				,				):
       SCREAMING_SNAKE_CASE_							=			get_size_dict(_lowerCAmelCase				,				default_to_square=_lowerCAmelCase						)
       if "shortest_edge" not in size:
             raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"						)
       SCREAMING_SNAKE_CASE_							=			get_resize_output_image_size(_lowerCAmelCase				,				size=size['shortest_edge']				,				default_to_square=_lowerCAmelCase						)
       return resize(_lowerCAmelCase				,				size=_lowerCAmelCase				,				resample=_lowerCAmelCase				,				data_format=_lowerCAmelCase				,				**_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		int				,				_lowerCAmelCase  :		np.ndarray				,				_lowerCAmelCase  :		Dict[str, int]				,				_lowerCAmelCase  :		Optional[Union[str, ChannelDimension]] = None				,				**_lowerCAmelCase  :		List[str]				,				):
       SCREAMING_SNAKE_CASE_							=			get_size_dict(_lowerCAmelCase						)
       if "height" not in size or "width" not in size:
             raise ValueError(F"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"						)
       return center_crop(_lowerCAmelCase				,				size=(size['height'], size['width'])				,				data_format=_lowerCAmelCase				,				**_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		List[str]				,				_lowerCAmelCase  :		np.ndarray				,				_lowerCAmelCase  :		float				,				_lowerCAmelCase  :		Optional[Union[str, ChannelDimension]] = None				,				**_lowerCAmelCase  :		Tuple						):
       return rescale(_lowerCAmelCase				,				scale=_lowerCAmelCase				,				data_format=_lowerCAmelCase				,				**_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Tuple				,				_lowerCAmelCase  :		np.ndarray				,				_lowerCAmelCase  :		Union[float, List[float]]				,				_lowerCAmelCase  :		Union[float, List[float]]				,				_lowerCAmelCase  :		Optional[Union[str, ChannelDimension]] = None				,				**_lowerCAmelCase  :		Union[str, Any]				,				):
       return normalize(_lowerCAmelCase				,				mean=_lowerCAmelCase				,				std=_lowerCAmelCase				,				data_format=_lowerCAmelCase				,				**_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Tuple				,				_lowerCAmelCase  :		ImageInput				,				_lowerCAmelCase  :		Optional[bool] = None				,				_lowerCAmelCase  :		Dict[str, int] = None				,				_lowerCAmelCase  :		PILImageResampling = None				,				_lowerCAmelCase  :		bool = None				,				_lowerCAmelCase  :		Dict[str, int] = None				,				_lowerCAmelCase  :		Optional[bool] = None				,				_lowerCAmelCase  :		Optional[float] = None				,				_lowerCAmelCase  :		Optional[bool] = None				,				_lowerCAmelCase  :		Optional[Union[float, List[float]]] = None				,				_lowerCAmelCase  :		Optional[Union[float, List[float]]] = None				,				_lowerCAmelCase  :		Optional[Union[str, TensorType]] = None				,				_lowerCAmelCase  :		Union[str, ChannelDimension] = ChannelDimension.FIRST				,				**_lowerCAmelCase  :		List[Any]				,				):
       SCREAMING_SNAKE_CASE_							=			do_resize if do_resize is not None else self.do_resize
       SCREAMING_SNAKE_CASE_							=			size if size is not None else self.size
       SCREAMING_SNAKE_CASE_							=			get_size_dict(_lowerCAmelCase				,				default_to_square=_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			resample if resample is not None else self.resample
       SCREAMING_SNAKE_CASE_							=			do_center_crop if do_center_crop is not None else self.do_center_crop
       SCREAMING_SNAKE_CASE_							=			crop_size if crop_size is not None else self.crop_size
       SCREAMING_SNAKE_CASE_							=			get_size_dict(_lowerCAmelCase				,				param_name='crop_size'						)
       SCREAMING_SNAKE_CASE_							=			do_rescale if do_rescale is not None else self.do_rescale
       SCREAMING_SNAKE_CASE_							=			rescale_factor if rescale_factor is not None else self.rescale_factor
       SCREAMING_SNAKE_CASE_							=			do_normalize if do_normalize is not None else self.do_normalize
       SCREAMING_SNAKE_CASE_							=			image_mean if image_mean is not None else self.image_mean
       SCREAMING_SNAKE_CASE_							=			image_std if image_std is not None else self.image_std

       SCREAMING_SNAKE_CASE_							=			make_list_of_images(_lowerCAmelCase						)

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

       if do_resize and size is None:
             raise ValueError('Size 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.
       SCREAMING_SNAKE_CASE_							=			[to_numpy_array(_lowerCAmelCase						) for image in images]

       if do_resize:
             SCREAMING_SNAKE_CASE_							=			[self.resize(image=_lowerCAmelCase				,				size=_lowerCAmelCase				,				resample=_lowerCAmelCase						) for image in images]

       if do_center_crop:
             SCREAMING_SNAKE_CASE_							=			[self.center_crop(image=_lowerCAmelCase				,				size=_lowerCAmelCase						) for image in images]

       if do_rescale:
             SCREAMING_SNAKE_CASE_							=			[self.rescale(image=_lowerCAmelCase				,				scale=_lowerCAmelCase						) for image in images]

       if do_normalize:
             SCREAMING_SNAKE_CASE_							=			[self.normalize(image=_lowerCAmelCase				,				mean=_lowerCAmelCase				,				std=_lowerCAmelCase						) for image in images]

       SCREAMING_SNAKE_CASE_							=			[to_channel_dimension_format(_lowerCAmelCase				,				_lowerCAmelCase						) for image in images]

       SCREAMING_SNAKE_CASE_							=			{'pixel_values': images}
       return BatchFeature(data=_lowerCAmelCase				,				tensor_type=_lowerCAmelCase						)




 def       lowerCAmelCase_  (							self  :		Optional[int]				,				_lowerCAmelCase  :		Optional[Any]				,				_lowerCAmelCase  :		List[Tuple] = None						):
       SCREAMING_SNAKE_CASE_							=			outputs.logits

       # Resize logits and compute semantic segmentation maps
       if target_sizes is not None:
             if len(_lowerCAmelCase						) != len(_lowerCAmelCase						):
                   raise ValueError(
                       'Make sure that you pass in as many target sizes as the batch dimension of the logits'						)

             if is_torch_tensor(_lowerCAmelCase						):
                   SCREAMING_SNAKE_CASE_							=			target_sizes.numpy()

             SCREAMING_SNAKE_CASE_							=			[]

             for idx in range(len(_lowerCAmelCase						)						):
                   SCREAMING_SNAKE_CASE_							=			torch.nn.functional.interpolate(
                       logits[idx].unsqueeze(dim=0						)				,				size=target_sizes[idx]				,				mode='bilinear'				,				align_corners=_lowerCAmelCase						)
                   SCREAMING_SNAKE_CASE_							=			resized_logits[0].argmax(dim=0						)
                   semantic_segmentation.append(_lowerCAmelCase						)
       else:
             SCREAMING_SNAKE_CASE_							=			logits.argmax(dim=1						)
             SCREAMING_SNAKE_CASE_							=			[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]						)]

       return semantic_segmentation





import json
import os
from typing import Dict, List, Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowerCamelCase__ :   List[Any]					=							logging.get_logger(__name__)


lowerCamelCase__ :   List[str]					=							{
    'vocab_file': 'vocab.json',
    'tokenizer_config_file': 'tokenizer_config.json',
    'merges_file': 'merges.txt',
}

lowerCamelCase__ :   Union[str, Any]					=							{
    'vocab_file': {
        'facebook/s2t-wav2vec2-large-en-de': (
            'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json'
        ),
    },
    'tokenizer_config_file': {
        'facebook/s2t-wav2vec2-large-en-de': (
            'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json'
        ),
    },
    'merges_file': {
        'facebook/s2t-wav2vec2-large-en-de': (
            'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt'
        ),
    },
}

lowerCamelCase__ :   Optional[Any]					=							'</w>'
lowerCamelCase__ :   Union[str, Any]					=							'@@ '

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Optional[Any]							)					-> Dict:
      SCREAMING_SNAKE_CASE_							=			set()
      SCREAMING_SNAKE_CASE_							=			word[0]
      for char in word[1:]:
            pairs.add((prev_char, char)							)
            SCREAMING_SNAKE_CASE_							=			char
      return pairs


# Speech2Text2 has no max input length
lowerCamelCase__ :   Any					=							{'facebook/s2t-wav2vec2-large-en-de': 1_024}





class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE					):


 '''simple docstring'''







 lowercase_				    =    VOCAB_FILES_NAMES
 lowercase_				    =    PRETRAINED_VOCAB_FILES_MAP
 lowercase_				    =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 lowercase_				    =    ["input_ids", "attention_mask"]



 def __init__(							self  :		List[str]				,				_lowerCAmelCase  :		Union[str, Any]				,				_lowerCAmelCase  :		List[Any]="<s>"				,				_lowerCAmelCase  :		Any="<pad>"				,				_lowerCAmelCase  :		List[str]="</s>"				,				_lowerCAmelCase  :		int="<unk>"				,				_lowerCAmelCase  :		Optional[Any]=False				,				_lowerCAmelCase  :		Dict=None				,				**_lowerCAmelCase  :		Tuple				,				):
       super().__init__(
           unk_token=_lowerCAmelCase				,				bos_token=_lowerCAmelCase				,				eos_token=_lowerCAmelCase				,				pad_token=_lowerCAmelCase				,				do_lower_case=_lowerCAmelCase				,				**_lowerCAmelCase				,				)

       SCREAMING_SNAKE_CASE_							=			do_lower_case

       with open(_lowerCAmelCase				,				encoding='utf-8'						) as vocab_handle:
             SCREAMING_SNAKE_CASE_							=			json.load(_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			{v: k for k, v in self.encoder.items()}

       if merges_file is None:
             logger.info(F"No merges files provided. {self.__class__.__name__} can only be used for decoding."						)

             SCREAMING_SNAKE_CASE_							=			None
             SCREAMING_SNAKE_CASE_							=			None
       else:
             with open(_lowerCAmelCase				,				encoding='utf-8'						) as merges_handle:
                   SCREAMING_SNAKE_CASE_							=			merges_handle.read().split('\n'						)[:-1]

             SCREAMING_SNAKE_CASE_							=			[tuple(merge.split()[:2]						) for merge in merges]
             SCREAMING_SNAKE_CASE_							=			dict(zip(_lowerCAmelCase				,				range(len(_lowerCAmelCase						)						)						)						)
             SCREAMING_SNAKE_CASE_							=			{}



 @property
 def       lowerCAmelCase_  (							self  :		List[str]						):
       return len(self.decoder						)



 def       lowerCAmelCase_  (							self  :		Tuple						):
       return dict(self.encoder				,				**self.added_tokens_encoder						)



 def       lowerCAmelCase_  (							self  :		Tuple				,				_lowerCAmelCase  :		Tuple						):
       SCREAMING_SNAKE_CASE_							=			tuple(token[:-1]						) + (token[-1] + BPE_TOKEN_MERGES,)
       if token in self.cache:
             return self.cache[token]
       SCREAMING_SNAKE_CASE_							=			get_pairs(_lowerCAmelCase						)

       if not pairs:
             return token

       while True:
             SCREAMING_SNAKE_CASE_							=			min(_lowerCAmelCase				,				key=lambda _lowerCAmelCase						: self.bpe_ranks.get(_lowerCAmelCase				,				float('inf'						)						)						)
             if bigram not in self.bpe_ranks:
                   break
             SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			bigram
             SCREAMING_SNAKE_CASE_							=			[]
             SCREAMING_SNAKE_CASE_							=			0
             while i < len(_lowerCAmelCase						):
                   try:
                         SCREAMING_SNAKE_CASE_							=			word.index(_lowerCAmelCase				,				_lowerCAmelCase						)
                   except ValueError:
                         new_word.extend(word[i:]						)
                         break
                   else:
                         new_word.extend(word[i:j]						)
                         SCREAMING_SNAKE_CASE_							=			j

                   if word[i] == first and i < len(_lowerCAmelCase						) - 1 and word[i + 1] == second:
                         new_word.append(first + second						)
                         i += 2
                   else:
                         new_word.append(word[i]						)
                         i += 1
             SCREAMING_SNAKE_CASE_							=			tuple(_lowerCAmelCase						)
             SCREAMING_SNAKE_CASE_							=			new_word
             if len(_lowerCAmelCase						) == 1:
                   break
             else:
                   SCREAMING_SNAKE_CASE_							=			get_pairs(_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			' '.join(_lowerCAmelCase						)
       if word == "\n  " + BPE_TOKEN_MERGES:
             SCREAMING_SNAKE_CASE_							=			'\n' + BPE_TOKEN_MERGES

       if word.endswith(_lowerCAmelCase						):
             SCREAMING_SNAKE_CASE_							=			word.replace(_lowerCAmelCase				,				''						)

       SCREAMING_SNAKE_CASE_							=			word.replace(' '				,				_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			word
       return word



 def       lowerCAmelCase_  (							self  :		Optional[int]				,				_lowerCAmelCase  :		Optional[int]						):

       if self.bpe_ranks is None:
             raise ValueError(
                 'This tokenizer was instantiated without a `merges.txt` file, so'
                 ' that it can only be used for decoding, not for encoding.'
                 'Make sure to provide `merges.txt` file at instantiation to enable '
                 'encoding.'						)

       if self.do_lower_case:
             SCREAMING_SNAKE_CASE_							=			text.lower()

       SCREAMING_SNAKE_CASE_							=			text.split()

       SCREAMING_SNAKE_CASE_							=			[]
       for token in text:
             if token:
                   split_tokens.extend(list(self.bpe(_lowerCAmelCase						).split(' '						)						)						)

       return split_tokens



 def       lowerCAmelCase_  (							self  :		Union[str, Any]				,				_lowerCAmelCase  :		str						):
       return self.encoder.get(_lowerCAmelCase				,				self.encoder.get(self.unk_token						)						)



 def       lowerCAmelCase_  (							self  :		int				,				_lowerCAmelCase  :		int						):
       SCREAMING_SNAKE_CASE_							=			self.decoder.get(_lowerCAmelCase				,				self.unk_token						)
       return result



 def       lowerCAmelCase_  (							self  :		int				,				_lowerCAmelCase  :		List[str]						):
       SCREAMING_SNAKE_CASE_							=			' '.join(_lowerCAmelCase						)

       # make sure @@ tokens are concatenated
       SCREAMING_SNAKE_CASE_							=			''.join(string.split(_lowerCAmelCase						)						)

       return string




 def       lowerCAmelCase_  (							self  :		int				,				_lowerCAmelCase  :		str				,				_lowerCAmelCase  :		Optional[str] = None						):
       if not os.path.isdir(_lowerCAmelCase						):
             logger.error(F"Vocabulary path ({save_directory}) should be a directory"						)
             return
       SCREAMING_SNAKE_CASE_							=			os.path.join(
           _lowerCAmelCase				,				(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']						)
       SCREAMING_SNAKE_CASE_							=			os.path.join(
           _lowerCAmelCase				,				(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']						)

       with open(_lowerCAmelCase				,				'w'				,				encoding='utf-8'						) as f:
             f.write(json.dumps(self.encoder				,				indent=2				,				sort_keys=_lowerCAmelCase				,				ensure_ascii=_lowerCAmelCase						) + '\n'						)

       SCREAMING_SNAKE_CASE_							=			0
       if self.bpe_ranks is None:
             return (vocab_file,)

       with open(_lowerCAmelCase				,				'w'				,				encoding='utf-8'						) as writer:
             for bpe_tokens, token_index in sorted(self.bpe_ranks.items()				,				key=lambda _lowerCAmelCase						: kv[1]						):
                   if index != token_index:
                         logger.warning(
                             F"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."
                             ' Please check that the tokenizer is not corrupted!'						)
                         SCREAMING_SNAKE_CASE_							=			token_index
                   writer.write(' '.join(_lowerCAmelCase						) + '\n'						)
                   index += 1

       return (vocab_file, merges_file)