Skip to content
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

Maximum number of clients reached #372

Open
vizvasrj opened this issue Dec 19, 2024 · 0 comments
Open

Maximum number of clients reached #372

vizvasrj opened this issue Dec 19, 2024 · 0 comments
Assignees
Labels
component:examples Issues/PR referencing examples folder status:triaged Issue/PR triaged to the corresponding sub-team type:help Support-related issues

Comments

@vizvasrj
Copy link

vizvasrj commented Dec 19, 2024

i use screen share mode in this

Description of the bug:

python audioVideo.py --mode=screen

from https://github.com/google-gemini/cookbook/blob/main/gemini-2/live_api_starter.py
every thing like screen share and audio and text all work great but it say maximum number of clients reached

# -*- coding: utf-8 -*-
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# To install the dependencies for this script, run:
#  pip install google-genai opencv-python pyaudio pillow mss
# And to run this script, ensure the GOOGLE_API_KEY environment
# variable is set to the key you obtained from Google AI Studio.

# Add the "--mode screen" if you want to share your screen to the model
# instead of your camera stream
from termcolor import colored

import asyncio
import base64
import io
import os
import sys
import traceback

import cv2
import pyaudio
import PIL.Image
import mss

import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    "--mode",
    type=str,
    default="camera",
    help="pixels to stream from",
    choices=["camera", "screen"],
)
args = parser.parse_args()

from google import genai

if sys.version_info < (3, 11, 0):
    import taskgroup, exceptiongroup

    asyncio.TaskGroup = taskgroup.TaskGroup
    asyncio.ExceptionGroup = exceptiongroup.ExceptionGroup

FORMAT = pyaudio.paInt16
CHANNELS = 1
SEND_SAMPLE_RATE = 16000
RECEIVE_SAMPLE_RATE = 24000
CHUNK_SIZE = 1024
from termcolor import colored
MODEL = "models/gemini-2.0-flash-exp"

MODE = args.mode

client = genai.Client(http_options={"api_version": "v1alpha"})

CONFIG = {"generation_config": {"response_modalities": ["TEXT"]}}

pya = pyaudio.PyAudio()


class AudioLoop:
    def __init__(self):
        self.audio_in_queue = None
        self.audio_out_queue = None
        self.video_out_queue = None

        self.session = None

        self.send_text_task = None
        self.receive_audio_task = None
        self.play_audio_task = None
        self.colors = ['red', 'green', 'yellow', 'blue', 'magenta']
        self.color_index = 0
    
    def get_next_color(self):
        color = self.colors[self.color_index]
        self.color_index = (self.color_index + 1) % len(self.colors)
        return color

    async def send_text(self):
        while True:
            text = await asyncio.to_thread(
                input,
                "message > ",
            )
            if text.lower() == "q":
                break
            await self.session.send(text or ".", end_of_turn=True)

    def _get_frame(self, cap):
        # Read the frameq
        ret, frame = cap.read()
        # Check if the frame was read successfully
        if not ret:
            return None
        # Fix: Convert BGR to RGB color space
        # OpenCV captures in BGR but PIL expects RGB format
        # This prevents the blue tint in the video feed
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        img = PIL.Image.fromarray(frame_rgb)  # Now using RGB frame
        img.thumbnail([1024, 1024])

        image_io = io.BytesIO()
        img.save(image_io, format="jpeg")
        image_io.seek(0)

        mime_type = "image/jpeg"
        image_bytes = image_io.read()
        return {"mime_type": mime_type, "data": base64.b64encode(image_bytes).decode()}

    async def get_frames(self):
        # This takes about a second, and will block the whole program
        # causing the audio pipeline to overflow if you don't to_thread it.
        cap = await asyncio.to_thread(
            cv2.VideoCapture, 0
        )  # 0 represents the default camera

        while True:
            frame = await asyncio.to_thread(self._get_frame, cap)
            if frame is None:
                break

            await asyncio.sleep(1.0)

            await self.out_queue.put(frame)

        # Release the VideoCapture object
        cap.release()

    def _get_screen(self):
        sct = mss.mss()
        monitor = sct.monitors[0]
        # print(colored(f"Monitor: {monitor}", "green"))

        # ┌──(root㉿kali)-[~/hw/github]
        # └─# xdotool getmouselocation
        # x:444 y:117 screen:0 window:48234508
                                                                                        
        # ┌──(root㉿kali)-[~/hw/github]
        # └─# xdotool getmouselocation
        # x:906 y:762 screen:0 window:44040254

        # i = sct.grab(monitor)
        i = sct.grab((444, 117, 906, 762))

        mime_type = "image/jpeg"
        image_bytes = mss.tools.to_png(i.rgb, i.size)
        img = PIL.Image.open(io.BytesIO(image_bytes))

        image_io = io.BytesIO()
        img.save(image_io, format="jpeg")
        image_io.seek(0)

        image_bytes = image_io.read()
        return {"mime_type": mime_type, "data": base64.b64encode(image_bytes).decode()}

    async def get_screen(self):

        while True:
            frame = await asyncio.to_thread(self._get_screen)
            if frame is None:
                break

            await asyncio.sleep(1.0)

            await self.out_queue.put(frame)

    async def send_realtime(self):
        while True:
            msg = await self.out_queue.get()
            await self.session.send(msg)

    async def listen_audio(self):
        mic_info = pya.get_default_input_device_info()
        self.audio_stream = await asyncio.to_thread(
            pya.open,
            format=FORMAT,
            channels=CHANNELS,
            rate=SEND_SAMPLE_RATE,
            input=True,
            input_device_index=mic_info["index"],
            frames_per_buffer=CHUNK_SIZE,
        )
        if __debug__:
            kwargs = {"exception_on_overflow": False}
        else:
            kwargs = {}
        while True:
            data = await asyncio.to_thread(self.audio_stream.read, CHUNK_SIZE, **kwargs)
            await self.out_queue.put({"data": data, "mime_type": "audio/pcm"})

    # async def receive_audio(self):
    #     "Background task to reads from the websocket and write pcm chunks to the output queue"
    #     while True:
    #         turn = self.session.receive()
    #         async for response in turn:
    #             if data := response.data:
    #                 self.audio_in_queue.put_nowait(data)
    #                 continue
    #             if text := response.text:
    #                 color = self.get_next_color()
    #                 print(colored(text, color), end="")

    #         # If you interrupt the model, it sends a turn_complete.
    #         # For interruptions to work, we need to stop playback.
    #         # So empty out the audio queue because it may have loaded
    #         # much more audio than has played yet.
    #         while not self.audio_in_queue.empty():
    #             self.audio_in_queue.get_nowait()
    async def receive_audio(self):
        "Background task to reads from the websocket and write pcm chunks to the output queue"
        while True:
            async for response in self.session.receive():
                server_content = response.server_content
                if server_content is not None:
                    model_turn = server_content.model_turn
                    if model_turn is not None:
                        parts = model_turn.parts

                        for part in parts:
                            if part.text is not None:
                                color = self.get_next_color()
                                print(colored(part.text, color), end="")
                            elif part.inline_data is not None:
                                self.audio_in_queue.put_nowait(part.inline_data.data)

                    server_content.model_turn = None
                    turn_complete = server_content.turn_complete
                    if turn_complete:
                        # If you interrupt the model, it sends a turn_complete.
                        # For interruptions to work, we need to stop playback.
                        # So empty out the audio queue because it may have loaded
                        # much more audio than has played yet.
                        print("Turn complete")
                        while not self.audio_in_queue.empty():
                            self.audio_in_queue.get_nowait()

    async def play_audio(self):
        stream = await asyncio.to_thread(
            pya.open,
            format=FORMAT,
            channels=CHANNELS,
            rate=RECEIVE_SAMPLE_RATE,
            output=True,
        )
        while True:
            bytestream = await self.audio_in_queue.get()
            await asyncio.to_thread(stream.write, bytestream)

    async def run(self):
        try:
            async with (
                client.aio.live.connect(model=MODEL, config=CONFIG) as session,
                asyncio.TaskGroup() as tg,
            ):
                self.session = session

                self.audio_in_queue = asyncio.Queue()
                self.out_queue = asyncio.Queue(maxsize=5)

                send_text_task = tg.create_task(self.send_text())
                tg.create_task(self.send_realtime())
                tg.create_task(self.listen_audio())
                if MODE == "camera":
                    tg.create_task(self.get_frames())
                elif MODE == "screen":
                    tg.create_task(self.get_screen())
                tg.create_task(self.receive_audio())
                tg.create_task(self.play_audio())

                await send_text_task
                raise asyncio.CancelledError("User requested exit")

        except asyncio.CancelledError:
            pass
        except ExceptionGroup as EG:
            self.audio_stream.close()
            traceback.print_exception(EG)


if __name__ == "__main__":
    main = AudioLoop()
    asyncio.run(main.run())

Actual vs expected behavior:

No response

Any other information you'd like to share?

No response

@gmKeshari gmKeshari added type:help Support-related issues status:triaged Issue/PR triaged to the corresponding sub-team component:examples Issues/PR referencing examples folder labels Dec 20, 2024
@Giom-V Giom-V assigned Giom-V, markmcd and MarkDaoust and unassigned Giom-V Dec 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component:examples Issues/PR referencing examples folder status:triaged Issue/PR triaged to the corresponding sub-team type:help Support-related issues
Projects
None yet
Development

No branches or pull requests

5 participants