import sys
import numpy as np
from faster_whisper import WhisperModel

# --------------------------
# LOAD MODEL
# --------------------------
model = WhisperModel(
    "base.en",
    device="cpu",
    compute_type="int8"
)

buffer = b""
CHUNK_SIZE = 16000 * 2 * 2   # 2 seconds of PCM16 (64000 bytes)

print("PYTHON_WORKER_READY", flush=True)

# --------------------------
# MAIN LOOP (READ STDIN PCM)
# --------------------------
while True:
    data = sys.stdin.buffer.read(4096)

    if not data:
        continue

    buffer += data

    # process only when chunk is large enough
    if len(buffer) < CHUNK_SIZE:
        continue

    pcm = buffer[:CHUNK_SIZE]
    buffer = buffer[CHUNK_SIZE:]

    # --------------------------
    # PCM16 → float32 conversion
    # --------------------------
    audio = np.frombuffer(pcm, dtype=np.int16).astype(np.float32) / 32768.0

    # --------------------------
    # RUN WHISPER
    # --------------------------
    segments, _ = model.transcribe(
        audio,
        language="en",
        beam_size=1
    )

    text = ""
    for segment in segments:
        text += segment.text + " "

    text = text.strip()

    # Print transcript to Node
    if text:
        print(text, flush=True)
