|
import librosa |
|
from transformers import Wav2Vec2ForCTC, AutoProcessor |
|
import torch |
|
import json |
|
|
|
from huggingface_hub import hf_hub_download |
|
from torchaudio.models.decoder import ctc_decoder |
|
|
|
ASR_SAMPLING_RATE = 16_000 |
|
|
|
ASR_LANGUAGES = {} |
|
with open(f"data/asr/all_langs.tsv") as f: |
|
for line in f: |
|
iso, name = line.split(" ", 1) |
|
ASR_LANGUAGES[iso] = name |
|
|
|
MODEL_ID = "facebook/mms-1b-all" |
|
|
|
processor = AutoProcessor.from_pretrained(MODEL_ID) |
|
model = Wav2Vec2ForCTC.from_pretrained(MODEL_ID) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def transcribe( |
|
audio_source=None, microphone=None, file_upload=None, lang="eng (English)" |
|
): |
|
if type(microphone) is dict: |
|
|
|
microphone = microphone["name"] |
|
audio_fp = ( |
|
file_upload if "upload" in str(audio_source or "").lower() else microphone |
|
) |
|
|
|
if audio_fp is None: |
|
return "ERROR: You have to either use the microphone or upload an audio file" |
|
|
|
audio_samples = librosa.load(audio_fp, sr=ASR_SAMPLING_RATE, mono=True)[0] |
|
|
|
lang_code = lang.split()[0] |
|
processor.tokenizer.set_target_lang(lang_code) |
|
model.load_adapter(lang_code) |
|
|
|
inputs = processor( |
|
audio_samples, sampling_rate=ASR_SAMPLING_RATE, return_tensors="pt" |
|
) |
|
|
|
|
|
if torch.cuda.is_available(): |
|
device = torch.device("cuda") |
|
elif ( |
|
hasattr(torch.backends, "mps") |
|
and torch.backends.mps.is_available() |
|
and torch.backends.mps.is_built() |
|
): |
|
device = torch.device("mps") |
|
else: |
|
device = torch.device("cpu") |
|
|
|
model.to(device) |
|
inputs = inputs.to(device) |
|
|
|
with torch.no_grad(): |
|
outputs = model(**inputs).logits |
|
|
|
if lang_code != "eng" or True: |
|
ids = torch.argmax(outputs, dim=-1)[0] |
|
transcription = processor.decode(ids) |
|
else: |
|
assert False |
|
|
|
|
|
|
|
return transcription |
|
|
|
|
|
ASR_EXAMPLES = [ |
|
[None, "assets/føroyskt1.wav", None, "fao (Faroese)"], |
|
[None, "assets/føroyskt2.wav", None, "fao (Faroese)"], |
|
[None, "assets/føroyskt3.wav", None, "fao (Faroese)"], |
|
[None, "assets/føroyskt4.wav", None, "fao (Faroese)"], |
|
] |
|
|
|
ASR_NOTE = """ |
|
Talukennarin omanfyri brúkar ikki beam-search decoding, tá ið hann brúkar málmyndilin. |
|
Les hesa [vegleiðingina](https://huggingface.co/facebook/mms-1b-all), sum greiðir frá, hvussu tú kanst koyra LM decoding og fáa betri talukenning. |
|
""" |
|
|