




'''simple docstring'''







import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
   from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'):
   A     =True
   from torch.cuda.amp import autocast

A     =logging.getLogger(__name__)





def 						snake_case_							(_a	:							str=None    ,   _a	:							List[Any]=None     ):
    return field(default_factory=lambda: default    ,   metadata=_a     )


@dataclass
class 			_a  :
       __a				:     str   				=					field(
           metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} )
       __a				:     Optional[str]   				=					field(
           default=__a							,							metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}							,							)
       __a				:     Optional[bool]   				=					field(
           default=__a							,							metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""} )
       __a				:     Optional[float]   				=					field(
           default=0.1							,							metadata={"""help""": """The dropout ratio for the attention probabilities."""} )
       __a				:     Optional[float]   				=					field(
           default=0.1							,							metadata={"""help""": """The dropout ratio for activations inside the fully connected layer."""} )
       __a				:     Optional[float]   				=					field(
           default=0.1							,							metadata={
               """help""": """The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."""
           }							,							)
       __a				:     Optional[float]   				=					field(
           default=0.1							,							metadata={"""help""": """The dropout probabilitiy for all 1D convolutional layers in feature extractor."""}							,							)
       __a				:     Optional[float]   				=					field(
           default=0.05							,							metadata={
               """help""": (
                   """Propability of each feature vector along the time axis to be chosen as the start of the vector"""
                   """span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"""
                   """vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``."""
               )
           }							,							)
       __a				:     Optional[float]   				=					field(default=0.0							,							metadata={"""help""": """The LayerDrop probability."""} )






@dataclass
class 			_a  :
       __a				:     Optional[str]   				=					field(
           default=__a							,							metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} )
       __a				:     Optional[str]   				=					field(
           default="""train+validation"""							,							metadata={
               """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
           }							,							)
       __a				:     bool   				=					field(
           default=__a							,							metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""} )
       __a				:     Optional[int]   				=					field(
           default=__a							,							metadata={"""help""": """The number of processes to use for the preprocessing."""}							,							)
       __a				:     Optional[int]   				=					field(
           default=__a							,							metadata={
               """help""": (
                   """For debugging purposes or quicker training, truncate the number of training examples to this """
                   """value if set."""
               )
           }							,							)
       __a				:     Optional[int]   				=					field(
           default=__a							,							metadata={
               """help""": (
                   """For debugging purposes or quicker training, truncate the number of validation examples to this """
                   """value if set."""
               )
           }							,							)
       __a				:     List[str]   				=					list_field(
           default=[""",""", """?""", """.""", """!""", """-""", """;""", """:""", """\"\"""", """%""", """'""", """\"""", """�"""]							,							metadata={"""help""": """A list of characters to remove from the transcripts."""}							,							)






@dataclass
class 			_a  :
       __a				:     WavaVecaProcessor
       __a				:     Union[bool, str]   				=					True
       __a				:     Optional[int]   				=					None
       __a				:     Optional[int]   				=					None
       __a				:     Optional[int]   				=					None
       __a				:     Optional[int]   				=					None
       def __call__(	self						:	int   ,				lowercase						:	List[Dict[str, Union[List[int], torch.Tensor]]]				):



           '''simple docstring'''

           UpperCAmelCase			       =		[{'''input_values''': feature['''input_values''']} for feature in features]
           UpperCAmelCase			       =		[{'''input_ids''': feature['''labels''']} for feature in features]

           UpperCAmelCase			       =		self.processor.pad(
               lowercase   ,				padding=self.padding   ,				max_length=self.max_length   ,				pad_to_multiple_of=self.pad_to_multiple_of   ,				return_tensors='''pt'''   ,				)
           UpperCAmelCase			       =		self.processor.pad(
               labels=lowercase   ,				padding=self.padding   ,				max_length=self.max_length_labels   ,				pad_to_multiple_of=self.pad_to_multiple_of_labels   ,				return_tensors='''pt'''   ,				)

           # replace padding with -100 to ignore loss correctly
           UpperCAmelCase			       =		labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1				)   ,				-100				)

           UpperCAmelCase			       =		labels

           return batch






class 			_a  (	__a ):
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	nn.Module   ,				lowercase						:	Dict[str, Union[torch.Tensor, Any]]				):



           '''simple docstring'''

           model.train()
           UpperCAmelCase			       =		self._prepare_inputs(lowercase				)

           if self.use_amp:
               with autocast():
                   UpperCAmelCase			       =		self.compute_loss(lowercase   ,				lowercase				)
           else:
               UpperCAmelCase			       =		self.compute_loss(lowercase   ,				lowercase				)

           if self.args.n_gpu > 1:
               if model.module.config.ctc_loss_reduction == "mean":
                   UpperCAmelCase			       =		loss.mean()
               elif model.module.config.ctc_loss_reduction == "sum":
                   UpperCAmelCase			       =		loss.sum() / (inputs['''labels'''] >= 0).sum()
               else:
                   raise ValueError(f"{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']"				)

           if self.args.gradient_accumulation_steps > 1:
               UpperCAmelCase			       =		loss / self.args.gradient_accumulation_steps

           if self.use_amp:
               self.scaler.scale(lowercase				).backward()
           elif self.use_apex:
               with amp.scale_loss(lowercase   ,				self.optimizer				) as scaled_loss:
                   scaled_loss.backward()
           elif self.deepspeed:
               self.deepspeed.backward(lowercase				)
           else:
               loss.backward()

           return loss.detach()






def 						snake_case_							():
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    UpperCAmelCase			       =		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )
    if len(sys.argv     ) == 2 and sys.argv[1].endswith('''.json'''     ):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        UpperCAmelCase       ,     UpperCAmelCase       ,     UpperCAmelCase			       =		parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
    else:
        UpperCAmelCase       ,     UpperCAmelCase       ,     UpperCAmelCase			       =		parser.parse_args_into_dataclasses()

    # Detecting last checkpoint.
    UpperCAmelCase			       =		None
    if os.path.isdir(training_args.output_dir     ) and training_args.do_train and not training_args.overwrite_output_dir:
        UpperCAmelCase			       =		get_last_checkpoint(training_args.output_dir     )
        if last_checkpoint is None and len(os.listdir(training_args.output_dir     )     ) > 0:
            raise ValueError(
                F"Output directory ({training_args.output_dir}) already exists and is not empty. "
                '''Use --overwrite_output_dir to overcome.'''     )
        elif last_checkpoint is not None:
            logger.info(
                F"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
                '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''     )

    # Setup logging
    logging.basicConfig(
        format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''    ,   datefmt='''%m/%d/%Y %H:%M:%S'''    ,   handlers=[logging.StreamHandler(sys.stdout     )]    ,   )
    logger.setLevel(logging.INFO if is_main_process(training_args.local_rank     ) else logging.WARN     )

    # Log on each process the small summary:
    logger.warning(
        F"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
        + F"distributed training: {bool(training_args.local_rank != -1     )}, 16-bits training: {training_args.fpaa}"     )
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(training_args.local_rank     ):
        transformers.utils.logging.set_verbosity_info()
    logger.info('''Training/evaluation parameters %s'''    ,   _a     )

    # Set seed before initializing model.
    set_seed(training_args.seed     )

    # Get the datasets:
    UpperCAmelCase			       =		datasets.load_dataset(
        '''common_voice'''    ,   data_args.dataset_config_name    ,   split=data_args.train_split_name     )
    UpperCAmelCase			       =		datasets.load_dataset('''common_voice'''    ,   data_args.dataset_config_name    ,   split='''test'''     )

    # Create and save tokenizer
    UpperCAmelCase			       =		F"[{''.join(data_args.chars_to_ignore     )}]"

    def remove_special_characters(_a	:							str     ):
        UpperCAmelCase			       =		re.sub(_a    ,   ''''''    ,   batch['''sentence''']     ).lower() + ''' '''
        return batch

    UpperCAmelCase			       =		train_dataset.map(_a    ,   remove_columns=['''sentence''']     )
    UpperCAmelCase			       =		eval_dataset.map(_a    ,   remove_columns=['''sentence''']     )

    def extract_all_chars(_a	:							int     ):
        UpperCAmelCase			       =		''' '''.join(batch['''text''']     )
        UpperCAmelCase			       =		list(set(_a     )     )
        return {"vocab": [vocab], "all_text": [all_text]}

    UpperCAmelCase			       =		train_dataset.map(
        _a    ,   batched=_a    ,   batch_size=-1    ,   keep_in_memory=_a    ,   remove_columns=train_dataset.column_names    ,   )
    UpperCAmelCase			       =		train_dataset.map(
        _a    ,   batched=_a    ,   batch_size=-1    ,   keep_in_memory=_a    ,   remove_columns=eval_dataset.column_names    ,   )

    UpperCAmelCase			       =		list(set(vocab_train['''vocab'''][0]     ) | set(vocab_test['''vocab'''][0]     )     )
    UpperCAmelCase			       =		{v: k for k, v in enumerate(_a     )}
    UpperCAmelCase			       =		vocab_dict[''' ''']
    del vocab_dict[" "]
    UpperCAmelCase			       =		len(_a     )
    UpperCAmelCase			       =		len(_a     )

    with open('''vocab.json'''    ,   '''w'''     ) as vocab_file:
        json.dump(_a    ,   _a     )

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.
    UpperCAmelCase			       =		WavaVecaCTCTokenizer(
        '''vocab.json'''    ,   unk_token='''[UNK]'''    ,   pad_token='''[PAD]'''    ,   word_delimiter_token='''|'''    ,   )
    UpperCAmelCase			       =		WavaVecaFeatureExtractor(
        feature_size=1    ,   sampling_rate=1_6_0_0_0    ,   padding_value=0.0    ,   do_normalize=_a    ,   return_attention_mask=_a     )
    UpperCAmelCase			       =		WavaVecaProcessor(feature_extractor=_a    ,   tokenizer=_a     )
    UpperCAmelCase			       =		WavaVecaForCTC.from_pretrained(
        model_args.model_name_or_path    ,   cache_dir=model_args.cache_dir    ,   activation_dropout=model_args.activation_dropout    ,   attention_dropout=model_args.attention_dropout    ,   hidden_dropout=model_args.hidden_dropout    ,   feat_proj_dropout=model_args.feat_proj_dropout    ,   mask_time_prob=model_args.mask_time_prob    ,   gradient_checkpointing=training_args.gradient_checkpointing    ,   layerdrop=model_args.layerdrop    ,   ctc_loss_reduction='''mean'''    ,   pad_token_id=processor.tokenizer.pad_token_id    ,   vocab_size=len(processor.tokenizer     )    ,   )

    if data_args.max_train_samples is not None:
        UpperCAmelCase			       =		min(len(_a     )    ,   data_args.max_train_samples     )
        UpperCAmelCase			       =		train_dataset.select(range(_a     )     )

    if data_args.max_val_samples is not None:
        UpperCAmelCase			       =		eval_dataset.select(range(data_args.max_val_samples     )     )

    UpperCAmelCase			       =		torchaudio.transforms.Resample(4_8_0_0_0    ,   1_6_0_0_0     )

    # Preprocessing the datasets.
    # We need to read the aduio files as arrays and tokenize the targets.
    def speech_file_to_array_fn(_a	:							Optional[Any]     ):
        UpperCAmelCase       ,     UpperCAmelCase			       =		torchaudio.load(batch['''path''']     )
        UpperCAmelCase			       =		resampler(_a     ).squeeze().numpy()
        UpperCAmelCase			       =		1_6_0_0_0
        UpperCAmelCase			       =		batch['''text''']
        return batch

    UpperCAmelCase			       =		train_dataset.map(
        _a    ,   remove_columns=train_dataset.column_names    ,   num_proc=data_args.preprocessing_num_workers    ,   )
    UpperCAmelCase			       =		eval_dataset.map(
        _a    ,   remove_columns=eval_dataset.column_names    ,   num_proc=data_args.preprocessing_num_workers    ,   )

    def prepare_dataset(_a	:							int     ):
        # check that all files have the correct sampling rate
        assert (
            len(set(batch['''sampling_rate''']     )     ) == 1
        ), F"Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}."

        UpperCAmelCase			       =		processor(
            audio=batch['''speech''']    ,   text=batch['''target_text''']    ,   sampling_rate=batch['''sampling_rate'''][0]     )
        batch.update(_a     )
        return batch

    UpperCAmelCase			       =		train_dataset.map(
        _a    ,   remove_columns=train_dataset.column_names    ,   batch_size=training_args.per_device_train_batch_size    ,   batched=_a    ,   num_proc=data_args.preprocessing_num_workers    ,   )
    UpperCAmelCase			       =		eval_dataset.map(
        _a    ,   remove_columns=eval_dataset.column_names    ,   batch_size=training_args.per_device_train_batch_size    ,   batched=_a    ,   num_proc=data_args.preprocessing_num_workers    ,   )

    # Metric
    UpperCAmelCase			       =		datasets.load_metric('''wer'''     )

    def compute_metrics(_a	:							Tuple     ):
        UpperCAmelCase			       =		pred.predictions
        UpperCAmelCase			       =		np.argmax(_a    ,   axis=-1     )

        UpperCAmelCase			       =		processor.tokenizer.pad_token_id

        UpperCAmelCase			       =		processor.batch_decode(_a     )
        # we do not want to group tokens when computing the metrics
        UpperCAmelCase			       =		processor.batch_decode(pred.label_ids    ,   group_tokens=_a     )

        UpperCAmelCase			       =		wer_metric.compute(predictions=_a    ,   references=_a     )

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    # Data collator
    UpperCAmelCase			       =		DataCollatorCTCWithPadding(processor=_a    ,   padding=_a     )

    # Initialize our Trainer
    UpperCAmelCase			       =		CTCTrainer(
        model=_a    ,   data_collator=_a    ,   args=_a    ,   compute_metrics=_a    ,   train_dataset=train_dataset if training_args.do_train else None    ,   eval_dataset=eval_dataset if training_args.do_eval else None    ,   tokenizer=processor.feature_extractor    ,   )

    # Training
    if training_args.do_train:
        if last_checkpoint is not None:
            UpperCAmelCase			       =		last_checkpoint
        elif os.path.isdir(model_args.model_name_or_path     ):
            UpperCAmelCase			       =		model_args.model_name_or_path
        else:
            UpperCAmelCase			       =		None

        # Save the feature_extractor and the tokenizer
        if is_main_process(training_args.local_rank     ):
            processor.save_pretrained(training_args.output_dir     )

        UpperCAmelCase			       =		trainer.train(resume_from_checkpoint=_a     )
        trainer.save_model()

        UpperCAmelCase			       =		train_result.metrics
        UpperCAmelCase			       =		(
            data_args.max_train_samples if data_args.max_train_samples is not None else len(_a     )
        )
        UpperCAmelCase			       =		min(_a    ,   len(_a     )     )

        trainer.log_metrics('''train'''    ,   _a     )
        trainer.save_metrics('''train'''    ,   _a     )
        trainer.save_state()

    # Evaluation
    UpperCAmelCase			       =		{}
    if training_args.do_eval:
        logger.info('''*** Evaluate ***'''     )
        UpperCAmelCase			       =		trainer.evaluate()
        UpperCAmelCase			       =		data_args.max_val_samples if data_args.max_val_samples is not None else len(_a     )
        UpperCAmelCase			       =		min(_a    ,   len(_a     )     )

        trainer.log_metrics('''eval'''    ,   _a     )
        trainer.save_metrics('''eval'''    ,   _a     )

    return results


if __name__ == "__main__":
   main()










'''simple docstring'''







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


A     =logging.get_logger(__name__)


class 			_a  (	__a ):
       __a				:     str   				=					["""pixel_values"""]
       def __init__(	self						:	Optional[int]   ,				lowercase						:	bool = True   ,				lowercase						:	Optional[Dict[str, int]] = None   ,				lowercase						:	PILImageResampling = PILImageResampling.BILINEAR   ,				lowercase						:	bool = True   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	bool = True   ,				lowercase						:	Union[int, float] = 1 / 255   ,				lowercase						:	bool = True   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				**lowercase						:	Union[str, Any]   ,				):



           '''simple docstring'''

           super().__init__(**lowercase				)
           UpperCAmelCase			       =		size if size is not None else {'''shortest_edge''': 256}
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           UpperCAmelCase			       =		crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				param_name='''crop_size'''				)
           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 if image_mean is not None else IMAGENET_STANDARD_MEAN
           UpperCAmelCase			       =		image_std if image_std is not None else IMAGENET_STANDARD_STD
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Dict[str, int]   ,				lowercase						:	PILImageResampling = PILImageResampling.BICUBIC   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	Any   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           if "shortest_edge" not in size:
               raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"				)
           UpperCAmelCase			       =		get_resize_output_image_size(lowercase   ,				size=size['''shortest_edge''']   ,				default_to_square=lowercase				)
           return resize(lowercase   ,				size=lowercase   ,				resample=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Dict[str, int]   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	int   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		get_size_dict(lowercase				)
           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(lowercase   ,				size=(size['''height'''], size['''width'''])   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Tuple   ,				lowercase						:	np.ndarray   ,				lowercase						:	float   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	List[str]				):



           '''simple docstring'''

           return rescale(lowercase   ,				scale=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Optional[int]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Union[float, List[float]]   ,				lowercase						:	Union[float, List[float]]   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	Union[str, Any]   ,				):



           '''simple docstring'''

           return normalize(lowercase   ,				mean=lowercase   ,				std=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Optional[int]   ,				lowercase						:	ImageInput   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	PILImageResampling = None   ,				lowercase						:	bool = None   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Optional[float] = None   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[str, TensorType]] = None   ,				lowercase						:	Union[str, ChannelDimension] = ChannelDimension.FIRST   ,				**lowercase						:	Dict   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		do_resize if do_resize is not None else self.do_resize
           UpperCAmelCase			       =		size if size is not None else self.size
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           UpperCAmelCase			       =		resample if resample is not None else self.resample
           UpperCAmelCase			       =		do_center_crop if do_center_crop is not None else self.do_center_crop
           UpperCAmelCase			       =		crop_size if crop_size is not None else self.crop_size
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				param_name='''crop_size'''				)
           UpperCAmelCase			       =		do_rescale if do_rescale is not None else self.do_rescale
           UpperCAmelCase			       =		rescale_factor if rescale_factor is not None else self.rescale_factor
           UpperCAmelCase			       =		do_normalize if do_normalize is not None else self.do_normalize
           UpperCAmelCase			       =		image_mean if image_mean is not None else self.image_mean
           UpperCAmelCase			       =		image_std if image_std is not None else self.image_std

           UpperCAmelCase			       =		make_list_of_images(lowercase				)

           if not valid_images(lowercase				):
               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.
           UpperCAmelCase			       =		[to_numpy_array(lowercase				) for image in images]

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

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

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

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

           UpperCAmelCase			       =		[to_channel_dimension_format(lowercase   ,				lowercase				) for image in images]

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







       def     A      (	self						:	Tuple   ,				lowercase						:	str   ,				lowercase						:	List[Tuple] = None				):



           '''simple docstring'''

           UpperCAmelCase			       =		outputs.logits

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

               if is_torch_tensor(lowercase				):
                   UpperCAmelCase			       =		target_sizes.numpy()

               UpperCAmelCase			       =		[]

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

           return semantic_segmentation




