TifinLab commited on
Commit
62f29a3
1 Parent(s): 5164063

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import Wav2Vec2ForCTC, AutoProcessor
3
+ import torch
4
+ import librosa
5
+ import json
6
+
7
+ with open('ISO_codes.json', 'r') as file:
8
+ iso_codes = json.load(file)
9
+
10
+ languages = list(iso_codes.keys())
11
+
12
+ model_id = "facebook/mms-1b-all"
13
+ processor = AutoProcessor.from_pretrained(model_id)
14
+ model = Wav2Vec2ForCTC.from_pretrained(model_id)
15
+
16
+ def transcribe(audio_file_mic=None, audio_file_upload=None, language="English (eng)"):
17
+ if audio_file_mic:
18
+ audio_file = audio_file_mic
19
+ elif audio_file_upload:
20
+ audio_file = audio_file_upload
21
+ else:
22
+ return "Please upload an audio file or record one"
23
+
24
+ # Make sure audio is 16kHz
25
+ speech, sample_rate = librosa.load(audio_file)
26
+ if sample_rate != 16000:
27
+ speech = librosa.resample(speech, orig_sr=sample_rate, target_sr=16000)
28
+
29
+ # Keep the same model in memory and simply switch out the language adapters by calling load_adapter() for the model and set_target_lang() for the tokenizer
30
+ language_code = iso_codes[language]
31
+ processor.tokenizer.set_target_lang(language_code)
32
+ model.load_adapter(language_code)
33
+
34
+ inputs = processor(speech, sampling_rate=16_000, return_tensors="pt")
35
+
36
+ with torch.no_grad():
37
+ outputs = model(**inputs).logits
38
+
39
+ ids = torch.argmax(outputs, dim=-1)[0]
40
+ transcription = processor.decode(ids)
41
+ return transcription
42
+
43
+ examples = [["kab_1.mp3", None, "Amazigh (kab)"],
44
+ ["kab_2.mp3", None, "Amazigh (kab)"]]
45
+
46
+ description = '''Automatic Speech Recognition with [MMS](https://ai.facebook.com/blog/multilingual-model-speech-recognition/) (Massively Multilingual Speech) by Meta.
47
+ Supports [1162 languages](https://dl.fbaipublicfiles.com/mms/misc/language_coverage_mms.html). Read the paper for more details: [Scaling Speech Technology to 1,000+ Languages](https://arxiv.org/abs/2305.13516).'''
48
+
49
+ iface = gr.Interface(fn=transcribe,
50
+ inputs=[
51
+ gr.Audio(source="microphone", type="filepath", label="Record Audio"),
52
+ gr.Audio(source="upload", type="filepath", label="Upload Audio"),
53
+ gr.Dropdown(choices=languages, label="Language", value="English (eng)")
54
+ ],
55
+ outputs=gr.Textbox(label="Transcription"),
56
+ examples=examples,
57
+ description=description
58
+ )
59
+ iface.launch()