Skip to content

Instantly share code, notes, and snippets.

@anuragmishra1
Last active January 17, 2018 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anuragmishra1/e89776d237befa6e905a8ef2b8074229 to your computer and use it in GitHub Desktop.
Save anuragmishra1/e89776d237befa6e905a8ef2b8074229 to your computer and use it in GitHub Desktop.
import json
from watson_developer_cloud import SpeechToTextV1
import time
from datetime import timedelta
import sys
import os
import io
import argparse
#We need to get our API credentials in the code for authentication that we have stored as Environment Variables locally
STT_USER_WATSON = os.environ.get("STT_USER_WATSON")
STT_PASS_WATSON = os.environ.get("STT_PASS_WATSON")
#Following line is used to save all the console output into a text file
sys.stdout = open('speech_api_content_stt_output.txt', 'w')
start_time = time.monotonic()
def input_file(speech_file_path):
global result
#Initialize SpeechToText function using the API credentials
stt = SpeechToTextV1(
username = STT_USER_WATSON,
password = STT_PASS_WATSON)
if os.path.isfile(speech_file_path):
with io.open(speech_file_path, 'rb') as audio_file:
result = stt.recognize(audio_file, content_type = 'audio/wav') #This line will recognize the audio file and transcribe it into text format
else:
print("File doesn't exist in the directory!")
def speech_stt():
text = result['results'][0]['alternatives'][0]['transcript'] #Text output of the audio file after transcription
print("Text: " + text + "\n")
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description = __doc__,
formatter_class = argparse.RawDescriptionHelpFormatter)
parser.add_argument(
'speech_file_path',
help = 'The complete file path of the speech file you want to convert from speech to text.')
args = parser.parse_args()
input_file(args.speech_file_path)
speech_stt()
end_time = time.monotonic()
print("Execution_Time:", timedelta(seconds = end_time - start_time))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment