Skip to content

Enforce 25Kb limit for infinite transcription #13301

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion speech/microphone/transcribe_streaming_infinite_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
STREAMING_LIMIT = 240000 # 4 minutes
SAMPLE_RATE = 16000
CHUNK_SIZE = int(SAMPLE_RATE / 10) # 100ms
# 25KB API limit for streaming requests. Exceeding this limit will result in an error.
MAX_STREAMING_CHUNK = 25 * 1024

RED = "\033[0;31m"
GREEN = "\033[0;32m"
Expand Down Expand Up @@ -213,7 +215,23 @@ def generator(self: object) -> object:
except queue.Empty:
break

yield b"".join(data)
# Enforce max streaming chunk size supported by the API
combined_size = sum(len(chunk) for chunk in data)
if combined_size <= MAX_STREAMING_CHUNK:
yield b"".join(data)
else:
run_chunks = []
run_size = 0
for chunk in data:
if len(chunk) + run_size > MAX_STREAMING_CHUNK:
yield b"".join(run_chunks)
run_chunks = [chunk]
run_size = len(chunk)
else:
run_chunks.append(chunk)
run_size += len(chunk)
if run_chunks:
yield b"".join(run_chunks)
Comment on lines +219 to +234
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The code iterates through the data list twice. First to calculate combined_size and then to create the chunks. This could be combined into a single loop for better efficiency. Consider calculating the combined_size while creating the chunks, and only yielding the combined data if it's within the limit. If it exceeds the limit, yield the accumulated chunks and start a new chunk.

            current_chunk = []
            current_chunk_size = 0
            for chunk in data:
                if current_chunk_size + len(chunk) <= MAX_STREAMING_CHUNK:
                    current_chunk.append(chunk)
                    current_chunk_size += len(chunk)
                else:
                    if current_chunk:
                        yield b''.join(current_chunk)
                    current_chunk = [chunk]
                    current_chunk_size = len(chunk)
            if current_chunk:
                yield b''.join(current_chunk)



def listen_print_loop(responses: object, stream: object) -> None:
Expand Down