


'''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'):
 UpperCAmelCase_			:  Union[str, Any]										=   True
 from torch.cuda.amp import autocast

UpperCAmelCase_			:  List[Any]										=   logging.getLogger(__name__)


def       _lowercase							(					UpperCamelCase__							:       int=None,					UpperCamelCase__							:       List[Any]=None      ):
 return field(default_factory=lambda: default,					metadata=UpperCamelCase__      )

@dataclass
class     _lowerCamelCase       :




 '''simple docstring'''
 __lowercase					:		str     				=    field(
     metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}					)
 __lowercase					:		Optional[str]     				=    field(
     default=snake_case_     ,		metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}     ,		)
 __lowercase					:		Optional[bool]     				=    field(
     default=snake_case_     ,		metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}					)
 __lowercase					:		Optional[float]     				=    field(
     default=0.1     ,		metadata={'''help''': '''The dropout ratio for the attention probabilities.'''}					)
 __lowercase					:		Optional[float]     				=    field(
     default=0.1     ,		metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''}					)
 __lowercase					:		Optional[float]     				=    field(
     default=0.1     ,		metadata={
         '''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
     }     ,		)
 __lowercase					:		Optional[float]     				=    field(
     default=0.1     ,		metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''}     ,		)
 __lowercase					:		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``.'''
         )
     }     ,		)
 __lowercase					:		Optional[float]     				=    field(default=0.0     ,		metadata={'''help''': '''The LayerDrop probability.'''}					)


@dataclass
class     _lowerCamelCase       :




 '''simple docstring'''
 __lowercase					:		Optional[str]     				=    field(
     default=snake_case_     ,		metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}					)
 __lowercase					:		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\''''
     }     ,		)
 __lowercase					:		bool     				=    field(
     default=snake_case_     ,		metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}					)
 __lowercase					:		Optional[int]     				=    field(
     default=snake_case_     ,		metadata={'''help''': '''The number of processes to use for the preprocessing.'''}     ,		)
 __lowercase					:		Optional[int]     				=    field(
     default=snake_case_     ,		metadata={
         '''help''': (
             '''For debugging purposes or quicker training, truncate the number of training examples to this '''
             '''value if set.'''
         )
     }     ,		)
 __lowercase					:		Optional[int]     				=    field(
     default=snake_case_     ,		metadata={
         '''help''': (
             '''For debugging purposes or quicker training, truncate the number of validation examples to this '''
             '''value if set.'''
         )
     }     ,		)
 __lowercase					:		List[str]     				=    list_field(
     default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�''']     ,		metadata={'''help''': '''A list of characters to remove from the transcripts.'''}     ,		)


@dataclass
class     _lowerCamelCase       :




 '''simple docstring'''
 __lowercase					:		WavaVecaProcessor
 __lowercase					:		Union[bool, str]     				=    True
 __lowercase					:		Optional[int]     				=    None
 __lowercase					:		Optional[int]     				=    None
 __lowercase					:		Optional[int]     				=    None
 __lowercase					:		Optional[int]     				=    None


 def __call__(   self   ,   __lowercase    ):

  """simple docstring"""







  __A	:		Dict	  =      [{'input_values': feature['input_values']} for feature in features]
  __A	:		Optional[Any]	  =      [{'input_ids': feature['labels']} for feature in features]

  __A	:		Tuple	  =      self.processor.pad(
      __lowercase   ,   padding=self.padding   ,   max_length=self.max_length   ,   pad_to_multiple_of=self.pad_to_multiple_of   ,   return_tensors='pt'   ,   )
  __A	:		List[str]	  =      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
  __A	:		Optional[Any]	  =      labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1    )   ,   -100    )

  __A	:		str	  =      labels

  return batch


class     _lowerCamelCase       (     snake_case_					):




 '''simple docstring'''


 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase    ):

  """simple docstring"""







  model.train()
  __A	:		Union[str, Any]	  =      self._prepare_inputs(__lowercase    )

  if self.use_amp:
   with autocast():
    __A	:		Optional[Any]	  =      self.compute_loss(__lowercase   ,   __lowercase    )
  else:
   __A	:		Optional[Any]	  =      self.compute_loss(__lowercase   ,   __lowercase    )

  if self.args.n_gpu > 1:
   if model.module.config.ctc_loss_reduction == "mean":
    __A	:		Tuple	  =      loss.mean()
   elif model.module.config.ctc_loss_reduction == "sum":
    __A	:		List[str]	  =      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:
   __A	:		Optional[Any]	  =      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       _lowercase							(					):
 # 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.

 __A	:		Optional[Any]	  =      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.
  __A  ,__A  ,__A	:		Dict	  =      parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]      )      )
 else:
  __A  ,__A  ,__A	:		Optional[int]	  =      parser.parse_args_into_dataclasses()

 # Detecting last checkpoint.
 __A	:		Tuple	  =      None
 if os.path.isdir(training_args.output_dir      ) and training_args.do_train and not training_args.overwrite_output_dir:
  __A	:		Optional[int]	  =      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',					UpperCamelCase__      )

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

 # Get the datasets:
 __A	:		Union[str, Any]	  =      datasets.load_dataset(
     'common_voice',					data_args.dataset_config_name,					split=data_args.train_split_name      )
 __A	:		Optional[Any]	  =      datasets.load_dataset('common_voice',					data_args.dataset_config_name,					split='test'      )

 # Create and save tokenizer
 __A	:		List[Any]	  =      f"""[{''.join(data_args.chars_to_ignore      )}]"""

 def remove_special_characters(UpperCamelCase__							:       List[str]      ):
  __A	:		List[str]	  =      re.sub(UpperCamelCase__,					'',					batch['sentence']      ).lower() + ' '
  return batch

 __A	:		Tuple	  =      train_dataset.map(UpperCamelCase__,					remove_columns=['sentence']      )
 __A	:		Tuple	  =      eval_dataset.map(UpperCamelCase__,					remove_columns=['sentence']      )

 def extract_all_chars(UpperCamelCase__							:       str      ):
  __A	:		str	  =      ' '.join(batch['text']      )
  __A	:		List[str]	  =      list(set(UpperCamelCase__      )      )
  return {"vocab": [vocab], "all_text": [all_text]}

 __A	:		Tuple	  =      train_dataset.map(
     UpperCamelCase__,					batched=UpperCamelCase__,					batch_size=-1,					keep_in_memory=UpperCamelCase__,					remove_columns=train_dataset.column_names,					)
 __A	:		List[str]	  =      train_dataset.map(
     UpperCamelCase__,					batched=UpperCamelCase__,					batch_size=-1,					keep_in_memory=UpperCamelCase__,					remove_columns=eval_dataset.column_names,					)

 __A	:		List[str]	  =      list(set(vocab_train['vocab'][0]      ) | set(vocab_test['vocab'][0]      )      )
 __A	:		Optional[Any]	  =      {v: k for k, v in enumerate(UpperCamelCase__      )}
 __A	:		Tuple	  =      vocab_dict[' ']
 del vocab_dict[" "]
 __A	:		Union[str, Any]	  =      len(UpperCamelCase__      )
 __A	:		int	  =      len(UpperCamelCase__      )

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

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.
 __A	:		List[Any]	  =      WavaVecaCTCTokenizer(
     'vocab.json',					unk_token='[UNK]',					pad_token='[PAD]',					word_delimiter_token='|',					)
 __A	:		str	  =      WavaVecaFeatureExtractor(
     feature_size=1,					sampling_rate=16000,					padding_value=0.0,					do_normalize=UpperCamelCase__,					return_attention_mask=UpperCamelCase__      )
 __A	:		Optional[int]	  =      WavaVecaProcessor(feature_extractor=UpperCamelCase__,					tokenizer=UpperCamelCase__      )
 __A	:		Tuple	  =      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:
  __A	:		List[Any]	  =      min(len(UpperCamelCase__      ),					data_args.max_train_samples      )
  __A	:		Union[str, Any]	  =      train_dataset.select(range(UpperCamelCase__      )      )

 if data_args.max_val_samples is not None:
  __A	:		Optional[Any]	  =      eval_dataset.select(range(data_args.max_val_samples      )      )

 __A	:		List[Any]	  =      torchaudio.transforms.Resample(48000,					16000      )

 # Preprocessing the datasets.
 # We need to read the aduio files as arrays and tokenize the targets.
 def speech_file_to_array_fn(UpperCamelCase__							:       Union[str, Any]      ):
  __A  ,__A	:		List[Any]	  =      torchaudio.load(batch['path']      )
  __A	:		Dict	  =      resampler(UpperCamelCase__      ).squeeze().numpy()
  __A	:		str	  =      16000
  __A	:		Dict	  =      batch['text']
  return batch

 __A	:		List[str]	  =      train_dataset.map(
     UpperCamelCase__,					remove_columns=train_dataset.column_names,					num_proc=data_args.preprocessing_num_workers,					)
 __A	:		str	  =      eval_dataset.map(
     UpperCamelCase__,					remove_columns=eval_dataset.column_names,					num_proc=data_args.preprocessing_num_workers,					)

 def prepare_dataset(UpperCamelCase__							:       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}."""

  __A	:		Dict	  =      processor(
      audio=batch['speech'],					text=batch['target_text'],					sampling_rate=batch['sampling_rate'][0]      )
  batch.update(UpperCamelCase__      )
  return batch

 __A	:		str	  =      train_dataset.map(
     UpperCamelCase__,					remove_columns=train_dataset.column_names,					batch_size=training_args.per_device_train_batch_size,					batched=UpperCamelCase__,					num_proc=data_args.preprocessing_num_workers,					)
 __A	:		Any	  =      eval_dataset.map(
     UpperCamelCase__,					remove_columns=eval_dataset.column_names,					batch_size=training_args.per_device_train_batch_size,					batched=UpperCamelCase__,					num_proc=data_args.preprocessing_num_workers,					)

 # Metric
 __A	:		str	  =      datasets.load_metric('wer'      )

 def compute_metrics(UpperCamelCase__							:       Union[str, Any]      ):
  __A	:		List[Any]	  =      pred.predictions
  __A	:		int	  =      np.argmax(UpperCamelCase__,					axis=-1      )

  __A	:		int	  =      processor.tokenizer.pad_token_id

  __A	:		List[Any]	  =      processor.batch_decode(UpperCamelCase__      )
  # we do not want to group tokens when computing the metrics
  __A	:		List[Any]	  =      processor.batch_decode(pred.label_ids,					group_tokens=UpperCamelCase__      )

  __A	:		int	  =      wer_metric.compute(predictions=UpperCamelCase__,					references=UpperCamelCase__      )

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

 # Data collator
 __A	:		Dict	  =      DataCollatorCTCWithPadding(processor=UpperCamelCase__,					padding=UpperCamelCase__      )

 # Initialize our Trainer
 __A	:		List[Any]	  =      CTCTrainer(
     model=UpperCamelCase__,					data_collator=UpperCamelCase__,					args=UpperCamelCase__,					compute_metrics=UpperCamelCase__,					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:
   __A	:		List[str]	  =      last_checkpoint
  elif os.path.isdir(model_args.model_name_or_path      ):
   __A	:		List[Any]	  =      model_args.model_name_or_path
  else:
   __A	:		List[str]	  =      None

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

  __A	:		List[Any]	  =      trainer.train(resume_from_checkpoint=UpperCamelCase__      )
  trainer.save_model()

  __A	:		Optional[Any]	  =      train_result.metrics
  __A	:		Union[str, Any]	  =      (
      data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCamelCase__      )
  )
  __A	:		Union[str, Any]	  =      min(UpperCamelCase__,					len(UpperCamelCase__      )      )

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

 # Evaluation
 __A	:		Dict	  =      {}
 if training_args.do_eval:
  logger.info('*** Evaluate ***'      )
  __A	:		Union[str, Any]	  =      trainer.evaluate()
  __A	:		str	  =      data_args.max_val_samples if data_args.max_val_samples is not None else len(UpperCamelCase__      )
  __A	:		str	  =      min(UpperCamelCase__,					len(UpperCamelCase__      )      )

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

 return results


if __name__ == "__main__":
 main()










'''simple docstring'''
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

import torch

from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
 from PIL import Image

class     _lowerCamelCase       (     snake_case_					):




 '''simple docstring'''
 __lowercase					:		int     				=    '''dandelin/vilt-b32-finetuned-vqa'''
 __lowercase					:		int     				=    (
     '''This is a tool that answers a question about an image. It takes an input named `image` which should be the '''
     '''image containing the information, as well as a `question` which should be the question in English. It '''
     '''returns a text that is the answer to the question.'''
 )
 __lowercase					:		Union[str, Any]     				=    '''image_qa'''
 __lowercase					:		Optional[Any]     				=    AutoProcessor
 __lowercase					:		Tuple     				=    AutoModelForVisualQuestionAnswering

 __lowercase					:		Tuple     				=    ['''image''', '''text''']
 __lowercase					:		List[str]     				=    ['''text''']


 def __init__(   self   ,   *__lowercase   ,   **__lowercase    ):

  """simple docstring"""







  requires_backends(self   ,   ['vision']    )
  super().__init__(*__lowercase   ,   **__lowercase    )


 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase    ):

  """simple docstring"""







  return self.pre_processor(__lowercase   ,   __lowercase   ,   return_tensors='pt'    )


 def 			snake_case__ (   self   ,   __lowercase    ):

  """simple docstring"""







  with torch.no_grad():
   return self.model(**__lowercase    ).logits







 def 			snake_case__ (   self   ,   __lowercase    ):

  """simple docstring"""







  __A	:		List[str]	  =      outputs.argmax(-1    ).item()
  return self.model.config.idalabel[idx]






