Sure! Below is a comprehensive Gradio application that fulfills your requirements. This application consists of two main tabs:
-
Record Tab: Allows users to record audio for a specified duration or until stopped. After recording, the audio is transcribed using the faster_whisper library and summarized using Ollama.
-
Live Tab: Facilitates continuous audio recording in 30-second intervals. Each audio chunk is transcribed and appended to an accumulated transcription. Users can trigger a summary of the last minute's transcription and interact with a chatbox to ask specific questions related to the ongoing transcription.
Prerequisites
Before running the application, ensure you have the following installed:
-
Python Libraries:
gradio
faster_whisper
requests
You can install them using pip:
pip install gradio faster-whisper requests
-
Ollama:
- Ensure that Ollama is installed and running on your local machine.
- The application assumes that Ollama's API is accessible at
http://localhost:11434. If it's running on a different host or port, adjust the OLLAMA_API_URL accordingly in the code.
-
Hardware:
- A CUDA-compatible GPU is recommended for faster transcription with
faster_whisper. If you don't have a GPU, adjust the device and compute_type parameters accordingly.
Complete Code
import gradio as gr
from faster_whisper import WhisperModel
import os
import requests
import tempfile
# Set environment variable to avoid potential issues
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# ---------------------------
# Configuration
# ---------------------------
# Path to save temporary audio files
TEMP_DIR = tempfile.gettempdir()
# Whisper model configuration
MODEL_SIZE = "large-v2" # Options: 'tiny', 'base', 'small', 'medium', 'large', etc.
DEVICE = "cuda" # Change to 'cpu' if GPU is not available
COMPUTE_TYPE = "float16" # Use 'int8' for lower memory usage on GPU
# Ollama API configuration
OLLAMA_API_URL = "http://localhost:11434/v1/ollama/run"
DEFAULT_OLLAMA_MODEL = "llama3.1" # Adjust based on your Ollama model
# Live transcription settings
LIVE_CHUNK_DURATION = 30 # in seconds
LIVE_CHUNKS_PER_MINUTE = 2 # Number of chunks to represent one minute
# ---------------------------
# Initialize Whisper Model
# ---------------------------
print("Loading Whisper model. This may take a while...")
model = WhisperModel(MODEL_SIZE, device=DEVICE, compute_type=COMPUTE_TYPE)
print("Whisper model loaded.")
# ---------------------------
# Helper Functions
# ---------------------------
def transcribe_audio(audio_path):
"""
Transcribe the given audio file using Faster Whisper.
Args:
audio_path (str): Path to the audio file.
Returns:
str: Transcribed text.
"""
segments, info = model.transcribe(audio_path, beam_size=5)
transcription = ' '.join([segment.text for segment in segments]).strip()
return transcription
def call_ollama(prompt, model_name=DEFAULT_OLLAMA_MODEL):
"""
Send a prompt to the Ollama API and retrieve the response.
Args:
prompt (str): The prompt to send.
model_name (str): The Ollama model to use.
Returns:
str: Response from Ollama.
"""
payload = {
"model": model_name,
"prompt": prompt,
"stream": False
}
try:
response = requests.post(OLLAMA_API_URL, json=payload, timeout=60)
response.raise_for_status()
ollama_response = response.json().get('response', '')
return ollama_response
except Exception as e:
return f"Error communicating with Ollama: {str(e)}"
def process_recorded_audio(audio):
"""
Process the recorded audio: transcribe and summarize.
Args:
audio (str): Path to the recorded audio file.
Returns:
tuple: (Transcription, Summary)
"""
if audio is None:
return "No audio recorded.", ""
transcription = transcribe_audio(audio)
summary_prompt = f"Summarize the following text:\n{transcription}"
summary = call_ollama(summary_prompt)
return transcription, summary
def append_transcription(audio, all_text, last_minute_text):
"""
Append new transcription to accumulated texts.
Args:
audio (str): Path to the new audio chunk.
all_text (str): All accumulated transcription.
last_minute_text (str): Accumulated transcription for the last minute.
Returns:
tuple: Updated all_text and last_minute_text
"""
if audio is None:
return all_text, last_minute_text
new_transcription = transcribe_audio(audio)
updated_all_text = all_text + new_transcription + ' '
# Update last_minute_text
updated_last_minute_text = last_minute_text + new_transcription + ' '
# Split into chunks based on LIVE_CHUNK_DURATION
transcriptions = updated_last_minute_text.strip().split('. ')
if len(transcriptions) > LIVE_CHUNKS_PER_MINUTE:
# Keep only the last LIVE_CHUNKS_PER_MINUTE transcriptions
updated_last_minute_text = '. '.join(transcriptions[-LIVE_CHUNKS_PER_MINUTE:]) + '. '
return updated_all_text, updated_last_minute_text
def summarize_last_minute(last_minute_text):
"""
Summarize the last minute's transcription.
Args:
last_minute_text (str): Transcription of the last minute.
Returns:
str: Summary generated by Ollama.
"""
prompt = (
"I am in class right now and I want you to generate answers for the questions "
"the teacher asked or generate an overview of the current topic based on the following transcription:\n\n"
f"{last_minute_text}"
)
summary = call_ollama(prompt)
return summary
def handle_chat(all_transcription, user_question):
"""
Handle user questions by generating answers based on all transcription.
Args:
all_transcription (str): All accumulated transcription.
user_question (str): The user's question.
Returns:
str: Answer generated by Ollama.
"""
if not user_question.strip():
return "Please enter a question."
prompt = (
"I am in class right now and I want you to generate answers for the questions "
"the teacher asked or generate an overview of the current topic based on the following transcription:\n\n"
f"{all_transcription}\n\n"
f"Question: {user_question}"
)
answer = call_ollama(prompt)
return answer
# ---------------------------
# Gradio Interface
# ---------------------------
with gr.Blocks() as demo:
gr.Markdown("## Audio Recording and Live Transcription Interface")
with gr.Tab("Record"):
gr.Markdown("### Record Audio and Get Summary")
with gr.Row():
record_button = gr.UploadButton("Record Audio", file_types=[".wav", ".mp3"], label="Start Recording")
duration_input = gr.Number(label="Duration (seconds)", value=30, interactive=True)
transcription_output = gr.Textbox(label="Transcription", lines=5, interactive=False)
summary_output = gr.Textbox(label="Summary", lines=5, interactive=False)
def record_audio_handler(audio):
return process_recorded_audio(audio)
record_button.upload(
fn=process_recorded_audio,
inputs=record_button,
outputs=[transcription_output, summary_output]
)
with gr.Tab("Live"):
gr.Markdown("### Live Transcription and Interaction")
with gr.Row():
live_record_button = gr.UploadButton("Record 30s Audio Chunk", file_types=[".wav", ".mp3"], label="Record 30s")
all_transcription_state = gr.State(value="")
last_minute_transcription_state = gr.State(value="")
all_transcription = gr.Textbox(label="All Transcriptions", lines=10, interactive=False)
last_minute_transcription = gr.Textbox(label="Last Minute Transcription", lines=5, interactive=False)
with gr.Row():
summarize_button = gr.Button("Summarize Last Minute")
summary_live_output = gr.Textbox(label="Summary of Last Minute", lines=5, interactive=False)
with gr.Row():
user_question = gr.Textbox(label="Ask a Question", lines=1)
chat_button = gr.Button("Get Answer")
chat_output = gr.Textbox(label="Answer", lines=5, interactive=False)
# Live Recording Upload Handler
live_record_button.upload(
fn=append_transcription,
inputs=[live_record_button, all_transcription_state, last_minute_transcription_state],
outputs=[all_transcription, last_minute_transcription, all_transcription_state, last_minute_transcription_state],
)
# Summarize Last Minute Handler
summarize_button.click(
fn=summarize_last_minute,
inputs=last_minute_transcription,
outputs=summary_live_output
)
# Chat Handler
chat_button.click(
fn=handle_chat,
inputs=[all_transcription, user_question],
outputs=chat_output
)
gr.Markdown(
"""
---
**Note**: Ensure that Ollama is running and accessible at `http://localhost:11434`.
Adjust the `OLLAMA_API_URL` in the script if it's running elsewhere.
"""
)
# ---------------------------
# Launch the App
# ---------------------------
if __name__ == "__main__":
demo.launch()
Explanation of the Code
-
Configuration Section:
- Paths and Model Settings: Defines paths for temporary audio storage, selects the Whisper model size, device (GPU or CPU), and compute type for optimization.
- Ollama Settings: Specifies the Ollama API endpoint and the default model to use.
- Live Transcription Settings: Configures the duration of each live transcription chunk and how many chunks constitute a minute.
-
Whisper Model Initialization:
- Loads the specified Whisper model using
faster_whisper. This is done globally to avoid reloading the model with each transcription request, ensuring efficiency.
-
Helper Functions:
transcribe_audio: Takes an audio file path, transcribes it using the Whisper model, and returns the transcription.
call_ollama: Sends a prompt to the Ollama API and retrieves the response. Handles exceptions and returns error messages if any issues occur during the API call.
process_recorded_audio: Handles audio from the Record tab by transcribing and summarizing it.
append_transcription: Manages live transcriptions by appending new transcriptions to the accumulated text and maintaining a separate transcription of the last minute.
summarize_last_minute: Sends the last minute's transcription to Ollama with a specific prompt to generate a summary or answers.
handle_chat: Processes user questions by combining them with the accumulated transcription and querying Ollama for answers.
-
Gradio Interface:
-
Record Tab:
- Recording: Users can upload a recorded audio file. The application supports formats like
.wav and .mp3.
- Processing: Upon uploading, the audio is transcribed and summarized.
- Outputs: Displays both the transcription and its summary.
-
Live Tab:
- Live Recording: Users can upload 30-second audio chunks. Each chunk is transcribed and appended to the accumulated transcription. The last minute's transcription is maintained separately.
Usage Instructions
-
Record Tab:
- Click on the "Record Audio" button to upload an audio file.
- After uploading, the transcription and its summary will be displayed in their respective text boxes.
-
Live Tab:
- Click on the "Record 30s Audio Chunk" button to upload a 30-second audio segment.
- Each uploaded chunk will be transcribed and appended to the "All Transcriptions" box.
- The "Last Minute Transcription" box maintains the transcription of the last minute based on the configured number of chunks.
- Click on "Summarize Last Minute" to generate a summary of the recent transcription.
- Use the "Ask a Question" textbox to input specific queries related to the ongoing transcription and click "Get Answer" to receive context-aware responses.
Final Notes
-
Performance: Transcription and summarization processes might take some time depending on the length of the audio and the computational resources available.
-
Error Handling: The application includes basic error handling for API calls. Ensure that Ollama is running correctly to avoid communication errors.
-
Customization: Adjust the configuration section as needed, especially the model sizes, device settings, and Ollama API URL based on your setup.
-
Scalability: For production environments or larger-scale deployments, consider optimizing the transcription and summarization processes, possibly by implementing asynchronous handling or leveraging more efficient resource management.
Feel free to further customize and enhance the application based on your specific needs!