-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathemotions.py
319 lines (252 loc) · 15.1 KB
/
emotions.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
314
315
316
317
318
319
import cufflinks as cf
from collections import Counter
# nltk
from nltk.corpus import names
from nltk import tokenize
import nltk
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag
from nltk.tokenize import sent_tokenize
from nltk.stem.snowball import SnowballStemmer
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import re
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.pyplot as plt
# plotly
import chart_studio.plotly as py
import plotly.graph_objs as go
from plotly import tools
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)
import plotly.express as px
class emotions_sentiments:
def __init__(self, df_movie, moviename):
self.df_movie = df_movie
self.movie = moviename
def film_sentiment(self, colour):
analyzer = SentimentIntensityAnalyzer()
sc_sent = {}
for x in range(0, len(self.df_movie), 1):
scene = re.sub(r"[^a-zA-Z0-9.? ]+", '', self.df_movie.Contents[x])
scene_sentence = tokenize.sent_tokenize(scene)
sentiments = {'compound': 0.0, 'neg': 0.0, 'neu': 0.0, 'pos': 0.0}
for sentence in scene_sentence:
vs = analyzer.polarity_scores(sentence)
sentiments['compound'] += vs['compound']
sentiments['neg'] += vs['neg']
sentiments['neu'] += vs['neu']
sentiments['pos'] += vs['pos']
sentiments['compound'] = sentiments['compound'] / float(len(scene_sentence))
sentiments['neg'] = sentiments['neg'] / float(len(scene_sentence))
sentiments['neu'] = sentiments['neu'] / float(len(scene_sentence))
sentiments['pos'] = sentiments['pos'] / float(len(scene_sentence))
dic = 'scene_' + str(x)
sc_sent[dic] = sentiments
#Extract the compound, negative, neutral and positive sentiments for each Scene
sents = [sc_sent[keys] for keys in sc_sent]
df_sentiment = pd.DataFrame(sents)
df_zero = pd.DataFrame(0, df_sentiment.index, columns = ['Zero'])
fig = go.Figure()
fig.add_trace(go.Scatter(x=df_sentiment.index, y=df_sentiment['compound'], mode='lines', name='Average Sentiment',
line=dict(color=colour)))
fig.add_trace(go.Scatter(x=df_zero.index, y=df_zero['Zero'], mode='lines', name = 'Zero line',
line=dict(color='crimson', dash='dot')))
fig.update_layout(title='<b> Sentiment across the ' + self.movie + ' Movie <b>',
xaxis_title='<b> Scenes <b>', yaxis_title='<b> Average Sentiments <b>', showlegend=True)
fig.show()
return df_sentiment
def film_emotional_arc(self):
def cap_sentence(s):
return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)
df_contents = self.df_movie[['Scene_Names', 'Contents']]
df_emotions = pd.read_csv('./emotions/NRC-Sentiment-Emotion-Lexicons/NRC-Emotion-Lexicon-v0.92/NRC-Emotion-Lexicon-Wordlevel-v0.92.txt',
names=["word", "emotion", "association"], sep='\t')
df_emotion_word = df_emotions.pivot(index='word', columns='emotion', values='association').reset_index()
emotions = df_emotion_word.columns.drop('word').tolist() ##Emotions annotated based on the NRC Sentiment Lexicons
df_emo = pd.DataFrame(0, df_contents.index, columns = emotions)
stemmer = SnowballStemmer("english")
for x in range(0, len(df_contents), 1):
scene_conts = re.sub(r"[^a-zA-Z0-9 ]+", '', df_contents.Contents[x])
doc = word_tokenize(scene_conts)
#print(doc, '\n\n')
for word in doc:
word = stemmer.stem(word.lower())
emotion_score = df_emotion_word[df_emotion_word.word == word]
if not emotion_score.empty:
for emotion in emotions:
df_emo.at[x, emotion] += emotion_score[emotion]
#Concatenate contents and emotions for each context
df_scene_emotions = pd.concat([df_contents, df_emo], axis=1)
df_scene_emotions['word_count'] = df_scene_emotions['Contents'].apply(tokenize.word_tokenize).apply(len)
for emotion in emotions:
df_scene_emotions[emotion] = df_scene_emotions[emotion] / df_scene_emotions['word_count']
fig = make_subplots(rows=5, cols=2, subplot_titles=(cap_sentence(emotions[0]), cap_sentence(emotions[1]), cap_sentence(emotions[2]),
cap_sentence(emotions[3]), cap_sentence(emotions[4]), cap_sentence(emotions[5]),
cap_sentence(emotions[6]), cap_sentence(emotions[7]),
cap_sentence(emotions[8]), cap_sentence(emotions[9])))
row = 0
count = 0
for x in emotions:
if count % 2:
fig.add_trace(go.Scatter(x=df_scene_emotions.index, y=df_scene_emotions[x]), row = row, col = 2)
else:
row += 1
fig.add_trace(go.Scatter(x=df_scene_emotions.index, y=df_scene_emotions[x]), row = row, col = 1)
count += 1
fig.update_xaxes(title_text= 'Scenes', dtick=20)
fig.update_yaxes(title_text="Average Sentiment")
# Edit the layout
fig.update_layout(height=1500, width=1000, title_text="<b> Emotional arcs identified across the scenes in the " + self.movie + " movie <b>", showlegend=False)
fig.show()
return df_scene_emotions
def emotional_arc_xter_plot(self, df, character):
def cap_sentence(s):
return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)
def xter_count_perscene(df, characters):
sc_xters = []
sc_dia = []
for x in range(0, len(df), 1):
sc_xtrs = []
sc_di = []
if df['Scene_Characters'][x] != None:
for y in range(0, len(df['Scene_Characters'][x]), 1):
if type(characters) == list:
kk = re.compile("({})+".format("|".join(re.escape(c) for c in characters)))
xters = kk.findall(df['Scene_Characters'][x][y])
else:
xters = re.findall(characters, df['Scene_Characters'][x][y])
if xters:
dialogue = df['Scene_Dialogue'][x][y]
sc_xtrs.append(xters)
sc_di.append(dialogue)
sc_xtrs = [''.join(el) for el in sc_xtrs]
sc_xters.append(sc_xtrs)
sc_dia.append(sc_di)
#print(xters, '\n', dialogue)
else:
sc_xters.append(None)
sc_dia.append(None)
#Count the appearance of 1, 2 or more characters per scene
sc_cts = []
for x in range(0,len(sc_xters),1):
xtrs = dict(Counter(sc_xters[x]).most_common())
sc_cts.append(xtrs)
#Create a dataframe of their appearance
df_counts = pd.DataFrame(sc_cts)
#drop items not in the characters we want
ct_columns = df_counts.columns.tolist()
drop_items = [x for x in ct_columns if x not in characters]
for x in drop_items:
df_counts.drop([x], axis = 1, inplace = True)
df_counts.dropna(inplace = True)
df_scene_dialogue = pd.DataFrame(list(zip(sc_xters, sc_dia)), columns = ['characters', 'dialogues'])
return df_counts, df_scene_dialogue
##Get the character dialogues per Scene
df_cts, df_xt = xter_count_perscene(self.df_movie, character)
##Get the emotions
df_emotions = pd.read_csv('./emotions/NRC-Sentiment-Emotion-Lexicons/NRC-Emotion-Lexicon-v0.92/NRC-Emotion-Lexicon-Wordlevel-v0.92.txt',
names=["word", "emotion", "association"], sep='\t')
df_emotion_word = df_emotions.pivot(index='word', columns='emotion', values='association').reset_index()
emotions = df_emotion_word.columns.drop('word').tolist()
df_emo = pd.DataFrame(0, df_xt.index, columns = emotions)
stemmer = SnowballStemmer("english")
df_xt['dialogues'] = df_xt.apply(lambda x : re.sub(r'[^a-zA-Z0-9 ]', '', str(x['dialogues'])).lower(),axis=1)
for x in range(0, len(df_xt), 1):
scene_contents = df_xt['dialogues'][x]
doc = word_tokenize(scene_contents)
#print(doc, '\n\n')
for word in doc:
word = stemmer.stem(word.lower())
emotion_score = df_emotion_word[df_emotion_word.word == word]
if not emotion_score.empty:
for emotion in emotions:
df_emo.at[x, emotion] += emotion_score[emotion]
##Concatenate the dialogue of the character and the emotions per scene
df_xter_emotions = pd.concat([df_xt, df_emo], axis=1)
df_xter_emotions['word_count'] = df_xter_emotions['dialogues'].apply(tokenize.word_tokenize).apply(len)
for emotion in emotions:
df_xter_emotions[emotion] = df_xter_emotions[emotion] / df['word_count']
fig = make_subplots(rows=5, cols=2, subplot_titles=(cap_sentence(emotions[0]), cap_sentence(emotions[1]), cap_sentence(emotions[2]),
cap_sentence(emotions[3]), cap_sentence(emotions[4]), cap_sentence(emotions[5]),
cap_sentence(emotions[6]), cap_sentence(emotions[7]),
cap_sentence(emotions[8]), cap_sentence(emotions[9])))
row = 0
count = 0
for x in emotions:
if count % 2:
fig.add_trace(go.Scatter(x=df_xter_emotions.index, y=df_xter_emotions[x]), row = row, col = 2)
else:
row += 1
fig.add_trace(go.Scatter(x=df_xter_emotions.index, y=df_xter_emotions[x]), row = row, col = 1)
count += 1
fig.update_xaxes(title_text= 'Scenes', dtick=20)
fig.update_yaxes(title_text="Average Sentiment")
# Edit the layout
fig.update_layout(height=1500, width=1000, title_text="<b> Emotional arcs of " + character + " across the scenes in the " + self.movie + " movie <b>", showlegend=False)
fig.show()
return df_xter_emotions
def emotional_content_plot(self, df, characters, num_of_characters):
##Capitalize each word
def cap_sentence(s):
return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)
##Extract Each Character's Dialogue
xters_dialogue = {}
for x in characters:
xters_dialogue[x] = re.sub(r"[^a-zA-Z0-9 ]+", '', \
str(df.loc[df.characters == x].Character_dialogue.values.tolist()))
df_xters_dialogues = pd.DataFrame(xters_dialogue.items(), columns = ['characters', 'Contents'])
##Extract the Emotions
df_emotions = pd.read_csv('./emotions/NRC-Sentiment-Emotion-Lexicons/NRC-Emotion-Lexicon-v0.92/NRC-Emotion-Lexicon-Wordlevel-v0.92.txt',
names=["word", "emotion", "association"], sep='\t')
df_emotion_word = df_emotions.pivot(index='word', columns='emotion', values='association').reset_index()
emotions = df_emotion_word.columns.drop('word').tolist()
df_emo = pd.DataFrame(0, df_xters_dialogues.index, columns = emotions)
stemmer = SnowballStemmer("english")
for x in range(0, len(df_xters_dialogues), 1):
scene_conts = re.sub(r"[^a-zA-Z0-9 ]+", '', df_xters_dialogues.Contents[x]).lower()
doc = word_tokenize(scene_conts)
#print(doc, '\n\n')
for word in doc:
word = stemmer.stem(word.lower())
emotion_score = df_emotion_word[df_emotion_word.word == word]
if not emotion_score.empty:
for emotion in emotions:
df_emo.at[x, emotion] += emotion_score[emotion]
df_scene_emotions = pd.concat([df_xters_dialogues, df_emo], axis=1)
df_scene_emotions = df_scene_emotions.drop(['Contents'], axis = 1)
df_scene_emotions = df_scene_emotions.T
df_scene_emotions.columns = df_scene_emotions.iloc[0]
df_scene_emotions.drop(df_scene_emotions.index[0], inplace = True)
df_scene_emotions.reset_index(inplace = True)
df_scene_emotions.rename(columns={'index': 'Emotions'}, inplace=True)
df_scene_emotions['Emotions'] = df_scene_emotions['Emotions'].apply(cap_sentence)
##Number of characters emotional counts you want to display
major_characters = df_scene_emotions.columns.tolist()[1:num_of_characters]
fig = make_subplots(rows=5, cols=2, subplot_titles=(major_characters[0], major_characters[1], major_characters[2], major_characters[3],
major_characters[4], major_characters[5],
major_characters[6], major_characters[7],
major_characters[8], major_characters[9]))
row = 0
count = 0
colors = ['lightslategray', 'crimson', 'darkcyan', 'darkgoldenrod', 'cornsilk', 'turquoise', 'limegreen', \
'darkorchid', 'palevioletred', 'deeppink']
for x in major_characters:
if count % 2:
fig.add_trace(go.Bar(x=df_scene_emotions['Emotions'], y=df_scene_emotions[x], marker_color=colors, name = x + ' Sentiment'),
row = row, col = 2)
else:
row += 1
fig.add_trace(go.Bar(x=df_scene_emotions['Emotions'], y=df_scene_emotions[x], marker_color=colors, name = x + ' Sentiment'),
row = row, col = 1)
count += 1
fig.update_yaxes(title_text="Sentiment counts")
# Edit the layout
fig.update_layout(height=1200, width=1000,
title_text="<b> Emotional Sentiments of the 10 (Ten) Major Characters in the " + self.movie + " Movie <b>", showlegend= False)
fig.show()
return df_scene_emotions