#!/usr/bin/env python
# File Name: googleScript.py
# Author: Meiyi (Lexi) He
# Description: A program that use google SpeechRecognition to recognize voice
# To Compile & Run : python googleScript.py [OUTPUT]
# output: a file of scripts that generated by google SR

from sys import argv
import speech_recognition as sr
import os

script, filename = argv

# Reminds the user of the output file name
print "The output will be in %r." % filename 

print "Opening the file..."
target = open(filename, 'w')


# the directory containing *.wav files to be recognized
unrelated_paths = ['..', './splittedAudioFiles/']
chunk_files = (os.path.join(p, o) for p in unrelated_paths
              for o in os.listdir(p)
              if (o.lower().endswith('.wav')
                  and os.path.isfile(os.path.join(p, o))))
# use the audio file as the audio source

r = sr.Recognizer()
for chunk_file in chunk_files:
    print chunk_file
    with sr.AudioFile(chunk_file) as source:
    	audio = r.record(source) # read the entire audio file
	try:
		#print the scripts, if cannot recognize, print ERROR
		target.write(r.recognize_google(audio))
		target.write("\n")
	except sr.UnknownValueError:
		target.write("ERROR")
	except sr.RequestError as e:
	    target.write("Google error; {0}".format(e))
