File size: 6,034 Bytes
d7ba1b9
 
 
 
 
 
 
 
 
 
 
 
 
 
c0561a7
d7ba1b9
c0561a7
d7ba1b9
 
 
 
 
 
b68a112
d7ba1b9
 
c0561a7
d7ba1b9
b68a112
0e4db4a
d7ba1b9
 
 
 
 
 
 
 
 
 
 
 
 
e21f7ff
 
d7ba1b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e4db4a
 
 
 
 
 
d7ba1b9
 
 
 
 
 
 
 
 
 
 
 
 
 
0e4db4a
d7ba1b9
 
 
 
 
 
 
 
 
 
e21f7ff
 
 
 
 
d7ba1b9
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
from __future__ import annotations

import os

import gradio as gr

import torch
import torchaudio

import spaces

import nemo.collections.asr as nemo_asr

LANGUAGE_NAME_TO_CODE = {
    
    "Hindi": "hi",
    
}


DESCRIPTION = """\
### **IndicConformer: Speech Recognition for Indian Languages** πŸŽ™οΈβž‘οΈπŸ“œ  

**IndicConformer**, a speech recognition model for **22 Indian languages**. The model operates in two modes: **CTC (Connectionist Temporal Classification)** and **RNNT (Recurrent Neural Network Transducer)**

#### **How to Use:**  
1. **Upload or record** an audio clip in Hindi.  
2. Select the **mode** (CTC or RNNT) for transcription.  
3. Click **"Transcribe"** to generate the corresponding text.    

"""

hf_token = os.getenv("HF_TOKEN")
device = "cuda:0" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
torch_dtype = torch.bfloat16 if device != "cpu" else torch.float32
model_name_or_path = "ai4bharat/IndicConformer"
model = nemo_asr.models.EncDecCTCModel.from_pretrained(model_name_or_path).to(device)
# model = nemo_asr.models.EncDecCTCModel.restore_from("indicconformer_stt_bn_hybrid_rnnt_large.nemo").to(device)
model.eval()

CACHE_EXAMPLES = os.getenv("CACHE_EXAMPLES") == "1" and torch.cuda.is_available()

AUDIO_SAMPLE_RATE = 16000
MAX_INPUT_AUDIO_LENGTH = 600  # in seconds
DEFAULT_TARGET_LANGUAGE = "Hindi"

@spaces.GPU
def run_asr_ctc(input_audio: str, target_language: str) -> str:
    lang_id = LANGUAGE_NAME_TO_CODE[target_language]

    # Load and preprocess audio
    audio_tensor, orig_freq = torchaudio.load(input_audio)
    
    # Convert to mono if not already
    if audio_tensor.shape[0] > 1:
        audio_tensor = torch.mean(audio_tensor, dim=0, keepdim=True)
    
    # Ensure shape [B x T]
    if len(audio_tensor.shape) == 1:
        audio_tensor = audio_tensor.unsqueeze(0)  # Add batch dimension if missing

    if audio_tensor.ndim > 1:
        audio_tensor = audio_tensor.squeeze(0)
    
    # Resample to 16kHz
    audio_tensor = torchaudio.functional.resample(audio_tensor, orig_freq=orig_freq, new_freq=16000)
    
    model.cur_decoder = "ctc"
    ctc_text = model.transcribe([audio_tensor.numpy()], batch_size=1, logprobs=False, language_id=lang_id)[0]
    
    return ctc_text[0]

# @spaces.GPU
# def run_asr_ctc(input_audio: str, target_language: str) -> str:
#     # preprocess_audio(input_audio)
#     # input_audio, orig_freq = torchaudio.load(input_audio)
#     # input_audio = torchaudio.functional.resample(input_audio, orig_freq=orig_freq, new_freq=16000)
#     lang_id = LANGUAGE_NAME_TO_CODE[target_language]

#     model.cur_decoder = "ctc"
#     ctc_text = model.transcribe([input_audio], batch_size=1, logprobs=False, language_id=lang_id)[0]

#     return ctc_text[0]

@spaces.GPU
def run_asr_rnnt(input_audio: str, target_language: str) -> str:
    lang_id = LANGUAGE_NAME_TO_CODE[target_language]

    # Load and preprocess audio
    audio_tensor, orig_freq = torchaudio.load(input_audio)
    
    # Convert to mono if not already
    if audio_tensor.shape[0] > 1:
        audio_tensor = torch.mean(audio_tensor, dim=0, keepdim=True)
    
    # Ensure shape [B x T]
    if len(audio_tensor.shape) == 1:
        audio_tensor = audio_tensor.unsqueeze(0)  # Add batch dimension if missing

    if audio_tensor.ndim > 1:
        audio_tensor = audio_tensor.squeeze(0)
    
    # Resample to 16kHz
    audio_tensor = torchaudio.functional.resample(audio_tensor, orig_freq=orig_freq, new_freq=16000)
    
    model.cur_decoder = "rnnt"
    ctc_text = model.transcribe([audio_tensor.numpy()], batch_size=1, logprobs=False, language_id=lang_id)[0]
    
    return ctc_text[0]

# @spaces.GPU
# def run_asr_rnnt(input_audio: str, target_language: str) -> str:
#     # preprocess_audio(input_audio)
#     # input_audio, orig_freq = torchaudio.load(input_audio)
#     # input_audio = torchaudio.functional.resample(input_audio, orig_freq=orig_freq, new_freq=16000)
#     lang_id = LANGUAGE_NAME_TO_CODE[target_language]

#     model.cur_decoder = "rnnt"
#     ctc_text = model.transcribe([input_audio], batch_size=1,logprobs=False, language_id=lang_id)[0]

#     return ctc_text[0]



with gr.Blocks() as demo_asr_ctc:
    with gr.Row():
        with gr.Column():
            with gr.Group():
                input_audio = gr.Audio(label="Input speech", type="filepath")
                target_language = gr.Dropdown(
                    label="Target language",
                    choices=LANGUAGE_NAME_TO_CODE.keys(),
                    value=DEFAULT_TARGET_LANGUAGE,
                )
            btn = gr.Button("Transcribe")
        with gr.Column():
            output_text = gr.Textbox(label="Transcribed text")
    btn.click(
        fn=run_asr_ctc,
        inputs=[input_audio, target_language],
        outputs=output_text,
        api_name="asr",
    )

with gr.Blocks() as demo_asr_rnnt:
    with gr.Row():
        with gr.Column():
            with gr.Group():
                input_audio = gr.Audio(label="Input speech", type="filepath")
                target_language = gr.Dropdown(
                    label="Target language",
                    choices=LANGUAGE_NAME_TO_CODE.keys(),
                    value=DEFAULT_TARGET_LANGUAGE,
                )
            btn = gr.Button("Transcribe")
        with gr.Column():
            output_text = gr.Textbox(label="Transcribed text")

    btn.click(
        fn=run_asr_rnnt,
        inputs=[input_audio, target_language],
        outputs=output_text,
        api_name="asr",
    )


with gr.Blocks(css="style.css") as demo:
    gr.Markdown(DESCRIPTION)
#    gr.DuplicateButton(
#        value="Duplicate Space for private use",
#        elem_id="duplicate-button",
#        visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
#    )

    with gr.Tabs():
        with gr.Tab(label="CTC"):
            demo_asr_ctc.render()
        with gr.Tab(label="RNNT"):
            demo_asr_rnnt.render()


if __name__ == "__main__":
    demo.queue(max_size=50).launch()