Skip to content
This repository has been archived by the owner on Apr 13, 2018. It is now read-only.

Commit

Permalink
Modernize Python 2 code to get ready for Python 3 (#92)
Browse files Browse the repository at this point in the history
  • Loading branch information
cclauss authored and wzpan committed Jan 8, 2018
1 parent c128123 commit 66c192f
Show file tree
Hide file tree
Showing 20 changed files with 158 additions and 104 deletions.
15 changes: 8 additions & 7 deletions client/app_utils.py
@@ -1,4 +1,5 @@
# -*- coding: utf-8-*-
from __future__ import print_function
import smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
Expand Down Expand Up @@ -40,7 +41,7 @@ def sendEmail(SUBJECT, BODY, ATTACH_LIST, TO, FROM, SENDER,
session.sendmail(SENDER, TO, msg.as_string())
session.close()
return True
except Exception, e:
except Exception as e:
_logger.error(e)
return False

Expand Down Expand Up @@ -78,7 +79,7 @@ def emailUser(profile, SUBJECT="", BODY="", ATTACH_LIST=[]):
recipient, password, server, port)

return True
except Exception, e:
except Exception as e:
_logger.error(e)
return False

Expand All @@ -100,7 +101,7 @@ def wechatUser(profile, wxbot, SUBJECT="", BODY="",
wxbot.send_img_msg_by_uid(fpath, user_id)
return True
return True
except Exception, e:
except Exception as e:
_logger.error(e)
return False
return False
Expand Down Expand Up @@ -141,14 +142,14 @@ def create_reminder(remind_event, remind_time):
remind_time[:4] + '-' + remind_time[4:6] + '-' + \
remind_time[6:8] + 'T' + remind_time[8:10] + ':' + \
remind_time[10:12] + ':' + remind_time[12:]
print cmd
print(cmd)
try:
res = subprocess.call(
[cmd],
stdout=subprocess.PIPE, shell=True)
print res
print(res)
return(res == 0)
except Exception, e:
except Exception as e:
_logger.error(e)
return False
else:
Expand Down Expand Up @@ -200,7 +201,7 @@ def get_due_reminders():
stdin=subprocess.PIPE)
p.stdin.write('yes\n')

except Exception, e:
except Exception as e:
_logger.error(e)

return due_tasks
3 changes: 2 additions & 1 deletion client/audio_utils.py
@@ -1,5 +1,6 @@
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
import os
from pydub import AudioSegment

Expand All @@ -11,4 +12,4 @@ def mp3_to_wav(mp3_file):
voice.export(target, format="wav")
return target
else:
print u"文件错误"
print(u"文件错误")
3 changes: 2 additions & 1 deletion client/brain.py
@@ -1,7 +1,8 @@
# -*- coding: utf-8-*-
from __future__ import absolute_import
import logging
import pkgutil
import dingdangpath
from . import dingdangpath


class Brain(object):
Expand Down
5 changes: 3 additions & 2 deletions client/conversation.py
@@ -1,7 +1,8 @@
# -*- coding: utf-8-*-
from __future__ import absolute_import
import logging
from notifier import Notifier
from brain import Brain
from .notifier import Notifier
from .brain import Brain
import time


Expand Down
3 changes: 2 additions & 1 deletion client/diagnose.py
@@ -1,4 +1,5 @@
# -*- coding: utf-8-*-
from __future__ import absolute_import
import os
import sys
import time
Expand All @@ -7,7 +8,7 @@
import pkgutil
import logging
import pip.req
import dingdangpath
from . import dingdangpath
if sys.version_info < (3, 3):
from distutils.spawn import find_executable
else:
Expand Down
5 changes: 3 additions & 2 deletions client/g2p.py
@@ -1,4 +1,5 @@
# -*- coding: utf-8-*-
from __future__ import absolute_import
import os
import re
import subprocess
Expand All @@ -7,8 +8,8 @@

import yaml

import diagnose
import dingdangpath
from . import diagnose
from . import dingdangpath


class PhonetisaurusG2P(object):
Expand Down
6 changes: 6 additions & 0 deletions client/local_mic.py
Expand Up @@ -4,6 +4,12 @@
over the terminal. Useful for debugging. Unlike with the typical Mic
implementation, Dingdang is always active listening with local_mic.
"""
from __future__ import print_function

try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3


class Mic:
Expand Down
27 changes: 14 additions & 13 deletions client/mic.py
Expand Up @@ -2,16 +2,17 @@
"""
The Mic class handles all interactions with the microphone and speaker.
"""
from __future__ import absolute_import
import ctypes
import logging
import tempfile
import wave
import audioop
import time
import pyaudio
import dingdangpath
import mute_alsa
from app_utils import wechatUser
from . import dingdangpath
from . import mute_alsa
from .app_utils import wechatUser


class Mic:
Expand Down Expand Up @@ -97,14 +98,14 @@ def fetchThreshold(self):
lastN.append(self.getScore(data))
average = sum(lastN) / len(lastN)

except Exception, e:
except Exception as e:
self._logger.debug(e)
continue

try:
stream.stop_stream()
stream.close()
except Exception, e:
except Exception as e:
self._logger.debug(e)
pass

Expand Down Expand Up @@ -174,7 +175,7 @@ def passiveListen(self, PERSONA):

# flag raised when sound disturbance detected
didDetect = False
except Exception, e:
except Exception as e:
self._logger.debug(e)
pass

Expand All @@ -193,7 +194,7 @@ def passiveListen(self, PERSONA):
if score > THRESHOLD:
didDetect = True
break
except Exception, e:
except Exception as e:
self._logger.debug(e)
continue

Expand All @@ -204,7 +205,7 @@ def passiveListen(self, PERSONA):
# self.stop_passive = False
stream.stop_stream()
stream.close()
except Exception, e:
except Exception as e:
self._logger.debug(e)
pass
return (None, None)
Expand All @@ -221,7 +222,7 @@ def passiveListen(self, PERSONA):
break
data = stream.read(CHUNK)
frames.append(data)
except Exception, e:
except Exception as e:
self._logger.debug(e)
continue

Expand All @@ -230,7 +231,7 @@ def passiveListen(self, PERSONA):
# self.stop_passive = False
stream.stop_stream()
stream.close()
except Exception, e:
except Exception as e:
self._logger.debug(e)
pass

Expand Down Expand Up @@ -307,7 +308,7 @@ def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True,
# TODO: 0.8 should not be a MAGIC NUMBER!
if average < THRESHOLD * 0.8:
break
except Exception, e:
except Exception as e:
self._logger.error(e)
continue

Expand All @@ -317,7 +318,7 @@ def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True,
try:
stream.stop_stream()
stream.close()
except Exception, e:
except Exception as e:
self._logger.debug(e)
pass

Expand All @@ -343,7 +344,7 @@ def say(self, phrase,
# incase calling say() method which
# have not implement cache feature yet.
# the count of args should be 3.
if self.speaker.say.func_code.co_argcount > 2:
if self.speaker.say.__code__.co_argcount > 2:
self.speaker.say(phrase, cache)
else:
self.speaker.say(phrase)
Expand Down
5 changes: 3 additions & 2 deletions client/notifier.py
@@ -1,10 +1,11 @@
# -*- coding: utf-8-*-
from __future__ import absolute_import
import Queue
import atexit
from plugins import Email
from .plugins import Email
from apscheduler.schedulers.background import BackgroundScheduler
import logging
import app_utils
from . import app_utils
import time


Expand Down
3 changes: 2 additions & 1 deletion client/plugins/Camera.py
@@ -1,8 +1,9 @@
# -*- coding: utf-8-*-

from __future__ import absolute_import
import os
import subprocess
import time
from . import time
import sys

WORDS = [u"PAIZHAO", u"ZHAOPIAN"]
Expand Down
6 changes: 6 additions & 0 deletions client/plugins/Chatting.py
@@ -1,5 +1,11 @@
# -*- coding: utf-8-*-
# 闲聊插件

try:
reload # Python 2
except NameError: # Python 3
from importlib import reload

import sys
reload(sys)
sys.setdefaultencoding('utf8')
Expand Down
5 changes: 3 additions & 2 deletions client/plugins/Email.py
@@ -1,7 +1,8 @@
# -*- coding: utf-8-*-
from __future__ import absolute_import
import imaplib
import email
import time
from . import email
from . import time
import datetime
import logging
from dateutil import parser
Expand Down
11 changes: 9 additions & 2 deletions client/plugins/Hass.py
@@ -1,7 +1,14 @@
# -*- coding:utf-8 -*-
from __future__ import print_function
import requests
import json
import logging

try:
reload # Python 2
except NameError: # Python 3
from importlib import reload

import sys
reload(sys)
sys.setdefaultencoding('utf8')
Expand Down Expand Up @@ -54,7 +61,7 @@ def hass(text, mic, profile):
if text in dingdang:
try:
measurement = attributes["unit_of_measurement"]
except Exception, e:
except Exception as e:
pass
if 'measurement' in locals().keys():
text = text + "状态是" + state + measurement
Expand All @@ -79,7 +86,7 @@ def hass(text, mic, profile):
else:
mic.say(u"对不起,执行失败", cache=True)
print(format(request.status_code))
except Exception, e:
except Exception as e:
pass
break
else:
Expand Down
11 changes: 8 additions & 3 deletions client/robot.py
@@ -1,14 +1,19 @@
# -*- coding: utf-8-*-
from __future__ import print_function
from __future__ import absolute_import
import requests
import json
import logging
from uuid import getnode as get_mac
from app_utils import sendToUser, create_reminder
from .app_utils import sendToUser, create_reminder
from abc import ABCMeta, abstractmethod

import sys

try:
reload # Python 2
except NameError: # Python 3
from importlib import reload

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

Expand Down
5 changes: 3 additions & 2 deletions client/snowboy/snowboydetect.py
@@ -1,3 +1,4 @@
from __future__ import absolute_import
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.10
#
Expand All @@ -17,7 +18,7 @@ def swig_import_helper():
try:
fp, pathname, description = imp.find_module('_snowboydetect', [dirname(__file__)])
except ImportError:
import _snowboydetect
from . import _snowboydetect
return _snowboydetect
if fp is not None:
try:
Expand All @@ -28,7 +29,7 @@ def swig_import_helper():
_snowboydetect = swig_import_helper()
del swig_import_helper
else:
import _snowboydetect
from . import _snowboydetect
del _swig_python_version_info
try:
_swig_property = property
Expand Down

0 comments on commit 66c192f

Please sign in to comment.