viditk commited on
Commit
d0ebd00
·
verified ·
1 Parent(s): a0de033

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -0
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor, AutoModelForSeq2SeqLM, AutoTokenizer
4
+ from IndicTransToolkit import IndicProcessor
5
+ import librosa
6
+ import numpy as np
7
+
8
+ # Constants
9
+ BATCH_SIZE = 4
10
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
11
+
12
+ # ---- Initialize Wav2Vec2 Model for Malayalam Speech Recognition ----
13
+ def initialize_wav2vec2_model(model_name):
14
+ processor = Wav2Vec2Processor.from_pretrained(model_name)
15
+ model = Wav2Vec2ForCTC.from_pretrained(model_name).to(DEVICE)
16
+ model.eval()
17
+ return processor, model
18
+
19
+ wav2vec2_model_name = "addy88/wav2vec2-malayalam-stt"
20
+ wav2vec2_processor, wav2vec2_model = initialize_wav2vec2_model(wav2vec2_model_name)
21
+
22
+ # ---- IndicTrans2 Model Initialization ----
23
+ def initialize_translation_model_and_tokenizer(ckpt_dir):
24
+ tokenizer = AutoTokenizer.from_pretrained(ckpt_dir, trust_remote_code=True)
25
+ model = AutoModelForSeq2SeqLM.from_pretrained(
26
+ ckpt_dir,
27
+ trust_remote_code=True,
28
+ low_cpu_mem_usage=True,
29
+ ).to(DEVICE)
30
+ model.eval()
31
+ return tokenizer, model
32
+
33
+ en_indic_ckpt_dir = "ai4bharat/indictrans2-indic-en-1B"
34
+ en_indic_tokenizer, en_indic_model = initialize_translation_model_and_tokenizer(en_indic_ckpt_dir)
35
+ ip = IndicProcessor(inference=True)
36
+
37
+ # ---- Batch Translation Function ----
38
+ def batch_translate(input_sentences, src_lang, tgt_lang, model, tokenizer, ip):
39
+ translations = []
40
+ for i in range(0, len(input_sentences), BATCH_SIZE):
41
+ batch = input_sentences[i : i + BATCH_SIZE]
42
+ batch = ip.preprocess_batch(batch, src_lang=src_lang, tgt_lang=tgt_lang)
43
+ inputs = tokenizer(
44
+ batch,
45
+ truncation=True,
46
+ padding="longest",
47
+ return_tensors="pt",
48
+ return_attention_mask=True,
49
+ ).to(DEVICE)
50
+
51
+ with torch.no_grad():
52
+ generated_tokens = model.generate(
53
+ **inputs,
54
+ use_cache=True,
55
+ min_length=0,
56
+ max_length=256,
57
+ num_beams=5,
58
+ num_return_sequences=1,
59
+ )
60
+
61
+ with tokenizer.as_target_tokenizer():
62
+ generated_tokens = tokenizer.batch_decode(
63
+ generated_tokens.detach().cpu().tolist(),
64
+ skip_special_tokens=True,
65
+ clean_up_tokenization_spaces=True,
66
+ )
67
+
68
+ translations += ip.postprocess_batch(generated_tokens, lang=tgt_lang)
69
+ del inputs
70
+ torch.cuda.empty_cache()
71
+
72
+ return translations
73
+
74
+ # ---- Gradio Function ----
75
+ def transcribe_and_translate(audio):
76
+ try:
77
+ # Load audio using librosa and force sample rate to 16kHz
78
+ audio_input, sample_rate = librosa.load(audio, sr=16000)
79
+
80
+ # Normalize audio
81
+ if np.max(np.abs(audio_input)) != 0:
82
+ audio_input = audio_input / np.max(np.abs(audio_input))
83
+
84
+ except Exception as e:
85
+ return f"Error reading audio: {e}", ""
86
+
87
+ # Process audio
88
+ input_values = wav2vec2_processor(audio_input, sampling_rate=sample_rate, return_tensors="pt").input_values.to(DEVICE)
89
+
90
+ # Perform inference
91
+ with torch.no_grad():
92
+ logits = wav2vec2_model(input_values).logits
93
+ predicted_ids = torch.argmax(logits, dim=-1)
94
+
95
+ # Decode transcription
96
+ malayalam_text = wav2vec2_processor.decode(predicted_ids[0].cpu(), skip_special_tokens=True)
97
+
98
+ # Translation
99
+ en_sents = [malayalam_text]
100
+ src_lang, tgt_lang = "mal_Mlym", "eng_Latn"
101
+ translations = batch_translate(en_sents, src_lang, tgt_lang, en_indic_model, en_indic_tokenizer, ip)
102
+
103
+ return malayalam_text, translations[0]
104
+
105
+ # ---- Gradio Interface ----
106
+ iface = gr.Interface(
107
+ fn=transcribe_and_translate,
108
+ inputs=gr.Audio(sources=["microphone", "upload"], type="filepath"),
109
+ outputs=[
110
+ gr.Textbox(label="Malayalam Transcription"),
111
+ gr.Textbox(label="English Translation")
112
+ ],
113
+ title="Malayalam Speech Recognition & Translation",
114
+ description="Speak in Malayalam → Transcribe using Wav2Vec2 → Translate to English using IndicTrans2."
115
+ )
116
+
117
+ iface.launch(debug=True, share=True)