got this error:
Traceback (most recent call last):
  File "c:\Users\theod\Desktop\Coding\AI\!School Assistant\1.py", line 201, in <module>
    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

# Ollama API configuration
OLLAMA_API_URL = "http://localhost:11434/api/generate"
OLLAMA_MODEL = "llama3.1"    # Adjust based on your Ollama model

# Live transcription settings
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)}"

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:

def predict(
	value: str | tuple[int, np.ndarray] | None
)
	...


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:

def predict(···) -> str | Path | bytes | tuple[int, np.ndarray] | None
	...	
	return value

Initialization
Parameters

value: str | Path | tuple[int, np.ndarray] | Callable | None

sources: list[Literal['upload', 'microphone']] | Literal['upload', 'microphone'] | None

type: Literal['numpy', 'filepath']

label: str | None

every: Timer | float | None

inputs: Component | list[Component] | set[Component] | None

show_label: bool | None

container: bool

scale: int | None

min_width: int

interactive: bool | None

visible: bool

streaming: bool

elem_id: str | None

elem_classes: list[str] | str | None

render: bool

key: int | str | None

format: Literal['wav', 'mp3']

autoplay: bool

show_download_button: bool | None

show_share_button: bool | None

editable: bool

min_length: int | None

max_length: int | None

waveform_options: WaveformOptions | dict | None

loop: bool

Shortcuts
Class 	Interface String Shortcut 	Initialization

gradio.Audio
	

"audio"
	Uses default values

gradio.Microphone
	

"microphone"
	Uses sources=["microphone"]
Demos
app.py
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
⌄
⌄
⌄
import numpy as np
import gradio as gr

notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]

def generate_tone(note, octave, duration):
    sr = 48000
    a4_freq, tones_from_a4 = 440, 12 * (octave - 4) + (note - 9)
    frequency = a4_freq * 2 ** (tones_from_a4 / 12)
    duration = int(duration)
    audio = np.linspace(0, duration, duration * sr)
    audio = (20000 * np.sin(audio * (2 * np.pi * frequency))).astype(np.int16)
    return sr, audio

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

fn: Callable | None | Literal['decorator']

inputs: Component | BlockContext | list[Component | BlockContext] | set[Component | BlockContext] | None

outputs: Component | BlockContext | list[Component | BlockContext] | set[Component | BlockContext] | None

api_name: str | None | Literal[False]

scroll_to_output: bool

show_progress: Literal['full', 'minimal', 'hidden']

queue: bool

batch: bool

max_batch_size: int

preprocess: bool

postprocess: bool

cancels: dict[str, Any] | list[dict[str, Any]] | None

every: float | None

trigger_mode: Literal['once', 'multiple', 'always_last'] | None

js: str | None

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