#!/usr/bin/env python3

import time
import speech_recognition as sr

r = sr.Recognizer()
r.pause_threshold = 0.5

# Setting chunk_size to a small value (e.g. 256) increases the sensitiy of the sound detection
m = sr.Microphone(device_index=0, sample_rate=16000, chunk_size=256)

def process_trigger(data):
    print(data)
    if "computer" in data.lower():
        print("computer found")

def stop_listen_for_trigger():
    print("Stopping listener for trigger")
    stop_listening(wait_for_stop=False)

def listen_for_trigger(recognizer, audio):
    try:
        print("Sound detected...")
        trigger = recognizer.recognize_sphinx(audio, keyword_entries=[('computer', 0.5)])
        if trigger:
            print(f"Trigger detected! - {trigger}")
            process_trigger(trigger)
            # stop_listen_for_trigger()
    except sr.UnknownValueError:
        print("Sphinx could not understand audio")
    except sr.RequestError as e:
        print("Sphinx error; {0}".format(e))

with m as source:
    r.adjust_for_ambient_noise(source, duration=2.0)

stop_listening = r.listen_in_background(m, listen_for_trigger, phrase_time_limit=1.5)

counter = 0
while counter < 500:
    counter += 1
    print("Listening...")
    time.sleep(1.0)

# stop_listening(wait_for_stop=False)
