-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatson.py
314 lines (221 loc) · 8.03 KB
/
watson.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions, CategoriesOptions, ConceptsOptions, EmotionOptions, RelationsOptions, SemanticRolesOptions, SentimentOptions, SyntaxOptions
import statistics
import datetime
from pprint import pprint
'''
NOTE
in order to use properly ...
- log in function
- gather corpus into array ... each item == ai_to_Text(message)
- run averages on the array ---> averages_calc( text_Models )
-after you have the averaged array (input works with just one item as well.)... you will recieve a dictionary with all sentiment frequencies.
-
'''
# Login to NLU service
def login():
# Login to IBM (30K requests a month.... goes fast if you run each line on its own analysis)
# NOTE COMMENT AND UNCOMMENT api_key & url combinations for API limit
api_key = ''
url = ''
authenticator = IAMAuthenticator(api_key)
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2020-08-01',
authenticator=authenticator)
natural_language_understanding.set_service_url(url)
return natural_language_understanding
def analyzeText(client, text):
# Analyze Text
response = client.analyze(
text=text,
features=Features(
entities=EntitiesOptions(emotion=True, sentiment=True, limit=2),
keywords=KeywordsOptions(emotion=True, sentiment=True, limit=2),
categories=CategoriesOptions(limit=100),
concepts=ConceptsOptions(limit=100),
emotion=EmotionOptions(),
# emotion=EmotionOptions(targets=['apples','oranges'])
relations=RelationsOptions(),
semantic_roles=SemanticRolesOptions(keywords=True , entities=True),
sentiment=SentimentOptions(),
# sentiment=SentimentOptions(targets=['stocks']),
syntax=SyntaxOptions(sentences=True),
)
).get_result()
return json.dumps(response, indent=2)
# CLEAN DATA
def ai_to_Text(message):
response = analyzeText(nlu_client, message)
response = json.loads(response)
# MAKE A DICTIONARY THAT HOLDS THE AVERAGES OF THE OUTPUT
# after saving the averages, refer to the message_Dictionary to get a total avg of all messages user sent
emotion = response['emotion']['document']['emotion'] #dict
entities = response['entities'] #list
keywords = response['keywords'] #list
relations = response['relations'] #list
semantic_roles = response['semantic_roles'] #list
sentiment = response['sentiment'] #dict
concepts = response['concepts'] #list
categories = response['categories'] #list
# clean data
clean_relations = []
for r in relations:
# print(r['sentence'])
for a in r['arguments']:
for e in a['entities']:
clean_relations.append( (e['type'] , e['text']) )
# # wowowowowoww
# lolz = [ (e['type'] , e['text']) for r in relations for a in r['arguments'] for e in a['entities'] ]
model = {
'overall_emotion' : emotion,
'relations' : clean_relations,
'sentiment' : sentiment['document']['label'] ,
'entities' : [ ( i['text'] , i['type'] , i['sentiment']['label'] ) for i in entities ],
'keywords' : [ ( i['text'] , i['sentiment']['label'] ) for i in keywords ],
'subjects' : [ ( i['subject']['text'] , i['action']['verb']['tense'] ) for i in semantic_roles ],
'concepts' : [ i['label'] for i in categories ],
}
return model
# calculations of arr with ai outputs *** USING ai_to_Text ***
def averages_calc( text_Models ):
# NOTE: TEXT MODEL ITEM KEYS
# dict_keys ['overall_emotion', 'relations', 'subjects', 'entities', 'keywords', 'concepts']
# initialization of all model points through one loop
overallEmotion = {
'anger': [],
'disgust': [],
'fear': [],
'joy': [],
'sadness': []
}
allRelations = []
allSentiments = []
allEntities = []
allKeywords = []
allConcepts = []
allSubjects = []
for i in text_Models:
# OVERALL EMOTION
overallEmotion['anger'].append(i['overall_emotion']['anger'])
overallEmotion['disgust'].append(i['overall_emotion']['disgust'])
overallEmotion['fear'].append(i['overall_emotion']['fear'])
overallEmotion['joy'].append(i['overall_emotion']['joy'])
overallEmotion['sadness'].append(i['overall_emotion']['sadness'])
# relations
for r in i['relations']:
allRelations.append(r)
# sentiment
allSentiments.append(i['sentiment'])
# entities
for e in i['entities']:
allEntities.append(e)
# keywords
for k in i['keywords']:
allKeywords.append(k)
# keywords
for l in i['concepts']:
allConcepts.append(l)
# subject
for s in i['subjects']:
allSubjects.append(s)
# OVER ALL EMOTION AVERAGE
averageEmotion = {
'Anger' : sum(overallEmotion['anger']) / len(overallEmotion['anger']) ,
'Disgust': statistics.mean(overallEmotion['disgust']),
'Fear': statistics.mean(overallEmotion['fear']),
'Joy': statistics.mean(overallEmotion['joy']),
'Sadness': statistics.mean(overallEmotion['sadness']),
}
# RELATIONS
relationsfrequencies = {}
for item in allRelations:
if item[0] in relationsfrequencies:
relationsfrequencies[item[0]].append(item[1])
else:
relationsfrequencies[item[0]] = [ item[1] ]
# sentiment
sentiment_frequencies = {}
for item in allSentiments:
if item in sentiment_frequencies:
sentiment_frequencies[item] += 1
else:
sentiment_frequencies[item] = 1
# NOTE checks if entities and keywords have duplicates
removes = []
if len(allEntities) > 0 and len(allKeywords) > 0:
keywords_Length = len(allKeywords)
for x in range(len(allEntities)):
for y in range(keywords_Length):
if allEntities[x][0] == allKeywords[y][0]:
removes.append(allKeywords[y])
# remove the item and handle key error if duplicates of multiples
if len(removes) > 0:
for y in removes:
try:
allKeywords.remove(y)
except ValueError:
pass
except:
print('\n\n################## ERROR in calculations ##################\n\n')
# entities
entityfrequencies = {}
for item in allEntities:
if item[2] in entityfrequencies:
entityfrequencies[item[2]].append( ( item[0] , item[1]) )
else:
entityfrequencies[item[2]] = [ ( item[0] , item[1]) ]
# keywords
keywordfrequencies = {}
for item in allKeywords:
if item[1] in keywordfrequencies:
keywordfrequencies[item[1]].append(item[0])
else:
keywordfrequencies[item[1]] = [item[0]]
# Concepts
allConcepts = set(allConcepts)
conceptfrequencies = {}
for x in allConcepts:
x = x.split("/")[1:]
if x[0] in conceptfrequencies:
if len(x[1:]) > 0:
conceptfrequencies[x[0]].extend( x[1:] )
else:
conceptfrequencies[x[0]] = x[1:]
# subjects
# i['subject']['text'] , i['action']['verb']['tense']
subjectsfrequencies = {}
for item in allSubjects:
if item[1] in subjectsfrequencies:
subjectsfrequencies[item[1]].append(item[0])
else:
subjectsfrequencies[item[1]] = [item[0]]
# CLEAN AVERAGE DATA MODELS
# averageEmotion
# relationsfrequencies
# sentiment_frequencies
# entityfrequencies
# keywordfrequencies
# conceptfrequencies
# subjectsfrequencies
sentiment_model = {
'averageEmotion' : averageEmotion,
'relationsfrequencies' : relationsfrequencies,
'sentiment_frequencies' : sentiment_frequencies,
'entityfrequencies' : entityfrequencies,
'keywordfrequencies' : keywordfrequencies,
'conceptfrequencies' : conceptfrequencies,
'subjectsfrequencies' : subjectsfrequencies
}
return sentiment_model
# mood sentiment takes clean data from averages_calc
# averageEmotion
# relationsfrequencies
# sentiment_frequencies
# entityfrequencies
# keywordfrequencies
# conceptfrequencies
# subjectsfrequencies
# runs on import
nlu_client = login()