from vosk import Model, KaldiRecognizer
import pyaudio
import json
import numpy as np
import os
import time

def amplify(data, dB):
    factor = 10 ** (dB / 20)
    audio = np.frombuffer(data, dtype=np.int16)
    boosted = np.clip(audio * factor, -32768, 32767).astype(np.int16)
    return boosted.tobytes()

model = Model("model")
rec = KaldiRecognizer(model, 48000)
rec.SetWords(False)

p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
                channels=1,
                rate=48000,
                input=True,
                input_device_index=1,
                frames_per_buffer=8000)
stream.start_stream()

print("Listening with pause control...")

pause_file = "/dev/shm/pause_recognition"

while True:
    # Check if pause flag file exists
    if os.path.exists(pause_file):
        time.sleep(0.1)
        #print("Paused...")
        continue

    data = stream.read(4000, exception_on_overflow=False)
    amplified = amplify(data, 30)

    if rec.AcceptWaveform(amplified):
        result = json.loads(rec.Result())
        text = result.get("text", "").strip()
        print(f"✅ Final: {text}")  # Debug final output
        if text:
            with open("/dev/shm/input.txt", "w") as f:
                f.write(text)
    else:
        partial = json.loads(rec.PartialResult()).get("partial", "").strip()
        if partial:
            print(f"⏳ Partial: {partial}")  # Debug partial input
