Automatic Speech Recognition
Transformers
PyTorch
TensorFlow
JAX
Safetensors
English
whisper
audio
hf-asr-leaderboard
Eval Results (legacy)
Eval Results
Run this model with HF Jobs
Run openai/whisper-medium.en on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/openai/whisper-medium.en. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/openai/whisper-medium.en on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use openai/whisper-medium.en with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use openai/whisper-medium.en with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("automatic-speech-recognition", model="openai/whisper-medium.en")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForSpeechSeq2Seq processor = AutoProcessor.from_pretrained("openai/whisper-medium.en") model = AutoModelForSpeechSeq2Seq.from_pretrained("openai/whisper-medium.en", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Commit ·
a8f3af2
1
Parent(s): e3bd65e
Update README.md (#6)
Browse files- Update README.md (a43c9dc3eafffa30c6ad3bea53620565a79f9c7c)
44 unmodified lines4546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316430 unmodified lines19519619719819920020120220320420520644 unmodified lineslicense: apache-2.0---# Whisper[OpenAI's Whisper](https://openai.com/blog/whisper/)The Whisper model was proposed in [Robust Speech Recognition via Large-Scale Weak Supervision](https://cdn.openai.com/papers/whisper.pdf) by Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever.**Disclaimer**: Content from **this** model card has been written by the Hugging Face team, and parts of it were copy pasted from the original model card.## IntroThe first paragraphs of the abstract read as follows :> 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.The original code repository can be found [here](https://github.com/openai/whisper).## Model detailsThe Whisper models are trained for speech recognition and translation tasks, capable of transcribing speech audio into the text in the language it is spoken (ASR) as well as translated into English (speech translation). Researchers at OpenAI developed the models to study the robustness of speech processing systems trained under large-scale weak supervision. There are 9 models of different sizes and capabilities, summarised in the following table.| Size | Parameters | English-only model | Multilingual model ||:------:|:----------:|:------------------:|:------------------:|| tiny | 39 M | ✓ | ✓ || base | 74 M | ✓ | ✓ || small | 244 M | ✓ | ✓ || medium | 769 M | ✓ | ✓ || large | 1550 M | | ✓ |## Model descriptionWhisper is an auto-regressive automatic speech recognition encoder-decoder model that was trained on 680 000 hours of 16kHz sampled multilingual audio. It was fully trained in a supervised manner, with multiple tasks :- English transcription- Any-to-English speech translation- Non-English transcription- No speech predictionTo each task corresponds a sequence of tokens that are given to the decoder as *context tokens*. The beginning of a transcription always starts with `<|startoftranscript|>` which is why the `decoder_start_token` is always set to `tokenizer.encode("<|startoftranscript|>")`. The following token should be the language token, which is automatically detected in the original code. Finally, the task is define using either `<|transcribe|>` or `<|translate|>`. In addition, a `<|notimestamps|>` token is added if the task does not include timestamp prediction.# UsageTo transcribe or translate audio files, the model has to be used along a `WhisperProcessor`. The `WhisperProcessor.get_decoder_prompt_ids` function is used to get a list of `( idx, token )` tuples, which can either be set in the config, or directly passed to the generate function, as `forced_decoder_ids`.## TranscriptionIn the following example, the english only model is used. We set the `decoder_input_ids` accordingly.### English to englishThe "<|en|>" token is used to specify that the speech is in english and should be transcribed to english```python>>> from transformers import WhisperProcessor, WhisperForConditionalGeneration>>> from datasets import load_dataset>>> import torch>>> # load model and processor>>> processor = WhisperProcessor.from_pretrained("openai/whisper-medium.en")>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-medium.en")>>> # load dummy dataset and read soundfiles>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")>>> input_features = processor(ds[0]["audio"]["array"], return_tensors="pt").input_features>>> # Generate logits>>> logits = model(input_features, decoder_input_ids = torch.tensor([[50258]]).logits>>> # take argmax and decode>>> predicted_ids = torch.argmax(logits, dim=-1)>>> transcription = processor.batch_decode(predicted_ids)['<|startoftranscript|>']```## EvaluationThis code snippet shows how to evaluate **openai/whisper-medium.en** on LibriSpeech's "clean" and "other" test data.```python>>> from datasets import load_dataset>>> from transformers import WhisperForConditionalGeneration, WhisperProcessor>>> import soundfile as sf>>> import torch>>> from evaluate import load>>> librispeech_eval = load_dataset("librispeech_asr", "clean", split="test")>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-medium.en").to("cuda")>>> processor = WhisperProcessor.from_pretrained("openai/whisper-medium.en")>>> def map_to_pred(batch):>>> input_features = processor(batch["audio"]["array"], return_tensors="pt").input_features>>> with torch.no_grad():>>> logits = model(input_features.to("cuda")).logits>>> predicted_ids = torch.argmax(logits, dim=-1)>>> transcription = processor.batch_decode(predicted_ids, normalize = True)>>> batch['text'] = processor.tokenizer._normalize(batch['text'])>>> batch["transcription"] = transcription>>> return batch>>> result = librispeech_eval.map(map_to_pred, batched=True, batch_size=1, remove_columns=["speech"])>>> wer = load("wer")>>> print(wer.compute(predictions=ds["text"], references=ds["transcription"]))0.07639504403417127```### Evaluated Use30 unmodified lines### BibTeX entry and citation info*Since no official citation was provided, we use the following in the mean time*```bibtex@misc{radford2022whisper,title={Robust Speech Recognition via Large-Scale Weak Supervision.},author={Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever},year={2022},url={https://cdn.openai.com/papers/whisper.pdf},}```44 unmodified lines4546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619730 unmodified lines22822923023123223323423523623723823924024144 unmodified lineslicense: apache-2.0---# WhisperWhisper is a pre-trained model for automatic speech recognition (ASR) and speech translation. Trained on 680k hoursof labelled data, Whisper models demonstrate a strong ability to generalise to many datasets and domains **without** the needfor fine-tuning.Whisper was proposed in the paper [Robust Speech Recognition via Large-Scale Weak Supervision](https://arxiv.org/abs/2212.04356)by Alec Radford et al. from OpenAI. The original code repository can be found [here](https://github.com/openai/whisper).**Disclaimer**: Content for this model card has partly been written by the Hugging Face team, and parts of it werecopied and pasted from the original model card.## Model detailsWhisper is a Transformer based encoder-decoder model, also referred to as a _sequence-to-sequence_ model.It was trained on 680k hours of labelled speech data annotated using large-scale weak supervision.The models were trained on either English-only data or multilingual data. The English-only models were trainedon the task of speech recognition. The multilingual models were trained on both speech recognition and speechtranslation. For speech recognition, the model predicts transcriptions in the *same* language as the audio.For speech translation, the model predicts transcriptions to a *different* language to the audio.Whisper checkpoints come in five configurations of varying model sizes.The smallest four are trained on either English-only or multilingual data.The largest checkpoints are multilingual only. All ten of the pre-trained checkpointsare available on the [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper). Thecheckpoints are summarised in the following table with links to the models on the Hub:| Size | Parameters | English-only | Multilingual ||----------|------------|------------------------------------------------------|-----------------------------------------------------|| tiny | 39 M | [✓](https://huggingface.co/openai/whisper-tiny.en) | [✓](https://huggingface.co/openai/whisper-tiny) || base | 74 M | [✓](https://huggingface.co/openai/whisper-base.en) | [✓](https://huggingface.co/openai/whisper-base) || small | 244 M | [✓](https://huggingface.co/openai/whisper-small.en) | [✓](https://huggingface.co/openai/whisper-small) || medium | 769 M | [✓](https://huggingface.co/openai/whisper-medium.en) | [✓](https://huggingface.co/openai/whisper-medium) || large | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large) || large-v2 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large-v2) |# UsageThis checkpoint is an *English-only* model, meaning it can be used for English speech recognition. Multilingual speechrecognition or speech translation is possible through use of a multilingual checkpoint.To transcribe audio samples, the model has to be used alongside a [`WhisperProcessor`](https://huggingface.co/docs/transformers/model_doc/whisper#transformers.WhisperProcessor).The `WhisperProcessor` is used to:1. Pre-process the audio inputs (converting them to log-Mel spectrograms for the model)2. Post-process the model outputs (converting them from tokens to text)## Transcription```python>>> from transformers import WhisperProcessor, WhisperForConditionalGeneration>>> from datasets import load_dataset>>> # load model and processor>>> processor = WhisperProcessor.from_pretrained("openai/whisper-medium.en")>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-medium.en")>>> # load dummy dataset and read audio files>>> 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>>> # generate token ids>>> predicted_ids = model.generate(input_features)>>> # decode token ids to text>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=False)['<|startoftranscript|><|notimestamps|> Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.<|endoftext|>']>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[' Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.']```The context tokens can be removed from the start of the transcription by setting `skip_special_tokens=True`.## EvaluationThis code snippet shows how to evaluate Whisper medium.en on [LibriSpeech test-clean](https://huggingface.co/datasets/librispeech_asr):```python>>> from datasets import load_dataset>>> from transformers import WhisperForConditionalGeneration, WhisperProcessor>>> import torch>>> from evaluate import load>>> librispeech_test_clean = load_dataset("librispeech_asr", "clean", split="test")>>> processor = WhisperProcessor.from_pretrained("openai/whisper-medium.en")>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-medium.en").to("cuda")>>> def map_to_pred(batch):>>> audio = batch["audio"]>>> input_features = processor(audio["array"], sampling_rate=audio["sampling_rate"], return_tensors="pt").input_features>>> batch["reference"] = processor.tokenizer._normalize(batch['text'])>>>>>> with torch.no_grad():>>> predicted_ids = model.generate(input_features.to("cuda"))[0]>>> transcription = processor.decode(predicted_ids)>>> batch["prediction"] = processor.tokenizer._normalize(transcription)>>> return batch>>> result = librispeech_test_clean.map(map_to_pred)>>> wer = load("wer")>>> print(100 * wer.compute(references=result["reference"], predictions=result["prediction"]))3.0154449620004904```## Long-Form TranscriptionThe Whisper model is intrinsically designed to work on audio samples of up to 30s in duration. However, by using a chunkingalgorithm, it can be used to transcribe audio samples of up to arbitrary length. This is possible through Transformers[`pipeline`](https://huggingface.co/docs/transformers/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline)method. Chunking is enabled by setting `chunk_length_s=30` when instantiating the pipeline. It can also be extended topredict utterance level timestamps by passing `return_timestamps=True`:```python>>> import torch>>> from transformers import pipeline>>> from datasets import load_dataset>>> device = "cuda:0" if torch.cuda.is_available() else "cpu">>> pipe = pipeline(>>> "automatic-speech-recognition",>>> model="openai/whisper-medium.en",>>> chunk_length_s=30,>>> device=device,>>> )>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")>>> sample = ds[0]["audio"]>>> prediction = pipe(sample)["text"]" Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.">>> # we can also return timestamps for the predictions>>> prediction = pipe(sample, return_timestamps=True)["chunks"][{'text': ' Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.','timestamp': (0.0, 5.44)}]```## Fine-TuningThe pre-trained Whisper model demonstrates a strong ability to generalise to different datasets and domains. However,its predictive capabilities can be improved further for certain languages and tasks through *fine-tuning*. The blogpost [Fine-Tune Whisper with 🤗 Transformers](https://huggingface.co/blog/fine-tune-whisper) provides a step-by-stepguide to fine-tuning the Whisper model with as little as 5 hours of labelled data.### Evaluated Use30 unmodified lines### BibTeX entry and citation info```bibtex@misc{radford2022whisper,doi = {10.48550/ARXIV.2212.04356},url = {https://arxiv.org/abs/2212.04356},author = {Radford, Alec and Kim, Jong Wook and Xu, Tao and Brockman, Greg and McLeavey, Christine and Sutskever, Ilya},title = {Robust Speech Recognition via Large-Scale Weak Supervision},publisher = {arXiv},year = {2022},copyright = {arXiv.org perpetual, non-exclusive license}}```
README.md+108-73