Skip to content

Commit

Permalink
better logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikolay-Kha committed Mar 24, 2017
1 parent 935b3ef commit 1ff96d2
Show file tree
Hide file tree
Showing 8 changed files with 32 additions and 21 deletions.
3 changes: 3 additions & 0 deletions alexa.py
Expand Up @@ -2,8 +2,11 @@

import alexa_auth
import alexa_audio_device
import logging

def main():
logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s] %(message)s', datefmt='%d/%m/%Y %H:%M:%S')
logging.getLogger("requests").setLevel(logging.CRITICAL)
alexa_audio_device.init()
alexa_auth.start()
try:
Expand Down
21 changes: 11 additions & 10 deletions alexa_audio.py
Expand Up @@ -5,6 +5,7 @@
import struct
import time
import alexa_audio_device
import logging
from subprocess import Popen, PIPE, STDOUT
from pocketsphinx import *

Expand All @@ -30,7 +31,7 @@ def __init__(self, threshold, callback):
config.set_string('-dict', os.path.join(get_model_path(), 'cmudict-en-us.dict'))
config.set_string('-logfn', '/dev/null')
config.set_string('-keyphrase', 'alexa')
print("Voice threshold is " + str(threshold))
logging.info("Voice threshold is " + str(threshold))
config.set_float('-kws_threshold', threshold)
self.decoder = Decoder(config)
self.decoder.start_utt()
Expand Down Expand Up @@ -68,11 +69,11 @@ def start_capture(self, notify = True):
self.notify = notify

def processAudio(self):
print("Audio Processing started.")
logging.info("Audio Processing started.")
while self.is_run:
buf = self.ad.read(16000)
if buf is None:
print("Alexa audio processing exit")
logging.info("Alexa audio processing exit")
break
if self.skip > 0:
self.skip -= len(buf)
Expand All @@ -93,30 +94,30 @@ def processAudio(self):
level < self.average * DETECT_HYSTERESIS):
self.capture_in_progress = False
if self.detect_buffer_max > self.average * DETECT_HYSTERESIS:
print("Finished " + str(duration) + "s")
logging.info("Finished " + str(duration) + "s")
self.buffer = self.detect_buffer
if self.notify:
threading.Thread(target=self.callback).start()
self.skip += 16000
#self.play(self.detect_buffer)
else:
print("Cancel " + str(duration) + "s due to the low level ")
logging.info("Cancel " + str(duration) + "s due to the low level ")
#self.beep_failed()
else:
self.decoder.process_raw(buf, False, False)
if self.decoder.hyp() != None and self.init_counter > DETECT_BUFFERS_FOR_INIT:
self.start_capture()
self.detect_buffer += buf
print("Found Alexa keyword")
logging.info("Found Alexa keyword")
self.decoder.end_utt()
self.decoder.start_utt()
else:
if self.init_counter <= DETECT_BUFFERS_FOR_INIT:
if self.init_counter == DETECT_BUFFERS_FOR_INIT:
print("Alexa is initialized and started.")
logging.info("Alexa is initialized and started.")
self.init_counter += 1
self.average = self.average * 0.75 + level * 0.25
print("Audio Processing finished.")
logging.info("Audio Processing finished.")

def close(self):
self.is_run = False
Expand All @@ -134,11 +135,11 @@ def get_audio(self, timeout = None):
if self.detect_buffer_max > self.average * DETECT_HYSTERESIS:
res = self.detect_buffer
self.capture_in_progress = False
print('Timeout exceed, phrase might not be completed')
logging.info('Timeout exceed, phrase might not be completed')
self.beep_finished()
return res
else:
print('Timeout exceed, but nothing was detected')
logging.info('Timeout exceed, but nothing was detected')
self.beep_failed()
return None
res = self.buffer
Expand Down
2 changes: 1 addition & 1 deletion alexa_audio_device.py
Expand Up @@ -3,5 +3,5 @@
try:
from alexa_audio_device_pulse import *
except ImportError:
from alexa_audio_device_pyduio import *
from alexa_audio_device_pyaduio import *

3 changes: 2 additions & 1 deletion alexa_audio_device_pulse.py
Expand Up @@ -3,6 +3,7 @@
import math
import struct
import ctypes
import logging

class _struct_pa_sample_spec(ctypes.Structure):
_fields_ = [('format', ctypes.c_int),
Expand Down Expand Up @@ -34,7 +35,7 @@ def init():
if not in_stream:
raise Exception('Could not create pulse audio input stream: '
+ str(pa.strerror(error), 'ascii'))
print('PulseAudio is initialized.')
logging.info('PulseAudio is initialized.')

def deinit():
pa.pa_simple_free(in_stream)
Expand Down
7 changes: 4 additions & 3 deletions alexa_auth.py
Expand Up @@ -4,6 +4,7 @@
import alexa_http_config
import socket
import threading
import logging
from zeroconf import raw_input, ServiceInfo, Zeroconf
from http.server import HTTPServer

Expand All @@ -21,7 +22,7 @@ def get_local_address():
def start():
global localHTTP, zeroconf, info, httpthread
ip = get_local_address()
print("Local IP is " + ip)
logging.info("Local IP is " + ip)

desc = {'version': '0.1'}
info = ServiceInfo("_http._tcp.local.",
Expand All @@ -30,11 +31,11 @@ def start():
desc, alexa_params.LOCAL_HOST + ".")
zeroconf = Zeroconf()
zeroconf.registerService(info)
print("Local mDNS is started, domain is " + alexa_params.LOCAL_HOST)
logging.info("Local mDNS is started, domain is " + alexa_params.LOCAL_HOST)
localHTTP = HTTPServer(("", alexa_params.LOCAL_PORT), alexa_http_config.AlexaConfig)
httpthread = threading.Thread(target=localHTTP.serve_forever)
httpthread.start()
print("Local HTTP is " + alexa_params.BASE_URL)
logging.info("Local HTTP is " + alexa_params.BASE_URL)
alexa_control.start()

def close():
Expand Down
3 changes: 2 additions & 1 deletion alexa_control.py
Expand Up @@ -2,6 +2,7 @@

import os
import json
import logging
import alexa_params
import alexa_device
import alexa_http_config
Expand All @@ -14,7 +15,7 @@ def start():
return
alexa_config = alexa_http_config.load_config()
if alexa_config is not None:
print("Alexa found config.")
logging.info("Alexa found config.")
alexa = alexa_device.AlexaDevice(alexa_config)

def close():
Expand Down
11 changes: 6 additions & 5 deletions alexa_device.py
Expand Up @@ -4,6 +4,7 @@
import threading
import json
import time
import logging

import alexa_audio

Expand Down Expand Up @@ -78,27 +79,27 @@ def get_audio_and_send(self, timeout = None):
try:
r = requests.post(url, headers=headers, files=files)
except requests.exceptions.ConnectionError as e:
print(type(e).__name__)
logging.info(type(e).__name__)
time.sleep(0.1)
self.alexa_audio_instance.beep_failed()
return
if r.status_code != requests.codes.ok:
print("Audio response faile with " + str(r.status_code) + " code: " + r.text)
logging.info("Audio response faile with " + str(r.status_code) + " code: " + r.text)
self.alexa_audio_instance.beep_failed()
return
content = r.content
mpegpos = content.find(b'audio/mpeg')
if mpegpos < 0:
print("No audio found in response: " + r.text)
logging.info("No audio found in response: " + r.text)
self.alexa_audio_instance.beep_failed()
return
rawmpegpos = content.find(b'\r\n\r\n', mpegpos);
if rawmpegpos < 0:
print("No raw audio data found: " + r.text)
logging.info("No raw audio data found: " + r.text)
self.alexa_audio_instance.beep_failed()
return
data = content[rawmpegpos + 4:]
print("Alexa got response")
logging.info("Alexa got response")
self.alexa_audio_instance.play_mp3(data)
if self.check_response(content):
time.sleep(0.5)
Expand Down
3 changes: 3 additions & 0 deletions alexa_http_config.py
Expand Up @@ -151,3 +151,6 @@ def authorizedAnswer(self):
self.wfile.write(bytes("<p><a href=/restart>Click here to restart Alexa.</a></p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))

def log_message(self, format, *args):
return

0 comments on commit 1ff96d2

Please sign in to comment.