File size: 7,238 Bytes
6f63a5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import os
import spaces
import torch
import torchaudio
import gradio as gr
import logging
from whosper import WhosperTranscriber


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


if torch.cuda.is_available():
    device = "cuda"
    logger.info("Using CUDA for inference.")
elif torch.backends.mps.is_available():
    device = "mps"
    logger.info("Using MPS for inference.")
else:
    device = "cpu"
    logger.info("Using CPU for inference.")


model_id = "sudoping01/maliba-asr-v1"
transcriber = WhosperTranscriber(model_id=model_id)
logger.info(f"Transcriber initialized with model: {model_id}")

def resample_audio(audio_path, target_sample_rate=16000):

    """
    Converts the audio file to the target sampling rate (16000 Hz).
    
    Args:
        audio_path (str): Path to the audio file.
        target_sample_rate (int): The desired sample rate.
    Returns:
        A tensor containing the resampled audio data and the target sample rate.
    """
    try:
        waveform, original_sample_rate = torchaudio.load(audio_path)
        
        if original_sample_rate != target_sample_rate:
            resampler = torchaudio.transforms.Resample(
                orig_freq=original_sample_rate, 
                new_freq=target_sample_rate
            )
            waveform = resampler(waveform)
        
        return waveform, target_sample_rate
    except Exception as e:
        logger.error(f"Error resampling audio: {e}")
        raise e

@spaces.GPU()
def transcribe_audio(audio_file):

    """
    Transcribes the provided audio file into Bambara text using Whosper.
    
    Args:
        audio_file: The path to the audio file to transcribe.
    Returns:
        A string representing the transcribed Bambara text.
    """

    if audio_file is None:
        return "Please provide an audio file for transcription."
    
    try:
        logger.info(f"Transcribing audio file: {audio_file}")
        

        result = transcriber.transcribe_audio(audio_file)
        
        logger.info("Transcription successful.")
        return result
        
    except Exception as e:
        logger.error(f"Transcription failed: {e}")
        return f"Error during transcription: {str(e)}"

def get_example_files(directory="./examples"):

    """
    Returns a list of audio files from the examples directory.
    
    Args:
        directory (str): The directory to search for audio files.
    Returns:
        list: A list of paths to the audio files.
    """

    if not os.path.exists(directory):
        logger.warning(f"Examples directory {directory} not found.")
        return []
    

    audio_extensions = ['.wav', '.mp3', '.m4a', '.flac', '.ogg']
    audio_files = []
    
    try:
        files = os.listdir(directory)
        for file in files:
            if any(file.lower().endswith(ext) for ext in audio_extensions):
                full_path = os.path.abspath(os.path.join(directory, file))
                audio_files.append(full_path)
        
        logger.info(f"Found {len(audio_files)} example audio files.")
        return audio_files[:5]  
        
    except Exception as e:
        logger.error(f"Error reading examples directory: {e}")
        return []

def build_interface():
    """
    Builds the Gradio interface for Bambara speech recognition.
    """

    example_files = get_example_files()
    
    with gr.Blocks(title="Bambara Speech Recognition") as demo:
        gr.Markdown(
            """
            # 🎀 Bambara Automatic Speech Recognition
            
            **Powered by MALIBA-AI**
            
            Convert Bambara speech to text using our state-of-the-art ASR model. You can either:
            - πŸŽ™οΈ **Record** your voice directly
            - πŸ“ **Upload** an audio file
            - 🎡 **Try** our example audio files
            
            ## Supported Audio Formats
            WAV, MP3, M4A, FLAC, OGG
            """
        )
        
        with gr.Row():
            with gr.Column():

                audio_input = gr.Audio(
                    label="🎀 Record or Upload Audio",
                    type="filepath",
                    sources=["microphone", "upload"]
                )
                
                transcribe_btn = gr.Button(
                    "πŸ”„ Transcribe Audio", 
                    variant="primary",
                    size="lg"
                )
                

                clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
            
            with gr.Column():
                output_text = gr.Textbox(
                    label="πŸ“ Transcribed Text (Bambara)",
                    lines=8,
                    placeholder="Your transcribed Bambara text will appear here...",
                    interactive=False
                )
        
        # Examples section
        if example_files:
            gr.Markdown("## 🎡 Try These Examples")
            gr.Examples(
                examples=[[f] for f in example_files],
                inputs=[audio_input],
                outputs=output_text,
                fn=transcribe_audio,
                cache_examples=False,
                label="Example Audio Files"
            )
        
        # Information section
        gr.Markdown(
            """
            ---
            
            ## ℹ️ About This Model
            
            - **Model:** [sudoping01/maliba-asr-v1](https://huggingface.co/sudoping01/maliba-asr-v1)
            - **Developer:** MALIBA-AI
            - **Language:** Bambara (bm)
            - **Task:** Automatic Speech Recognition (ASR)
            - **Sample Rate:** 16kHz (automatically resampled)
            
            ## πŸš€ How to Use
            
            1. **Record Audio:** Click the microphone button and speak in Bambara
            2. **Upload File:** Click the upload button to select an audio file
            3. **Transcribe:** Click the "Transcribe Audio" button
            4. **View Results:** See your transcribed text in Bambara
            
            ## πŸ“Š Performance Notes
            
            - Best results with clear speech and minimal background noise
            - Supports various audio formats and durations
            - Optimized for Bambara language patterns and phonetics
            """
        )
        

        transcribe_btn.click(
            fn=transcribe_audio,
            inputs=[audio_input],
            outputs=output_text,
            show_progress=True
        )
        
        clear_btn.click(
            fn=lambda: (None, ""),
            outputs=[audio_input, output_text]
        )
        

        audio_input.change(
            fn=transcribe_audio,
            inputs=[audio_input],
            outputs=output_text,
            show_progress=True
        )
    
    return demo

def main():
    """
    Main function to launch the Gradio interface.
    """
    logger.info("Starting Bambara ASR Gradio interface.")
    

    interface = build_interface()
    interface.launch(
        share=False,
        server_name="0.0.0.0",
        server_port=7860
    )
    
    logger.info("Gradio interface launched successfully.")

if __name__ == "__main__":
    main()