






"""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       :					List[Any]									=		True
   from torch.cuda.amp import autocast

_UpperCamelCase       :					Any									=		logging.getLogger(__name__)




def     snake_case						(A_   :Dict=None			,    A_   :Any=None   ):







  '''simple docstring'''

  return field(default_factory=lambda: default			,    metadata=A_   )






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






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






@dataclass
class 		snake_case						:
    __magic_name__					  =  42
    __magic_name__					  =  True
    __magic_name__					  =  None
    __magic_name__					  =  None
    __magic_name__					  =  None
    __magic_name__					  =  None





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


      '''simple docstring'''




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

      a  :    Any       =     self.processor.pad(
          A       ,	padding=self.padding       ,	max_length=self.max_length       ,	pad_to_multiple_of=self.pad_to_multiple_of       ,	return_tensors='pt'       ,	)
      a  :    Union[str, Any]       =     self.processor.pad(
          labels=A       ,	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  :    int       =     labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1    )       ,	-1_0_0    )

      a  :    List[Any]       =     labels

      return batch






class 		snake_case						(						UpperCAmelCase ):





    def        lowerCamelCase__   (							self			:      Optional[int]       ,	A			:      nn.Module       ,	A			:      Dict[str, Union[torch.Tensor, Any]]    ):


      '''simple docstring'''




      model.train()
      a  :    List[Any]       =     self._prepare_inputs(A    )

      if self.use_amp:
        with autocast():
          a  :    Any       =     self.compute_loss(A       ,	A    )
      else:
        a  :    int       =     self.compute_loss(A       ,	A    )

      if self.args.n_gpu > 1:
        if model.module.config.ctc_loss_reduction == "mean":
          a  :    List[str]       =     loss.mean()
        elif model.module.config.ctc_loss_reduction == "sum":
          a  :    Tuple       =     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  :    int       =     loss / self.args.gradient_accumulation_steps

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

      return loss.detach()




def     snake_case						():







  '''simple docstring'''

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

  # Detecting last checkpoint.
  a  :    Optional[int]       =     None
  if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
    a  :    Any       =     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:
  a  :    Tuple       =     datasets.load_dataset(
      'common_voice'			,    data_args.dataset_config_name			,    split=data_args.train_split_name   )
  a  :    List[str]       =     datasets.load_dataset('common_voice'			,    data_args.dataset_config_name			,    split='test'   )

  # Create and save tokenizer
  a  :    Dict       =     f'''[{''.join(data_args.chars_to_ignore   )}]'''

  def remove_special_characters(A_   :Optional[Any]   ):
    a  :    List[str]       =     re.sub(A_			,    ''			,    batch['sentence']   ).lower() + ' '
    return batch

  a  :    Tuple       =     train_dataset.map(A_			,    remove_columns=['sentence']   )
  a  :    Optional[Any]       =     eval_dataset.map(A_			,    remove_columns=['sentence']   )

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

  a  :    Any       =     train_dataset.map(
      A_			,    batched=A_			,    batch_size=-1			,    keep_in_memory=A_			,    remove_columns=train_dataset.column_names			,    )
  a  :    int       =     train_dataset.map(
      A_			,    batched=A_			,    batch_size=-1			,    keep_in_memory=A_			,    remove_columns=eval_dataset.column_names			,    )

  a  :    str       =     list(set(vocab_train['vocab'][0]   ) | set(vocab_test['vocab'][0]   )   )
  a  :    int       =     {v: k for k, v in enumerate(A_   )}
  a  :    List[str]       =     vocab_dict[' ']
  del vocab_dict[" "]
  a  :    int       =     len(A_   )
  a  :    List[str]       =     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.
  a  :    Optional[Any]       =     WavaVecaCTCTokenizer(
      'vocab.json'			,    unk_token='[UNK]'			,    pad_token='[PAD]'			,    word_delimiter_token='|'			,    )
  a  :    Tuple       =     WavaVecaFeatureExtractor(
      feature_size=1			,    sampling_rate=1_6_0_0_0			,    padding_value=0.0			,    do_normalize=A_			,    return_attention_mask=A_   )
  a  :    str       =     WavaVecaProcessor(feature_extractor=A_			,    tokenizer=A_   )
  a  :    Union[str, Any]       =     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  :    Dict       =     min(len(A_   )			,    data_args.max_train_samples   )
    a  :    Optional[int]       =     train_dataset.select(range(A_   )   )

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

  a  :    Tuple       =     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_   :Any   ):
    a,  a  :    str       =     torchaudio.load(batch['path']   )
    a  :    Any       =     resampler(A_   ).squeeze().numpy()
    a  :    Optional[int]       =     1_6_0_0_0
    a  :    Any       =     batch['text']
    return batch

  a  :    Optional[int]       =     train_dataset.map(
      A_			,    remove_columns=train_dataset.column_names			,    num_proc=data_args.preprocessing_num_workers			,    )
  a  :    int       =     eval_dataset.map(
      A_			,    remove_columns=eval_dataset.column_names			,    num_proc=data_args.preprocessing_num_workers			,    )

  def prepare_dataset(A_   :Dict   ):
    # 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  :    List[str]       =     processor(
        audio=batch['speech']			,    text=batch['target_text']			,    sampling_rate=batch['sampling_rate'][0]   )
    batch.update(A_   )
    return batch

  a  :    int       =     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			,    )
  a  :    Dict       =     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
  a  :    Optional[int]       =     datasets.load_metric('wer'   )

  def compute_metrics(A_   :Tuple   ):
    a  :    str       =     pred.predictions
    a  :    Optional[int]       =     np.argmax(A_			,    axis=-1   )

    a  :    Optional[int]       =     processor.tokenizer.pad_token_id

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

    a  :    Optional[int]       =     wer_metric.compute(predictions=A_			,    references=A_   )

    return {"wer": wer}

  if model_args.freeze_feature_extractor:
    model.freeze_feature_extractor()

  # Data collator
  a  :    Union[str, Any]       =     DataCollatorCTCWithPadding(processor=A_			,    padding=A_   )

  # Initialize our Trainer
  a  :    List[str]       =     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:
      a  :    int       =     last_checkpoint
    elif os.path.isdir(model_args.model_name_or_path   ):
      a  :    str       =     model_args.model_name_or_path
    else:
      a  :    List[Any]       =     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=A_   )
    trainer.save_model()

    a  :    str       =     train_result.metrics
    a  :    List[Any]       =     (
        data_args.max_train_samples if data_args.max_train_samples is not None else len(A_   )
    )
    a  :    str       =     min(A_			,    len(A_   )   )

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

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

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

  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.
import numpy as np
import torch

from ..models.clipseg import CLIPSegForImageSegmentation
from ..utils import is_vision_available, requires_backends
from .base import PipelineTool


if is_vision_available():
   from PIL import Image






class 		snake_case						(						UpperCAmelCase ):
    __magic_name__					  =  (
        '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.'''
        '''It takes two arguments named `image` which should be the original image, and `label` which should be a text '''
        '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.'''
    )
    __magic_name__					  =  '''CIDAS/clipseg-rd64-refined'''
    __magic_name__					  =  '''image_segmenter'''
    __magic_name__					  =  CLIPSegForImageSegmentation

    __magic_name__					  =  ['''image''', '''text''']
    __magic_name__					  =  ['''image''']





    def __init__(							self			:      str       ,	*A			:      Any       ,	**A			:      Any    ):


      '''simple docstring'''




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





    def        lowerCamelCase__   (							self			:      Any       ,	A			:      "Image"       ,	A			:      str    ):


      '''simple docstring'''




      return self.pre_processor(text=[label]       ,	images=[image]       ,	padding=A       ,	return_tensors='pt'    )





    def        lowerCamelCase__   (							self			:      str       ,	A			:      List[Any]    ):


      '''simple docstring'''




      with torch.no_grad():
        a  :    Optional[Any]       =     self.model(**A    ).logits
      return logits





    def        lowerCamelCase__   (							self			:      List[Any]       ,	A			:      List[str]    ):


      '''simple docstring'''




      a  :    List[str]       =     outputs.cpu().detach().numpy()
      a  :    List[Any]       =     0
      a  :    str       =     1
      return Image.fromarray((array * 2_5_5).astype(np.uinta    )    )




