コード例 #1
0
def getSentiment(s):

    if s is None or len(s) == 0:
        #no review_text for some reason
        return []

    tone_analyzer = ToneAnalyzerV3Beta(
        username='******',
        password='******',
        version='2016-02-11')
    time.sleep(1)
    try:
        myvar = tone_analyzer.tone(text=s)
    except:
        return []

    temp1 = myvar['document_tone']
    temp2 = temp1['tone_categories']

    mylist = []
    for ele in temp2:
        alltones = ele['tones']
        for tone in alltones:
            tone_name = tone['tone_name']
            tone_score = tone['score']
            mylist.append(str(tone_name) + ':' + str(tone_score))

    return mylist
コード例 #2
0
ファイル: watson.py プロジェクト: fabienf/FH
    def __init__(self):
        logging.debug("Loading Watson...")

        self.tone_analyzer = ToneAnalyzerV3Beta(
            username='******',
            password='******',
            version='2016-02-11')
コード例 #3
0
ファイル: watson.py プロジェクト: fabienf/FH
    def __init__(self):
        logging.debug("Loading Watson...")

        self.tone_analyzer = ToneAnalyzerV3Beta(
            username='******',
            password='******',
            version='2016-02-11')
コード例 #4
0
 def __init__(self, database):
     self.db = database
     self.bluemix_credentials = json.load(open('bluemix_credentials.json'))
     self.tone_analyzer = ToneAnalyzerV3Beta(
         username=self.bluemix_credentials["username"],
         password=self.bluemix_credentials["password"],
         version="2016-02-11")
コード例 #5
0
def analyze_tone(candidate, in_fn, out_fn):
    tone_analyzer = ToneAnalyzerV3Beta(username=os.getenv('TONE_USER'),
                                       password=os.getenv('TONE_PASS'),
                                       version='2016-02-11')

    with open(in_fn, 'r') as in_f, open(out_fn, 'a') as out_f:
        for i, line in enumerate(in_f):
            try:
                out_data = {'candidate': candidate, 'sentiment': -1.0}
                in_data = json.loads(line)
                tone_data = tone_analyzer.tone(text=in_data['text'])
                emotion = tone_data['document_tone']['tone_categories'][0][
                    'tones']
                # writing = tone_data['document_tone']['tone_categories'][1]['tones']
                social = tone_data['document_tone']['tone_categories'][2][
                    'tones']

                for e in emotion:
                    out_data[e['tone_name'].lower()] = e['score']
                for s in social:
                    out_data[s['tone_name'].lower()] = s['score']

                out_data.update(in_data)
                out_data['user'] = out_data.pop('uid')
                out_data['range'] = out_data.pop('emotional range')
                json.dump(out_data, out_f)
                out_f.write('\n')
            except Exception as e:
                print(e.args, i)
                in_data.update({'candidate': candidate, 'sentiment': -1.0})
                json.dump(in_data, out_f)
                out_f.write('\n')
コード例 #6
0
def analyze(bot, update):
    tone_analyzer = ToneAnalyzerV3Beta(
        username=config('USERNAME'),
        password=config('PASSWORD'),
        version='2016-05-19',
        url='https://gateway.watsonplatform.net/tone-analyzer/api')

    response = tone_analyzer.tone(text=update.message.text)

    text = create_emotion_text(response)
    bot.sendMessage(update.message.chat_id, text=text)
コード例 #7
0
class IBMToneAnalyzer(object):
	def __init__(self):
		from watson_developer_cloud import ToneAnalyzerV3Beta as ToneAnalyzer
		self.tone_analyzer = ToneAnalyzer(
			username=TOKENS.ibm_username,
			password=TOKENS.ibm_password,
			version='2016-02-11')
	def TestIBM(self):
		print "IBM function"
		print(json.dumps(self.tone_analyzer.tone(text='I am very happy'), indent=2))
		print "Program Exiting"
		exit()
コード例 #8
0
ファイル: trygmail.py プロジェクト: Spockify/spockify
def getGmailMessages(email):
    
    #~~~PUT MESSAGE ID BELOW~~~
    messages = ListMessagesMatchingQuery(build_service(get_credentials()), "me", query='from:'+email)

    convos = []

    i = 0
    while (i<len(messages)):
        msg_id = messages[i]["threadId"]
        msg_info = GetMimeMessage(build_service(get_credentials()), "me", msg_id)
        #print msg_info
        #TODO: Find a better way to get the message string, ex: by newlines
        index1 = str(msg_info).index("Content-Type: text/plain; charset=UTF-8")
        index1 += len("Content-Type: text/plain; charset=UTF-8")
        index2 = str(msg_info).index("Content-Type: text/html; charset=UTF-8")
        index2 -= len("--001a113d38862b78c0052be7b244")
        msg_content = str(msg_info)[index1:index2]
        convos.append(msg_content)
        i+=1

    #print convos



    tone_analyzer = ToneAnalyzer(username='******',
                             password='******',
                             version='2016-02-11')

    analyzed_text = []

    for c in convos:
        analyzed_text.append(json.dumps(tone_analyzer.tone(text=c), indent=2))

    tones = {}

    tones["emotion"]=ast.literal_eval(analyzed_text[0])["document_tone"]["tone_categories"][0]["tones"]

    tones["language"]=ast.literal_eval(analyzed_text[0])["document_tone"]["tone_categories"][1]["tones"]
    
    tones["social"]=ast.literal_eval(analyzed_text[0])["document_tone"]["tone_categories"][2]["tones"]

    values = []
    scores = []

    for el in tones["emotion"]:
        values.append(el["tone_name"])
    for el in tones["language"]:
        values.append(el["tone_name"])
    for el in tones["social"]:
        values.append(el["tone_name"])

    print values


    for el in tones["emotion"]:
        scores.append(el["score"])
    for el in tones["language"]:
        scores.append(el["score"])
    for el in tones["social"]:
        scores.append(el["score"])
    print scores

    #print values
    #print scores

    ret={}
    
    ret["values"] = values
    ret["scores"] = scores

    f = open('out.json', 'w+')
    f.write(str(ret))

    return util.json_response(ret);
コード例 #9
0
import json
from watson_developer_cloud import ToneAnalyzerV3Beta as ToneAnalyzer


tone_analyzer = ToneAnalyzer(username='******',
                             password='******',
                             version='2016-02-11')

print(json.dumps(tone_analyzer.tone(text='I am very happy'), indent=2))
コード例 #10
0
import json
from watson_developer_cloud import ToneAnalyzerV3Beta


tone_analyzer = ToneAnalyzerV3Beta(
    username='******',
    password='******',
    version='2016-02-11')

print(json.dumps(tone_analyzer.tone(text='I am very happy'), indent=2))
コード例 #11
0
def hello():
	input_string = request.args['any']
	
	fire = firebase.FirebaseApplication('https://sigjesus.firebaseio.com/', None)
	fire.delete('/messages', None)

	# input_string is the string the user gives you to analyze
	#script, input_string = argv
	messages=""
	#print input_string
	tone_analyzer = ToneAnalyzerV3Beta(
		username = watsonUser,
		password = watsonPassword,
		version = '2016-02-11')

	data = tone_analyzer.tone(text=input_string)

	#print data
	#These are the time ranges we can bug people about. 

	now = datetime.datetime.now()
	nowtest = now.replace(hour=4, minute=20, second=0, microsecond=0)

	today8am = now.replace(hour=8, minute=0, second=0, microsecond=0)

	today11pm = now.replace(hour=23, minute=0, second=0, microsecond=0)
	today1159pm = now.replace(hour=23, minute=59, second=0, microsecond=0)

	today12am = now.replace(hour=0, minute=0, second=0, microsecond=0)
	today1259am = now.replace(hour=0, minute=59, second=0, microsecond=0)

	today1am = now.replace(hour=1, minute=0, second=0, microsecond=0)
	today230am = now.replace(hour=2, minute=30, second=0, microsecond=0)

	today231am = now.replace(hour=2, minute=31, second=0, microsecond=0)
	today5am = now.replace(hour=5, minute=0, second=0, microsecond=0)

	today501am = now.replace(hour=5, minute=01, second=0, microsecond=0)
	today630am = now.replace(hour=6, minute=3, second=0, microsecond=0)


	sentenceOrdinalArray = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth']

	#Arrays for the messages that could be presented when a certain emotion is present, chosen at random

	angerArray = ["you might come off a bit angry...", "you may or may not sound like a dick.", "you might need to chill.", \
	"you might need to take it down a notch.", "you sound a bit angry.", "you sound sort of moody."]
	disgustArray = ["you might want to try to be nicer.", "you could rub someone the wrong way.", "you do not sound very enthused."]
	joyArray =["you say some nice things.", "you are very positive."]
	fearArray=["you sound a little uneasy.", "you are being somewhat paranoid."]
	sadnessArray=["it sounds like something is wrong... Are you ok?","you sound a little bit under the weather.", \
	"it sounds like you haz the sadz."]
	angerImages=["Images/Angry/AngryBird.jpg","Images/Angry/Cat.jpg","Images/Angry/Challenged.jpg","Images/Angry/Chicken.jpg","Images/Angry/Hate everything.jpg"]
	disgustImages = ["Images/Disgust/FreshPrince.jpg","Images/Disgust/MontyPython.jpg","Images/Disgust/Picard.jpg","Images/Disgust/dsgstd.gif","Images/Disgust/kristen-wiig-target-lady-grossed-out.gif"]
	fearImages = ["Images/Fear/Bread.jpg","Images/Fear/Dog.jpg","Images/Fear/PoolShark.jpg","Images/Fear/Turtle.jpg","Images/Fear/WaterBallon.jpg"]
	joyImages = ["Images/Joy/Elephant.jpg","Images/Joy/hedgehog.jpg","Images/Joy/Rabbits.jpg","Images/Joy/Seal.jpg","Images/Joy/Turtle.jpg","Images/Joy/laughing-baby.jpg"]
	sadImages = ["Images/Sad/Frog.jpg","Images/Sad/SadCat.jpg","Images/Sad/Sheldon.jpg","Images/Sad/StarWars.jpg","Images/Sad/Trex.jpg"]
	#These are the time ranges we can bug people about. 

	if (today11pm < now< today1159pm):
		messages = messages + "Business hours are over, it might be a little late. "
	elif (today12am < now < today1259am):
		messages = messages + "Should you be texting this person this late. "
	elif (today1am < now< today230am):
		messages = messages + "Heading back from the bars? Just checking. "
	elif (today231am < now< today5am):
		messages = messages + "This is not an hour to text someone, you can probably wait a couple of hours. "
	elif (today501am < now< today630am):
		messages = messages + "It'a pretty early, this person is probably sleeping, are you sure? "

	def strip(uglystring):
		return str(uglystring).replace('[','').replace("'",'').replace("'",'').replace(']','')
	i=0
	if ("sentences_tone" in data):
		numberofsentences = len(data["sentences_tone"])

		

		for y in range(0, numberofsentences):

			this = data["sentences_tone"][y]["tone_categories"][0]["tones"]
			sentencenumber = y + 1
			# hardcoded tones within "Emotional Sentiment"
			for x in range(0, 4):
				sentiment = this[x]
				
			# print(
			# if( data["document_tone"]["tone_categories"][0]["tones"][0]["tone_name"] == "Anger"):

				if ((sentiment["tone_name"] == "Anger") and (sentiment["score"] >= .40)):
					i=i+1
					angerChoice = strip(random.sample(angerArray,  1))
					messages = messages + "In the " + sentenceOrdinalArray[sentencenumber] + " sentence " + angerChoice + " "

				elif((sentiment["tone_name"] == "Disgust") and (sentiment["score"] >= .40)):	
					i=i+1
					disgustChoice = strip(random.sample(disgustArray,  1))
					messages = messages + "In the " + sentenceOrdinalArray[sentencenumber] + " sentence " + disgustChoice + " "

				elif((sentiment["tone_name"] == "Fear") and (sentiment["score"] >= .40)):	
					i=i+1
					fearChoice = strip(random.sample(fearArray,  1))
					messages = messages + "In the " + sentenceOrdinalArray[sentencenumber] + " sentence " + fearChoice + " "


				elif((sentiment["tone_name"] == "Joy") and (sentiment["score"] >= .40)):	
					i=i+1
					joyChoice = strip(random.sample(joyArray,  1) )
					messages = messages + "In the " + sentenceOrdinalArray[sentencenumber] + " sentence " + joyChoice + " "

				elif((sentiment["tone_name"] == "Sadness") and (sentiment["score"] >= .40)):	
					i=i+1
					sadnessChoice = strip(random.sample(sadnessArray,  1) )
					messages = messages + "In the " + sentenceOrdinalArray[sentencenumber] + " sentence " + sadnessChoice + " "

	docTone = data["document_tone"]["tone_categories"][0]["tones"]

	if(i<2):
		overtone = angerImages;
		anger=docTone[0]
		disgust=docTone[1]
		fear=docTone[2]
		joy=docTone[3]
		sad=docTone[4]
		text="In your text"
		ans = anger["score"]
		dis = disgust["score"]
		fes = fear["score"]
		jos = joy["score"]
		sas = sad["score"]
		max = ans;
		if (dis > max):
			max = dis
			overtone=disgustImages
		if (fes > max):
			max = fes
			overtone=fearImages
		if (jos > max):
			max =jos
			overtone=joyImages
		if (sas > max):
			max = sas
			overtone = sadImages
		fireImage = random.sample(overtone,1)
		if (ans >= .2):
			angerChoice = strip(random.sample(angerArray, 1))
			messages = messages + text + " " + angerChoice + " "
		elif (dis >= .3):
			disgustChoice = strip(random.sample(disgustArray, 1))
			messages = messages + text + " " + disgustChoice + " "
		elif (fes >= .4):
			fearChoice = strip(random.sample(fearArray, 1))
			messages = messages + text + " " + fearChoice + " "
		elif (jos >= .4):
			joyChoice = strip(random.sample(joyArray, 1))
			messages = messages + text + " " + joyChoice + " "
		elif (sas >= .3):
			sadnessChoice = strip(random.sample(sadnessArray, 1))
			messages = messages + text + " " + sadnessChoice + " "
		else:
			messages = messages + "The overall tone of your message was neutral."
	temp = messages
	messageJson = {'messages': messages, 'imagePath': fireImage}
	messages = fire.post("/messages", messageJson)

	return temp
コード例 #12
0
	def __init__(self):
		from watson_developer_cloud import ToneAnalyzerV3Beta as ToneAnalyzer
		self.tone_analyzer = ToneAnalyzer(
			username=TOKENS.ibm_username,
			password=TOKENS.ibm_password,
			version='2016-02-11')
コード例 #13
0
#-------------------------------------------------------------------------------
#Author: Kahini Wadhawan
#------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
import json
from watson_developer_cloud import ToneAnalyzerV3Beta as ToneAnalyzer

#create Bluemix account to get service_username and service_password
tone_analyzer = ToneAnalyzer(username=service_username,
                             password=service_password,
                             version='2016-02-11')

text = "The IBM Watson™ Tone Analyzer Service uses linguistic analysis to detect three types of tones from written text emotions, social tendencies, and writing style. Emotions identified include things like anger, cheerfulness and sadness. Identified social tendencies include things from the Big Five personality traits used by some psychologists."

print(json.dumps(tone_analyzer.tone(text=text), indent=2))
コード例 #14
0
from cassandra.cluster import Cluster
from watson_developer_cloud import ToneAnalyzerV3Beta
from credentials import watsonUser, watsonPassword
import datetime
import json
cluster = Cluster(['172.31.38.201'], port=9042)
session = cluster.connect()
session.execute('USE Tracker')
tone_analyzer = ToneAnalyzerV3Beta(username=watsonUser,
                                   password=watsonPassword,
                                   version='2016-02-11')

count = 0
now = datetime.datetime.now()
year = str(now.year)
month = now.month
if (month < 10):
    month = "0" + str(month)
day = now.day
if (day < 10):
    day = "0" + str(day)
currentDate = str(year) + str(month) + str(day)
queryHandle = session.prepare("SELECT * FROM Tweets WHERE created_at=?")
testdata = session.execute(queryHandle, [currentDate])

for data in testdata:
    if count < 10:
        contents = data.text
        geo = data.geo
        badDate = data.created_at
        tid = data.id_str
コード例 #15
0
# get audio from mic
r = sr.Recognizer()
with sr.Microphone() as source:
    print("Listening for input...")
    audio = r.listen(source)

# Watson Credentials
IBM_USERNAME = ""
IBM_PASSWORD = ""

try:
    audOut = r.recognize_ibm(audio,
                             username=IBM_USERNAME,
                             password=IBM_PASSWORD)
    print("Watson thinks you said: " + audOut)
except sr.UnknownValueError:
    print("WHAT DID YOU SAY!? - Watson")
except sr.RequestError as e:
    print("WATSONS DOWN OR SOMETHING; {0}".format(e))

TONE_USERNAME = ""
TONE_PASSWORD = ""
TONE_VERSION = ""

tone_analysis = ToneAnalyzerV3Beta(username=TONE_USERNAME,
                                   password=TONE_PASSWORD,
                                   version=TONE_VERSION)

print(json.dumps(tone_analysis.tone(text=audOut), indent=2))
コード例 #16
0
    raise RuntimeError(
        "Cannot connect to Watson.  Credentials not found for personality insights."
    )
else:
    personality_insights = PersonalityInsights(
        username=WATSON['credentials']['username'],
        password=WATSON['credentials']['password'])

TONE = json.loads(os.environ['VCAP_SERVICES'])['tone_analyzer'][0]
if 'credentials' not in TONE:
    raise RuntimeError(
        "Cannot connect to Watson.  Credentials not found for personality insights."
    )
else:
    tone_analyzer = ToneAnalyzerV3Beta(
        username=TONE['credentials']['username'],
        password=TONE['credentials']['password'],
        version='2016-02-11')

CLOUDANT = json.loads(os.environ['VCAP_SERVICES'])['cloudantNoSQLDB'][0]
if 'credentials' not in CLOUDANT:
    raise RuntimeError(
        "Cannot connect to database, Cloudant credentials not found.")
else:
    client = Cloudant(CLOUDANT['credentials']['username'],
                      CLOUDANT['credentials']['password'],
                      url=CLOUDANT['credentials']['url'])
    client.connect()

databases = ['personas', 'albums', 'songs']
for db in databases:
    if db not in client.all_dbs():