Watson Tutorial #1: Speech to Text + AlchemyLanguage Sentiment Analysis in Python

Introduction

Edit: Watson AlchemyLanguage has since been replaced by Natural Language Understanding. The capabilities and usage remain very similar.

Step 0: What You’ll Need

Step 1: Create Bluemix Account

Step 2: Create the Watson Speech to Text Service

Step 3: Create Speech to Text Credentials

Step 4: Register for AlchemyLanguage API Key

Step 5: Python Setup

Step 6: Code

import os
import json
from os.path import join, dirname
from dotenv import load_dotenv
from watson_developer_cloud import SpeechToTextV1 as SpeechToText
from watson_developer_cloud import AlchemyLanguageV1 as AlchemyLanguage
from speech_sentiment_python.recorder import Recorder
recorder = Recorder(“speech.wav”)
recorder.record_to_file()
def transcribe_audio(path_to_audio_file):
username = os.environ.get(“BLUEMIX_USERNAME”)
password = os.environ.get(“BLUEMIX_PASSWORD”)
speech_to_text = SpeechToText(username=username,
password=password)
with open(join(dirname(__file__), path_to_audio_file), ‘rb’) as
audio_file:
return speech_to_text.recognize(audio_file,
content_type=’audio/wav’)
def get_text_sentiment(text):
alchemy_api_key = os.environ.get(“ALCHEMY_API_KEY”)

alchemy_language = AlchemyLanguage(api_key=alchemy_api_key)
result = alchemy_language.sentiment(text=text)
if result[‘docSentiment’][‘type’] == ‘neutral’:
return ‘netural’, 0
return result[‘docSentiment’][‘type’],
result[‘docSentiment’[‘score’]

Step 7: What’s Next

Leads developer relations at IBM Watson. Would like to teach robots how to love. Hates writing.