-
Notifications
You must be signed in to change notification settings - Fork 2.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Pure Python audio chat app with Multimodal Live API #1551
Open
freddyaboulton
wants to merge
10
commits into
GoogleCloudPlatform:main
Choose a base branch
from
freddyaboulton:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+138
−0
Open
Changes from 5 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
8c7cd11
voice chat
freddyaboulton 746f876
format
freddyaboulton 7c9f4aa
Merge branch 'main' into main
holtskinner dcc503f
Formatting
holtskinner d5138ec
Add code
freddyaboulton a342051
Merge branch 'main' into main
holtskinner 9fa5e8c
add code
freddyaboulton 9b16d37
Fix spelling
freddyaboulton 5b43fce
requirements
freddyaboulton 7c6d20f
add code
freddyaboulton File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
import asyncio | ||
import base64 | ||
|
||
import gradio as gr | ||
from gradio_webrtc import AsyncStreamHandler, WebRTC, async_aggregate_bytes_to_16bit | ||
import numpy as np | ||
from google import genai | ||
|
||
|
||
def encode_audio(data: np.ndarray, sample_rate: int) -> str: | ||
"""Encode Audio data to send to the server""" | ||
return base64.b64encode(data.tobytes()).decode("UTF-8") | ||
|
||
|
||
class GeminiHandler(AsyncStreamHandler): | ||
def __init__( | ||
self, expected_layout="mono", output_sample_rate=24000, output_frame_size=480 | ||
) -> None: | ||
super().__init__( | ||
expected_layout, | ||
output_sample_rate, | ||
output_frame_size, | ||
input_sample_rate=16000, | ||
) | ||
self.all_output_data = None | ||
self.client: genai.Client | None = None | ||
self.input_queue = asyncio.Queue() | ||
self.output_queue = asyncio.Queue() | ||
self.quit = asyncio.Event() | ||
|
||
def copy(self) -> "GeminiHandler": | ||
return GeminiHandler( | ||
expected_layout=self.expected_layout, | ||
output_sample_rate=self.output_sample_rate, | ||
output_frame_size=self.output_frame_size, | ||
) | ||
|
||
async def stream(self): | ||
while not self.quit.is_set(): | ||
audio = await self.input_queue.get() | ||
yield audio | ||
|
||
async def connect(self, api_key: str): | ||
client = genai.Client(api_key=api_key) | ||
config = {"response_modalities": ["AUDIO"]} | ||
async with client.aio.live.connect( | ||
model="models/gemini-2.0-flash-exp", config=config | ||
) as session: | ||
async for audio in session.start_stream( | ||
stream=self.stream(), mime_type="audio/pcm" | ||
): | ||
if audio.data: | ||
yield audio.data | ||
|
||
async def receive(self, frame: tuple[int, np.ndarray]) -> None: | ||
_, array = frame | ||
array = array.squeeze() | ||
auio_message = encode_audio(array, self.output_sample_rate) | ||
self.input_queue.put_nowait(auio_message) | ||
|
||
async def generator(self): | ||
async for audio_response in async_aggregate_bytes_to_16bit( | ||
self.connect(self.latest_args[1]) | ||
): | ||
self.output_queue.put_nowait(audio_response) | ||
|
||
async def emit(self): | ||
if not self.args_set.is_set(): | ||
if not self.channel: | ||
return | ||
await self.wait_for_args() | ||
asyncio.create_task(self.generator()) | ||
|
||
array = await self.output_queue.get() | ||
return (self.output_sample_rate, array) | ||
|
||
def reset(self) -> None: | ||
if hasattr(self, "_generator"): | ||
delattr(self, "_generator") | ||
self.all_output_data = None | ||
|
||
def shutdown(self) -> None: | ||
self.quit.set() | ||
|
||
|
||
with gr.Blocks() as demo: | ||
gr.HTML( | ||
""" | ||
<div style='text-align: center'> | ||
<h1>Gemini 2.0 Voice Chat</h1> | ||
<p>Speak with Gemini using real-time audio streaming</p> | ||
<p>Get a Gemini API key from <a href="https://ai.google.dev/gemini-api/docs/api-key">Google</a></p> | ||
</div> | ||
""" | ||
) | ||
|
||
with gr.Row(visible=True) as api_key_row: | ||
api_key = gr.Textbox( | ||
label="Gemini API Key", | ||
placeholder="Enter your Gemini API Key", | ||
type="password", | ||
) | ||
with gr.Row(visible=False) as row: | ||
webrtc = WebRTC( | ||
label="Conversation", | ||
modality="audio", | ||
mode="send-receive", | ||
# See for changes needed to deploy behind a firewall | ||
# https://freddyaboulton.github.io/gradio-webrtc/deployment/ | ||
rtc_configuration=None, | ||
) | ||
|
||
webrtc.stream( | ||
GeminiHandler(), | ||
inputs=[webrtc, api_key], | ||
outputs=[webrtc], | ||
time_limit=90, | ||
concurrency_limit=2, | ||
) | ||
api_key.submit( | ||
lambda: (gr.update(visible=False), gr.update(visible=True)), | ||
None, | ||
[api_key_row, row], | ||
) | ||
|
||
|
||
if __name__ == "__main__": | ||
demo.launch() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
gradio_webrtc>=0.0.24,<1.0 | ||
librosa | ||
google-genai |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It looks like this demo connects to Gemini via Google AI Studio. This repository is for demos and code samples for Vertex AI. Please check out this repo to contribute Google AI Studio samples, https://github.com/google-gemini/cookbook/
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for pointing that out, Katie! This PR is indeed using the Gemini API, and it's a valid point that this repo is focused on Vertex AI. I'll work with freddyaboulton to determine the best next steps for this demo. It might be best suited for the Google Gemini cookbook as you suggested.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Alternatively, if you can switch this demo to use Vertex AI instead, we're happy to host it in this repo.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @holtskinner @katiemn - just switched over to use Vertex AI!
2024-12-20.13-39-58.mp4