i have whispler, i i translate offline and free from audio output (i use stereo mix but maybe is better solution). how can i improve translation for example to translate all sentence without cuting audio to parts this is cod:
import pyaudio
import numpy as np
import whisper
import argostranslate.package
import argostranslate.translate
import queue
import threading
import time
import torch
import curses
from curses import wrapper
Audio stream configuration
CHUNK = 1024*32 # Number of audio frames per buffer
FORMAT = pyaudio.paFloat32 # Audio format
CHANNELS = 1 # Mono audio
RATE = 16000 # Sampling rate (Whisper works well with 16kHz)
Queue to handle audio chunks
audio_queue = queue.Queue()
Queue to handle transcribed and translated text for display
display_queue = queue.Queue()
Function to load Whisper model with GPU support
def load_whisper_model(model_name="base"):
print("Loading Whisper model...")
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
# Load the model
model = whisper.load_model(model_name, device=device)
return model
Load Whisper model
whisper_model = load_whisper_model("base")
device = "cuda" if torch.cuda.is_available() else "cpu"
fp16 = True if device == "cuda" else False
Function to process audio chunks with Whisper
def process_audio(audio_data):
# Convert audio data to numpy array
audio_np = np.frombuffer(audio_data, dtype=np.float32)
# Ensure audio data is in the correct format for Whisper (float32, mono, 16kHz)
if len(audio_np) < RATE: # Pad short audio clips
audio_np = np.pad(audio_np, (0, RATE - len(audio_np)), mode='constant')
# Transcribe audio using Whisper
# Use fp16=False if on CPU to avoid the warning
result = whisper_model.transcribe(audio_np, language="he", fp16=fp16)
return result["text"]
Function to translate text using Argos Translate
def translate_text(text, from_code="en", to_code="pl"):
try:
# Download and install translation package (only needs to be done once)
argostranslate.package.update_package_index()
available_packages = argostranslate.package.get_available_packages()
package_to_install = next(
filter(
lambda x: x.from_code == from_code and x.to_code == to_code, available_packages
),
None,
)
if package_to_install:
argostranslate.package.install_from_path(package_to_install.download())
# Perform translation
translated_text = argostranslate.translate.translate(text, from_code, to_code)
return translated_text
except Exception as e:
print(f"Translation error: {e}")
return text # Return original text if translation fails
Function to capture audio stream from system output (Stereo Mix)
def audio_stream(input_device_index):
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
input_device_index=input_device_index, # Specify the device index for Stereo Mix
frames_per_buffer=CHUNK)
print("Capturing system audio... Press Ctrl+C to stop.")
try:
while True:
data = stream.read(CHUNK, exception_on_overflow=False)
audio_queue.put(data)
except KeyboardInterrupt:
print("Stopping audio capture...")
finally:
stream.stop_stream()
stream.close()
p.terminate()
Function to process audio and translate in real-time
def process_and_translate():
while True:
if not audio_queue.empty():
audio_data = audio_queue.get()
# Process audio to text
text = process_audio(audio_data)
if text.strip(): # Only process non-empty text
# Translate text (e.g., English to Spanish)
translated_text = translate_text(text, from_code="he", to_code="en")
translated_text = translate_text(translated_text, from_code="en", to_code="pl")
# Put the results in the display queue
display_queue.put((text, translated_text))
Function to display text in two windows using curses
Function to display text in two windows using curses
def display_text(stdscr):
# Clear the screen
stdscr.clear()
curses.curs_set(0) # Hide cursor
stdscr.nodelay(True) # Non-blocking input
# Get screen dimensions
height, width = stdscr.getmaxyx()
# Create two windows: top for transcribed text, bottom for translated text
top_win_height = height // 2
bottom_win_height = height - top_win_height
top_win = curses.newwin(top_win_height, width, 0, 0)
bottom_win = curses.newwin(bottom_win_height, width, top_win_height, 0)
# Add borders to separate windows
top_win.border()
bottom_win.border()
# Add titles to windows
top_win.addstr(0, 2, " Transcribed Text ")
bottom_win.addstr(0, 2, " Translated Text ")
# Initialize text buffers for continuous display
top_text_buffer = "" # Zmiana na string zamiast listy
bottom_text_buffer = "" # Zmiana na string zamiast listy
while True:
try:
# Check for new text in the display queue
if not display_queue.empty():
text, translated_text = display_queue.get()
top_text_buffer += " " + text # Dodawanie tekstu do ciągu
bottom_text_buffer += " " + translated_text # Dodawanie tekstu do ciągu
# Update top window (transcribed text)
top_win.erase()
top_win.border()
top_win.addstr(0, 2, " Transcribed Text ")
max_lines_top = top_win_height - 2 # Account for border and title
# Przewijanie tekstu, jeśli jest za długi
lines_top = [top_text_buffer[i:i + width - 2] for i in range(0, len(top_text_buffer), width - 2)]
for i, line in enumerate(lines_top[-max_lines_top:]):
top_win.addstr(i + 1, 1, line)
top_win.refresh()
# Update bottom window (translated text)
bottom_win.erase()
bottom_win.border()
bottom_win.addstr(0, 2, " Translated Text ")
max_lines_bottom = bottom_win_height - 2 # Account for border and title
# Przewijanie tekstu, jeśli jest za długi
lines_bottom = [bottom_text_buffer[i:i + width - 2] for i in range(0, len(bottom_text_buffer), width - 2)]
for i, line in enumerate(lines_bottom[-max_lines_bottom:]):
bottom_win.addstr(i + 1, 1, line)
bottom_win.refresh()
# Check for 'q' key to quit
key = stdscr.getch()
if key == ord('q'):
break
time.sleep(0.1) # Small delay to prevent high CPU usage
except KeyboardInterrupt:
break
Main function to run the app
def main(stdscr):
# Replace this with the index of your "Stereo Mix" device (found using the device listing script)
STEREO_MIX_DEVICE_INDEX = 1 # Example index, change to your Stereo Mix index
# Start audio streaming in a separate thread
audio_thread = threading.Thread(target=audio_stream, args=(STEREO_MIX_DEVICE_INDEX,))
audio_thread.daemon = True # Make thread daemon so it exits when main thread exits
audio_thread.start()
# Start processing and translation in a separate thread
process_thread = threading.Thread(target=process_and_translate)
process_thread.daemon = True # Make thread daemon
process_thread.start()
# Start the display in the main thread
display_text(stdscr)
if name == "main":
wrapper(main) # Use curses wrapper to initialize and clean up curses