From 76669c0ed32619bcd5d9a5ecbbea4980000f9e81 Mon Sep 17 00:00:00 2001 From: godax84 Date: Tue, 26 Nov 2024 06:31:52 -0800 Subject: [PATCH] Carregar ficheiros para "/" --- Download Librarys HuggingFace.txt | 111 ++ Instalation Transformer.txt | 160 +++ Transformer Readme.txt | 1654 +++++++++++++++++++++++++++++ main.py | 483 +++++++++ 4 files changed, 2408 insertions(+) create mode 100644 Download Librarys HuggingFace.txt create mode 100644 Instalation Transformer.txt create mode 100644 Transformer Readme.txt create mode 100644 main.py diff --git a/Download Librarys HuggingFace.txt b/Download Librarys HuggingFace.txt new file mode 100644 index 0000000..57b2f15 --- /dev/null +++ b/Download Librarys HuggingFace.txt @@ -0,0 +1,111 @@ +Download files from the Hub +The huggingface_hub library provides functions to download files from the repositories stored on the Hub. You can use these functions independently or integrate them into your own library, making it more convenient for your users to interact with the Hub. This guide will show you how to: + +Download and cache a single file. +Download and cache an entire repository. +Download files to a local folder. +Download a single file +The hf_hub_download() function is the main function for downloading files from the Hub. It downloads the remote file, caches it on disk (in a version-aware way), and returns its local file path. + +The returned filepath is a pointer to the HF local cache. Therefore, it is important to not modify the file to avoid having a corrupted cache. If you are interested in getting to know more about how files are cached, please refer to our caching guide. + +From latest version +Select the file to download using the repo_id, repo_type and filename parameters. By default, the file will be considered as being part of a model repo. + +Copied +from huggingface_hub import hf_hub_download +hf_hub_download(repo_id="lysandre/arxiv-nlp", filename="config.json") +'/root/.cache/huggingface/hub/models--lysandre--arxiv-nlp/snapshots/894a9adde21d9a3e3843e6d5aeaaf01875c7fade/config.json' + +# Download from a dataset +hf_hub_download(repo_id="google/fleurs", filename="fleurs.py", repo_type="dataset") +'/root/.cache/huggingface/hub/datasets--google--fleurs/snapshots/199e4ae37915137c555b1765c01477c216287d34/fleurs.py' +From specific version +By default, the latest version from the main branch is downloaded. However, in some cases you want to download a file at a particular version (e.g. from a specific branch, a PR, a tag or a commit hash). To do so, use the revision parameter: + +Copied +# Download from the `v1.0` tag +hf_hub_download(repo_id="lysandre/arxiv-nlp", filename="config.json", revision="v1.0") + +# Download from the `test-branch` branch +hf_hub_download(repo_id="lysandre/arxiv-nlp", filename="config.json", revision="test-branch") + +# Download from Pull Request #3 +hf_hub_download(repo_id="lysandre/arxiv-nlp", filename="config.json", revision="refs/pr/3") + +# Download from a specific commit hash +hf_hub_download(repo_id="lysandre/arxiv-nlp", filename="config.json", revision="877b84a8f93f2d619faa2a6e514a32beef88ab0a") +Note: When using the commit hash, it must be the full-length hash instead of a 7-character commit hash. + +Construct a download URL +In case you want to construct the URL used to download a file from a repo, you can use hf_hub_url() which returns a URL. Note that it is used internally by hf_hub_download(). + +Download an entire repository +snapshot_download() downloads an entire repository at a given revision. It uses internally hf_hub_download() which means all downloaded files are also cached on your local disk. Downloads are made concurrently to speed-up the process. + +To download a whole repository, just pass the repo_id and repo_type: + +Copied +from huggingface_hub import snapshot_download +snapshot_download(repo_id="lysandre/arxiv-nlp") +'/home/lysandre/.cache/huggingface/hub/models--lysandre--arxiv-nlp/snapshots/894a9adde21d9a3e3843e6d5aeaaf01875c7fade' + +# Or from a dataset +snapshot_download(repo_id="google/fleurs", repo_type="dataset") +'/home/lysandre/.cache/huggingface/hub/datasets--google--fleurs/snapshots/199e4ae37915137c555b1765c01477c216287d34' +snapshot_download() downloads the latest revision by default. If you want a specific repository revision, use the revision parameter: + +Copied +from huggingface_hub import snapshot_download +snapshot_download(repo_id="lysandre/arxiv-nlp", revision="refs/pr/1") +Filter files to download +snapshot_download() provides an easy way to download a repository. However, you don’t always want to download the entire content of a repository. For example, you might want to prevent downloading all .bin files if you know you’ll only use the .safetensors weights. You can do that using allow_patterns and ignore_patterns parameters. + +These parameters accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as documented here. The pattern matching is based on fnmatch. + +For example, you can use allow_patterns to only download JSON configuration files: + +Copied +from huggingface_hub import snapshot_download +snapshot_download(repo_id="lysandre/arxiv-nlp", allow_patterns="*.json") +On the other hand, ignore_patterns can exclude certain files from being downloaded. The following example ignores the .msgpack and .h5 file extensions: + +Copied +from huggingface_hub import snapshot_download +snapshot_download(repo_id="lysandre/arxiv-nlp", ignore_patterns=["*.msgpack", "*.h5"]) +Finally, you can combine both to precisely filter your download. Here is an example to download all json and markdown files except vocab.json. + +Copied +from huggingface_hub import snapshot_download +snapshot_download(repo_id="gpt2", allow_patterns=["*.md", "*.json"], ignore_patterns="vocab.json") +Download file(s) to a local folder +By default, we recommend using the cache system to download files from the Hub. You can specify a custom cache location using the cache_dir parameter in hf_hub_download() and snapshot_download(), or by setting the HF_HOME environment variable. + +However, if you need to download files to a specific folder, you can pass a local_dir parameter to the download function. This is useful to get a workflow closer to what the git command offers. The downloaded files will maintain their original file structure within the specified folder. For example, if filename="data/train.csv" and local_dir="path/to/folder", the resulting filepath will be "path/to/folder/data/train.csv". + +A .cache/huggingface/ folder is created at the root of your local directory containing metadata about the downloaded files. This prevents re-downloading files if they’re already up-to-date. If the metadata has changed, then the new file version is downloaded. This makes the local_dir optimized for pulling only the latest changes. + +After completing the download, you can safely remove the .cache/huggingface/ folder if you no longer need it. However, be aware that re-running your script without this folder may result in longer recovery times, as metadata will be lost. Rest assured that your local data will remain intact and unaffected. + +Don’t worry about the .cache/huggingface/ folder when committing changes to the Hub! This folder is automatically ignored by both git and upload_folder(). + +Download from the CLI +You can use the huggingface-cli download command from the terminal to directly download files from the Hub. Internally, it uses the same hf_hub_download() and snapshot_download() helpers described above and prints the returned path to the terminal. + +Copied +>>> huggingface-cli download gpt2 config.json +/home/wauplin/.cache/huggingface/hub/models--gpt2/snapshots/11c5a3d5811f50298f278a704980280950aedb10/config.json +You can download multiple files at once which displays a progress bar and returns the snapshot path in which the files are located: + +Copied +>>> huggingface-cli download gpt2 config.json model.safetensors +Fetching 2 files: 100%|████████████████████████████████████████████| 2/2 [00:00<00:00, 23831.27it/s] +/home/wauplin/.cache/huggingface/hub/models--gpt2/snapshots/11c5a3d5811f50298f278a704980280950aedb10 +For more details about the CLI download command, please refer to the CLI guide. + +Faster downloads +If you are running on a machine with high bandwidth, you can increase your download speed with hf_transfer, a Rust-based library developed to speed up file transfers with the Hub. To enable it: + +Specify the hf_transfer extra when installing huggingface_hub (e.g. pip install huggingface_hub[hf_transfer]). +Set HF_HUB_ENABLE_HF_TRANSFER=1 as an environment variable. +hf_transfer is a power user tool! It is tested and production-ready, but it lacks user-friendly features like advanced error handling or proxies. For more details, please take a look at this section. \ No newline at end of file diff --git a/Instalation Transformer.txt b/Instalation Transformer.txt new file mode 100644 index 0000000..6f8ea19 --- /dev/null +++ b/Instalation Transformer.txt @@ -0,0 +1,160 @@ +Installation +Install 🤗 Transformers for whichever deep learning library you’re working with, setup your cache, and optionally configure 🤗 Transformers to run offline. + +🤗 Transformers is tested on Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, and Flax. Follow the installation instructions below for the deep learning library you are using: + +PyTorch installation instructions. +TensorFlow 2.0 installation instructions. +Flax installation instructions. +Install with pip +You should install 🤗 Transformers in a virtual environment. If you’re unfamiliar with Python virtual environments, take a look at this guide. A virtual environment makes it easier to manage different projects, and avoid compatibility issues between dependencies. + +Start by creating a virtual environment in your project directory: + +Copied +python -m venv .env +Activate the virtual environment. On Linux and MacOs: + +Copied +source .env/bin/activate +Activate Virtual environment on Windows + +Copied +.env/Scripts/activate +Now you’re ready to install 🤗 Transformers with the following command: + +Copied +pip install transformers +For CPU-support only, you can conveniently install 🤗 Transformers and a deep learning library in one line. For example, install 🤗 Transformers and PyTorch with: + +Copied +pip install 'transformers[torch]' +🤗 Transformers and TensorFlow 2.0: + +Copied +pip install 'transformers[tf-cpu]' +M1 / ARM Users + +You will need to install the following before installing TensorFlow 2.0 + +Copied +brew install cmake +brew install pkg-config +🤗 Transformers and Flax: + +Copied +pip install 'transformers[flax]' +Finally, check if 🤗 Transformers has been properly installed by running the following command. It will download a pretrained model: + +Copied +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))" +Then print out the label and score: + +Copied +[{'label': 'POSITIVE', 'score': 0.9998704791069031}] +Install from source +Install 🤗 Transformers from source with the following command: + +Copied +pip install git+https://github.com/huggingface/transformers +This command installs the bleeding edge main version rather than the latest stable version. The main version is useful for staying up-to-date with the latest developments. For instance, if a bug has been fixed since the last official release but a new release hasn’t been rolled out yet. However, this means the main version may not always be stable. We strive to keep the main version operational, and most issues are usually resolved within a few hours or a day. If you run into a problem, please open an Issue so we can fix it even sooner! + +Check if 🤗 Transformers has been properly installed by running the following command: + +Copied +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))" +Editable install +You will need an editable install if you’d like to: + +Use the main version of the source code. +Contribute to 🤗 Transformers and need to test changes in the code. +Clone the repository and install 🤗 Transformers with the following commands: + +Copied +git clone https://github.com/huggingface/transformers.git +cd transformers +pip install -e . +These commands will link the folder you cloned the repository to and your Python library paths. Python will now look inside the folder you cloned to in addition to the normal library paths. For example, if your Python packages are typically installed in ~/anaconda3/envs/main/lib/python3.7/site-packages/, Python will also search the folder you cloned to: ~/transformers/. + +You must keep the transformers folder if you want to keep using the library. + +Now you can easily update your clone to the latest version of 🤗 Transformers with the following command: + +Copied +cd ~/transformers/ +git pull +Your Python environment will find the main version of 🤗 Transformers on the next run. + +Install with conda +Install from the conda channel conda-forge: + +Copied +conda install conda-forge::transformers +Cache setup +Pretrained models are downloaded and locally cached at: ~/.cache/huggingface/hub. This is the default directory given by the shell environment variable TRANSFORMERS_CACHE. On Windows, the default directory is given by C:\Users\username\.cache\huggingface\hub. You can change the shell environment variables shown below - in order of priority - to specify a different cache directory: + +Shell environment variable (default): HUGGINGFACE_HUB_CACHE or TRANSFORMERS_CACHE. +Shell environment variable: HF_HOME. +Shell environment variable: XDG_CACHE_HOME + /huggingface. +🤗 Transformers will use the shell environment variables PYTORCH_TRANSFORMERS_CACHE or PYTORCH_PRETRAINED_BERT_CACHE if you are coming from an earlier iteration of this library and have set those environment variables, unless you specify the shell environment variable TRANSFORMERS_CACHE. + +Offline mode +Run 🤗 Transformers in a firewalled or offline environment with locally cached files by setting the environment variable HF_HUB_OFFLINE=1. + +Add 🤗 Datasets to your offline training workflow with the environment variable HF_DATASETS_OFFLINE=1. + +Copied +HF_DATASETS_OFFLINE=1 HF_HUB_OFFLINE=1 \ +python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ... +This script should run without hanging or waiting to timeout because it won’t attempt to download the model from the Hub. + +You can also bypass loading a model from the Hub from each from_pretrained() call with the local_files_only parameter. When set to True, only local files are loaded: + +Copied +from transformers import T5Model + +model = T5Model.from_pretrained("./path/to/local/directory", local_files_only=True) +Fetch models and tokenizers to use offline +Another option for using 🤗 Transformers offline is to download the files ahead of time, and then point to their local path when you need to use them offline. There are three ways to do this: + +Download a file through the user interface on the Model Hub by clicking on the ↓ icon. + +download-icon + +Use the PreTrainedModel.from_pretrained() and PreTrainedModel.save_pretrained() workflow: + +Download your files ahead of time with PreTrainedModel.from_pretrained(): + +Copied +from transformers import AutoTokenizer, AutoModelForSeq2SeqLM + +tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B") +model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B") +Save your files to a specified directory with PreTrainedModel.save_pretrained(): + +Copied +tokenizer.save_pretrained("./your/path/bigscience_t0") +model.save_pretrained("./your/path/bigscience_t0") +Now when you’re offline, reload your files with PreTrainedModel.from_pretrained() from the specified directory: + +Copied +tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0") +model = AutoModel.from_pretrained("./your/path/bigscience_t0") +Programmatically download files with the huggingface_hub library: + +Install the huggingface_hub library in your virtual environment: + +Copied +python -m pip install huggingface_hub +Use the hf_hub_download function to download a file to a specific path. For example, the following command downloads the config.json file from the T0 model to your desired path: + +Copied +from huggingface_hub import hf_hub_download + +hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0") +Once your file is downloaded and locally cached, specify it’s local path to load and use it: + +Copied +from transformers import AutoConfig + +config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json") \ No newline at end of file diff --git a/Transformer Readme.txt b/Transformer Readme.txt new file mode 100644 index 0000000..39b31fe --- /dev/null +++ b/Transformer Readme.txt @@ -0,0 +1,1654 @@ +Whisper +Overview +The Whisper model was proposed in Robust Speech Recognition via Large-Scale Weak Supervision by Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever. + +The abstract from the paper is the following: + +We study the capabilities of speech processing systems trained simply to predict large amounts of transcripts of audio on the internet. When scaled to 680,000 hours of multilingual and multitask supervision, the resulting models generalize well to standard benchmarks and are often competitive with prior fully supervised results but in a zeroshot transfer setting without the need for any finetuning. When compared to humans, the models approach their accuracy and robustness. We are releasing models and inference code to serve as a foundation for further work on robust speech processing. + +This model was contributed by Arthur Zucker. The Tensorflow version of this model was contributed by amyeroberts. The original code can be found here. + +Quick usage +You can run Whisper in less than 4 lines of code and transcribe in less than a minute! + +Copied +# pip install transformers torch + +import torch +from transformers import pipeline + +whisper = pipeline("automatic-speech-recognition", "openai/whisper-large-v3", torch_dtype=torch.float16, device="cuda:0") + +transcription = whisper("") + +print(transcription["text"]) +Voila! You can swap the model with any Whisper checkpoints on the Hugging Face Hub with the same pipeline based on your needs. + +Bonus: You can replace "cuda" with "mps" to make it seamlessly work on Macs. + +Usage tips +The model usually performs well without requiring any finetuning. + +The architecture follows a classic encoder-decoder architecture, which means that it relies on the generate() function for inference. + +One can use WhisperProcessor to prepare audio for the model, and decode the predicted ID’s back into text. + +To convert the model and the processor, we recommend using the following: + +Copied +python src/transformers/models/whisper/convert_openai_to_hf.py --checkpoint_path "" --pytorch_dump_folder_path "Arthur/whisper-3" --convert_preprocessor True +The script will automatically determine all necessary parameters from the OpenAI checkpoint. A tiktoken library needs to be installed to perform the conversion of the OpenAI tokenizer to the tokenizers version. + +Inference +Here is a step-by-step guide to transcribing an audio sample using a pre-trained Whisper model: + +Copied +from datasets import load_dataset +from transformers import WhisperProcessor, WhisperForConditionalGeneration + +# Select an audio file and read it: +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +audio_sample = ds[0]["audio"] + +# Load the Whisper model in Hugging Face format: +processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") +model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + +# Use the model and processor to transcribe the audio: +input_features = processor( + audio_sample["array"], sampling_rate=audio_sample["sampling_rate"], return_tensors="pt" +).input_features + +# Generate token ids +predicted_ids = model.generate(input_features) + +# Decode token ids to text +transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True) + +transcription[0] +' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.' +Whisper is compatible with the following optimisations for both short and long-form generation: + +PyTorch Scaled Dot Product Attention (SDPA): flash attention and memory-efficient attention kernels. Enabled by default for torch>=2.1.1. +Flash Attention 2: improved implementation of flash attention through better parallelism and work partitioning. +torch.compile: JIT-compile the forward pass to dispatch to efficient fused kernels. +As an example, the following codesnippet enables SDPA and torch.compile for up to 5x faster inference: + +Copied +from datasets import load_dataset +from transformers import WhisperProcessor, WhisperForConditionalGeneration + +# Select an audio file and read it: +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +audio_sample = ds[0]["audio"] + +# Load the Whisper model with SDPA attention +processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") +model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en", attn_implementation="sdpa") + +# Enable static cache and compile the forward pass +model.generation_config.cache_implementation = "static" +model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True) + +# Use the model and processor to transcribe the audio: +input_features = processor( + audio_sample["array"], sampling_rate=audio_sample["sampling_rate"], return_tensors="pt" +).input_features + +# Compile the forward pass +for _ in range(2): + model.generate(input_features) + +# Generate token ids using compiled graph (fast!) +predicted_ids = model.generate(input_features) + +# Decode token ids to text +transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True) + +transcription[0] +' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.' +For more details on each optimisation, refer to the documentation linked above. + +Resources +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Whisper. If you’re interested in submitting a resource to be included here, please feel free to open a Pull Request and we’ll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +Fine-tune Whisper on your own dataset for better downstream performance. +Distil-Whisper: Upto 6x faster, 2x smaller distilled Whisper models for English. We release the model checkpoints, and distillation code. +A fork with a script to convert a Whisper model in Hugging Face format to OpenAI format. 🌎 Usage example: +Copied +pip install -U openai-whisper +python convert_hf_to_openai.py \ + --checkpoint openai/whisper-tiny \ + --whisper_dump_path whisper-tiny-openai.pt +WhisperConfig +class transformers.WhisperConfig +< +source +> +( vocab_size = 51865num_mel_bins = 80encoder_layers = 4encoder_attention_heads = 6decoder_layers = 4decoder_attention_heads = 6decoder_ffn_dim = 1536encoder_ffn_dim = 1536encoder_layerdrop = 0.0decoder_layerdrop = 0.0decoder_start_token_id = 50257use_cache = Trueis_encoder_decoder = Trueactivation_function = 'gelu'd_model = 384dropout = 0.0attention_dropout = 0.0activation_dropout = 0.0init_std = 0.02scale_embedding = Falsemax_source_positions = 1500max_target_positions = 448pad_token_id = 50256bos_token_id = 50256eos_token_id = 50256suppress_tokens = Nonebegin_suppress_tokens = [220, 50256]use_weighted_layer_sum = Falseclassifier_proj_size = 256apply_spec_augment = Falsemask_time_prob = 0.05mask_time_length = 10mask_time_min_masks = 2mask_feature_prob = 0.0mask_feature_length = 10mask_feature_min_masks = 0median_filter_width = 7**kwargs ) + +Parameters + +vocab_size (int, optional, defaults to 51865) — Vocabulary size of the Whisper model. Defines the number of different tokens that can be represented by the decoder_input_ids passed when calling WhisperModel +num_mel_bins (int, optional, defaults to 80) — Number of mel features used per input features. Should correspond to the value used in the WhisperProcessor class. +encoder_layers (int, optional, defaults to 4) — Number of encoder layers. +decoder_layers (int, optional, defaults to 4) — Number of decoder layers. +encoder_attention_heads (int, optional, defaults to 6) — Number of attention heads for each attention layer in the Transformer encoder. +decoder_attention_heads (int, optional, defaults to 6) — Number of attention heads for each attention layer in the Transformer decoder. +encoder_ffn_dim (int, optional, defaults to 1536) — Dimensionality of the “intermediate” (often named feed-forward) layer in encoder. +decoder_ffn_dim (int, optional, defaults to 1536) — Dimensionality of the “intermediate” (often named feed-forward) layer in decoder. +encoder_layerdrop (float, optional, defaults to 0.0) — The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more details. +decoder_layerdrop (float, optional, defaults to 0.0) — The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more details. +decoder_start_token_id (int, optional, defaults to 50257) — Corresponds to the ”<|startoftranscript|>” token, which is automatically used when no decoder_input_ids are provided to the generate function. It is used to guide the model`s generation process depending on the task. +use_cache (bool, optional, defaults to True) — Whether or not the model should return the last key/values attentions (not used by all models). +is_encoder_decoder (bool, optional, defaults to True) — Whether the model is used as an encoder/decoder or not. +activation_function (str, optional, defaults to "gelu") — The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu", "relu", "silu" and "gelu_new" are supported. +d_model (int, optional, defaults to 384) — Dimensionality of the layers. +dropout (float, optional, defaults to 0.1) — The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. +attention_dropout (float, optional, defaults to 0.0) — The dropout ratio for the attention probabilities. +activation_dropout (float, optional, defaults to 0.0) — The dropout ratio for activations inside the fully connected layer. +init_std (float, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. +scale_embedding (bool, optional, defaults to False) — Scale embeddings by diving by sqrt(d_model). +max_source_positions (int, optional, defaults to 1500) — The maximum sequence length of log-mel filter-bank features that this model might ever be used with. +max_target_positions (int, optional, defaults to 448) — The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). +pad_token_id (int, optional, defaults to 50256) — Padding token id. +bos_token_id (int, optional, defaults to 50256) — Begin of stream token id. +eos_token_id (int, optional, defaults to 50256) — End of stream token id. +suppress_tokens (List[int], optional) — A list containing the non-speech tokens that will be used by the logit processor in the generate function. NON_SPEECH_TOKENS and NON_SPEECH_TOKENS_MULTI each correspond to the english-only and the multilingual model. +begin_suppress_tokens (List[int], optional, defaults to [220,50256]) — A list containing tokens that will be supressed at the beginning of the sampling process. Initialized as the token for " " (blank_token_id) and the eos_token_id +use_weighted_layer_sum (bool, optional, defaults to False) — Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an instance of WhisperForAudioClassification. +classifier_proj_size (int, optional, defaults to 256) — Dimensionality of the projection before token mean-pooling for classification. Only relevant when using an instance of WhisperForAudioClassification. +apply_spec_augment (bool, optional, defaults to False) — Whether to apply SpecAugment data augmentation to the outputs of the feature encoder. For reference see SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition. +mask_time_prob (float, optional, defaults to 0.05) — Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking procecure generates mask_time_prob*len(time_axis)/mask_time_length independent masks over the axis. If reasoning from the propability of each feature vector to be chosen as the start of the vector span to be masked, mask_time_prob should be prob_vector_start*mask_time_length. Note that overlap may decrease the actual percentage of masked vectors. This is only relevant if apply_spec_augment == True. +mask_time_length (int, optional, defaults to 10) — Length of vector span along the time axis. +mask_time_min_masks (int, optional, defaults to 2), — The minimum number of masks of length mask_feature_length generated along the time axis, each time step, irrespectively of mask_feature_prob. Only relevant if ”mask_time_prob*len(time_axis)/mask_time_length < mask_time_min_masks” +mask_feature_prob (float, optional, defaults to 0.0) — Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The masking procecure generates mask_feature_prob*len(feature_axis)/mask_time_length independent masks over the axis. If reasoning from the propability of each feature vector to be chosen as the start of the vector span to be masked, mask_feature_prob should be prob_vector_start*mask_feature_length. Note that overlap may decrease the actual percentage of masked vectors. This is only relevant if apply_spec_augment is True. +mask_feature_length (int, optional, defaults to 10) — Length of vector span along the feature axis. +mask_feature_min_masks (int, optional, defaults to 0), — The minimum number of masks of length mask_feature_length generated along the feature axis, each time step, irrespectively of mask_feature_prob. Only relevant if mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks. +median_filter_width (int, optional, defaults to 7) — Width of the median filter used to smoothen to cross-attention outputs when computing token timestamps. Should be an odd number. +This is the configuration class to store the configuration of a WhisperModel. It is used to instantiate a Whisper model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Whisper openai/whisper-tiny architecture. + +Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information. + +Example: + +Copied +from transformers import WhisperConfig, WhisperModel + +# Initializing a Whisper tiny style configuration +configuration = WhisperConfig() + +# Initializing a model (with random weights) from the tiny style configuration +model = WhisperModel(configuration) + +# Accessing the model configuration +configuration = model.config +WhisperTokenizer +class transformers.WhisperTokenizer +< +source +> +( vocab_filemerges_filenormalizer_file = Noneerrors = 'replace'unk_token = '<|endoftext|>'bos_token = '<|endoftext|>'eos_token = '<|endoftext|>'pad_token = Noneadd_prefix_space = Falselanguage = Nonetask = Nonepredict_timestamps = False**kwargs ) + +Parameters + +vocab_file (str) — Path to the vocabulary file. +merges_file (str) — Path to the merges file. +normalizer_file (str, optional) — Path to the normalizer_file file. +errors (str, optional, defaults to "replace") — Paradigm to follow when decoding bytes to UTF-8. See bytes.decode for more information. +unk_token (str, optional, defaults to "<|endoftext|>") — The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. +bos_token (str, optional, defaults to "<|endoftext|>") — The beginning of sequence token. The decoder_start_token_id is used to set the first token as "<|startoftranscript|>" when generating. +eos_token (str, optional, defaults to "<|endoftext|>") — The end of sequence token. +pad_token (str, optional) — The token used for padding, for example when batching sequences of different lengths. +add_prefix_space (bool, optional, defaults to False) — Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. +language (str, optional) — The language of the transcription text. The corresponding language id token is appended to the start of the sequence for multilingual speech recognition and speech translation tasks, e.g. for Spanish the token "<|es|>" is appended to the start of sequence. This should be used for multilingual fine-tuning only. +task (str, optional) — Task identifier to append at the start of sequence (if any). This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and "translate" for speech translation. +predict_timestamps (bool, optional, defaults to False) — Whether to omit the <|notimestamps|> token at the start of the sequence. +Construct a Whisper tokenizer. + +This tokenizer inherits from PreTrainedTokenizer which contains some of the main methods. Users should refer to the superclass for more information regarding such methods. + +set_prefix_tokens +< +source +> +( language: str = Nonetask: str = Nonepredict_timestamps: bool = None ) + +Parameters + +language (str, optional, defaults to None) — The language of the transcription text. +task (str, optional, defaults to None) — Task identifier to append at the start of sequence (if any). +predict_timestamps (bool, optional, defaults to None) — Whether to omit the <|notimestamps|> token at the start of the sequence. +Override the prefix tokens appended to the start of the label sequence. This method can be used standalone to + +update the prefix tokens as required when fine-tuning. Example: + +Copied +# instantiate the tokenizer and set the prefix token to Spanish +tokenizer = WhisperTokenizer.from_pretrained("openai/whisper-tiny", language="spanish") +# now switch the prefix token from Spanish to French +tokenizer.set_prefix_tokens(language="french") +build_inputs_with_special_tokens +< +source +> +( token_ids_0token_ids_1 = None ) + +Build model inputs from a sequence by appending eos_token_id. + +get_special_tokens_mask +< +source +> +( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = Nonealready_has_special_tokens: bool = False ) → List[int] + +Parameters + +token_ids_0 (List[int]) — List of IDs. +token_ids_1 (List[int], optional) — Optional second list of IDs for sequence pairs. +already_has_special_tokens (bool, optional, defaults to False) — Whether or not the token list is already formatted with special tokens for the model. +Returns + +List[int] + +A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. + + +Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer prepare_for_model method. + +create_token_type_ids_from_sequences +< +source +> +( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int] + +Parameters + +token_ids_0 (List[int]) — The first tokenized sequence. +token_ids_1 (List[int], optional) — The second tokenized sequence. +Returns + +List[int] + +The token type ids. + + +Create the token type IDs corresponding to the sequences passed. What are token type IDs? + +Should be overridden in a subclass if the model has a special way of building those. + +save_vocabulary +< +source +> +( save_directory: strfilename_prefix: typing.Optional[str] = None ) + +batch_decode +< +source +> +( sequences: typing.Union[typing.List[int], typing.List[typing.List[int]], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')]skip_special_tokens: bool = Falseclean_up_tokenization_spaces: bool = None**kwargs ) → List[str] + +Parameters + +sequences (Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]) — List of tokenized input ids. Can be obtained using the __call__ method. +skip_special_tokens (bool, optional, defaults to False) — Whether or not to remove special tokens in the decoding. +clean_up_tokenization_spaces (bool, optional) — Whether or not to clean up the tokenization spaces. If None, will default to self.clean_up_tokenization_spaces. +kwargs (additional keyword arguments, optional) — Will be passed to the underlying model specific decode method. +Returns + +List[str] + +The list of decoded sentences. + + +Convert a list of lists of token ids into a list of strings by calling decode. + +decode +< +source +> +( token_idsskip_special_tokens: bool = Falseclean_up_tokenization_spaces: bool = Noneoutput_offsets: bool = Falsetime_precision: float = 0.02decode_with_timestamps: bool = Falsenormalize: bool = Falsebasic_normalize: bool = Falseremove_diacritics: bool = False**kwargs ) → str + +Parameters + +token_ids (Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]) — List of tokenized input ids. Can be obtained using the __call__ method. +skip_special_tokens (bool, optional, defaults to False) — Whether or not to remove special tokens in the decoding. Will remove the previous tokens (pre-prompt) if present. +clean_up_tokenization_spaces (bool, optional) — Whether or not to clean up the tokenization spaces. If None, will default to self.clean_up_tokenization_spaces (available in the tokenizer_config). +output_offsets (bool, optional, defaults to False) — Whether or not to output the offsets of the tokens. This should only be set if the model predicted timestamps. If there are previous tokens (pre-prompt) to decode, they will only appear in the decoded text if they contain timestamp tokens. +time_precision (float, optional, defaults to 0.02) — The time ratio to convert from token to time. +decode_with_timestamps (bool, optional, defaults to False) — Whether or not to decode with timestamps included in the raw text. +normalize (bool, optional, defaults to False) — Whether or not to apply the English text normalizer to the decoded text. Only applicable when the target text is in English. Otherwise, the basic text normalizer should be applied. +basic_normalize (bool, optional, defaults to False) — Whether or not to apply the Basic text normalizer to the decoded text. Applicable to multilingual target text. +remove_diacritics (bool, optional, defaults to False) — Whether or not to remove diacritics when applying the Basic text normalizer. Removing diacritics may destroy information in the decoded text, hence it should be used with caution. +kwargs (additional keyword arguments, optional) — Will be passed to the underlying model specific decode method. +Returns + +str + +The decoded sentence. + + +Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special tokens and clean up tokenization spaces. + +Similar to doing self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids)). + +basic_normalize +< +source +> +( textremove_diacritics = False ) + +Normalize a given string using the BasicTextNormalizer class, which preforms commons transformation on multilingual text. + +normalize +< +source +> +( text ) + +Normalize a given string using the EnglishTextNormalizer class, which preforms commons transformation on english text. + +WhisperTokenizerFast +class transformers.WhisperTokenizerFast +< +source +> +( vocab_file = Nonemerges_file = Nonenormalizer_file = Nonetokenizer_file = Noneunk_token = '<|endoftext|>'bos_token = '<|endoftext|>'eos_token = '<|endoftext|>'add_prefix_space = Falselanguage = Nonetask = Nonepredict_timestamps = False**kwargs ) + +Parameters + +vocab_file (str, optional) — Path to the vocabulary file. +merges_file (str, optional) — Path to the merges file. +normalizer_file (str, optional) — Path to the normalizer_file file. +tokenizer_file (str, optional) — Path to tokenizers file (generally has a .json extension) that contains everything needed to load the tokenizer. +unk_token (str, optional, defaults to "<|endoftext|>") — The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. +bos_token (str, optional, defaults to "<|endoftext|>") — The beginning of sequence token. The decoder_start_token_id is used to set the first token as "<|startoftranscript|>" when generating. +eos_token (str, optional, defaults to "<|endoftext|>") — The end of sequence token. +add_prefix_space (bool, optional, defaults to False) — Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. (Whisper tokenizer detect beginning of words by the preceding space). +language (str, optional) — The language of the transcription text. The corresponding language id token is appended to the start of the sequence for multilingual speech recognition and speech translation tasks, e.g. for Spanish the token "<|es|>" is appended to the start of sequence. This should be used for multilingual fine-tuning only. +task (str, optional) — Task identifier to append at the start of sequence (if any). This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and "translate" for speech translation. +predict_timestamps (bool, optional, defaults to False) — Whether to omit the <|notimestamps|> token at the start of the sequence. +Construct a “fast” Whisper tokenizer (backed by HuggingFace’s tokenizers library). + +This tokenizer inherits from PreTrainedTokenizerFast which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. + +set_prefix_tokens +< +source +> +( language: str = Nonetask: str = Nonepredict_timestamps: bool = None ) + +Parameters + +language (str, optional, defaults to None) — The language of the transcription text. +task (str, optional, defaults to None) — Task identifier to append at the start of sequence (if any). +predict_timestamps (bool, optional, defaults to None) — Whether to omit the <|notimestamps|> token at the start of the sequence. +Override the prefix tokens appended to the start of the label sequence. This method can be used standalone to + +update the prefix tokens as required when fine-tuning. Example: + +Copied +# instantiate the tokenizer and set the prefix token to Spanish +tokenizer = WhisperTokenizerFast.from_pretrained("openai/whisper-tiny", language="spanish") +# now switch the prefix token from Spanish to French +tokenizer.set_prefix_tokens(language="french") +build_inputs_with_special_tokens +< +source +> +( token_ids_0token_ids_1 = None ) + +Build model inputs from a sequence by appending eos_token_id. + +get_special_tokens_mask +< +source +> +( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = Nonealready_has_special_tokens: bool = False ) → List[int] + +Parameters + +token_ids_0 (List[int]) — List of IDs. +token_ids_1 (List[int], optional) — Optional second list of IDs for sequence pairs. +already_has_special_tokens (bool, optional, defaults to False) — Whether or not the token list is already formatted with special tokens for the model. +Returns + +List[int] + +A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. + + +Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer prepare_for_model method. + +create_token_type_ids_from_sequences +< +source +> +( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int] + +Parameters + +token_ids_0 (List[int]) — The first tokenized sequence. +token_ids_1 (List[int], optional) — The second tokenized sequence. +Returns + +List[int] + +The token type ids. + + +Create the token type IDs corresponding to the sequences passed. What are token type IDs? + +Should be overridden in a subclass if the model has a special way of building those. + +save_vocabulary +< +source +> +( save_directory: strfilename_prefix: typing.Optional[str] = None ) + +batch_decode +< +source +> +( sequences: typing.Union[typing.List[int], typing.List[typing.List[int]], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')]skip_special_tokens: bool = Falseclean_up_tokenization_spaces: bool = None**kwargs ) → List[str] + +Parameters + +sequences (Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]) — List of tokenized input ids. Can be obtained using the __call__ method. +skip_special_tokens (bool, optional, defaults to False) — Whether or not to remove special tokens in the decoding. +clean_up_tokenization_spaces (bool, optional) — Whether or not to clean up the tokenization spaces. If None, will default to self.clean_up_tokenization_spaces. +kwargs (additional keyword arguments, optional) — Will be passed to the underlying model specific decode method. +Returns + +List[str] + +The list of decoded sentences. + + +Convert a list of lists of token ids into a list of strings by calling decode. + +decode +< +source +> +( token_idsskip_special_tokens: bool = Falseclean_up_tokenization_spaces: bool = Noneoutput_offsets: bool = Falsetime_precision: float = 0.02decode_with_timestamps: bool = Falsenormalize: bool = Falsebasic_normalize: bool = Falseremove_diacritics: bool = False**kwargs ) → str + +Parameters + +token_ids (Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]) — List of tokenized input ids. Can be obtained using the __call__ method. +skip_special_tokens (bool, optional, defaults to False) — Whether or not to remove special tokens in the decoding. Will remove the previous tokens (pre-prompt) if present. +clean_up_tokenization_spaces (bool, optional) — Whether or not to clean up the tokenization spaces. If None, will default to self.clean_up_tokenization_spaces (available in the tokenizer_config). +output_offsets (bool, optional, defaults to False) — Whether or not to output the offsets of the tokens. This should only be set if the model predicted timestamps. If there are previous tokens (pre-prompt) to decode, they will only appear in the decoded text if they contain timestamp tokens. +time_precision (float, optional, defaults to 0.02) — The time ratio to convert from token to time. +decode_with_timestamps (bool, optional, defaults to False) — Whether or not to decode with timestamps included in the raw text. +normalize (bool, optional, defaults to False) — Whether or not to apply the English text normalizer to the decoded text. Only applicable when the target text is in English. Otherwise, the basic text normalizer should be applied. +basic_normalize (bool, optional, defaults to False) — Whether or not to apply the Basic text normalizer to the decoded text. Applicable to multilingual target text. +remove_diacritics (bool, optional, defaults to False) — Whether or not to remove diacritics when applying the Basic text normalizer. Removing diacritics may destroy information in the decoded text, hence it should be used with caution. +kwargs (additional keyword arguments, optional) — Will be passed to the underlying model specific decode method. +Returns + +str + +The decoded sentence. + + +Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special tokens and clean up tokenization spaces. + +Similar to doing self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids)). + +basic_normalize +< +source +> +( textremove_diacritics = False ) + +Normalize a given string using the BasicTextNormalizer class, which preforms commons transformation on multilingual text. + +normalize +< +source +> +( text ) + +Normalize a given string using the EnglishTextNormalizer class, which preforms commons transformation on english text. + +WhisperFeatureExtractor +class transformers.WhisperFeatureExtractor +< +source +> +( feature_size = 80sampling_rate = 16000hop_length = 160chunk_length = 30n_fft = 400padding_value = 0.0return_attention_mask = False**kwargs ) + +Parameters + +feature_size (int, optional, defaults to 80) — The feature dimension of the extracted features. +sampling_rate (int, optional, defaults to 16000) — The sampling rate at which the audio files should be digitalized expressed in hertz (Hz). +hop_length (int, optional, defaults to 160) — Length of the overlaping windows for the STFT used to obtain the Mel Frequency coefficients. +chunk_length (int, optional, defaults to 30) — The maximum number of chuncks of sampling_rate samples used to trim and pad longer or shorter audio sequences. +n_fft (int, optional, defaults to 400) — Size of the Fourier transform. +padding_value (float, optional, defaults to 0.0) — Padding value used to pad the audio. Should correspond to silences. +Constructs a Whisper feature extractor. + +This feature extractor inherits from SequenceFeatureExtractor which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. + +This class extracts mel-filter bank features from raw speech using a custom numpy implementation of the Short Time Fourier Transform which should match pytorch’s torch.stft equivalent. + +__call__ +< +source +> +( raw_speech: typing.Union[numpy.ndarray, typing.List[float], typing.List[numpy.ndarray], typing.List[typing.List[float]]]truncation: bool = Truepad_to_multiple_of: typing.Optional[int] = Nonereturn_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = Nonereturn_attention_mask: typing.Optional[bool] = Nonepadding: typing.Optional[str] = 'max_length'max_length: typing.Optional[int] = Nonesampling_rate: typing.Optional[int] = Nonedo_normalize: typing.Optional[bool] = Nonedevice: typing.Optional[str] = 'cpu'return_token_timestamps: typing.Optional[bool] = None**kwargs ) + +Parameters + +raw_speech (np.ndarray, List[float], List[np.ndarray], List[List[float]]) — The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not stereo, i.e. single float per timestep. +truncation (bool, optional, default to True) — Activates truncation to cut input sequences longer than max_length to max_length. +pad_to_multiple_of (int, optional, defaults to None) — If set will pad the sequence to a multiple of the provided value. +This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. + +return_attention_mask (bool, optional) — Whether to return the attention mask. If left to the default, will return the attention mask according to the specific feature_extractor’s default. +What are attention masks? + +For Whisper models, attention_mask should always be passed for batched inference, to avoid subtle bugs. + +return_tensors (str or TensorType, optional) — If set, will return tensors instead of list of python integers. Acceptable values are: +'tf': Return TensorFlow tf.constant objects. +'pt': Return PyTorch torch.Tensor objects. +'np': Return Numpy np.ndarray objects. +sampling_rate (int, optional) — The sampling rate at which the raw_speech input was sampled. It is strongly recommended to pass sampling_rate at the forward call to prevent silent errors and allow automatic speech recognition pipeline. +padding_value (float, optional, defaults to 0.0) — The value that is used to fill the padding values / vectors. +do_normalize (bool, optional, defaults to False) — Whether or not to zero-mean unit-variance normalize the input. Normalizing can help to significantly improve the performance of the model. +device (str, optional, defaults to 'cpu') — Specifies the device for computation of the log-mel spectrogram of audio signals in the _torch_extract_fbank_features method. (e.g., “cpu”, “cuda”) +return_token_timestamps (bool, optional, defaults to None) — Whether or not to return the number of frames of the input raw_speech. These num_frames can be used by the model to compute word level timestamps. +Main method to featurize and prepare for the model one or several sequence(s). Implementation uses PyTorch for the STFT computation if available, otherwise a slower NumPy based one. + +WhisperProcessor +class transformers.WhisperProcessor +< +source +> +( feature_extractortokenizer ) + +Parameters + +feature_extractor (WhisperFeatureExtractor) — An instance of WhisperFeatureExtractor. The feature extractor is a required input. +tokenizer (WhisperTokenizer) — An instance of WhisperTokenizer. The tokenizer is a required input. +Constructs a Whisper processor which wraps a Whisper feature extractor and a Whisper tokenizer into a single processor. + +WhisperProcessor offers all the functionalities of WhisperFeatureExtractor and WhisperTokenizer. See the call() and decode() for more information. + +__call__ +< +source +> +( *args**kwargs ) + +Forwards the audio argument to WhisperFeatureExtractor’s call() and the text argument to call(). Please refer to the doctsring of the above two methods for more information. + +from_pretrained +< +source +> +( pretrained_model_name_or_path: typing.Union[str, os.PathLike]cache_dir: typing.Union[str, os.PathLike, NoneType] = Noneforce_download: bool = Falselocal_files_only: bool = Falsetoken: typing.Union[str, bool, NoneType] = Nonerevision: str = 'main'**kwargs ) + +Parameters + +pretrained_model_name_or_path (str or os.PathLike) — This can be either: +a string, the model id of a pretrained feature_extractor hosted inside a model repo on huggingface.co. +a path to a directory containing a feature extractor file saved using the save_pretrained() method, e.g., ./my_model_directory/. +a path or url to a saved feature extractor JSON file, e.g., ./my_model_directory/preprocessor_config.json. +**kwargs — Additional keyword arguments passed along to both from_pretrained() and ~tokenization_utils_base.PreTrainedTokenizer.from_pretrained. +Instantiate a processor associated with a pretrained model. + +This class method is simply calling the feature extractor from_pretrained(), image processor ImageProcessingMixin and the tokenizer ~tokenization_utils_base.PreTrainedTokenizer.from_pretrained methods. Please refer to the docstrings of the methods above for more information. + +save_pretrained +< +source +> +( save_directorypush_to_hub: bool = False**kwargs ) + +Parameters + +save_directory (str or os.PathLike) — Directory where the feature extractor JSON file and the tokenizer files will be saved (directory will be created if it does not exist). +push_to_hub (bool, optional, defaults to False) — Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with repo_id (will default to the name of save_directory in your namespace). +kwargs (Dict[str, Any], optional) — Additional key word arguments passed along to the push_to_hub() method. +Saves the attributes of this processor (feature extractor, tokenizer…) in the specified directory so that it can be reloaded using the from_pretrained() method. + +This class method is simply calling save_pretrained() and save_pretrained(). Please refer to the docstrings of the methods above for more information. + +batch_decode +< +source +> +( *args**kwargs ) + +This method forwards all its arguments to WhisperTokenizer’s batch_decode(). Please refer to the docstring of this method for more information. + +decode +< +source +> +( *args**kwargs ) + +This method forwards all its arguments to WhisperTokenizer’s decode(). Please refer to the docstring of this method for more information. + +Pytorch +Hide Pytorch content +WhisperModel +class transformers.WhisperModel +< +source +> +( config: WhisperConfig ) + +Parameters + +config (WhisperConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights. +The bare Whisper Model outputting raw hidden-states without any specific head on top. This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) + +This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. + +forward +< +source +> +( input_features: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Nonedecoder_head_mask: typing.Optional[torch.Tensor] = Nonecross_attn_head_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonepast_key_values: typing.Union[transformers.cache_utils.EncoderDecoderCache, typing.Tuple[torch.FloatTensor], NoneType] = Nonedecoder_inputs_embeds: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonedecoder_position_ids: typing.Optional[typing.Tuple[torch.LongTensor]] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonecache_position: typing.Optional[torch.LongTensor] = None ) → transformers.modeling_outputs.Seq2SeqModelOutput or tuple(torch.FloatTensor) + +Parameters + +input_features (torch.FloatTensor of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call() +attention_mask (torch.LongTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing SpecAugment data augmentation on padding token indices. Mask values selected in [0, 1]: +1 for tokens that are not masked, +0 for tokens that are masked. +What are attention masks? + +decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary. +Indices can be obtained using WhisperTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. + +What are decoder input IDs? + +Whisper uses the decoder_start_token_id as the starting token for decoder_input_ids generation. If past_key_values is used, optionally only the last decoder_input_ids have to be input (see past_key_values). + +decoder_attention_mask (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default. +If you want to change padding behavior, you should read modeling_whisper._prepare_decoder_attention_mask and modify to your needs. See diagram 1 in the BART paper for more information on the default strategy. + +head_mask (torch.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +decoder_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +cross_attn_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — Mask to nullify selected heads of the cross-attention modules. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +encoder_outputs (tuple(tuple(torch.FloatTensor), optional) — Tuple consists of (last_hidden_state, optional: hidden_states, optional: attentions) last_hidden_state of shape (batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. +past_key_values (EncoderDecoderCache or tuple(tuple(torch.FloatTensor)), optional) — Pre-computed hidden-states that can be used to speed up auto-regressive (sequential) decoding. There are four sets of pre-computed hidden-states: key and values states in the self-attention blocks (2) and in the cross-attention blocks (2). The past_key_values are returned when use_cache=True is passed or when config.use_cache=True +Two formats are allowed: + +An EncoderDecoderCache instance; +Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). +If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of all decoder_input_ids of shape (batch_size, sequence_length). + +decoder_inputs_embeds (torch.FloatTensor of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix. +use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values). +output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. +output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. +return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. +cache_position (torch.LongTensor of shape (sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. It is used to update the cache in the correct position and to infer the complete sequence length. +Returns + +transformers.modeling_outputs.Seq2SeqModelOutput or tuple(torch.FloatTensor) + +A transformers.modeling_outputs.Seq2SeqModelOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WhisperConfig) and inputs. + +last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the decoder of the model. + +If past_key_values is used only the last hidden-state of the sequences of shape (batch_size, 1, hidden_size) is output. + +past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). + +Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding. + +decoder_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the decoder at the output of each layer plus the optional initial embedding outputs. + +decoder_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + +cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. + +encoder_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model. + +encoder_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the encoder at the output of each layer plus the optional initial embedding outputs. + +encoder_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + + +The WhisperModel forward method, overrides the __call__ special method. + +Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them. + +Example: + +Copied +import torch +from transformers import AutoFeatureExtractor, WhisperModel +from datasets import load_dataset + +model = WhisperModel.from_pretrained("openai/whisper-base") +feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-base") +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt") +input_features = inputs.input_features +decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id +last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state +list(last_hidden_state.shape) +[1, 2, 512] +_mask_input_features +< +source +> +( input_features: FloatTensorattention_mask: typing.Optional[torch.LongTensor] = None ) + +Masks extracted features along time axis and/or along feature axis according to SpecAugment. + +WhisperForConditionalGeneration +class transformers.WhisperForConditionalGeneration +< +source +> +( config: WhisperConfig ) + +Parameters + +config (WhisperConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights. +The Whisper Model with a language modeling head. Can be used for automatic speech recognition. This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) + +This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. + +forward +< +source +> +( input_features: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Nonedecoder_head_mask: typing.Optional[torch.Tensor] = Nonecross_attn_head_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonepast_key_values: typing.Union[transformers.cache_utils.EncoderDecoderCache, typing.Tuple[torch.FloatTensor], NoneType] = Nonedecoder_inputs_embeds: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonedecoder_position_ids: typing.Optional[typing.Tuple[torch.LongTensor]] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonecache_position: typing.Optional[torch.LongTensor] = None ) → transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor) + +Parameters + +input_features (torch.FloatTensor of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call() +attention_mask (torch.LongTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing SpecAugment data augmentation on padding token indices. Mask values selected in [0, 1]: +1 for tokens that are not masked, +0 for tokens that are masked. +What are attention masks? + +decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary. +Indices can be obtained using WhisperTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. + +What are decoder input IDs? + +Whisper uses the decoder_start_token_id as the starting token for decoder_input_ids generation. If past_key_values is used, optionally only the last decoder_input_ids have to be input (see past_key_values). + +decoder_attention_mask (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default. +If you want to change padding behavior, you should read modeling_whisper._prepare_decoder_attention_mask and modify to your needs. See diagram 1 in the BART paper for more information on the default strategy. + +head_mask (torch.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +decoder_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +cross_attn_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — Mask to nullify selected heads of the cross-attention modules. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +encoder_outputs (tuple(tuple(torch.FloatTensor), optional) — Tuple consists of (last_hidden_state, optional: hidden_states, optional: attentions) last_hidden_state of shape (batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. +past_key_values (EncoderDecoderCache or tuple(tuple(torch.FloatTensor)), optional) — Pre-computed hidden-states that can be used to speed up auto-regressive (sequential) decoding. There are four sets of pre-computed hidden-states: key and values states in the self-attention blocks (2) and in the cross-attention blocks (2). The past_key_values are returned when use_cache=True is passed or when config.use_cache=True +Two formats are allowed: + +An EncoderDecoderCache instance; +Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). +If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of all decoder_input_ids of shape (batch_size, sequence_length). + +decoder_inputs_embeds (torch.FloatTensor of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix. +use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values). +output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. +output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. +return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. +cache_position (torch.LongTensor of shape (sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. It is used to update the cache in the correct position and to infer the complete sequence length. +labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — Labels for computing the language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size]. sequence_length should be smaller than or equal to config.max_target_positions. +Returns + +transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor) + +A transformers.modeling_outputs.Seq2SeqLMOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WhisperConfig) and inputs. + +loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Language modeling loss. + +logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). + +past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). + +Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding. + +decoder_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. + +decoder_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + +cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. + +encoder_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model. + +encoder_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. + +encoder_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + + +The WhisperForConditionalGeneration forward method, overrides the __call__ special method. + +Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them. + +Example: + +Copied +import torch +from transformers import AutoProcessor, WhisperForConditionalGeneration +from datasets import load_dataset + +processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en") +model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + +inputs = processor(ds[0]["audio"]["array"], return_tensors="pt") +input_features = inputs.input_features + +generated_ids = model.generate(inputs=input_features) + +transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] +transcription +' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.' +generate +< +source +> +( input_features: typing.Optional[torch.Tensor] = Nonegeneration_config: typing.Optional[transformers.generation.configuration_utils.GenerationConfig] = Nonelogits_processor: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = Nonestopping_criteria: typing.Optional[transformers.generation.stopping_criteria.StoppingCriteriaList] = Noneprefix_allowed_tokens_fn: typing.Optional[typing.Callable[[int, torch.Tensor], typing.List[int]]] = Nonesynced_gpus: bool = Falsereturn_timestamps: typing.Optional[bool] = Nonetask: typing.Optional[str] = Nonelanguage: typing.Union[str, typing.List[str], NoneType] = Noneis_multilingual: typing.Optional[bool] = Noneprompt_ids: typing.Optional[torch.Tensor] = Noneprompt_condition_type: typing.Optional[str] = Nonecondition_on_prev_tokens: typing.Optional[bool] = Nonetemperature: typing.Union[float, typing.Tuple[float, ...], NoneType] = Nonecompression_ratio_threshold: typing.Optional[float] = Nonelogprob_threshold: typing.Optional[float] = Noneno_speech_threshold: typing.Optional[float] = Nonenum_segment_frames: typing.Optional[int] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonetime_precision: float = 0.02return_token_timestamps: typing.Optional[bool] = Nonereturn_segments: bool = Falsereturn_dict_in_generate: typing.Optional[bool] = None**kwargs ) → ModelOutput or torch.LongTensor or Dict[str, Any] + +Parameters + +input_features (torch.Tensor of shape (batch_size, feature_size, sequence_length), optional) — Float values of log-mel features extracted from the raw speech waveform. The raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call() for details. +generation_config (~generation.GenerationConfig, optional) — The generation configuration to be used as base parametrization for the generation call. **kwargs passed to generate matching the attributes of generation_config will override them. If generation_config is not provided, the default will be used, which had the following loading priority: 1) from the generation_config.json model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit GenerationConfig’s default values, whose documentation should be checked to parameterize generation. +logits_processor (LogitsProcessorList, optional) — Custom logits processors that complement the default logits processors built from arguments and generation config. If a logit processor is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users. +stopping_criteria (StoppingCriteriaList, optional) — Custom stopping criteria that complement the default stopping criteria built from arguments and a generation config. If a stopping criteria is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users. +prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], List[int]], optional) — If provided, this function constraints the beam search to allowed tokens only at each step. If not provided no constraint is applied. This function takes 2 arguments: the batch ID batch_id and input_ids. It has to return a list with the allowed tokens for the next generation step conditioned on the batch ID batch_id and the previously generated tokens inputs_ids. This argument is useful for constrained generation conditioned on the prefix, as described in Autoregressive Entity Retrieval. +synced_gpus (bool, optional, defaults to False) — Whether to continue running the while loop until max_length (needed to avoid deadlocking with FullyShardedDataParallel and DeepSpeed ZeRO Stage 3). +return_timestamps (bool, optional) — Whether to return the timestamps with the text. This enables the WhisperTimestampsLogitsProcessor. +task (str, optional) — Task to use for generation, either “translate” or “transcribe”. The model.config.forced_decoder_ids will be updated accordingly. +language (str or list of str, optional) — Language token to use for generation, can be either in the form of <|en|>, en or english. For batched generation, a list of language tokens can be passed. You can find all the possible language tokens in the model.generation_config.lang_to_id dictionary. +is_multilingual (bool, optional) — Whether or not the model is multilingual. +prompt_ids (torch.Tensor, optional) — Rank-1 tensor of token IDs created by passing text to get_prompt_ids() that is provided as a prompt to each chunk. This can be used to provide or “prompt-engineer” a context for transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words correctly. It cannot be used in conjunction with decoder_start_token_id as it overwrites this value. +prompt_condition_type (str, optional) — Only relevant for long-form transcription. Condition type of prompt_ids. ‘first-segment’ means only the first segment is conditioned on prompt_ids. ‘all-segments’ means each segment is conditioned on prompt_ids. Make sure to enable condition_on_prev_tokens for ‘all-segments’. Defaults to ‘first-segment’. For short-term transcription only ‘first-segment’ is possible. +condition_on_prev_tokens (bool, optional) — Only relevant for long-form transcription. Whether to condition each segment on the previous segment. As shown in the the Whisper paper, this can help to improve performance. +temperature (float or list of float, optional) — The temperature to be used for generation. Passing a single float value and do_sample=True activates generation using sampling. For long-form transcription, temperature fallback can be activated by passing a list of float values such as (0.0, 0.2, 0.4, 0.6, 0.8, 1.0). As shown in the the Whisper paper, this can help to improve performance. +compression_ratio_threshold (float, optional) — Only relevant for long-form transcription. If defined, the zlib compression rate of each segment will be computed. If the compression rate of a segment is higher than compression_ratio_threshold, temperature fallback is activated: the generated segment is discarded and the generation is repeated using a higher temperature. The intuition behind this feature is that segments with very high compression rates suffer from a lot of repetition. The unwanted repetition can be reduced by injecting more randomness by increasing the temperature. If compression_ratio_threshold is defined make sure that temperature is a list of values. A common value for compression_ratio_threshold is 1.35. As shown in the the Whisper paper, this can help to improve performance. +logprob_threshold (float, optional) — Only relevant for long-form transcription. If defined, the average log-probability of each segment will be computed. If the log-probability of a given segment is lower than logprob_threshold, temperature fallback is activated: the generated segment is discarded and the generation is repeated using a higher temperature. The intuition behind this feature is that segments of low log-probability can be improved by injecting more randomness by increasing the temperature. If logprob_threshold is defined make sure that temperature is a list of values. A common value for logprob_threshold is -1.0. As shown in the the Whisper paper, this can help to improve performance. +no_speech_threshold (float, optional) — Only relevant for long-form transcription. If defined, the “no-speech” token combined with the logprob_threshold is used to determine whether a segment contains only silence. In this case, the transcription for this segment is skipped. As shown in the the Whisper paper, this can help to improve performance. +num_segment_frames (int, optional) — The number of frames a single segment is made of. If not defined, num_segment_frames defaults to the model’s stride times the maximum input length. +attention_mask (torch.Tensor, optional) — attention_mask needs to be passed when doing long-form transcription using a batch size > 1. +time_precision (int, optional, defaults to 0.02) — The duration of output token in seconds. E.g. 0.02 means that a generated token on average accounts for 20 ms. +return_token_timestamps (bool, optional) — Whether to return token-level timestamps with the text. This can be used with or without the return_timestamps option. To get word-level timestamps, use the tokenizer to group the tokens into words. +return_segments (bool, optional, defaults to False) — Whether to additionally return a list of all segments. Note that this option can only be enabled when doing long-form transcription. +return_dict_in_generate (bool, optional, defaults to False) — Whether or not to return a ModelOutput instead of just returning the generated tokens. Note that when doing long-form transcription, return_dict_in_generate can only be enabled when return_segments is set True. In this case the generation outputs of each segment is added to each segment. +kwargs (Dict[str, Any], optional) — Ad hoc parametrization of generate_config and/or additional model-specific kwargs that will be forwarded to the forward function of the model. If the model is an encoder-decoder model, encoder specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with decoder_. +Returns + +ModelOutput or torch.LongTensor or Dict[str, Any] + +A ModelOutput (if return_dict_in_generate=True or when config.return_dict_in_generate=True) or a torch.FloatTensor or a dict of segments when return_segments=True. + +If the passed input is > 30 seconds / > 3000 mel input features and return_segments=True then a dictionary of generated sequence ids, called sequences and a list of each generated segment is returned. + +else if the passed input is <= 30 seconds / >= 3000 mel input features, the possible ModelOutput types are: + +GenerateEncoderDecoderOutput, +GenerateBeamEncoderDecoderOutput +else only the generated output sequence ids are returned. + + +Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids. + +Most generation-controlling parameters are set in generation_config which, if not passed, will be set to the model’s default generation configuration. You can override any generation_config by passing the corresponding parameters to generate(), e.g. .generate(inputs, num_beams=4, do_sample=True). + +For an overview of generation strategies and code examples, check out the following guide. + +Example: + +Longform transcription: To transcribe or translate audios longer than 30 seconds, process the audio files without truncation and pass all mel features at once to generate. +Copied +import torch +from transformers import AutoProcessor, WhisperForConditionalGeneration +from datasets import load_dataset, Audio + +processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en") +model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") +model.cuda() +# load audios > 30 seconds +ds = load_dataset("distil-whisper/meanwhile", "default")["test"] +# resample to 16kHz +ds = ds.cast_column("audio", Audio(sampling_rate=16000)) +# take first 8 audios and retrieve array +audio = ds[:8]["audio"] +audio = [x["array"] for x in audio] + +# make sure to NOT truncate the input audio, to return the `attention_mask` and to pad to the longest audio +inputs = processor(audio, return_tensors="pt", truncation=False, padding="longest", return_attention_mask=True, sampling_rate=16_000) +inputs = inputs.to("cuda", torch.float32) + +# transcribe audio to ids +generated_ids = model.generate(**inputs) + +transcription = processor.batch_decode(generated_ids, skip_special_tokens=True) +transcription[0] +" Folks, if you watch the show, you know, I spent a lot of time right over there. Patiently and astutely scrutinizing the boxwood and mahogany chest set of the day's biggest stories developing the central headline pawns, definitely maneuvering an oso topical night to F6, fainting a classic Sicilian, nade door variation on the news, all the while seeing eight moves deep and patiently marshalling the latest press releases into a fisher's shows in Lip Nitsky attack that culminates in the elegant lethal slow-played, all-passant checkmate that is my nightly monologue. But sometimes, sometimes, folks, I. CHEERING AND APPLAUSE Sometimes I startle away, cubside down in the monkey bars of a condemned playground on a super fun site. Get all hept up on goofballs. Rummage that were discarded tag bag of defective toys. Yank out a fist bowl of disembodied doll limbs, toss them on a stained kid's place mat from a defunct dennies. set up a table inside a rusty cargo container down by the Wharf and challenged toothless drifters to the godless bughouse blitz of tournament that is my segment. Meanwhile." +Shortform transcription: If passed mel input features are < 30 seconds, the whole audio will be transcribed with a single call to generate. +Copied +import torch +from transformers import AutoProcessor, WhisperForConditionalGeneration +from datasets import load_dataset + +processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en") +model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + +inputs = processor(ds[0]["audio"]["array"], return_tensors="pt") +input_features = inputs.input_features + +generated_ids = model.generate(inputs=input_features) + +transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] +transcription +' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.' +WhisperForCausalLM +class transformers.WhisperForCausalLM +< +source +> +( config ) + +Parameters + +config (WhisperConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights. +Whisper decoder with a language modeling head on top (linear layer with weights tied to the input embeddings). + +This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) + +This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. + +forward +< +source +> +( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonehead_mask: typing.Optional[torch.Tensor] = Nonecross_attn_head_mask: typing.Optional[torch.Tensor] = Nonepast_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonecache_position: typing.Optional[torch.LongTensor] = None ) → transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or tuple(torch.FloatTensor) + +Parameters + +input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are input IDs? +attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]: +1 for tokens that are not masked, +0 for tokens that are masked. What are attention masks? +encoder_outputs (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. +head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +cross_attn_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — Mask to nullify selected heads of the cross-attention modules. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). The two additional tensors are only required when the model is used as a decoder in a Sequence to Sequence model. Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding. If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of all decoder_input_ids of shape (batch_size, sequence_length). +inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix. +labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size]. +use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values). +1 for tokens that are not masked, +0 for tokens that are masked. +output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. +output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. +return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. +cache_position (torch.LongTensor of shape (sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. It is used to update the cache in the correct position and to infer the complete sequence length. +Returns + +transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or tuple(torch.FloatTensor) + +A transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WhisperConfig) and inputs. + +loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Language modeling loss (for next-token prediction). + +logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). + +hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. + +attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. + +cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Cross attentions weights after the attention softmax, used to compute the weighted average in the cross-attention heads. + +past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of torch.FloatTensor tuples of length config.n_layers, with each tuple containing the cached key, value states of the self-attention and the cross-attention layers if model is used in encoder-decoder setting. Only relevant if config.is_decoder = True. + +Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see past_key_values input) to speed up sequential decoding. + + +Example: + +Copied +from transformers import WhisperForCausalLM, WhisperForConditionalGeneration, WhisperProcessor +import torch +from datasets import load_dataset + +processor = WhisperProcessor.from_pretrained("openai/whisper-large-v2") +model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large-v2") + +assistant_model = WhisperForCausalLM.from_pretrained("distil-whisper/distil-large-v2") + +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +sample = ds[0]["audio"] +input_features = processor( + sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt" +).input_features + +predicted_ids = model.generate(input_features, assistant_model=assistant_model) + +# decode token ids to text +transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0] +transcription +' Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.' +WhisperForAudioClassification +class transformers.WhisperForAudioClassification +< +source +> +( config ) + +Parameters + +input_features (torch.FloatTensor of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call() +head_mask (torch.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +encoder_outputs (tuple(tuple(torch.FloatTensor), optional) — Tuple consists of (last_hidden_state, optional: hidden_states, optional: attentions) last_hidden_state of shape (batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. +output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. +output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. +return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. +Whisper Encoder Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting. + +forward +< +source +> +( input_features: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonelabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor) + +Parameters + +input_features (torch.FloatTensor of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call() +head_mask (torch.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +encoder_outputs (tuple(tuple(torch.FloatTensor), optional) — Tuple consists of (last_hidden_state, optional: hidden_states, optional: attentions) last_hidden_state of shape (batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. +output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. +output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. +return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. +labels (torch.LongTensor of shape (batch_size,), optional) — Labels for computing the sequence classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy). +Returns + +transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor) + +A transformers.modeling_outputs.SequenceClassifierOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WhisperConfig) and inputs. + +loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Classification (or regression if config.num_labels==1) loss. + +logits (torch.FloatTensor of shape (batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax). + +hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. + +attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. + + +The WhisperForAudioClassification forward method, overrides the __call__ special method. + +Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them. + +Example: + +Copied +import torch +from transformers import AutoFeatureExtractor, WhisperForAudioClassification +from datasets import load_dataset + +feature_extractor = AutoFeatureExtractor.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id") +model = WhisperForAudioClassification.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id") + +ds = load_dataset("google/fleurs", "all", split="validation", streaming=True) +sample = next(iter(ds)) + +inputs = feature_extractor( + sample["audio"]["array"], sampling_rate=sample["audio"]["sampling_rate"], return_tensors="pt" +) +input_features = inputs.input_features + +with torch.no_grad(): + logits = model(input_features).logits + +predicted_class_ids = torch.argmax(logits).item() +predicted_label = model.config.id2label[predicted_class_ids] +predicted_label +'Afrikaans' +TensorFlow +Hide TensorFlow content +TFWhisperModel +class transformers.TFWhisperModel +< +source +> +( config: WhisperConfig**kwargs ) + +Parameters + +config (WhisperConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights. +The bare Whisper Model outputting raw hidden-states without any specific head on top. This model inherits from TFPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) + +This model is also a keras.Model subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior. + +call +< +source +> +( input_features: TFModelInputType | None = Nonedecoder_input_ids: np.ndarray | tf.Tensor | None = Nonedecoder_attention_mask: np.ndarray | tf.Tensor | None = Nonedecoder_position_ids: np.ndarray | tf.Tensor | None = Nonehead_mask: np.ndarray | tf.Tensor | None = Nonedecoder_head_mask: np.ndarray | tf.Tensor | None = Nonecross_attn_head_mask: np.ndarray | tf.Tensor | None = Noneencoder_outputs: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = Nonepast_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = Nonedecoder_inputs_embeds: Optional[Tuple[Union[np.ndarray, tf.Tensor]]] = Noneuse_cache: Optional[bool] = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonetraining: bool = False ) → transformers.modeling_tf_outputs.TFSeq2SeqModelOutput or tuple(tf.Tensor) + +Parameters + +input_features (tf.Tensor of shape (batch_size, feature_size, sequence_length)) — Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the fbank features, padding and conversion into a tensor of type tf.Tensor. See call() +decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary. +Indices can be obtained using SpeechToTextTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. + +What are decoder input IDs? + +SpeechToText uses the eos_token_id as the starting token for decoder_input_ids generation. If past_key_values is used, optionally only the last decoder_input_ids have to be input (see past_key_values). + +decoder_attention_mask (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default. +If you want to change padding behavior, you should read modeling_whisper._prepare_decoder_attention_mask and modify to your needs. See diagram 1 in the paper for more information on the default strategy. + +head_mask (tf.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +decoder_head_mask (tf.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +cross_attn_head_mask (tf.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — Mask to nullify selected heads of the cross-attention modules. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +encoder_outputs (tuple(tuple(tf.Tensor), optional) — Tuple consists of (last_hidden_state, optional: hidden_states, optional: attentions) last_hidden_state of shape (batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. +past_key_values (tuple(tuple(tf.Tensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(tf.Tensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). +Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding. + +If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of all decoder_input_ids of shape (batch_size, sequence_length). + +decoder_inputs_embeds (tf.Tensor of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix. +use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values). +output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. +output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. +return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. +Returns + +transformers.modeling_tf_outputs.TFSeq2SeqModelOutput or tuple(tf.Tensor) + +A transformers.modeling_tf_outputs.TFSeq2SeqModelOutput or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WhisperConfig) and inputs. + +last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the decoder of the model. + +If past_key_values is used only the last hidden-state of the sequences of shape (batch_size, 1, hidden_size) is output. + +past_key_values (List[tf.Tensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of tf.Tensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)). + +Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be used (see past_key_values input) to speed up sequential decoding. + +decoder_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. + +decoder_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + +cross_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. + +encoder_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model. + +encoder_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. + +encoder_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + + +The TFWhisperModel forward method, overrides the __call__ special method. + +Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them. + +Example: + +Copied +import tensorflow as tf +from transformers import TFWhisperModel, AutoFeatureExtractor +from datasets import load_dataset + +model = TFWhisperModel.from_pretrained("openai/whisper-base") +feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-base") +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="tf") +input_features = inputs.input_features +decoder_input_ids = tf.convert_to_tensor([[1, 1]]) * model.config.decoder_start_token_id +last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state +list(last_hidden_state.shape) +[1, 2, 512] +TFWhisperForConditionalGeneration +class transformers.TFWhisperForConditionalGeneration +< +source +> +( config: WhisperConfig**kwargs ) + +Parameters + +config (WhisperConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights. +The Whisper Model with a language modeling head. Can be used for automatic speech recognition. This model inherits from TFPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) + +This model is also a keras.Model subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior. + +call +< +source +> +( input_features: TFModelInputType | None = Nonedecoder_input_ids: np.ndarray | tf.Tensor | None = Nonedecoder_attention_mask: np.ndarray | tf.Tensor | None = Nonedecoder_position_ids: np.ndarray | tf.Tensor | None = Nonehead_mask: np.ndarray | tf.Tensor | None = Nonedecoder_head_mask: np.ndarray | tf.Tensor | None = Nonecross_attn_head_mask: np.ndarray | tf.Tensor | None = Noneencoder_outputs: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = Nonepast_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = Nonedecoder_inputs_embeds: Optional[Tuple[Union[np.ndarray, tf.Tensor]]] = Nonelabels: np.ndarray | tf.Tensor | None = Noneuse_cache: Optional[bool] = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonetraining: bool = False ) → transformers.modeling_tf_outputs.TFSeq2SeqLMOutput or tuple(tf.Tensor) + +Parameters + +input_features (tf.Tensor of shape (batch_size, feature_size, sequence_length)) — Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the fbank features, padding and conversion into a tensor of type tf.Tensor. See call() +decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary. +Indices can be obtained using SpeechToTextTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. + +What are decoder input IDs? + +SpeechToText uses the eos_token_id as the starting token for decoder_input_ids generation. If past_key_values is used, optionally only the last decoder_input_ids have to be input (see past_key_values). + +decoder_attention_mask (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default. +If you want to change padding behavior, you should read modeling_whisper._prepare_decoder_attention_mask and modify to your needs. See diagram 1 in the paper for more information on the default strategy. + +head_mask (tf.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +decoder_head_mask (tf.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +cross_attn_head_mask (tf.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — Mask to nullify selected heads of the cross-attention modules. Mask values selected in [0, 1]: +1 indicates the head is not masked, +0 indicates the head is masked. +encoder_outputs (tuple(tuple(tf.Tensor), optional) — Tuple consists of (last_hidden_state, optional: hidden_states, optional: attentions) last_hidden_state of shape (batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. +past_key_values (tuple(tuple(tf.Tensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(tf.Tensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). +Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding. + +If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of all decoder_input_ids of shape (batch_size, sequence_length). + +decoder_inputs_embeds (tf.Tensor of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix. +use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values). +output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. +output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. +return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. +labels (tf.Tensor of shape (batch_size, sequence_length), optional) — Labels for computing the language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size]. +Returns + +transformers.modeling_tf_outputs.TFSeq2SeqLMOutput or tuple(tf.Tensor) + +A transformers.modeling_tf_outputs.TFSeq2SeqLMOutput or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WhisperConfig) and inputs. + +loss (tf.Tensor of shape (n,), optional, where n is the number of non-masked labels, returned when labels is provided) — Language modeling loss. + +logits (tf.Tensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). + +past_key_values (List[tf.Tensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of tf.Tensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)). + +Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be used (see past_key_values input) to speed up sequential decoding. + +decoder_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. + +decoder_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + +cross_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. + +encoder_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model. + +encoder_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. + +encoder_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + + +The TFWhisperForConditionalGeneration forward method, overrides the __call__ special method. + +Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them. + +Example: + +Copied +import tensorflow as tf +from transformers import AutoProcessor, TFWhisperForConditionalGeneration +from datasets import load_dataset + +processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en") +model = TFWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + +inputs = processor(ds[0]["audio"]["array"], return_tensors="tf") +input_features = inputs.input_features + +generated_ids = model.generate(input_features=input_features) + +transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] +transcription +' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.' +JAX +Hide JAX content +FlaxWhisperModel +class transformers.FlaxWhisperModel +< +source +> +( config: WhisperConfiginput_shape: typing.Tuple[int] = Noneseed: int = 0dtype: dtype = _do_init: bool = Truegradient_checkpointing: bool = False**kwargs ) + +Parameters + +config (WhisperConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights. +dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs). This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given dtype. Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters. If you wish to change the dtype of the model parameters, see to_fp16() and to_bf16(). +The bare Whisper Model transformer outputting raw hidden-states without any specific head on top. This model inherits from FlaxPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its models (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a Flax Linen flax.nn.Module subclass. Use it as a regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior. Finally, this model supports inherent JAX features such as: + +Just-In-Time (JIT) compilation +Automatic Differentiation +Vectorization +Parallelization +__call__ +< +source +> +( input_features: Arraydecoder_input_ids: Arrayattention_mask: typing.Optional[jax.Array] = Nonedecoder_attention_mask: typing.Optional[jax.Array] = Noneposition_ids: typing.Optional[jax.Array] = Nonedecoder_position_ids: typing.Optional[jax.Array] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonetrain: bool = Falseparams: dict = Nonedropout_rng: = None ) → transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutput or tuple(torch.FloatTensor) + +Parameters + +input_features (numpy.ndarray of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the WhisperFeatureExtractor should be used for extracting the features, padding and conversion into a tensor of type numpy.ndarray. See call() +attention_mask (numpy.ndarray of shape (batch_size, sequence_length), optional) — Whisper does not support masking of the input_features, this argument is preserved for compatibility, but is not used. By default the silence in the input log mel spectrogram are ignored. +decoder_input_ids (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using WhisperTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are decoder input IDs? Whisper uses the decoder_start_token_id as the starting token for decoder_input_ids generation. +decoder_attention_mask (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default. If you want to change padding behavior, you should modify to your needs. See diagram 1 in the paper for more information on the default strategy. +position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — Whisper does not use position_ids in the encoder as input_features is always the same size and doesn’t use masking, but this argument is preserved for compatibility. By default the silence in the input log mel spectrogram are ignored. +decoder_position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1]. +output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. +output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. +return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. +Returns + +transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutput or tuple(torch.FloatTensor) + +A transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WhisperConfig) and inputs. + +last_hidden_state (jnp.ndarray of shape (batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the decoder of the model. + +If past_key_values is used only the last hidden-state of the sequences of shape (batch_size, 1, hidden_size) is output. + +past_key_values (tuple(tuple(jnp.ndarray)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(jnp.ndarray) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). + +Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding. + +decoder_hidden_states (tuple(jnp.ndarray), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of jnp.ndarray (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. + +decoder_attentions (tuple(jnp.ndarray), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of jnp.ndarray (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + +cross_attentions (tuple(jnp.ndarray), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of jnp.ndarray (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. + +encoder_last_hidden_state (jnp.ndarray of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model. + +encoder_hidden_states (tuple(jnp.ndarray), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of jnp.ndarray (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. + +encoder_attentions (tuple(jnp.ndarray), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of jnp.ndarray (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + + +The FlaxWhisperPreTrainedModel forward method, overrides the __call__ special method. + +Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them. + +Example: + +Copied +from transformers import AutoTokenizer, FlaxWhisperModel + +tokenizer = AutoTokenizer.from_pretrained("openai/whisper-tiny") +model = FlaxWhisperModel.from_pretrained("openai/whisper-tiny") + +inputs = tokenizer("Hello, my dog is cute", return_tensors="jax") +outputs = model(**inputs) + +last_hidden_states = outputs.last_hidden_state +FlaxWhisperForConditionalGeneration +class transformers.FlaxWhisperForConditionalGeneration +< +source +> +( config: WhisperConfiginput_shape: typing.Tuple[int] = Noneseed: int = 0dtype: dtype = _do_init: bool = Truegradient_checkpointing: bool = False**kwargs ) + +Parameters + +config (WhisperConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights. +dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs). This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given dtype. Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters. If you wish to change the dtype of the model parameters, see to_fp16() and to_bf16(). +The Whisper Model with a language modeling head. This model inherits from FlaxPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its models (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a Flax Linen flax.nn.Module subclass. Use it as a regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior. Finally, this model supports inherent JAX features such as: + +Just-In-Time (JIT) compilation +Automatic Differentiation +Vectorization +Parallelization +__call__ +< +source +> +( input_features: Arraydecoder_input_ids: Arrayattention_mask: typing.Optional[jax.Array] = Nonedecoder_attention_mask: typing.Optional[jax.Array] = Noneposition_ids: typing.Optional[jax.Array] = Nonedecoder_position_ids: typing.Optional[jax.Array] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonetrain: bool = Falseparams: dict = Nonedropout_rng: = None ) → transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput or tuple(torch.FloatTensor) + +Parameters + +input_features (numpy.ndarray of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the WhisperFeatureExtractor should be used for extracting the features, padding and conversion into a tensor of type numpy.ndarray. See call() +attention_mask (numpy.ndarray of shape (batch_size, sequence_length), optional) — Whisper does not support masking of the input_features, this argument is preserved for compatibility, but is not used. By default the silence in the input log mel spectrogram are ignored. +decoder_input_ids (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using WhisperTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are decoder input IDs? Whisper uses the decoder_start_token_id as the starting token for decoder_input_ids generation. +decoder_attention_mask (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default. If you want to change padding behavior, you should modify to your needs. See diagram 1 in the paper for more information on the default strategy. +position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — Whisper does not use position_ids in the encoder as input_features is always the same size and doesn’t use masking, but this argument is preserved for compatibility. By default the silence in the input log mel spectrogram are ignored. +decoder_position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1]. +output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. +output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. +return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. +Returns + +transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput or tuple(torch.FloatTensor) + +A transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WhisperConfig) and inputs. + +logits (jnp.ndarray of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). + +past_key_values (tuple(tuple(jnp.ndarray)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(jnp.ndarray) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). + +Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding. + +decoder_hidden_states (tuple(jnp.ndarray), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of jnp.ndarray (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. + +decoder_attentions (tuple(jnp.ndarray), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of jnp.ndarray (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + +cross_attentions (tuple(jnp.ndarray), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of jnp.ndarray (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. + +encoder_last_hidden_state (jnp.ndarray of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model. + +encoder_hidden_states (tuple(jnp.ndarray), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of jnp.ndarray (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. + +encoder_attentions (tuple(jnp.ndarray), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of jnp.ndarray (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + + +The FlaxWhisperPreTrainedModel forward method, overrides the __call__ special method. + +Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them. + +Transcription example: + +Copied +from transformers import WhisperProcessor, FlaxWhisperForConditionalGeneration +from datasets import load_dataset + +processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") +model = FlaxWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en", from_pt=True) +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +inputs = processor(ds[0]["audio"]["array"], return_tensors="np") +input_features = inputs.input_features +generated_ids = model.generate(input_ids=input_features) +transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] +transcription +' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.' +FlaxWhisperForAudioClassification +class transformers.FlaxWhisperForAudioClassification +< +source +> +( config: WhisperConfiginput_shape: typing.Tuple[int] = Noneseed: int = 0dtype: dtype = _do_init: bool = Truegradient_checkpointing: bool = False**kwargs ) + +Parameters + +config (WhisperConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights. +dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs). This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given dtype. Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters. If you wish to change the dtype of the model parameters, see to_fp16() and to_bf16(). +The Whisper Model with an audio classification head on top. This model inherits from FlaxPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its models (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a Flax Linen flax.nn.Module subclass. Use it as a regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior. Finally, this model supports inherent JAX features such as: + +Just-In-Time (JIT) compilation +Automatic Differentiation +Vectorization +Parallelization +__call__ +< +source +> +( input_features: Arrayattention_mask: typing.Optional[jax.Array] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonetrain: bool = Falseparams: dict = Nonedropout_rng: = None**kwargs ) → transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput or tuple(torch.FloatTensor) + +Parameters + +input_features (numpy.ndarray of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the WhisperFeatureExtractor should be used for extracting the features, padding and conversion into a tensor of type numpy.ndarray. See call() +attention_mask (numpy.ndarray of shape (batch_size, sequence_length), optional) — Whisper does not support masking of the input_features, this argument is preserved for compatibility, but is not used. By default the silence in the input log mel spectrogram are ignored. +decoder_input_ids (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using WhisperTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are decoder input IDs? Whisper uses the decoder_start_token_id as the starting token for decoder_input_ids generation. +decoder_attention_mask (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default. If you want to change padding behavior, you should modify to your needs. See diagram 1 in the paper for more information on the default strategy. +position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — Whisper does not use position_ids in the encoder as input_features is always the same size and doesn’t use masking, but this argument is preserved for compatibility. By default the silence in the input log mel spectrogram are ignored. +decoder_position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1]. +output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. +output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. +return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. +Returns + +transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput or tuple(torch.FloatTensor) + +A transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WhisperConfig) and inputs. + +logits (jnp.ndarray of shape (batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax). + +hidden_states (tuple(jnp.ndarray), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of jnp.ndarray (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). + +Hidden-states of the model at the output of each layer plus the initial embedding outputs. + +attentions (tuple(jnp.ndarray), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of jnp.ndarray (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length). + +Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. + + +The FlaxWhisperForAudioClassification forward method, overrides the __call__ special method. + +Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them. + +Transcription example: + +Copied +import jax.numpy as jnp +from transformers import AutoFeatureExtractor, FlaxWhisperForAudioClassification +from datasets import load_dataset + +feature_extractor = AutoFeatureExtractor.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id") +model = FlaxWhisperForAudioClassification.from_pretrained( + "sanchit-gandhi/whisper-medium-fleurs-lang-id", from_pt=True +) +ds = load_dataset("google/fleurs", "all", split="validation", streaming=True, trust_remote_code=True) + +sample = next(iter(ds)) + +inputs = feature_extractor( + sample["audio"]["array"], sampling_rate=sample["audio"]["sampling_rate"], return_tensors="np" +) +input_features = inputs.input_features + +logits = model(input_features).logits + +predicted_class_ids = jnp.argmax(logits).item() +predicted_label = model.config.id2label[predicted_class_ids] +predicted_label +'af_za' \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..51f36c4 --- /dev/null +++ b/main.py @@ -0,0 +1,483 @@ +import tkinter as tk +from tkinter import ttk, filedialog, scrolledtext +from tkinter import messagebox +import torch +from transformers import AutoProcessor, WhisperForConditionalGeneration +import cv2 +from datetime import timedelta +import os +import threading +import subprocess +import time +import re +import numpy as np + +class VideoSubtitleApp: + def __init__(self, root): + self.root = root + self.root.title("Extrator de Legendas") + self.root.geometry("900x700") + + # Variáveis + self.video_path = tk.StringVar() + self.video_info = tk.StringVar() + self.selected_language = tk.StringVar(value='pt-BR') + self.subtitles_list = [] + + # Inicializar modelo Whisper e processador + self.initialize_whisper() + + # Dicionário de línguas disponíveis + self.languages = { + 'Português (Brasil)': 'pt', + 'Português (Portugal)': 'pt', + 'English': 'en', + 'Español': 'es', + 'Français': 'fr', + 'Deutsch': 'de', + 'Italiano': 'it' + } + + # Criar interface + self.create_widgets() + + # Variável para armazenar o vídeo + self.video = None + + def create_widgets(self): + # Frame principal + main_frame = ttk.Frame(self.root, padding="10") + main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S)) + + # Configurar expansão da grade + self.root.grid_rowconfigure(0, weight=1) + self.root.grid_columnconfigure(0, weight=1) + main_frame.grid_columnconfigure(1, weight=1) + + # Frame para seleção de arquivo e idioma + file_frame = ttk.Frame(main_frame) + file_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5) + + # Botão para selecionar arquivo + ttk.Button(file_frame, text="Selecionar Vídeo", command=self.select_file).pack(side=tk.LEFT, padx=5) + + # Seleção de idioma + ttk.Label(file_frame, text="Idioma:").pack(side=tk.LEFT, padx=5) + language_combo = ttk.Combobox(file_frame, + values=list(self.languages.keys()), + textvariable=self.selected_language, + state='readonly', + width=20) + language_combo.pack(side=tk.LEFT, padx=5) + language_combo.set('Português (Brasil)') + + # Label para mostrar caminho do arquivo + ttk.Label(main_frame, textvariable=self.video_path, wraplength=500).grid(row=1, column=0, columnspan=2, pady=5) + + # Frame para informações do vídeo + info_frame = ttk.LabelFrame(main_frame, text="Informações do Vídeo", padding="5") + info_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5) + + ttk.Label(info_frame, textvariable=self.video_info).grid(row=0, column=0, sticky=tk.W) + + # Frame para botões de ação + button_frame = ttk.Frame(main_frame) + button_frame.grid(row=3, column=0, columnspan=2, pady=5) + + ttk.Button(button_frame, text="Gerar Legendas", command=self.generate_subtitles).pack(side=tk.LEFT, padx=5) + ttk.Button(button_frame, text="Salvar Alterações", command=self.save_subtitles).pack(side=tk.LEFT, padx=5) + + # Progress bar + self.progress = ttk.Progressbar(main_frame, mode='indeterminate') + self.progress.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5) + + # Frame para edição de legendas + subtitle_frame = ttk.LabelFrame(main_frame, text="Editor de Legendas", padding="5") + subtitle_frame.grid(row=5, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=5) + subtitle_frame.grid_rowconfigure(0, weight=1) + subtitle_frame.grid_columnconfigure(0, weight=1) + + # Área de texto editável para legendas + self.subtitle_text = scrolledtext.ScrolledText(subtitle_frame, height=20, width=80, wrap=tk.WORD) + self.subtitle_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), padx=5, pady=5) + + # Instruções de uso + instructions = """Instruções: + 1. Selecione o idioma do áudio do vídeo + 2. Clique em 'Selecionar Vídeo' e escolha o arquivo + 3. Aguarde o processamento do modelo Whisper + 4. Edite as legendas se necessário + 5. Clique em 'Salvar Alterações' para gerar o arquivo .srt""" + + ttk.Label(main_frame, text=instructions, justify=tk.LEFT, wraplength=600).grid( + row=6, column=0, columnspan=2, pady=5, sticky=tk.W) + + def select_file(self): + filetypes = ( + ('Arquivos de vídeo', '*.mp4 *.avi *.mkv'), + ('Todos os arquivos', '*.*') + ) + + filename = filedialog.askopenfilename( + title='Selecione um vídeo', + filetypes=filetypes + ) + + if filename: + self.video_path.set(filename) + self.load_video_info(filename) + + def load_video_info(self, filename): + try: + self.video = cv2.VideoCapture(filename) + + # Obter informações do vídeo + fps = self.video.get(cv2.CAP_PROP_FPS) + frame_count = int(self.video.get(cv2.CAP_PROP_FRAME_COUNT)) + duration = frame_count / fps + width = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT)) + + info = f""" + Duração: {str(timedelta(seconds=int(duration)))} + Resolução: {width}x{height} + FPS: {fps:.2f} + Formato: {os.path.splitext(filename)[1]} + """ + self.video_info.set(info) + + except Exception as e: + messagebox.showerror("Erro", f"Erro ao carregar o vídeo: {str(e)}") + + def generate_subtitles(self): + if not self.video_path.get(): + messagebox.showwarning("Aviso", "Por favor, selecione um vídeo primeiro.") + return + + # Iniciar processamento em thread separada + self.progress.start() + thread = threading.Thread(target=self.process_video) + thread.start() + + def initialize_whisper(self): + """Inicializa o modelo Whisper e o processador com configurações otimizadas""" + try: + # Usar o modelo maior para melhor qualidade + model_name = "openai/whisper-large-v3" + self.processor = AutoProcessor.from_pretrained(model_name) + self.model = WhisperForConditionalGeneration.from_pretrained( + model_name, + device_map="auto", # Usar a melhor dispositivo disponível + torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, + low_cpu_mem_usage=True + ) + + if torch.cuda.is_available(): + print("Usando GPU para processamento") + else: + print("Usando CPU para processamento") + + except Exception as e: + messagebox.showerror("Erro", f"Erro ao carregar modelo Whisper: {str(e)}") + + def extract_audio(self, video_path, audio_path): + """Extrai o áudio do vídeo com configurações otimizadas""" + try: + print(f"Extraindo áudio de {video_path}") + + # Primeiro comando - qualidade máxima + command = [ + 'ffmpeg', + '-i', video_path, + '-vn', # Não processar vídeo + '-acodec', 'pcm_s16le', # Codec PCM 16-bit + '-ac', '1', # Mono + '-ar', '16000', # Taxa de amostragem para Whisper + '-af', 'volume=2.0,highpass=f=200,lowpass=f=3000,areverse,silenceremove=start_periods=1:start_duration=1:start_threshold=-60dB,areverse', # Filtros de áudio + '-y', # Sobrescrever arquivo + audio_path + ] + + print("Tentando primeira extração de áudio...") + process = subprocess.run( + command, + capture_output=True, + text=True, + encoding='utf-8' + ) + + if process.returncode != 0: + print("Primeira tentativa falhou, tentando método alternativo...") + # Comando alternativo - mais simples + alt_command = [ + 'ffmpeg', + '-i', video_path, + '-vn', + '-acodec', 'pcm_s16le', + '-ac', '1', + '-ar', '16000', + '-y', + audio_path + ] + process = subprocess.run( + alt_command, + capture_output=True, + text=True, + encoding='utf-8' + ) + + if os.path.exists(audio_path) and os.path.getsize(audio_path) > 0: + print(f"Áudio extraído com sucesso: {os.path.getsize(audio_path)} bytes") + return True + else: + raise Exception("Arquivo de áudio não foi criado ou está vazio") + + except Exception as e: + print(f"Erro detalhado na extração de áudio: {str(e)}") + if process and process.stderr: + print(f"Erro FFmpeg: {process.stderr}") + return False + + def process_audio_with_whisper(self, audio_path, language_code): + try: + import soundfile as sf + print(f"Processando áudio em {language_code}...") + + # Carregar áudio + audio, sample_rate = sf.read(audio_path) + print(f"Áudio carregado: {len(audio)} amostras, taxa de amostragem: {sample_rate}Hz") + + # Normalizar áudio + if audio.dtype == np.int16: + audio = audio.astype(np.float32) / 32768.0 + elif audio.dtype == np.int32: + audio = audio.astype(np.float32) / 2147483648.0 + + # Garantir que o áudio esteja entre -1 e 1 + max_abs = np.max(np.abs(audio)) + if max_abs > 1.0: + audio = audio / max_abs + + # Preparar input features com configurações explícitas + inputs = self.processor( + audio, + sampling_rate=sample_rate, + return_tensors="pt", + padding=True, + do_normalize=True, + return_attention_mask=True + ) + + print("Features de entrada processadas") + + # Mover para GPU se disponível + if torch.cuda.is_available(): + inputs = {k: v.to("cuda") for k, v in inputs.items()} + print("Dados movidos para GPU") + + # Configurar parâmetros de geração corrigidos + generate_kwargs = { + "temperature": 0.0, # Determinístico + "no_speech_threshold": 0.6, + "logprob_threshold": -1.0, + "compression_ratio_threshold": 2.4, + "condition_on_previous_text": True, + "max_initial_timestamp": 1.0, + "return_timestamps": True + } + + if language_code: + generate_kwargs["language"] = language_code + + print("Iniciando geração da transcrição...") + + # Gerar transcrição com timestamps + with torch.no_grad(): + outputs = self.model.generate( + inputs.input_features, + **generate_kwargs + ) + + print("Transcrição gerada, decodificando...") + + # Decodificar saída com timestamp_begin=True + transcription = self.processor.batch_decode( + outputs, + skip_special_tokens=True, + output_offsets=True + )[0] + + print(f"Transcrição decodificada: {len(transcription.text)} caracteres") + + if not transcription.text.strip(): + raise Exception("Transcrição vazia retornada pelo modelo") + + # Formatar segmentos com timestamps + segments = [] + for i, segment in enumerate(transcription.offsets, start=1): + start_time = self.format_timestamp(segment['timestamp'][0]) + end_time = self.format_timestamp(segment['timestamp'][1]) + text = segment['text'].strip() + + if text: # Só adicionar se houver texto + segment_str = f"{i}\n{start_time} --> {end_time}\n{text}\n\n" + segments.append(segment_str) + + print(f"Segmentos formatados: {len(segments)}") + return segments + + except Exception as e: + print(f"Erro detalhado no processamento do áudio: {str(e)}") + raise Exception(f"Erro no processamento do áudio: {str(e)}") + + def format_timestamp(self, seconds): + """Converte segundos em formato de timestamp SRT (HH:MM:SS,mmm)""" + hours = int(seconds // 3600) + minutes = int((seconds % 3600) // 60) + seconds = seconds % 60 + milliseconds = int((seconds % 1) * 1000) + seconds = int(seconds) + + return f"{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}" + + + def format_whisper_output(self, transcription): + """Formata a saída do Whisper em formato SRT""" + segments = [] + pattern = r"\[(\d+:\d+\.\d+) --> (\d+:\d+\.\d+)\](.*?)(?=\[|$)" + + matches = re.finditer(pattern, transcription, re.DOTALL) + + for idx, match in enumerate(matches, 1): + start_time = match.group(1) + end_time = match.group(2) + text = match.group(3).strip() + + # Converter para formato SRT + start_time = self.convert_timestamp_to_srt(start_time) + end_time = self.convert_timestamp_to_srt(end_time) + + segment = f"{idx}\n{start_time} --> {end_time}\n{text}\n\n" + segments.append(segment) + + return segments + + def convert_timestamp_to_srt(self, timestamp): + """Converte timestamp do Whisper para formato SRT""" + # Converter MM:SS.ms para HH:MM:SS,mmm + minutes, seconds = timestamp.split(":") + seconds, milliseconds = seconds.split(".") + + hours = int(minutes) // 60 + minutes = int(minutes) % 60 + + return f"{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}" + + def process_video(self): + try: + # Extrair áudio + audio_path = "temp_audio.wav" + print("Iniciando extração de áudio...") + + if not self.extract_audio(self.video_path.get(), audio_path): + raise Exception("Falha na extração do áudio") + + print("Áudio extraído com sucesso") + + # Obter código do idioma + selected_name = self.selected_language.get() + language_code = self.languages.get(selected_name, 'en') + print(f"Idioma selecionado: {selected_name} ({language_code})") + + # Processar áudio com Whisper + print("Iniciando reconhecimento de fala...") + self.subtitles_list = self.process_audio_with_whisper(audio_path, language_code) + + if not self.subtitles_list: + raise Exception("Nenhum texto foi reconhecido") + + print(f"Texto reconhecido com sucesso: {len(self.subtitles_list)} segmentos") + + # Mostrar legendas na interface + self.root.after(0, self.update_subtitle_text, ''.join(self.subtitles_list)) + + except Exception as e: + print(f"Erro no processamento: {str(e)}") + self.root.after(0, messagebox.showerror, "Erro", f"Erro ao gerar legendas: {str(e)}") + + finally: + # Limpar + self.root.after(0, self.progress.stop) + if self.video is not None: + self.video.release() + try: + if os.path.exists(audio_path): + print(f"Removendo arquivo temporário: {audio_path}") + os.remove(audio_path) + except Exception as e: + print(f"Erro ao remover arquivo temporário: {str(e)}") + + def update_subtitle_text(self, text): + self.subtitle_text.delete(1.0, tk.END) + self.subtitle_text.insert(tk.END, text) + + def save_subtitles(self): + try: + # Pegar texto atual + current_text = self.subtitle_text.get(1.0, tk.END).strip() + + # Validar formato básico das legendas + if not self.validate_subtitle_format(current_text): + raise ValueError("Formato de legendas inválido. Mantenha o formato: número + tempo + texto") + + # Salvar em arquivo + output_path = os.path.splitext(self.video_path.get())[0] + ".srt" + with open(output_path, 'w', encoding='utf-8') as f: + f.write(current_text) + + messagebox.showinfo("Sucesso", f"Legendas salvas com sucesso em:\n{output_path}") + + except Exception as e: + messagebox.showerror("Erro", f"Erro ao salvar legendas: {str(e)}") + + def validate_subtitle_format(self, text): + """Validação melhorada do formato das legendas""" + if not text.strip(): + return False + + lines = text.split('\n') + i = 0 + + while i < len(lines): + if not lines[i].strip(): + i += 1 + continue + + # Validar número da legenda + if not lines[i].strip().isdigit(): + return False + + # Validar formato do tempo + i += 1 + if i >= len(lines): + return False + + time_line = lines[i].strip() + if not (' --> ' in time_line and + time_line.count(':') == 4 and + len(time_line.split(' --> ')) == 2): + return False + + # Validar texto da legenda + i += 1 + if i >= len(lines) or not lines[i].strip(): + return False + + i += 1 + + return True + +if __name__ == "__main__": + root = tk.Tk() + app = VideoSubtitleApp(root) + root.mainloop() \ No newline at end of file