Skip to content

Commit

Permalink
ENH+TEST: remove .speex format option, more coverage of microphone.py
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremygray committed Mar 21, 2014
1 parent 67e87b1 commit 5e30a67
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 29 deletions.
41 changes: 16 additions & 25 deletions psychopy/microphone.py
Original file line number Diff line number Diff line change
Expand Up @@ -620,10 +620,10 @@ def elapsed(self):
else: # whether timed-out or not:
return self.duration
def _unpackRaw(self):
# parse raw string response from google, expose via data fields (see _reset):
try:
# parse raw url response from google, expose via data fields (see _reset):
if type(self.raw) != str:
self.json = json.load(self.raw)
except ValueError:
else:
self._reset()
self.status = 'FAILED'
self.stop()
Expand Down Expand Up @@ -652,7 +652,8 @@ def run(self):
self.duration = 0
try:
self.raw = urllib2.urlopen(self.request)
except: # yeah, its the internet, stuff happens
except: # pragma: no cover
# yeah, its the internet, stuff happens
# maybe temporary HTTPError: HTTP Error 502: Bad Gateway
try:
self.raw = urllib2.urlopen(self.request)
Expand Down Expand Up @@ -768,13 +769,13 @@ def __init__(self, filename,
self.timeout = timeout
useragent = PSYCHOPY_USERAGENT
host = "www.google.com/speech-api/v1/recognize"
flac_path = _getFlacPath()
#flac_path = _getFlacPath()

# determine file type, convert wav to flac if needed:
if not os.path.isfile(filename):
raise IOError("Cannot find file: %s" % filename)
ext = os.path.splitext(filename)[1]
if ext not in ['.flac', '.spx', '.wav']:
if ext not in ['.flac', '.wav']:
raise SoundFormatNotSupported("Unsupported filetype: %s\n" % ext)
if ext == '.wav':
__, samplingrate = readWavFile(filename)
Expand All @@ -783,8 +784,6 @@ def __init__(self, filename,
self.filename = filename
if ext == ".flac":
filetype = "x-flac"
elif ext == ".spx":
filetype = "x-speex-with-header-byte"
elif ext == ".wav": # convert to .flac
filetype = "x-flac"
filename = wav2flac(filename, level=level) # opt for speed
Expand All @@ -793,16 +792,10 @@ def __init__(self, filename,
while not os.path.isfile(filename) and c < 10:
core.wait(.1, 0)
c += 1
try:
audio = open(filename, 'rb').read()
except:
msg = "Can't read file %s from %s.\n" % (filename, self.filename)
logging.error(msg)
raise SoundFileError(msg)
finally:
if ext == '.wav' and filename.endswith('.flac'):
try: os.remove(filename)
except: pass
audio = open(filename, 'rb').read()
if ext == '.wav' and filename.endswith('.flac'):
try: os.remove(filename)
except: pass

# urllib2 makes no attempt to validate the server certificate. here's an idea:
# http://thejosephturner.com/blog/2011/03/19/https-certificate-verification-in-python-with-urllib2/
Expand All @@ -817,7 +810,8 @@ def __init__(self, filename,
web.requireInternetAccess() # needed to access google's speech API
try:
self.request = urllib2.Request(url, audio, header)
except: # try again before accepting defeat
except: # pragma: no cover
# try again before accepting defeat
logging.info("https request failed. %s, %s. trying again..." % (filename, self.filename))
core.wait(0.2, 0)
self.request = urllib2.Request(url, audio, header)
Expand Down Expand Up @@ -945,11 +939,8 @@ def flac2wav(path, keep=True):
wavfile = flacfile.strip('.flac') + '.wav'
flac_cmd = [flac_path, "-d", "--totally-silent", "-f", "-o", wavfile, flacfile]
__, se = core.shellCall(flac_cmd, stderr=True)
if se or not os.path.isfile(flacfile): # just try again
logging.warn('Failed to convert to .wav; trying again')
__, se = core.shellCall(flac_cmd, stderr=True)
if se:
logging.error(se)
if se:
logging.error(se)
if not keep:
os.unlink(flacfile)
wav_files.append(wavfile)
Expand Down Expand Up @@ -1024,7 +1015,7 @@ def switchOn(sampleRate=48000, outputDevice=None, bufferSize=None):
from pyo import getVersion, pa_get_input_devices, pa_get_output_devices, downsamp, upsamp
global haveMic
haveMic = True
except ImportError:
except ImportError: # pragma: no cover
msg = 'Microphone class not available, needs pyo; see http://code.google.com/p/pyo/'
logging.error(msg)
raise ImportError(msg)
Expand Down
23 changes: 19 additions & 4 deletions psychopy/tests/test_misc/test_microphone.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,14 @@ def test_AudioCapture_basics(self):
switchOn(48000)

mic = AdvAudioCapture(saveDir=self.tmp, autoLog=False)
mic = AdvAudioCapture(saveDir=self.tmp+'_test', autoLog=False)
mic.record(.10, block=False) # returns immediately
core.wait(.02)
mic.stop()
mic.reset()

mic.record(0.2, block=True)
assert os.path.isfile(mic.savedFile)

def test_AdvAudioCapture(self):
filename = os.path.join(self.tmp, 'test_mic.wav')
Expand Down Expand Up @@ -116,17 +121,19 @@ def teardown_class(self):
shutil.rmtree(self.tmp, ignore_errors=True)

def test_getFlacPath(self):
#microphone.FLAC_PATH = None
#with pytest.raises(MicrophoneError):
# _getFlacPath('this is not flac')
microphone.FLAC_PATH = None
_getFlacPath()
with pytest.raises(MicrophoneError):
_getFlacPath('this is not the flac you are looking for')

microphone.FLAC_PATH = None
_getFlacPath('flac')

microphone.FLAC_PATH = 'flac'
assert microphone.FLAC_PATH

microphone.FLAC_PATH = None
_getFlacPath()

def test_wav_flac(self):
filename = os.path.join(self.tmp, 'test_bad_readWav')
with open(filename, 'wb') as fd:
Expand All @@ -152,6 +159,8 @@ def test_wav_flac(self):
wav2flac('', keep=True)
flac2wav('', keep=True)

wav2flac(self.tmp, keep=True)

def test_Speech2Text(self):
try:
web.requireInternetAccess()
Expand All @@ -165,6 +174,12 @@ def test_Speech2Text(self):
resp = gs.getResponse()
assert resp.word == 'red'

# test batch-discover files in a directory
tmp = join(self.tmp, 'tmp')
os.mkdir(tmp)
shutil.copy(testFile, tmp)
bs = BatchSpeech2Text(files=tmp)

bs = BatchSpeech2Text(files=glob.glob(join(self.tmp, 'red_*.wav')))
while bs._activeCount():
core.wait(.1, 0)
Expand Down

0 comments on commit 5e30a67

Please sign in to comment.