Update README.md
Browse files
README.md
CHANGED
|
@@ -1,471 +1,12 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
1. The frontend application, built with modern vanilla JavaScript using an object-oriented and modular approach, which handles the user interface, media capture, and real-time audio/video processing.
|
| 15 |
-
|
| 16 |
-
2. The backend server, implemented in Python using FastAPI, which serves the frontend assets and acts as an intermediary proxy between the client application and Google's Gemini API. This backend component handles WebSocket connections, authentication, and message routing.
|
| 17 |
-
|
| 18 |
-
Communication between the frontend and backend is primarily conducted through WebSocket connections, which allow for persistent, low-latency, bidirectional data transfer – essential for the real-time nature of the application. The backend, in turn, communicates with the Gemini API via another WebSocket connection, relaying messages in both directions.
|
| 19 |
-
|
| 20 |
-
## Frontend Implementation Details
|
| 21 |
-
|
| 22 |
-
### Structure and Organization
|
| 23 |
-
|
| 24 |
-
The frontend follows a modern, modular structure that separates concerns into logical components, making the codebase more maintainable and easier to understand. Rather than using a complex frontend framework, it leverages pure JavaScript with ES6 modules to achieve a clean and efficient architecture.
|
| 25 |
-
|
| 26 |
-
The frontend code is organized as follows:
|
| 27 |
-
|
| 28 |
-
```
|
| 29 |
-
frontend/
|
| 30 |
-
├── index.html # Main HTML structure
|
| 31 |
-
├── css/
|
| 32 |
-
│ └── styles.css # All styles in one CSS file
|
| 33 |
-
└── js/
|
| 34 |
-
├── main.js # Application entry point and initialization
|
| 35 |
-
├── audio-manager.js # Audio capture and playback handling
|
| 36 |
-
├── video-manager.js # Video and screen capture management
|
| 37 |
-
├── websocket-client.js # WebSocket communication with backend
|
| 38 |
-
└── ui-controller.js # User interface updates and interactions
|
| 39 |
-
```
|
| 40 |
-
|
| 41 |
-
This organization reflects a component-based architecture where each JavaScript file encapsulates a specific functionality domain. For instance, `audio-manager.js` handles everything related to microphone access, audio processing, and playback, while `video-manager.js` is responsible for camera access and screen sharing functionality.
|
| 42 |
-
|
| 43 |
-
### The Entry Point: main.js
|
| 44 |
-
|
| 45 |
-
The `main.js` file serves as the application's entry point and orchestrates the overall flow. It initializes the other components, sets up event listeners, and manages the application state. This orchestrator pattern ensures that each component can focus on its specific domain while the main application handles cross-component interactions.
|
| 46 |
-
|
| 47 |
-
The `GeminiApp` class in this file is instantiated when the DOM is fully loaded, initializing the application. It coordinates the start and stop of streaming sessions, managing the lifecycle of audio and video capture, WebSocket connections, and UI updates. This centralized control point simplifies debugging and makes the application flow more predictable.
|
| 48 |
-
|
| 49 |
-
### Real-time Audio Processing
|
| 50 |
-
|
| 51 |
-
One of the most technically challenging aspects of the application is the real-time audio processing. The `AudioManager` class in `audio-manager.js` handles both microphone capture and audio playback with careful attention to sample rates and formats.
|
| 52 |
-
|
| 53 |
-
A critical technical detail is the handling of different audio sample rates. The Gemini API expects input audio at 16kHz (16-bit PCM, little-endian) but returns output audio at 24kHz (16-bit PCM, little-endian). The application addresses this by creating two separate `AudioContext` instances:
|
| 54 |
-
|
| 55 |
-
1. A capture context configured at 16kHz for microphone input
|
| 56 |
-
2. A playback context configured at 24kHz for Gemini's audio output
|
| 57 |
-
|
| 58 |
-
This approach eliminates the sample rate mismatch that would otherwise result in poor audio quality, avoiding the "headset-like" sound that occurs when trying to play 24kHz audio through a 16kHz context. The implementation uses the Web Audio API's `AudioContext`, `ScriptProcessorNode`, and buffer manipulation to handle this complex audio pipeline.
|
| 59 |
-
|
| 60 |
-
For the technically inclined, the audio capture process follows these steps:
|
| 61 |
-
|
| 62 |
-
1. Create an `AudioContext` with a sample rate of 16kHz
|
| 63 |
-
2. Obtain microphone access via `getUserMedia`
|
| 64 |
-
3. Create a `ScriptProcessor` to process audio frames
|
| 65 |
-
4. In the `audioprocess` event handler, extract raw audio data
|
| 66 |
-
5. Convert the Float32Array samples to 16-bit PCM format
|
| 67 |
-
6. Encode as base64 for transmission over WebSocket
|
| 68 |
-
7. Send to the backend server
|
| 69 |
-
|
| 70 |
-
Similarly, the audio playback process:
|
| 71 |
-
|
| 72 |
-
1. Receive base64-encoded 24kHz PCM audio from the backend
|
| 73 |
-
2. Decode from base64 to binary data
|
| 74 |
-
3. Convert from 16-bit PCM to normalized Float32Array
|
| 75 |
-
4. Create an `AudioBuffer` at 24kHz sample rate
|
| 76 |
-
5. Play the buffer through a 24kHz `AudioContext`
|
| 77 |
-
|
| 78 |
-
The application also implements a queueing system for audio chunks to ensure smooth playback without gaps between segments, even when network latency varies.
|
| 79 |
-
|
| 80 |
-
### Video and Screen Capture
|
| 81 |
-
|
| 82 |
-
The `VideoManager` class in `video-manager.js` handles capturing video from either the webcam or the user's screen. This functionality leverages the modern Media Capture and Streams API.
|
| 83 |
-
|
| 84 |
-
For camera capture, the application uses `navigator.mediaDevices.getUserMedia()` with optimized settings for resolution and frame rate. For screen capture, it uses `navigator.mediaDevices.getDisplayMedia()`, which prompts the user to select which screen or application window to share.
|
| 85 |
-
|
| 86 |
-
To minimize bandwidth and processing requirements, the application doesn't stream video continuously. Instead, it captures frames at regular intervals (once per second) and sends them as JPEG images. This approach balances the need for visual context with performance considerations.
|
| 87 |
-
|
| 88 |
-
The frame capture process involves:
|
| 89 |
-
|
| 90 |
-
1. Drawing the current video frame to an off-screen canvas
|
| 91 |
-
2. Converting the canvas content to a JPEG image
|
| 92 |
-
3. Encoding as base64 for transmission over WebSocket
|
| 93 |
-
4. Sending to the backend server
|
| 94 |
-
|
| 95 |
-
This periodic capture approach is particularly important for screen sharing, where full-motion video would consume significant bandwidth.
|
| 96 |
-
|
| 97 |
-
### WebSocket Communication
|
| 98 |
-
|
| 99 |
-
The `WebSocketClient` class in `websocket-client.js` manages the WebSocket connection between the frontend and backend. It handles connection establishment, message sending, and event processing.
|
| 100 |
-
|
| 101 |
-
The WebSocket communication follows a message-based protocol where each message has a `type` field that indicates its purpose (e.g., "audio", "image", "text", "config"). This allows for a flexible communication pattern where different types of data can be sent over the same WebSocket connection.
|
| 102 |
-
|
| 103 |
-
The client generates a unique UUID for each session, which is included in the WebSocket URL. This allows the backend to maintain separate state for each client session, supporting multiple concurrent users.
|
| 104 |
-
|
| 105 |
-
### User Interface Management
|
| 106 |
-
|
| 107 |
-
The `UIController` class in `ui-controller.js` centralizes all UI-related operations, including form element access, message display, and state updates. This separation of UI logic from business logic follows the Model-View-Controller (MVC) pattern, making the code more maintainable.
|
| 108 |
-
|
| 109 |
-
The user interface itself features a modern dark theme with thoughtful animations and transitions. It provides clear feedback about the current state of the application (connecting, streaming, errors) and displays messages from Gemini in a conversational format.
|
| 110 |
-
|
| 111 |
-
## Backend Implementation Details
|
| 112 |
-
|
| 113 |
-
### Structure and Organization
|
| 114 |
-
|
| 115 |
-
The backend follows a modular structure with clear separation of concerns:
|
| 116 |
-
|
| 117 |
-
```
|
| 118 |
-
backend/
|
| 119 |
-
├── app.py # FastAPI application entry point
|
| 120 |
-
├── gemini/
|
| 121 |
-
│ ├── __init__.py
|
| 122 |
-
│ └── client.py # Gemini API client implementation
|
| 123 |
-
├── routes/
|
| 124 |
-
│ ├── __init__.py
|
| 125 |
-
│ └── websocket.py # WebSocket endpoint handlers
|
| 126 |
-
├── requirements.txt # Python dependencies
|
| 127 |
-
└── .env # Environment variables (API keys)
|
| 128 |
-
```
|
| 129 |
-
|
| 130 |
-
This organization reflects a domain-driven design approach, where code is structured around business domains rather than technical layers. The `gemini` package encapsulates all Gemini API interaction logic, while the `routes` package handles HTTP and WebSocket routing.
|
| 131 |
-
|
| 132 |
-
### FastAPI Application
|
| 133 |
-
|
| 134 |
-
The `app.py` file is the entry point for the backend application. It initializes the FastAPI application, sets up middleware (CORS), includes routers, and configures static file serving for the frontend assets.
|
| 135 |
-
|
| 136 |
-
The application uses FastAPI, a modern, high-performance web framework for Python that's particularly well-suited for building APIs. FastAPI provides automatic validation, serialization, and OpenAPI documentation, making the backend robust and maintainable.
|
| 137 |
-
|
| 138 |
-
### WebSocket Handling
|
| 139 |
-
|
| 140 |
-
The `routes/websocket.py` file contains the WebSocket endpoint handler that manages client connections. This handler performs several key functions:
|
| 141 |
-
|
| 142 |
-
1. Accepting incoming WebSocket connections
|
| 143 |
-
2. Processing the initial configuration message
|
| 144 |
-
3. Establishing a connection to the Gemini API
|
| 145 |
-
4. Spawning two asynchronous tasks for bidirectional communication:
|
| 146 |
-
- One task that receives messages from the client and forwards them to Gemini
|
| 147 |
-
- Another task that receives responses from Gemini and forwards them to the client
|
| 148 |
-
5. Managing error handling and connection cleanup
|
| 149 |
-
|
| 150 |
-
The WebSocket handler uses Python's `asyncio` library for concurrent processing, allowing it to handle multiple simultaneous client connections efficiently. It maintains a dictionary of active connections, keyed by client ID, which enables proper resource management.
|
| 151 |
-
|
| 152 |
-
### Gemini API Client
|
| 153 |
-
|
| 154 |
-
The `gemini/client.py` file contains the `GeminiConnection` class, which encapsulates all interaction with the Gemini API. This class manages:
|
| 155 |
-
|
| 156 |
-
1. WebSocket connection to the Gemini API
|
| 157 |
-
2. Authentication using the API key
|
| 158 |
-
3. Initial setup message with configuration (system prompt, voice selection)
|
| 159 |
-
4. Methods for sending audio, text, and images to Gemini
|
| 160 |
-
5. Methods for receiving and processing responses from Gemini
|
| 161 |
-
|
| 162 |
-
The Gemini WebSocket API requires a specific message sequence, with the first message being a "setup" message that configures the session. The `GeminiConnection` class handles this protocol, abstracting away the complexity from the rest of the application.
|
| 163 |
-
|
| 164 |
-
## The WebSocket Protocol
|
| 165 |
-
|
| 166 |
-
WebSockets are used extensively in this application due to their ability to provide real-time, bidirectional communication between client and server. Unlike traditional HTTP requests, which follow a request-response pattern, WebSockets establish a persistent connection that allows both parties to send messages at any time.
|
| 167 |
-
|
| 168 |
-
### Why WebSockets?
|
| 169 |
-
|
| 170 |
-
There are several reasons why WebSockets are essential for this application:
|
| 171 |
-
|
| 172 |
-
1. **Real-time Audio Streaming**: To achieve a conversational experience, audio needs to be streamed in near real-time. WebSockets allow audio chunks to be sent as soon as they're captured.
|
| 173 |
-
|
| 174 |
-
2. **Bidirectional Communication**: Both the client and server need to send messages proactively. For example, the server needs to send audio responses as soon as they're available from Gemini.
|
| 175 |
-
|
| 176 |
-
3. **Reduced Overhead**: For frequent, small messages (like audio chunks), establishing a new HTTP connection for each would add significant overhead.
|
| 177 |
-
|
| 178 |
-
4. **Stateful Connection**: The WebSocket connection maintains state throughout the session, simplifying the management of the conversation flow.
|
| 179 |
-
|
| 180 |
-
### WebSocket Message Flow
|
| 181 |
-
|
| 182 |
-
The WebSocket communication follows a specific protocol:
|
| 183 |
-
|
| 184 |
-
1. The client establishes a WebSocket connection to the backend using a unique client ID.
|
| 185 |
-
2. The client sends an initial "config" message with system prompt, voice selection, and other settings.
|
| 186 |
-
3. The backend establishes a separate WebSocket connection to the Gemini API.
|
| 187 |
-
4. The client streams audio, images, or text to the backend.
|
| 188 |
-
5. The backend forwards these to the Gemini API.
|
| 189 |
-
6. Gemini sends responses (audio or text) to the backend.
|
| 190 |
-
7. The backend forwards these responses to the client.
|
| 191 |
-
8. When the session ends, all connections are properly closed.
|
| 192 |
-
|
| 193 |
-
Each WebSocket message is a JSON object with a `type` field that indicates its purpose, and additional fields specific to that type. For example, audio messages have a `data` field containing base64-encoded audio, while text messages have a `text` field containing the text content.
|
| 194 |
-
|
| 195 |
-
### WebSocket Security Considerations
|
| 196 |
-
|
| 197 |
-
While this implementation focuses on functionality, a production deployment should consider several security aspects:
|
| 198 |
-
|
| 199 |
-
1. **Authentication**: Implement proper authentication for WebSocket connections to prevent unauthorized access.
|
| 200 |
-
2. **Rate Limiting**: Apply rate limiting to prevent abuse of the API.
|
| 201 |
-
3. **Message Validation**: Thoroughly validate all incoming messages to prevent injection attacks.
|
| 202 |
-
4. **HTTPS**: Ensure WebSocket connections use WSS (WebSocket Secure) over HTTPS.
|
| 203 |
-
|
| 204 |
-
## Audio Format and Quality Considerations
|
| 205 |
-
|
| 206 |
-
One of the most critical technical aspects of this application is the handling of audio formats and sample rates. Incorrect handling can lead to significantly degraded audio quality, as was initially experienced with the "headset-like" sound.
|
| 207 |
-
|
| 208 |
-
### Gemini API Audio Requirements
|
| 209 |
-
|
| 210 |
-
The Gemini Multimodal API has specific requirements for audio:
|
| 211 |
-
|
| 212 |
-
- **Input audio format**: Raw 16-bit PCM audio at 16kHz, little-endian
|
| 213 |
-
- **Output audio format**: Raw 16-bit PCM audio at 24kHz, little-endian
|
| 214 |
-
|
| 215 |
-
This mismatch between input and output sample rates creates a technical challenge that must be addressed for optimal audio quality.
|
| 216 |
-
|
| 217 |
-
### The Sample Rate Mismatch Problem
|
| 218 |
-
|
| 219 |
-
When audio is produced at one sample rate (24kHz) but played through a system expecting another rate (16kHz), several issues can occur:
|
| 220 |
-
|
| 221 |
-
1. **Speed Distortion**: The audio might play at the wrong speed.
|
| 222 |
-
2. **Frequency Distortion**: Certain frequencies might be incorrectly represented.
|
| 223 |
-
3. **Aliasing Artifacts**: Digital artifacts can be introduced, causing the "headset-like" quality.
|
| 224 |
-
|
| 225 |
-
### The Dual AudioContext Solution
|
| 226 |
-
|
| 227 |
-
The solution implemented in this application uses two separate `AudioContext` instances:
|
| 228 |
-
|
| 229 |
-
1. A **capture context** set to 16kHz for microphone input, matching Gemini's input requirements.
|
| 230 |
-
2. A **playback context** set to 24kHz for audio output, matching Gemini's output format.
|
| 231 |
-
|
| 232 |
-
This approach ensures that:
|
| 233 |
-
|
| 234 |
-
1. Audio is captured at the exact rate expected by Gemini.
|
| 235 |
-
2. Audio from Gemini is played back at its native rate without resampling.
|
| 236 |
-
|
| 237 |
-
Additionally, the application properly handles the little-endian encoding of the PCM data using a `DataView` with explicit endianness control, ensuring correct interpretation of the binary audio data.
|
| 238 |
-
|
| 239 |
-
### PCM Data Handling
|
| 240 |
-
|
| 241 |
-
The application performs several conversions to properly handle the PCM audio data:
|
| 242 |
-
|
| 243 |
-
1. **For Capture**:
|
| 244 |
-
- Convert from Float32Array (-1.0 to 1.0) to Int16Array (-32768 to 32767)
|
| 245 |
-
- Ensure proper little-endian byte order
|
| 246 |
-
- Encode as base64 for WebSocket transmission
|
| 247 |
-
|
| 248 |
-
2. **For Playback**:
|
| 249 |
-
- Decode base64 to binary data
|
| 250 |
-
- Create a DataView to properly handle little-endian byte order
|
| 251 |
-
- Convert from Int16Array to Float32Array for the Web Audio API
|
| 252 |
-
- Create an AudioBuffer with the correct sample rate (24kHz)
|
| 253 |
-
|
| 254 |
-
These conversions ensure that audio quality is preserved throughout the processing pipeline.
|
| 255 |
-
|
| 256 |
-
## Local Server Architecture
|
| 257 |
-
|
| 258 |
-
The application uses a local server architecture, where the backend runs on the user's machine rather than a remote server. This architectural choice has several implications:
|
| 259 |
-
|
| 260 |
-
### Why a Local Server?
|
| 261 |
-
|
| 262 |
-
**Simplified Development**: The separation of frontend and backend concerns facilitates development and testing.
|
| 263 |
-
|
| 264 |
-
### Server Implementation
|
| 265 |
-
|
| 266 |
-
The server is implemented using FastAPI, a modern Python web framework that excels at building APIs with minimal code. FastAPI offers several advantages:
|
| 267 |
-
|
| 268 |
-
1. **Performance**: Built on Starlette and Pydantic, FastAPI is one of the fastest Python frameworks available.
|
| 269 |
-
|
| 270 |
-
2. **Async Support**: Native support for asynchronous programming enables efficient handling of multiple concurrent connections.
|
| 271 |
-
|
| 272 |
-
3. **Type Safety**: Leverages Python type hints for validation and better developer experience.
|
| 273 |
-
|
| 274 |
-
4. **WebSocket Support**: Built-in support for WebSockets, which are essential for this application.
|
| 275 |
-
|
| 276 |
-
5. **Automatic Documentation**: Generates OpenAPI documentation automatically.
|
| 277 |
-
|
| 278 |
-
The server runs locally on port 8000 by default, serving both the static frontend assets and the WebSocket endpoint. This arrangement allows the frontend to communicate with the backend via WebSocket connections to `ws://localhost:8000/ws/{client_id}`.
|
| 279 |
-
|
| 280 |
-
## Project Structure Rationale
|
| 281 |
-
|
| 282 |
-
The project's structure follows a clear separation between frontend and backend, with modular organization within each. This structure was chosen to balance simplicity and maintainability.
|
| 283 |
-
|
| 284 |
-
### Top-Level Separation
|
| 285 |
-
|
| 286 |
-
```
|
| 287 |
-
google-gemini-live-api-multimodal-demo/
|
| 288 |
-
├── frontend/
|
| 289 |
-
└── backend/
|
| 290 |
-
```
|
| 291 |
-
|
| 292 |
-
This top-level separation clearly distinguishes between client-side and server-side code, which:
|
| 293 |
-
|
| 294 |
-
1. **Clarifies Responsibilities**: Developers can immediately understand which code runs in the browser and which runs on the server.
|
| 295 |
-
|
| 296 |
-
2. **Facilitates Deployment**: The frontend can be deployed as static assets, while the backend can be deployed as a separate service.
|
| 297 |
-
|
| 298 |
-
3. **Enables Independent Scaling**: If needed, the frontend and backend can be scaled independently.
|
| 299 |
-
|
| 300 |
-
### Frontend Modularity
|
| 301 |
-
|
| 302 |
-
The frontend uses ES6 modules to separate concerns into logical components. This modular approach:
|
| 303 |
-
|
| 304 |
-
1. **Improves Maintainability**: Each module has a single responsibility, making changes safer and more focused.
|
| 305 |
-
|
| 306 |
-
2. **Enhances Readability**: Smaller, focused files are easier to understand than monolithic scripts.
|
| 307 |
-
|
| 308 |
-
3. **Facilitates Testing**: Modular code is more amenable to unit testing.
|
| 309 |
-
|
| 310 |
-
The object-oriented approach with classes like `AudioManager`, `VideoManager`, etc., provides clear interfaces between components and encapsulates internal implementation details.
|
| 311 |
-
|
| 312 |
-
### Backend Modularity
|
| 313 |
-
|
| 314 |
-
The backend follows a similar modular approach, organizing code into packages and modules by domain:
|
| 315 |
-
|
| 316 |
-
1. **gemini**: Contains all code related to interacting with the Gemini API.
|
| 317 |
-
2. **routes**: Contains HTTP and WebSocket route handlers.
|
| 318 |
-
|
| 319 |
-
This organization:
|
| 320 |
-
|
| 321 |
-
1. **Follows Domain-Driven Design**: Code is organized around business domains rather than technical layers.
|
| 322 |
-
|
| 323 |
-
2. **Improves Discoverability**: New developers can quickly find relevant code based on functionality.
|
| 324 |
-
|
| 325 |
-
3. **Facilitates Expansion**: New features can be added by creating new modules within the appropriate package.
|
| 326 |
-
|
| 327 |
-
## Setup and Installation
|
| 328 |
-
|
| 329 |
-
Setup requires a few steps to configure both the frontend and backend components.
|
| 330 |
-
|
| 331 |
-
### Prerequisites
|
| 332 |
-
|
| 333 |
-
1. **Python 3.11+**: The backend requires Python 3.11 or newer.
|
| 334 |
-
2. **Gemini API Key**: You need a valid API key for Google's Gemini API.
|
| 335 |
-
3. **Modern Web Browser**: The frontend requires a browser with good support for modern web APIs, such as Chrome, Firefox, or Edge.
|
| 336 |
-
|
| 337 |
-
### Installation Steps
|
| 338 |
-
|
| 339 |
-
1. **Clone or download the project**:
|
| 340 |
-
Create the project structure as described earlier, with `frontend` and `backend` directories.
|
| 341 |
-
|
| 342 |
-
2. **Install backend dependencies**:
|
| 343 |
-
Navigate to the `backend` directory and install the required packages:
|
| 344 |
-
```bash
|
| 345 |
-
cd backend
|
| 346 |
-
pip install -r requirements.txt
|
| 347 |
-
```
|
| 348 |
-
|
| 349 |
-
3. **Configure API key**:
|
| 350 |
-
Create a `.env` file in the `backend` directory with your Gemini API key:
|
| 351 |
-
```
|
| 352 |
-
GEMINI_API_KEY=your_api_key_here
|
| 353 |
-
```
|
| 354 |
-
|
| 355 |
-
### Running the Application
|
| 356 |
-
|
| 357 |
-
1. **Start the backend server**:
|
| 358 |
-
From the `backend` directory, run:
|
| 359 |
-
```bash
|
| 360 |
-
python app.py
|
| 361 |
-
```
|
| 362 |
-
This will start the FastAPI server on http://localhost:8000.
|
| 363 |
-
|
| 364 |
-
2. **Access the application**:
|
| 365 |
-
Open your web browser and navigate to:
|
| 366 |
-
```
|
| 367 |
-
http://localhost:8000
|
| 368 |
-
```
|
| 369 |
-
|
| 370 |
-
3. **Using the application**:
|
| 371 |
-
- Configure the system prompt and voice in the interface.
|
| 372 |
-
- Click "Start Chatting" for audio-only interaction.
|
| 373 |
-
- Use "Start Chatting with Video" to include your camera.
|
| 374 |
-
- Use "Start Chatting with Screen" to share your screen.
|
| 375 |
-
|
| 376 |
-
## Troubleshooting Common Issues
|
| 377 |
-
|
| 378 |
-
### WebSocket Connection Failures
|
| 379 |
-
|
| 380 |
-
If the WebSocket connection fails to establish:
|
| 381 |
-
|
| 382 |
-
1. **Verify the backend is running**: Make sure the FastAPI server is running and accessible at http://localhost:8000.
|
| 383 |
-
|
| 384 |
-
2. **Check browser console for errors**: Open the browser's developer tools (F12) and look for error messages in the console.
|
| 385 |
-
|
| 386 |
-
### Audio Capture Issues
|
| 387 |
-
|
| 388 |
-
If the microphone doesn't work:
|
| 389 |
-
|
| 390 |
-
1. **Browser permissions**: Ensure the browser has permission to access the microphone. Look for permission prompts or check browser settings.
|
| 391 |
-
|
| 392 |
-
2. **Correct microphone selected**: If you have multiple microphones, make sure the browser is using the correct one.
|
| 393 |
-
|
| 394 |
-
3. **Sample rate compatibility**: Some devices may not support the 16kHz sample rate. Check if your microphone supports this rate.
|
| 395 |
-
|
| 396 |
-
## Security Considerations
|
| 397 |
-
|
| 398 |
-
The current implementation focuses on functionality, but a production deployment should consider several security aspects:
|
| 399 |
-
|
| 400 |
-
### API Key Protection
|
| 401 |
-
|
| 402 |
-
The Gemini API key is stored in the `.env` file on the server, which prevents it from being exposed in client-side code. However, additional measures should be considered:
|
| 403 |
-
|
| 404 |
-
1. **Environment-specific keys**: Use different API keys for development, testing, and production.
|
| 405 |
-
|
| 406 |
-
2. **Key rotation**: Regularly rotate API keys to limit the impact of potential leaks.
|
| 407 |
-
|
| 408 |
-
3. **Usage limitations**: Set appropriate usage limits on the API key to prevent unexpected costs from abuse.
|
| 409 |
-
|
| 410 |
-
### Data Privacy
|
| 411 |
-
|
| 412 |
-
The application processes sensitive data, including:
|
| 413 |
-
|
| 414 |
-
1. **Audio recordings**: User voice is captured and sent to the Gemini API.
|
| 415 |
-
|
| 416 |
-
2. **Video and screen content**: Camera footage and screen content are captured and sent to Gemini.
|
| 417 |
-
|
| 418 |
-
Proper user consent should be obtained before capturing and processing this data. Additionally, clear privacy policies should inform users about how their data is used.
|
| 419 |
-
|
| 420 |
-
### WebSocket Security
|
| 421 |
-
|
| 422 |
-
For production use, you should consider:
|
| 423 |
-
|
| 424 |
-
1. **Authentication**: Implement user authentication for WebSocket connections.
|
| 425 |
-
|
| 426 |
-
2. **Message validation**: Thoroughly validate all incoming WebSocket messages.
|
| 427 |
-
|
| 428 |
-
3. **Rate limiting**: Implement rate limiting to prevent abuse.
|
| 429 |
-
|
| 430 |
-
4. **WSS (WebSocket Secure)**: Ensure WebSocket connections use secure protocols (WSS over HTTPS).
|
| 431 |
-
|
| 432 |
-
## Potential Performance Optimizations
|
| 433 |
-
|
| 434 |
-
The current implementation balances functionality and performance, but further optimizations could include:
|
| 435 |
-
|
| 436 |
-
### Audio Processing
|
| 437 |
-
|
| 438 |
-
1. **Worker threads**: Move audio processing to Web Workers to avoid impacting the main UI thread.
|
| 439 |
-
|
| 440 |
-
2. **Adjustable quality**: Allow users to select audio quality based on their bandwidth constraints.
|
| 441 |
-
|
| 442 |
-
3. **Audio compression**: Implement audio compression to reduce bandwidth usage.
|
| 443 |
-
|
| 444 |
-
### Video Processing
|
| 445 |
-
|
| 446 |
-
1. **Adaptive frame rate**: Adjust the frequency of screen/camera captures based on available bandwidth.
|
| 447 |
-
|
| 448 |
-
2. **Image compression**: Optimize JPEG compression parameters for better balance between quality and size.
|
| 449 |
-
|
| 450 |
-
3. **Change detection**: Only send new frames when significant changes are detected.
|
| 451 |
-
|
| 452 |
-
### Backend Optimization
|
| 453 |
-
|
| 454 |
-
1. **Connection pooling**: Implement connection pooling for Gemini API connections.
|
| 455 |
-
|
| 456 |
-
2. **Caching**: Cache certain responses or configurations to reduce API calls.
|
| 457 |
-
|
| 458 |
-
3. **Load balancing**: For multi-user deployments, implement load balancing across multiple backend instances.
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
### Potential Functionality Enhancements
|
| 462 |
-
|
| 463 |
-
1. **Conversation history**: Save and load conversation history.
|
| 464 |
-
|
| 465 |
-
2. **Transcription display**: Show real-time transcriptions of both user and Gemini speech.
|
| 466 |
-
|
| 467 |
-
3. **File sharing**: Allow users to share files for Gemini to analyze.
|
| 468 |
-
|
| 469 |
-
### Potential Technical Enhancements
|
| 470 |
-
**WebRTC integration**: Use WebRTC for more efficient real-time communication.
|
| 471 |
-
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Gemini Live Multimodal Demo
|
| 3 |
+
emoji: 🎙️
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
pinned: false
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# Google Gemini Live API Multimodal Demo
|
| 12 |
+
Hosted on Hugging Face Spaces.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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