got this error:
Traceback (most recent call last):
File "c:\Users\theod\Desktop\Coding\AI!School Assistant\1.py", line 201, in
record_audio = gr.Audio(source="microphone", label="Record Your Audio")
File "C:\Users\theod\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\component_meta.py", line 167, in wrapper
return fn(self, **kwargs)
TypeError: Audio.init() got an unexpected keyword argument 'source'
with this code:
import gradio as gr
from faster_whisper import WhisperModel
import os
import requests
import json
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
LIVE_CHUNK_DURATION = 30 # in seconds (for reference; actual handling is manual)
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, suffix="", images=None):
"""
Send a prompt to the Ollama API and retrieve the response.
Args:
prompt (str): The prompt to send.
suffix (str): The text to append after the model response.
images (list): List of base64-encoded images for multimodal models.
Returns:
str: Response from Ollama.
"""
payload = {
"model": OLLAMA_MODEL,
"prompt": prompt,
"suffix": suffix,
"format": "json",
"stream": False, # Set to True if you want to handle streaming responses
# Add any additional parameters here if needed
}
if images:
payload["images"] = images
headers = {
"Content-Type": "application/json"
}
try:
response = requests.post(OLLAMA_API_URL, headers=headers, data=json.dumps(payload), timeout=120)
response.raise_for_status()
response_json = response.json()
return response_json.get('response', 'No response from Ollama.')
except Exception as e:
return f"Error communicating with Ollama: {str(e)}"
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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.", ""
# Transcribe the audio
transcription = transcribe_audio(audio)
# Prepare prompt for summarization
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. Please respond in JSON format.\n\n"
f"{{\"transcription\": \"{transcription}\"}}\n\n"
)
# Get summary from Ollama
summary = call_ollama(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 Transcription, Updated Last Minute Transcription)
"""
if audio is None:
return all_text, last_minute_text
# Transcribe the new audio chunk
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 sentences to manage the last minute's transcription
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. Please respond in JSON format.\n\n"
f"{{\"transcription\": \"{last_minute_text}\"}}\n\n"
)
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. Please respond in JSON format.\n\n"
f"{{\"transcription\": \"{all_transcription}\", \"question\": \"{user_question}\"}}\n\n"
)
answer = call_ollama(prompt)
return answer
---------------------------
Gradio Interface
---------------------------
with gr.Blocks() as demo:
gr.Markdown("## 📢 Audio Recording and Transcription Interface")
with gr.Tab("🎤 Record"):
gr.Markdown("### Record Audio and Get Summary")
with gr.Row():
record_audio = gr.Audio(source="microphone", type="filepath", label="Record Your Audio")
transcription_output = gr.Textbox(label="📝 Transcription", lines=5, interactive=False)
summary_output = gr.Textbox(label="📄 Summary", lines=5, interactive=False)
record_audio.change(
fn=process_recorded_audio,
inputs=record_audio,
outputs=[transcription_output, summary_output]
)
with gr.Tab("🔄 Live"):
gr.Markdown("### Live Transcription and Interaction")
with gr.Row():
live_record_audio = gr.Audio(source="microphone", type="filepath", label="Record 30s Audio Chunk")
# States to hold accumulated transcription
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
def live_upload_handler(audio, all_text, last_minute_text):
updated_all, updated_last_minute = append_transcription(audio, all_text, last_minute_text)
return updated_all, updated_last_minute
live_record_audio.change(
fn=live_upload_handler,
inputs=[live_record_audio, all_transcription_state, last_minute_transcription_state],
outputs=[all_transcription, last_minute_transcription],
)
# 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()
here is some documentation:
Audio
gradio.Audio(···)
Description
Creates an audio component that can be used to upload/record audio (as an input) or display audio (as an output).
Behavior
As input component: passes audio as one of these formats (depending on type): a str filepath, or tuple of (sample rate in Hz, audio data as numpy array). If the latter, the audio data is a 16-bit int array whose values range from -32768 to 32767 and shape of the audio data array is (samples,) for mono audio or (samples, channels) for multi-channel audio.
Your function should accept one of these types:
As output component: expects audio data in any of these formats: a str or pathlib.Path filepath or URL to an audio file, or a bytes object (recommended for streaming), or a tuple of (sample rate in Hz, audio data as numpy array). Note: if audio is supplied as a numpy array, the audio will be normalized by its peak value to avoid distortion or clipping in the resulting audio.
Your function should return one of these types:
demo = gr.Interface(
generate_tone,
[
gr.Dropdown(notes, type="index"),
gr.Slider(4, 6, step=1),
gr.Textbox(value="1", label="Duration in seconds"),
],
"audio",
)
if name == "main":
demo.launch()
Event Listeners
Description
Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called.
Supported Event Listeners
The Audio component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below.
Listener Description
Audio.stream(fn, ···)
This listener is triggered when the user streams the Audio.
Audio.change(fn, ···)
Triggered when the value of the Audio changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input.
Audio.clear(fn, ···)
This listener is triggered when the user clears the Audio using the X button for the component.
Audio.play(fn, ···)
This listener is triggered when the user plays the media in the Audio.
Audio.pause(fn, ···)
This listener is triggered when the media in the Audio stops for any reason.
Audio.stop(fn, ···)
This listener is triggered when the user reaches the end of the media playing in the Audio.
Audio.pause(fn, ···)
This listener is triggered when the media in the Audio stops for any reason.
Audio.start_recording(fn, ···)
This listener is triggered when the user starts recording with the Audio.
Audio.pause_recording(fn, ···)
This listener is triggered when the user pauses recording with the Audio.
Audio.stop_recording(fn, ···)
This listener is triggered when the user stops recording with the Audio.
Audio.upload(fn, ···)
This listener is triggered when the user uploads a file into the Audio.
Audio.input(fn, ···)
This listener is triggered when the user changes the value of the Audio.
Event Parameters
Parameters
concurrency_limit: int | None | Literal['default']
concurrency_id: str | None
show_api: bool
Helper Classes
WaveformOptions
gradio.WaveformOptions(···)
Description
A dataclass for specifying options for the waveform display in the Audio component. An instance of this class can be passed into the waveform_options parameter of gr.Audio.
Initialization
Parameters
waveform_color: str | None
waveform_progress_color: str | None
trim_region_color: str | None
show_recording_waveform: bool
show_controls: bool
skip_length: int | float
sample_rate: int
The error you're encountering indicates that the gr.Audio component in Gradio does not recognize the source parameter. This is because the parameter has been updated in newer versions of Gradio. Instead of source, the correct parameter to use is sources.
Here's how you can fix your code:
Change source to sources
In your code, you have:
record_audio = gr.Audio(source="microphone", type="filepath", label="Record Your Audio")
This should be updated to:
record_audio = gr.Audio(sources="microphone", type="filepath", label="Record Your Audio")
Similarly, update any other instances where you have used source to sources. For example:
The Gradio Audio component has been designed to accept a parameter named sources (note the plural), which can take either a single string like "microphone" or a list of sources like ["upload", "microphone"]. The use of source (singular) is outdated and not recognized in newer versions of Gradio.
This parameter allows you to specify where the audio input should come from. By setting sources="microphone", you're indicating that the audio should be recorded from the microphone.
Updated Code Snippet
Here's the updated section of your code with the corrections:
with gr.Row():
record_audio = gr.Audio(sources="microphone", type="filepath", label="Record Your Audio")
And:
with gr.Row():
live_record_audio = gr.Audio(sources="microphone", type="filepath", label="Record 30s Audio Chunk")
Full Corrected Code Segment
with gr.Blocks() as demo:
gr.Markdown("## 📢 Audio Recording and Transcription Interface")
with gr.Tab("🎤 Record"):
gr.Markdown("### Record Audio and Get Summary")
with gr.Row():
record_audio = gr.Audio(sources="microphone", type="filepath", label="Record Your Audio")
transcription_output = gr.Textbox(label="📝 Transcription", lines=5, interactive=False)
summary_output = gr.Textbox(label="📄 Summary", lines=5, interactive=False)
record_audio.change(
fn=process_recorded_audio,
inputs=record_audio,
outputs=[transcription_output, summary_output]
)
with gr.Tab("🔄 Live"):
gr.Markdown("### Live Transcription and Interaction")
with gr.Row():
live_record_audio = gr.Audio(sources="microphone", type="filepath", label="Record 30s Audio Chunk")
# Rest of your code...
Additional Tips
Check Gradio Version: Ensure that you're using a compatible version of Gradio. You can check your Gradio version by running:
import gradio
print(gradio.__version__)
If you're not on the latest version, consider updating Gradio:
pip install --upgrade gradio
Consult the Latest Documentation: Always refer to the latest Gradio documentation or official website for any changes in the API.
Using Multiple Sources: If you want to allow both microphone input and file upload, you can set sources=["upload", "microphone"].
record_audio = gr.Audio(sources=["upload", "microphone"], type="filepath", label="Record or Upload Audio")
Summary
The error arises because gr.Audio does not have a source parameter; it uses sources instead. Updating your code to use the correct parameter should resolve the issue. Always make sure to keep your libraries updated and refer to the latest documentation when encountering such errors.
If you have any more questions or need further assistance, feel free to ask!