seriouspark commited on
Commit
4fe5bff
1 Parent(s): ffd8c4d

Add application file

Browse files
Files changed (1) hide show
  1. app.py +348 -0
app.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import numpy as np
3
+ import pandas as pd
4
+ import re
5
+ import json
6
+ import os
7
+ import glob
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from torch.optim import Adam
12
+ from tqdm import tqdm
13
+ from torch import nn
14
+ from transformers import AutoTokenizer
15
+
16
+ import argparse
17
+ from bs4 import BeautifulSoup
18
+ import requests
19
+
20
+ def split_essay_to_sentence(origin_essay):
21
+ origin_essay_sentence = sum([[a.strip() for a in i.split('.')] for i in origin_essay.split('\n')], [])
22
+ essay_sent = [a for a in origin_essay_sentence if len(a) > 0]
23
+ return essay_sent
24
+
25
+ def get_first_extraction(text_sentence):
26
+ row_dict = {}
27
+ for row in tqdm(text_sentence):
28
+ question = 'what is the feeling?'
29
+ answer = question_answerer(question=question, context=row)
30
+ row_dict[row] = answer
31
+ return row_dict
32
+
33
+
34
+ class myDataset_for_infer(torch.utils.data.Dataset):
35
+ def __init__(self, X):
36
+ self.X = X
37
+
38
+ def __len__(self):
39
+ return len(self.X)
40
+
41
+ def __getitem__(self,idx):
42
+ sentences = tokenizer(self.X[idx], return_tensors = 'pt', padding = 'max_length', max_length = 96, truncation = True)
43
+ return sentences
44
+
45
+
46
+ def infer_data(model, main_feeling_keyword):
47
+ #ds = myDataset_for_infer()
48
+ df_infer = myDataset_for_infer(main_feeling_keyword)
49
+
50
+ infer_dataloader = torch.utils.data.DataLoader(df_infer, batch_size= 16)
51
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
52
+
53
+ if device == 'cuda':
54
+ model = model.cuda()
55
+
56
+ result_list = []
57
+ with torch.no_grad():
58
+ for idx, infer_input in tqdm(enumerate(infer_dataloader)):
59
+ mask = infer_input['attention_mask'].to(device)
60
+ input_id = infer_input['input_ids'].squeeze(1).to(device)
61
+
62
+ output = model(input_id, mask)
63
+ result = np.argmax(output.logits, axis=1).numpy()
64
+ result_list.extend(result)
65
+ return result_list
66
+
67
+
68
+ def get_word_emotion_pair(cls_model, origin_essay_sentence, idx2emo):
69
+
70
+ import re
71
+ def get_noun(sent):
72
+ return [w for (w, p) in pos_tag(word_tokenize(p_texts[0])) if len(w) > 1 and p in (['NN','N','NP'])]
73
+ def get_adj(sent):
74
+ return [w for (w, p) in pos_tag(word_tokenize(p_texts[0])) if len(w) > 1 and p in (['ADJ'])]
75
+ def get_verb(sent):
76
+ return [w for (w, p) in pos_tag(word_tokenize(p_texts[0])) if len(w) > 1 and p in (['VERB'])]
77
+
78
+ result_list = infer_data(cls_model, origin_essay_sentence)
79
+ final_result = pd.DataFrame(data = {'text': origin_essay_sentence , 'label' : result_list})
80
+ final_result['emotion'] = final_result['label'].map(idx2emo)
81
+
82
+ final_result['noun_list'] = final_result['text'].map(get_noun)
83
+ final_result['adj_list'] = final_result['text'].map(get_adj)
84
+ final_result['verb_list'] = final_result['text'].map(get_verb)
85
+
86
+ final_result['title'] = 'none'
87
+ file_made_dt = datetime.datetime.now()
88
+ file_made_dt_str = datetime.datetime.strftime(file_made_dt, '%Y%m%d_%H%M%d')
89
+ os.makedirs(f'./result/{nickname}/{file_made_dt_str}/', exist_ok = True)
90
+ final_result.to_csv(f"./result/{nickname}/{file_made_dt_str}/essay_result.csv", index = False)
91
+
92
+ return final_result, file_made_dt_str
93
+
94
+ return final_result, file_made_dt_str
95
+
96
+
97
+ def get_essay_base_analysis(file_made_dt_str, nickname):
98
+ essay1 = pd.read_csv(f"./result/{nickname}/{file_made_dt_str}/essay_result.csv")
99
+ essay1['noun_list_len'] = essay1['noun_list'].apply(lambda x : len(x))
100
+ essay1['noun_list_uniqlen'] = essay1['noun_list'].apply(lambda x : len(set(x)))
101
+ essay1['adj_list_len'] = essay1['adj_list'].apply(lambda x : len(x))
102
+ essay1['adj_list_uniqlen'] = essay1['adj_list'].apply(lambda x : len(set(x)))
103
+ essay1['vocab_all'] = essay1[['noun_list','adj_list']].apply(lambda x : sum((eval(x[0]),eval(x[1])), []), axis=1)
104
+ essay1['vocab_cnt'] = essay1['vocab_all'].apply(lambda x : len(x))
105
+ essay1['vocab_unique_cnt'] = essay1['vocab_all'].apply(lambda x : len(set(x)))
106
+ essay1['noun_list'] = essay1['noun_list'].apply(lambda x : eval(x))
107
+ essay1['adj_list'] = essay1['adj_list'].apply(lambda x : eval(x))
108
+ d = essay1.groupby('title')[['noun_list','adj_list']].sum([]).reset_index()
109
+ d['noun_cnt'] = d['noun_list'].apply(lambda x : len(set(x)))
110
+ d['adj_cnt'] = d['adj_list'].apply(lambda x : len(set(x)))
111
+
112
+ # 문장 기준 최고 감정
113
+ essay_summary =essay1.groupby(['title'])['emotion'].value_counts().unstack(level =1)
114
+
115
+ emo_vocab_dict = {}
116
+ for k, v in essay1[['emotion','noun_list']].values:
117
+ for vocab in v:
118
+ if (k, 'noun', vocab) not in emo_vocab_dict:
119
+ emo_vocab_dict[(k, 'noun', vocab)] = 0
120
+
121
+ emo_vocab_dict[(k, 'noun', vocab)] += 1
122
+
123
+ for k, v in essay1[['emotion','adj_list']].values:
124
+ for vocab in v:
125
+ if (k, 'adj', vocab) not in emo_vocab_dict:
126
+ emo_vocab_dict[(k, 'adj', vocab)] = 0
127
+
128
+ emo_vocab_dict[(k, 'adj', vocab)] += 1
129
+ vocab_emo_cnt_dict = {}
130
+ for k, v in essay1[['emotion','noun_list']].values:
131
+ for vocab in v:
132
+ if (vocab, 'noun') not in vocab_emo_cnt_dict:
133
+ vocab_emo_cnt_dict[('noun', vocab)] = {}
134
+ if k not in vocab_emo_cnt_dict[( 'noun', vocab)]:
135
+ vocab_emo_cnt_dict[( 'noun', vocab)][k] = 0
136
+
137
+ vocab_emo_cnt_dict[('noun', vocab)][k] += 1
138
+
139
+ for k, v in essay1[['emotion','adj_list']].values:
140
+ for vocab in v:
141
+ if ('adj', vocab) not in vocab_emo_cnt_dict:
142
+ vocab_emo_cnt_dict[( 'adj', vocab)] = {}
143
+ if k not in vocab_emo_cnt_dict[( 'adj', vocab)]:
144
+ vocab_emo_cnt_dict[( 'adj', vocab)][k] = 0
145
+
146
+ vocab_emo_cnt_dict[('adj', vocab)][k] += 1
147
+
148
+ vocab_emo_cnt_df = pd.DataFrame(vocab_emo_cnt_dict).T
149
+ vocab_emo_cnt_df['total'] = vocab_emo_cnt_df.sum(axis=1)
150
+ # 단어별 최고 감정 및 감정 개수
151
+ all_result=vocab_emo_cnt_df.sort_values(by = 'total', ascending = False)
152
+
153
+ # 단어별 최고 감정 및 감정 개수 , 형용사 포함 시
154
+ adj_result=vocab_emo_cnt_df.sort_values(by = 'total', ascending = False)
155
+
156
+ # 명사만 사용 시
157
+ noun_result=vocab_emo_cnt_df[vocab_emo_cnt_df.index.get_level_values(0) == 'noun'].sort_values(by = 'total', ascending = False)
158
+
159
+ final_file_name = f"essay_all_vocab_result.csv"
160
+ adj_file_name = f"essay_adj_vocab_result.csv"
161
+ noun_file_name = f"essay_noun_vocab_result.csv"
162
+
163
+ os.makedirs(f'./result/{nickname}/{file_made_dt_str}/', exist_ok = True)
164
+
165
+ all_result.to_csv(f"./result/{nickname}/{file_made_dt_str}/essay_all_vocab_result.csv", index = False)
166
+ adj_result.to_csv(f"./result/{nickname}/{file_made_dt_str}/essay_adj_vocab_result.csv", index = False)
167
+ noun_result.to_csv(f"./result/{nickname}/{file_made_dt_str}/essay_noun_vocab_result.csv", index = False)
168
+
169
+ return all_result, adj_result, noun_result, essay_summary, file_made_dt_str
170
+
171
+
172
+
173
+ from transformers import AutoModelForSequenceClassification
174
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
175
+
176
+ def all_process(origin_essay, nickname):
177
+ essay_sent =split_essay_to_sentence(origin_essay)
178
+ idx2emo = {0: 'Anger', 1: 'Sadness', 2: 'Anxiety', 3: 'Hurt', 4: 'Embarrassment', 5: 'Joy'}
179
+ tokenizer = AutoTokenizer.from_pretrained('seriouspark/xlm-roberta-base-finetuning-sentimental-6label')
180
+ cls_model = AutoModelForSequenceClassification.from_pretrained('seriouspark/xlm-roberta-base-finetuning-sentimental-6label')
181
+
182
+ final_result, file_name_dt = get_word_emotion_pair(cls_model, essay_sent, idx2emo)
183
+ all_result, adj_result, noun_result, essay_summary, file_made_dt_str = get_essay_base_analysis(file_name_dt, nickname)
184
+
185
+ summary_result = pd.concat([adj_result, noun_result]).fillna(0).sort_values(by = 'total', ascending = False).fillna(0).reset_index()[:30]
186
+ with open(f'./result/{nickname}/{file_name_dt}/summary.json','w') as f:
187
+ json.dump( essay_summary.to_json(),f)
188
+ with open(f'./result/{nickname}/{file_made_dt_str}/all_result.json','w') as f:
189
+ json.dump( all_result.to_json(),f)
190
+ with open(f'./result/{nickname}/{file_made_dt_str}/adj_result.json','w') as f:
191
+ json.dump( adj_result.to_json(),f)
192
+ with open(f'./result/{nickname}/{file_made_dt_str}/noun_result.json','w') as f:
193
+ json.dump( noun_result.to_json(),f)
194
+ #return essay_summary, summary_result
195
+ total_cnt = essay_summary.sum(axis=1).values[0]
196
+ essay_summary_list = sorted(essay_summary.T.to_dict()['none'].items(), key = lambda x: x[1], reverse =True)
197
+ essay_summary_list_str = ' '.join([f'{row[0]} {int(row[1]*100 / total_cnt)}%' for row in essay_summary_list])
198
+ summary1 = f"""{nickname}, Your sentiments in your writting are [{essay_summary_list_str}] """
199
+
200
+ return summary1
201
+
202
+ def get_similar_vocab(message):
203
+ if (len(message) > 0) & (len(re.findall('[A-Za-z]+', message))> 0):
204
+ vocab = message
205
+ all_dict_url = f"https://www.dictionary.com/browse/{vocab}"
206
+ response = requests.get(all_dict_url)
207
+
208
+ html_content = response.text
209
+ # BeautifulSoup로 HTML 파싱
210
+ soup = BeautifulSoup(html_content, 'html.parser')
211
+ result = soup.find_all(class_='ESah86zaufmd2_YPdZtq')
212
+ p_texts = [p.get_text() for p in soup.find_all('p')]
213
+ whole_vocab = sum([ [word for word , pos in pos_tag(word_tokenize(text)) if pos in ['NN','JJ','NNP','NNS']] for text in p_texts],[])
214
+
215
+ similar_words_final = Counter(whole_vocab).most_common(10)
216
+ return [i[0] for i in similar_words_final]
217
+
218
+ else:
219
+ return message
220
+
221
+ def get_similar_means(vocab):
222
+ all_dict_url = f"https://www.dictionary.com/browse/{vocab}"
223
+ response = requests.get(all_dict_url)
224
+ html_content = response.text
225
+ soup = BeautifulSoup(html_content, 'html.parser')
226
+ result = soup.find_all(class_='ESah86zaufmd2_YPdZtq')
227
+ p_texts = [p.get_text() for p in soup.find_all('p')]
228
+ return p_texts[:10]
229
+
230
+
231
+ info_dict = {}
232
+ def run_all(message, history):
233
+ global info_dict
234
+ if message.find('NICKNAME:')>=0:
235
+ global nickname
236
+ nickname = message.replace('NICKNAME','').replace(':','').strip()
237
+ #global nickname
238
+ info_dict[nickname] = {}
239
+ return f'''Good [{nickname}]!! Let's start!.
240
+ Give me a vocabulary in your mind.
241
+ \n\n\nwhen you type the vocab, please include \"VOCAB: \"
242
+ e.g <VOCAB: orange>
243
+ '''
244
+ try :
245
+ #print(nickname)
246
+ if message.find('VOCAB:')>=0:
247
+ clear_message = message.replace('VOCAB','').replace(':','').strip()
248
+ info_dict[nickname]['main_word'] = clear_message
249
+ vocab_mean_list = []
250
+ similar_words_final = get_similar_vocab(clear_message)
251
+ print(similar_words_final)
252
+ similar_words_final_with_main = similar_words_final + [clear_message]
253
+ if len(similar_words_final_with_main)>0:
254
+ for w in similar_words_final_with_main:
255
+ temp_means = get_similar_means(w)
256
+ vocab_mean_list.append(temp_means[:2])
257
+ fixed_similar_words_final = list(set([i for i in sum(vocab_mean_list, []) if len(i) > 10]))[:10]
258
+
259
+
260
+ word_str = ' \n'.join([str(idx) + ") " + i for idx, i in enumerate(similar_words_final, 1)])
261
+ sentence_str = ' \n'.join([str(idx) + ") " + i for idx, i in enumerate(fixed_similar_words_final, 1)])
262
+
263
+ return f'''Let's start writing with the VOCAB<{clear_message}>!
264
+ First, how about those similar words?
265
+ {word_str} \n
266
+ The word has these meanings.
267
+ {sentence_str}\n
268
+ Pick and type one meaning of these list.
269
+ \n\n\n When you type in, please include \"SENT:\", like this.
270
+ \n e.g. <SENT: a globose, reddish-yellow, bitter or sweet, edible citrus fruit. >
271
+ '''
272
+ else:
273
+ return 'Include \"VOCAB:\" please (VOCAB: orange)'
274
+
275
+ elif message.find('SENT:')>=0:
276
+ clear_message = message.replace('SENT','').replace(':','').strip()
277
+ info_dict[nickname]['selected_sentence'] = clear_message
278
+ return f'''You've got [{clear_message}].
279
+ \n With this sentence, we can make creative short writings
280
+ \n\n\n Include \"SHORT_W: \", please.
281
+ \n e.g <SHORT_W: Whenever I smell the citrus, I always reminise him, first>
282
+
283
+ '''
284
+
285
+ elif message.find('SHORT_W:')>=0:
286
+ clear_message = message.replace('SHORT_W','').replace(':','').strip()
287
+ info_dict[nickname]['short_contents'] = clear_message
288
+
289
+ return f'''This is your short sentence <{clear_message}> .
290
+ \n With this sentence, let's step one more thing, please write long sentences more than 500 words.
291
+ \n\n\n When you input, please include\"LONG_W: \" like this.
292
+ \n e.g <LONG_W: He enjoyed wearing blue T-shirts at the gym, but the intense citrus scent he used on his clothes was noticeably excessive ... >
293
+ '''
294
+ elif message.find('LONG_W:')>=0:
295
+ long_message = message.replace('LONG_W','').replace(':','').strip()
296
+
297
+ length_of_lm = len(long_message)
298
+ if length_of_lm >= 500:
299
+ info_dict['long_contents'] = long_message
300
+ os.makedirs(f"./result/{nickname}/", exist_ok = True)
301
+ with open(f"./result/{nickname}/contents.txt",'w') as f:
302
+ f.write(long_message)
303
+ return f'Your entered text is {length_of_lm} characters. This text is worth analyzing. If you wish to start the analysis, please type "START ANALYSIS"'
304
+ else :
305
+ return f'The text you have entered is {length_of_lm} characters. It\'s a bit short for analysis. Could you please provide a bit more sentences'
306
+
307
+ elif message.find('START ANALYSIS')>=0:
308
+ with open(f"./result/{nickname}/contents.txt",'r') as f:
309
+ orign_essay = f.read()
310
+ summary = all_process(orign_essay, nickname)
311
+
312
+ #print(summary)
313
+ return summary
314
+ else:
315
+ return 'Please start from the beginning'
316
+
317
+ except:
318
+ return 'An error has occurred. Restarting from the beginning. Please enter your NICKNAME:'
319
+
320
+
321
+ import gradio as gr
322
+ import requests
323
+ history = []
324
+ info_dict = {}
325
+ iface = gr.ChatInterface(
326
+ fn=run_all,
327
+ chatbot = gr.Chatbot(),
328
+ textbox = gr.Textbox(placeholder="Please enter including the chatbot's request prefix.", container = True, scale = 7),
329
+ title = 'MooGeulMooGeul',
330
+ description = "Please start by choosing your nickname. Include 'NICKNAME: ' in your response",
331
+ theme = 'soft',
332
+ examples = ['NICKNAME: bluebottle',
333
+ 'VOCAB: orange',
334
+ 'SENT: a globose, reddish-yellow, bitter or sweet, edible citrus fruit.',
335
+ 'SHORT_W: Whenever I smell the citrus, I always reminise him, first',
336
+ '''LONG_W: Whenever I smell citrus, I always think of him. He used to come to the gym wearing a blue T-shirt, often spraying a strong citrus scent.
337
+ That scent was quite distinctive, letting me know when he was passing by.
338
+ I usually arrived to work out between 7:00 and 7:30 AM, and interestingly, he would arrive about 10 minutes after me.
339
+ On days I came early, he did too; and when I was late, he was also late.
340
+ The citrus scent from his body was always so intense, as if he had just sprayed it.'''
341
+ ],
342
+ cache_examples = False,
343
+ retry_btn = None,
344
+ undo_btn = 'Delete Previous',
345
+ clear_btn = 'Clear',
346
+
347
+ )
348
+ iface.launch(share=True)