Skip to content
This repository has been archived by the owner on Dec 20, 2023. It is now read-only.

Commit

Permalink
fix python 3 compatibility at various places
Browse files Browse the repository at this point in the history
  • Loading branch information
renekliment committed Feb 20, 2017
1 parent 5cb6cff commit d96228b
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 29 deletions.
6 changes: 3 additions & 3 deletions src/alexapi/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Capture(object):

VAD_SAMPLERATE = 16000
VAD_FRAME_MS = 30
VAD_PERIOD = (VAD_SAMPLERATE / 1000) * VAD_FRAME_MS
VAD_PERIOD = int((VAD_SAMPLERATE / 1000) * VAD_FRAME_MS)
VAD_SILENCE_TIMEOUT = 1000
VAD_THROWAWAY_FRAMES = 10

Expand Down Expand Up @@ -55,7 +55,7 @@ def silence_listener(self, throwaway_frames=None, force_record=None):
inp.setrate(self.VAD_SAMPLERATE)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(self.VAD_PERIOD)
audio = ""
audio = b''

start = time.time()

Expand Down Expand Up @@ -112,5 +112,5 @@ def silence_listener(self, throwaway_frames=None, force_record=None):
if self._state_callback:
self._state_callback(False)

with open(self._tmp_path + 'recording.wav', 'w') as rf:
with open(self._tmp_path + 'recording.wav', 'wb') as rf:
rf.write(audio)
4 changes: 3 additions & 1 deletion src/alexapi/device_platforms/chipplatform.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import CHIP_IO.GPIO as GPIO
# the library doesn't support python 3 actively (yet hopefully)
# pylint gives: Unable to import 'CHIP_IO.GPIO' (import-error)
import CHIP_IO.GPIO as GPIO # pylint: disable=import-error

from .rpilikeplatform import RPiLikePlatform

Expand Down
29 changes: 19 additions & 10 deletions src/alexapi/device_platforms/magicmirrorplatform.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import BaseHTTPServer
import threading
import urllib2
import urlparse
import logging
import threading

try:
import BaseHTTPServer
except ImportError:
import http.server as BaseHTTPServer

try:
from urllib.request import urlopen, URLError
import urllib.urlparse as urlparse
except ImportError:
from urllib2 import urlopen, URLError
import urlparse

from .baseplatform import BasePlatform

Expand Down Expand Up @@ -31,8 +40,8 @@ def __init__(self, config):
self.hb_timer = self._pconfig['hb_timer']

self.shutdown = False
self.httpd = ""
self.serverthread = ""
self.httpd = None
self.serverthread = None

def setup(self):
logger.debug("Setting up Magic Mirror platform")
Expand Down Expand Up @@ -88,8 +97,8 @@ def update_mm(self, status):
logger.debug("Calling URL: %s", address)

try:
response = urllib2.urlopen(address).read()
except urllib2.URLError, err:
response = urlopen(address).read()
except URLError as err:
logger.error("URLError: %s", err.reason)
return

Expand All @@ -106,8 +115,8 @@ def mm_heartbeat(self):
logger.debug("Sending MM Heatbeat")

try:
response = urllib2.urlopen(address).read()
except urllib2.URLError, err:
response = urlopen(address).read()
except URLError as err:
logger.error("URLError: %s", err.reason)
return

Expand Down
7 changes: 4 additions & 3 deletions src/alexapi/playback_handlers/soxhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,13 @@ def on_play(self, item):
sox_cmd.extend(['pad', self.playback_padding, self.playback_padding])

self.report_play(' '.join(sox_cmd))
play_err = u''
try:
self.proc = subprocess.Popen(sox_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
_, stderr = self.proc.communicate()
play_err = stderr
play_err = stderr.decode()
except OSError as ex:
play_err = ex.message
play_err = str(ex).decode()

if play_err:
self.report_error(play_err)
Expand All @@ -75,7 +76,7 @@ def on_stop(self):
try:
self.proc.kill()
except OSError as ex:
stop_err = ex.message
stop_err = str(ex)
else:
stop_err = 'No SoX process to stop'

Expand Down
21 changes: 16 additions & 5 deletions src/alexapi/tunein.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
from __future__ import unicode_literals

import ConfigParser as configparser
try:
import configparser
except ImportError:
import ConfigParser as configparser

import logging
import re
import time
import urlparse

try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse

from collections import OrderedDict
from contextlib import closing

import requests

try:
import cStringIO as StringIO
import io as StringIO
except ImportError:
import StringIO as StringIO
try:
import cStringIO as StringIO
except ImportError:
import StringIO as StringIO

try:
import xml.etree.cElementTree as elementtree
except ImportError:
Expand Down Expand Up @@ -297,7 +308,7 @@ def _station_info(self, station_id):

def parse_stream_url(self, url):
logger.debug('Extracting URIs from %s', url)
extension = urlparse.urlparse(url).path[-4:]
extension = urlparse(url).path[-4:]
if extension in ['.mp3', '.wma']:
logger.debug('Got %s', url)
return [url] # Catch these easy ones
Expand Down
8 changes: 6 additions & 2 deletions src/auth_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@
from __future__ import print_function
import os
import json
import urllib
import socket
import yaml
import cherrypy
import requests

try:
from urllib.parse import quote
except ImportError:
from urllib import quote

import alexapi.config

with open(alexapi.config.filename, 'r') as stream:
Expand Down Expand Up @@ -41,7 +45,7 @@ def index(self):
raise cherrypy.HTTPRedirect(prepared_req.url)

def code(self, var=None, **params): # pylint: disable=unused-argument
code = urllib.quote(cherrypy.request.params['code'])
code = quote(cherrypy.request.params['code'])
callback = cherrypy.url()
payload = {
"client_id": config['alexa']['Client_ID'],
Expand Down
15 changes: 10 additions & 5 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def tunein_playlist(self, url):
logger.debug("TUNE IN URL = %s", url)

req = requests.get(url)
lines = req.content.split('\n')
lines = req.content.decode().split('\n')

nurl = self.tunein_parser.parse_stream_url(lines[0])
if nurl:
Expand Down Expand Up @@ -306,7 +306,7 @@ def alexa_speech_recognizer():
}
}

with open(tmp_path + 'recording.wav') as inf:
with open(tmp_path + 'recording.wav', 'rb') as inf:
files = [
('file', ('request', json.dumps(data), 'application/json; charset=UTF-8')),
('file', ('audio', inf, 'audio/L16; rate=16000; channels=1'))
Expand Down Expand Up @@ -393,16 +393,21 @@ def process_response(response):
logger.debug("Processing Request Response...")

if response.status_code == 200:
data = "Content-Type: " + response.headers['content-type'] + '\r\n\r\n' + response.content
msg = email.message_from_string(data)
try:
data = bytes("Content-Type: ", 'utf-8') + bytes(response.headers['content-type'], 'utf-8') + bytes('\r\n\r\n', 'utf-8') + response.content
msg = email.message_from_bytes(data) # pylint: disable=no-member
except TypeError:
data = "Content-Type: " + response.headers['content-type'] + '\r\n\r\n' + response.content
msg = email.message_from_string(data)

for payload in msg.get_payload():
if payload.get_content_type() == "application/json":
j = json.loads(payload.get_payload())
logger.debug("JSON String Returned: %s", json.dumps(j, indent=2))
elif payload.get_content_type() == "audio/mpeg":
filename = tmp_path + payload.get('Content-ID').strip("<>") + ".mp3"
with open(filename, 'wb') as f:
f.write(payload.get_payload())
f.write(payload.get_payload(decode=True))
else:
logger.debug("NEW CONTENT TYPE RETURNED: %s", payload.get_content_type())

Expand Down

0 comments on commit d96228b

Please sign in to comment.