Skip to content

Commit

Permalink
python3 compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
xiongyihui committed Jun 4, 2018
1 parent 95901e5 commit d78351b
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 22 deletions.
25 changes: 13 additions & 12 deletions avs/alexa.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,16 +140,14 @@ def _run(self):
downchannel_response.headers['content-type'][0].decode('utf-8'))
downchannel_boundary = '--{}'.format(pdict['boundary']).encode('utf-8')
downchannel = conn.streams[downchannel_id]
downchannel_buffer = ''
downchannel_buffer = b''
eventchannel_boundary = 'seeed-voice-engine'

# ping every 5 minutes (60 seconds early for latency) to maintain the connection
self._ping_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=240)
self.event_queue.queue.clear()
self.System.SynchronizeState()
while not self.done:
# logger.info("Waiting for event to send to AVS")
# logger.info("Connection socket can_read %s", conn._sock.can_read)
try:
event, listener, attachment = self.event_queue.get(
timeout=0.25)
Expand Down Expand Up @@ -237,7 +235,7 @@ def _run(self):
if response.status == 200:
_, pdict = cgi.parse_header(
response.headers['content-type'][0].decode('utf-8'))
boundary = b'--{}'.format(pdict['boundary'])
boundary = '--{}'.format(pdict['boundary']).encode('utf-8')
self._parse_response(response.read(), boundary)
elif response.status == 204:
pass
Expand All @@ -248,7 +246,7 @@ def _run(self):
if listener and callable(listener):
listener()

def _parse_response(self, response, boundary, buffer=''):
def _parse_response(self, response, boundary, buffer=b''):
directives = []
blen = len(boundary)
response = buffer + response
Expand All @@ -260,17 +258,17 @@ def _parse_response(self, response, boundary, buffer=''):
# skip small data block
if pos > blen:
# a blank line is between parts
parts = response[:pos - 2].split('\r\n\r\n', 1)
if parts[0].find('application/json') >= 0:
parts = response[:pos - 2].split(b'\r\n\r\n', 1)
if parts[0].find(b'application/json') >= 0:
metadata = json.loads(parts[1].decode('utf-8'))
if 'directive' in metadata:
directives.append(metadata['directive'])
elif parts[0].find('application/octet-stream') >= 0:
elif parts[0].find(b'application/octet-stream') >= 0:
for line in parts[0].splitlines():
name, value = line.split(':', 1)
if name.lower() == 'content-id':
name, value = line.split(b':', 1)
if name.lower() == b'content-id':
content_id = value.strip()[1:-1]
filename = base64.urlsafe_b64encode(content_id)[:8]
filename = base64.urlsafe_b64encode(content_id)[:8].decode('utf-8')
with open(os.path.join(tempfile.gettempdir(), '{}.mp3'.format(filename)), 'wb') as f:
f.write(parts[1])
logger.info('write audio to {}.mp3'.format(filename))
Expand Down Expand Up @@ -401,14 +399,17 @@ def signal_handler(sig, frame):

signal.signal(signal.SIGINT, signal_handler)

while not is_quit.is_set():
while True:
try:
input('press ENTER to talk\n')
except SyntaxError:
pass
except NameError:
pass

if is_quit.is_set():
break

alexa.listen()

alexa.stop()
Expand Down
2 changes: 1 addition & 1 deletion avs/interface/alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def _stop(self):
"""
Stop all active alerts
"""
for token in self.active_alerts.keys():
for token in list(self.active_alerts.keys()):
self.AlertStopped(token)

self.active_alerts = {}
Expand Down
4 changes: 3 additions & 1 deletion avs/interface/speech_synthesizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def Speak(self, directive):
self.token = directive['payload']['token']
url = directive['payload']['url']
if url.startswith('cid:'):
filename = base64.urlsafe_b64encode(url[4:])[:8]
filename = base64.urlsafe_b64encode(url[4:].encode('utf-8'))[:8].decode('utf-8')
mp3_file = os.path.join(tempfile.gettempdir(), filename + '.mp3')
if os.path.isfile(mp3_file):
self.mp3_file = mp3_file
Expand All @@ -87,6 +87,8 @@ def Speak(self, directive):

# will be set at SpeechFinished() if the player reaches the End Of Stream or gets a error
# self.finished.wait()
else:
logger.warning('not find {}'.format(mp3_file))

def SpeechStarted(self):
self._state = 'PLAYING'
Expand Down
4 changes: 2 additions & 2 deletions avs/mic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
recorder_option = os.getenv('RECORDER', 'default').lower()

if recorder_option.find('pyaudio') >= 0 or os.system('which arecord >/dev/null') != 0:
from pyaudio_recorder import Audio
from .pyaudio_recorder import Audio
else:
from alsa_recorder import Audio
from .alsa_recorder import Audio

__all__ = ['Audio']
12 changes: 6 additions & 6 deletions avs/player/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@
player_option = os.getenv('PLAYER', 'default').lower()

if player_option.find('mpv') >= 0:
from mpv_player import Player
from .mpv_player import Player
elif player_option.find('mpg123') >= 0:
from mpg123_player import Player
from .mpg123_player import Player
elif player_option.find('gstreamer') >= 0:
from gstreamer_player import Player
from .gstreamer_player import Player
else:
try:
from gstreamer_player import Player
from .gstreamer_player import Player
except ImportError:
if os.system('which mpv >/dev/null') == 0:
from mpv_player import Player
from .mpv_player import Player
elif os.system('which mpg123 >/dev/null') == 0:
from mpg123_player import Player
from .mpg123_player import Player
else:
raise ImportError('No player available, install one of the players: gstreamer, mpv and mpg123 first')

Expand Down

0 comments on commit d78351b

Please sign in to comment.