Certainly! You can integrate Vosk-based speech recognition into your Gradio application by replacing the existing speech_recognition (which uses Google’s API) with Vosk. This approach is beneficial if you prefer an offline solution or want more control over the speech recognition process.
Below is a comprehensive guide to modifying your Gradio application to use Vosk for speech-to-text functionality.
Step 1: Install Required Dependencies
First, ensure you have all the necessary libraries installed. You can install them using pip:
pip install gradio numpy soundfile vosk librosa
- gradio: For creating the web interface.
- numpy: For numerical operations on audio data.
- soundfile: For handling audio file reading and writing.
- vosk: For offline speech recognition.
- librosa: For audio processing, especially resampling.
Step 2: Download a Vosk Model
Vosk requires a pre-trained model to perform speech recognition. Download a suitable model from Vosk Models. For English, you can use:
- Small Model (lightweight and faster):
vosk-model-small-en-us-0.15
- Large Model (more accurate):
vosk-model-en-us-0.22
After downloading, extract the model and note its path. For this guide, we'll assume you've extracted vosk-model-small-en-us-0.15 in the current directory.
Step 3: Update the Gradio Application
Here's the complete Gradio application integrating Vosk for speech recognition:
import os
import gradio as gr
import numpy as np
import soundfile as sf
import logging
import vosk
import librosa
# Configure logging
logging.basicConfig(
filename='speech_recognition.log',
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Initialize history list
text_history = []
# Set the model path
model_path = "vosk-model-small-en-us-0.15" # Update this path if different
# Check if the model exists
if not os.path.exists(model_path):
logging.error(f"Model not found at {model_path}. Please download a model from https://alphacephei.com/vosk/models")
raise FileNotFoundError(f"Model not found at {model_path}. Please download a model from https://alphacephei.com/vosk/models")
# Initialize the Vosk model
model = vosk.Model(model_path)
# Define the expected sample rate
RATE = 16000 # Vosk models typically expect 16kHz
def speech_to_text(audio):
"""
Transcribe speech from an audio input using Vosk.
Parameters:
audio (tuple): A tuple containing the sample rate and the numpy array of audio data.
Returns:
str: The transcribed text.
"""
global text_history
if audio is None:
return "No audio provided."
try:
# Unpack the audio input
sample_rate, data = audio
# Resample if the audio sample rate is different from Vosk's expected rate
if sample_rate != RATE:
logging.info(f"Resampling audio from {sample_rate} Hz to {RATE} Hz")
data = librosa.resample(data, orig_sr=sample_rate, target_sr=RATE)
# Ensure the audio is in 16-bit PCM format
data = (data * 32767).astype(np.int16)
# Convert numpy array to bytes
audio_bytes = data.tobytes()
# Initialize the recognizer
rec = vosk.KaldiRecognizer(model, RATE)
# Feed audio data to the recognizer
if rec.AcceptWaveform(audio_bytes):
result = rec.Result()
text = eval(result).get('text', '')
logging.info(f"Final Result: {text}")
else:
# If not accepted, get the partial result
partial = rec.PartialResult()
text = eval(partial).get('partial', '')
logging.info(f"Partial Result: {text}")
# Update the history
if text.strip() != "":
text_history.append(text)
# Combine history into a single string
return " ".join(text_history)
except Exception as e:
logging.error(f"Error in speech_to_text: {e}")
return "Error processing audio. Please check the logs for more details."
# Define the Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# Vosk-Powered Speech-to-Text")
with gr.Column():
# Audio input: microphone
input_audio = gr.Audio(source="microphone", type="numpy", label="Speak or Upload Audio")
# Button to trigger transcription
transcribe_button = gr.Button("Transcribe")
# Text output
output_text = gr.Textbox(label="Transcribed Text", lines=5)
# When the button is clicked, call the speech_to_text function
transcribe_button.click(
fn=speech_to_text,
inputs=input_audio,
outputs=output_text
)
# Optional: Reset history button
reset_button = gr.Button("Reset History")
def reset_history():
global text_history
text_history = []
return ""
reset_button.click(
fn=reset_history,
inputs=None,
outputs=output_text
)
gr.Markdown("Developed with ❤️ using Vosk and Gradio.")
# Launch the Gradio app
demo.launch()
Explanation of the Changes
-
Model Initialization:
- The Vosk model is loaded once when the application starts, ensuring it's ready for incoming transcription requests.
- The code checks whether the specified model path exists. If not, it logs an error and raises a
FileNotFoundError.
-
Resampling Audio:
- Vosk models typically expect audio at a 16kHz sample rate. If the incoming audio has a different sample rate, it's resampled using
librosa.
- The audio is also converted to 16-bit PCM format, which Vosk requires.
-
Transcription Function (speech_to_text):
- Receives audio input as a tuple containing the sample rate and the audio data as a NumPy array.
- Performs resampling if necessary and ensures the audio format is compatible with Vosk.
- Uses
KaldiRecognizer to transcribe the audio. It captures both final and partial results.
- Maintains a history of transcribed texts, allowing for continuous accumulation of recognized speech.
- Logs all significant steps and errors for easier debugging.
-
Gradio Interface:
- Audio Input: Configured to accept audio from the microphone or file upload, provided as a NumPy array.
- Transcribe Button: Users can click this button to trigger the transcription process.
- Output Textbox: Displays the transcribed text.
- Reset History Button (Optional): Allows users to clear the transcription history.
- Markdown Elements: Added titles and descriptions for a better user interface.
Running the Application
-
Ensure the Vosk Model is Downloaded:
- Make sure the Vosk model (
vosk-model-small-en-us-0.15) is downloaded and extracted in the specified path.
-
Execute the Script:
- Run the Python script containing the Gradio application.
python your_gradio_app.py
-
Access the Interface:
- After launching, Gradio will provide a local URL (e.g.,
http://127.0.0.1:7860/). Open this URL in your web browser.
-
Use the Application:
- Click on the "Record" button to speak or upload an audio file.
- Click "Transcribe" to convert the speech to text.
- The transcribed text will appear in the textbox below.
- Use the "Reset History" button to clear previous transcriptions if needed.
Additional Improvements
-
Error Handling: The application logs detailed error messages to speech_recognition.log, which can be invaluable for debugging.
-
Performance Optimization: For larger applications or higher traffic, consider optimizing the model loading and recognition process, possibly by handling concurrency or deploying the model in a more scalable environment.
-
User Feedback: Enhance the user interface with more feedback mechanisms, such as indicating when transcription is in progress.
-
Language Support: Vosk supports multiple languages. You can switch models based on user preferences to support different languages.
Conclusion
By following the above steps, you've successfully integrated Vosk-based offline speech recognition into your Gradio application. This setup provides a robust and scalable solution for converting speech to text without relying on external APIs. Feel free to further customize the interface and functionality to better suit your specific use case!