






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"):
    _SCREAMING_SNAKE_CASE   =  True
    from torch.cuda.amp import autocast

_SCREAMING_SNAKE_CASE   =  logging.getLogger(__name__)





def        _snake_case   (_snake_case				:       Optional[Any]=None      ,    _snake_case				:       Optional[int]=None)					->	Optional[int]:
   return field(default_factory=lambda: default      ,    metadata=_snake_case)






@dataclass
class 					SCREAMING_SNAKE_CASE_  :
       """simple docstring"""


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






@dataclass
class 					SCREAMING_SNAKE_CASE_  :
       """simple docstring"""


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






@dataclass
class 					SCREAMING_SNAKE_CASE_  :
       """simple docstring"""


       __lowerCAmelCase    :		WavaVecaProcessor
       __lowerCAmelCase    :		Union[bool, str]					=True
       __lowerCAmelCase    :		Optional[int]					=None
       __lowerCAmelCase    :		Optional[int]					=None
       __lowerCAmelCase    :		Optional[int]					=None
       __lowerCAmelCase    :		Optional[int]					=None





       def __call__(				self	:Dict,      snake_case	:List[Dict[str, Union[List[int], torch.Tensor]]]):



          """simple docstring"""

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

          _lowercase              =self.processor.pad(
              snake_case,      padding=self.padding,      max_length=self.max_length,      pad_to_multiple_of=self.pad_to_multiple_of,      return_tensors='pt',      )
          _lowercase              =self.processor.pad(
              labels=snake_case,      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
          _lowercase              =labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1),      -100)

          _lowercase              =labels

          return batch






class 					SCREAMING_SNAKE_CASE_  (       _a ):
       """simple docstring"""


       def 				UpperCamelCase__						(				self	:int,      snake_case	:nn.Module,      snake_case	:Dict[str, Union[torch.Tensor, Any]]):



          """simple docstring"""

          model.train()
          _lowercase              =self._prepare_inputs(snake_case)

          if self.use_amp:
             with autocast():
                _lowercase              =self.compute_loss(snake_case,      snake_case)
          else:
             _lowercase              =self.compute_loss(snake_case,      snake_case)

          if self.args.n_gpu > 1:
             if model.module.config.ctc_loss_reduction == "mean":
                _lowercase              =loss.mean()
             elif model.module.config.ctc_loss_reduction == "sum":
                _lowercase              =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:
             _lowercase              =loss / self.args.gradient_accumulation_steps

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

          return loss.detach()





def        _snake_case   ()					->	int:
   # 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.

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

   # Detecting last checkpoint.
   _lowercase              =None
   if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
      _lowercase              =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'      ,    _snake_case)

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

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

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

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

   _lowercase              =train_dataset.map(_snake_case      ,    remove_columns=['sentence'])
   _lowercase              =eval_dataset.map(_snake_case      ,    remove_columns=['sentence'])

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

   _lowercase              =train_dataset.map(
       _snake_case      ,    batched=_snake_case      ,    batch_size=-1      ,    keep_in_memory=_snake_case      ,    remove_columns=train_dataset.column_names      ,    )
   _lowercase              =train_dataset.map(
       _snake_case      ,    batched=_snake_case      ,    batch_size=-1      ,    keep_in_memory=_snake_case      ,    remove_columns=eval_dataset.column_names      ,    )

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

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

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

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

   _lowercase              =torchaudio.transforms.Resample(4_8000      ,    1_6000)

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

   _lowercase              =train_dataset.map(
       _snake_case      ,    remove_columns=train_dataset.column_names      ,    num_proc=data_args.preprocessing_num_workers      ,    )
   _lowercase              =eval_dataset.map(
       _snake_case      ,    remove_columns=eval_dataset.column_names      ,    num_proc=data_args.preprocessing_num_workers      ,    )

   def prepare_dataset(_snake_case				:       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}.'''

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

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

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

   def compute_metrics(_snake_case				:       str):
      _lowercase              =pred.predictions
      _lowercase              =np.argmax(_snake_case      ,    axis=-1)

      _lowercase              =processor.tokenizer.pad_token_id

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

      _lowercase              =wer_metric.compute(predictions=_snake_case      ,    references=_snake_case)

      return {"wer": wer}

   if model_args.freeze_feature_extractor:
      model.freeze_feature_extractor()

   # Data collator
   _lowercase              =DataCollatorCTCWithPadding(processor=_snake_case      ,    padding=_snake_case)

   # Initialize our Trainer
   _lowercase              =CTCTrainer(
       model=_snake_case      ,    data_collator=_snake_case      ,    args=_snake_case      ,    compute_metrics=_snake_case      ,    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:
         _lowercase              =last_checkpoint
      elif os.path.isdir(model_args.model_name_or_path):
         _lowercase              =model_args.model_name_or_path
      else:
         _lowercase              =None

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

      _lowercase              =trainer.train(resume_from_checkpoint=_snake_case)
      trainer.save_model()

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

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

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

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

   return results


if __name__ == "__main__":
    main()










import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available


if is_vision_available():
    from PIL import Image

    from transformers import (
        AutoProcessor,
        BertTokenizerFast,
        BlipImageProcessor,
        GPTaTokenizer,
        InstructBlipProcessor,
        PreTrainedTokenizerFast,
    )






@require_vision
class 					SCREAMING_SNAKE_CASE_  (       unittest.TestCase ):
       """simple docstring"""


       def 				UpperCamelCase__						(				self	:List[str]):



          """simple docstring"""

          _lowercase              =tempfile.mkdtemp()

          _lowercase              =BlipImageProcessor()
          _lowercase              =GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model')
          _lowercase              =BertTokenizerFast.from_pretrained('hf-internal-testing/tiny-random-bert')

          _lowercase              =InstructBlipProcessor(snake_case,      snake_case,      snake_case)

          processor.save_pretrained(self.tmpdirname)





       def 				UpperCamelCase__						(				self	:List[str],      **snake_case	:str):



          """simple docstring"""

          return AutoProcessor.from_pretrained(self.tmpdirname,      **snake_case).tokenizer





       def 				UpperCamelCase__						(				self	:Optional[Any],      **snake_case	:List[Any]):



          """simple docstring"""

          return AutoProcessor.from_pretrained(self.tmpdirname,      **snake_case).image_processor





       def 				UpperCamelCase__						(				self	:Tuple,      **snake_case	:Any):



          """simple docstring"""

          return AutoProcessor.from_pretrained(self.tmpdirname,      **snake_case).qformer_tokenizer





       def 				UpperCamelCase__						(				self	:Optional[int]):



          """simple docstring"""

          shutil.rmtree(self.tmpdirname)





       def 				UpperCamelCase__						(				self	:List[str]):



          """simple docstring"""

          _lowercase              =[np.random.randint(255,      size=(3, 30, 400),      dtype=np.uinta)]

          _lowercase              =[Image.fromarray(np.moveaxis(snake_case,      0,      -1)) for x in image_inputs]

          return image_inputs





       def 				UpperCamelCase__						(				self	:List[Any]):



          """simple docstring"""

          _lowercase              =InstructBlipProcessor(
              tokenizer=self.get_tokenizer(),      image_processor=self.get_image_processor(),      qformer_tokenizer=self.get_qformer_tokenizer(),      )
          processor.save_pretrained(self.tmpdirname)

          _lowercase              =self.get_tokenizer(bos_token='(BOS)',      eos_token='(EOS)')
          _lowercase              =self.get_image_processor(do_normalize=snake_case,      padding_value=1.0)

          _lowercase              =InstructBlipProcessor.from_pretrained(
              self.tmpdirname,      bos_token='(BOS)',      eos_token='(EOS)',      do_normalize=snake_case,      padding_value=1.0)

          self.assertEqual(processor.tokenizer.get_vocab(),      tokenizer_add_kwargs.get_vocab())
          self.assertIsInstance(processor.tokenizer,      snake_case)

          self.assertEqual(processor.image_processor.to_json_string(),      image_processor_add_kwargs.to_json_string())
          self.assertIsInstance(processor.image_processor,      snake_case)
          self.assertIsInstance(processor.qformer_tokenizer,      snake_case)





       def 				UpperCamelCase__						(				self	:Tuple):



          """simple docstring"""

          _lowercase              =self.get_image_processor()
          _lowercase              =self.get_tokenizer()
          _lowercase              =self.get_qformer_tokenizer()

          _lowercase              =InstructBlipProcessor(
              tokenizer=snake_case,      image_processor=snake_case,      qformer_tokenizer=snake_case)

          _lowercase              =self.prepare_image_inputs()

          _lowercase              =image_processor(snake_case,      return_tensors='np')
          _lowercase              =processor(images=snake_case,      return_tensors='np')

          for key in input_feat_extract.keys():
             self.assertAlmostEqual(input_feat_extract[key].sum(),      input_processor[key].sum(),      delta=1e-2)





       def 				UpperCamelCase__						(				self	:List[Any]):



          """simple docstring"""

          _lowercase              =self.get_image_processor()
          _lowercase              =self.get_tokenizer()
          _lowercase              =self.get_qformer_tokenizer()

          _lowercase              =InstructBlipProcessor(
              tokenizer=snake_case,      image_processor=snake_case,      qformer_tokenizer=snake_case)

          _lowercase              ='lower newer'

          _lowercase              =processor(text=snake_case)

          _lowercase              =tokenizer(snake_case,      return_token_type_ids=snake_case)
          _lowercase              =qformer_tokenizer(snake_case,      return_token_type_ids=snake_case)

          for key in encoded_tokens.keys():
             self.assertListEqual(encoded_tokens[key],      encoded_processor[key])

          for key in encoded_tokens_qformer.keys():
             self.assertListEqual(encoded_tokens_qformer[key],      encoded_processor['qformer_' + key])





       def 				UpperCamelCase__						(				self	:Any):



          """simple docstring"""

          _lowercase              =self.get_image_processor()
          _lowercase              =self.get_tokenizer()
          _lowercase              =self.get_qformer_tokenizer()

          _lowercase              =InstructBlipProcessor(
              tokenizer=snake_case,      image_processor=snake_case,      qformer_tokenizer=snake_case)

          _lowercase              ='lower newer'
          _lowercase              =self.prepare_image_inputs()

          _lowercase              =processor(text=snake_case,      images=snake_case)

          self.assertListEqual(
              list(inputs.keys()),      ['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values'],      )

          # test if it raises when no input is passed
          with pytest.raises(snake_case):
             processor()





       def 				UpperCamelCase__						(				self	:Dict):



          """simple docstring"""

          _lowercase              =self.get_image_processor()
          _lowercase              =self.get_tokenizer()
          _lowercase              =self.get_qformer_tokenizer()

          _lowercase              =InstructBlipProcessor(
              tokenizer=snake_case,      image_processor=snake_case,      qformer_tokenizer=snake_case)

          _lowercase              =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

          _lowercase              =processor.batch_decode(snake_case)
          _lowercase              =tokenizer.batch_decode(snake_case)

          self.assertListEqual(snake_case,      snake_case)





       def 				UpperCamelCase__						(				self	:int):



          """simple docstring"""

          _lowercase              =self.get_image_processor()
          _lowercase              =self.get_tokenizer()
          _lowercase              =self.get_qformer_tokenizer()

          _lowercase              =InstructBlipProcessor(
              tokenizer=snake_case,      image_processor=snake_case,      qformer_tokenizer=snake_case)

          _lowercase              ='lower newer'
          _lowercase              =self.prepare_image_inputs()

          _lowercase              =processor(text=snake_case,      images=snake_case)

          self.assertListEqual(
              list(inputs.keys()),      ['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values'],      )


