jitesh commited on
Commit
39e71d7
1 Parent(s): b240251

fixes error gen

Browse files
Files changed (3) hide show
  1. app.py +4 -22
  2. story_gen.py +0 -221
  3. story_gen_test.py +0 -34
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import streamlit as st
2
- from story_gen import StoryGenerator
3
- import plotly.figure_factory as ff
4
  import plotly.express as px
5
  import random
6
  import numpy as np
@@ -12,9 +11,11 @@ container_mode = st.sidebar.container()
12
  container_guide = st.container()
13
  container_param = st.sidebar.container()
14
  container_button = st.sidebar.container()
 
15
  mode = container_mode.radio(
16
  "Select a mode",
17
- ('Create Statistics', 'Play Storytelling'), index=0)
 
18
  choices_first_sentence = [
19
  'Custom',
20
  'Hello, I\'m a language model,',
@@ -93,14 +94,6 @@ elif mode == 'Play Storytelling':
93
  'score': first_emotion['score']}]
94
  if 'full_story' not in st.session_state:
95
  st.session_state.full_story = story_till_now
96
- # # , placeholder="Start writing your story...")
97
- # story_till_now = st.text_input(
98
- # label='First Sentence', value='Hello, I\'m a language model,')
99
-
100
- # num_generation = st.sidebar.slider(
101
- # label='Number of generation', min_value=1, max_value=100, value=10, step=1)
102
- # length = st.sidebar.slider(label='Length of the generated sentence',
103
- # min_value=1, max_value=100, value=20, step=1)
104
  container_button = container_button.columns([1, 1, 1])
105
  heading_container = st.container()
106
  col_turn, col_sentence, col_emo = st.columns([1, 8, 2])
@@ -121,17 +114,6 @@ elif mode == 'Play Storytelling':
121
  col_sentence.markdown(step['sentence'])
122
  col_emo.markdown(
123
  f'{step["emotion"]} {np.round(step["score"], 3)}', unsafe_allow_html=False)
124
- # i=0
125
- # while True:
126
- # story_till_now, emotion, new_sentence = gen.next_sentence(
127
- # story_till_now, length)
128
- # col_sentence.text(new_sentence)
129
- # col_emo.markdown(f'{emotion["label"]} {np.round(emotion["score"], 3)}', unsafe_allow_html=False)
130
- # # col_emo.markdown(f'The last sentence has the "{emotion["label"]}" **Emotion** with a confidence score of {emotion["score"]}.')
131
- # new_input_sentence = st.text_input(label='Next Sentence', key=f'next_sentence_{i}')
132
- # story_till_now += ' ' + new_input_sentence
133
-
134
- # i+=1
135
 
136
  else:
137
  step = st.session_state.sentence_list[0]
 
1
  import streamlit as st
2
+ from lib.story_gen import StoryGenerator
 
3
  import plotly.express as px
4
  import random
5
  import numpy as np
 
11
  container_guide = st.container()
12
  container_param = st.sidebar.container()
13
  container_button = st.sidebar.container()
14
+
15
  mode = container_mode.radio(
16
  "Select a mode",
17
+ ('Probability Emote', 'Create Statistics', 'Play Storytelling'), index=0)
18
+
19
  choices_first_sentence = [
20
  'Custom',
21
  'Hello, I\'m a language model,',
 
94
  'score': first_emotion['score']}]
95
  if 'full_story' not in st.session_state:
96
  st.session_state.full_story = story_till_now
 
 
 
 
 
 
 
 
97
  container_button = container_button.columns([1, 1, 1])
98
  heading_container = st.container()
99
  col_turn, col_sentence, col_emo = st.columns([1, 8, 2])
 
114
  col_sentence.markdown(step['sentence'])
115
  col_emo.markdown(
116
  f'{step["emotion"]} {np.round(step["score"], 3)}', unsafe_allow_html=False)
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  else:
119
  step = st.session_state.sentence_list[0]
story_gen.py DELETED
@@ -1,221 +0,0 @@
1
-
2
- import sys
3
- import time
4
-
5
- import printj
6
- from transformers import pipeline # , set_seed
7
- import numpy as np
8
- import pandas as pd
9
- # import nltk
10
- import re
11
- import streamlit as st
12
-
13
-
14
- class StoryGenerator:
15
- def __init__(self):
16
- self.initialise_models()
17
- self.stats_df = pd.DataFrame(data=[], columns=[])
18
- self.stories = []
19
- self.data = []
20
-
21
- @staticmethod
22
- @st.cache(allow_output_mutation=True)
23
- def get_generator():
24
- return pipeline('text-generation', model='gpt2')
25
-
26
- @staticmethod
27
- @st.cache(allow_output_mutation=True)
28
- def get_classifier():
29
- return pipeline("text-classification",
30
- model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=True)
31
-
32
- def initialise_models(self):
33
- # start = time.time()
34
- self.generator = self.get_generator()
35
- self.classifier = self.get_classifier()
36
- # initialising_time = time.time()-start
37
- # print(f'Initialising Time: {initialising_time}')
38
- # set_seed(42)
39
- # sys.exit()
40
-
41
- def reset():
42
- self.clear_stories()
43
- self.clear_stats()
44
-
45
- def clear_stories(self):
46
- self.data = []
47
- self.stories = []
48
-
49
- def clear_stats(self):
50
- self.stats_df = pd.DataFrame(data=[], columns=[])
51
-
52
- def get_emotion(self, text):
53
- emotions = self.classifier(text)
54
- emotion = max(emotions[0], key=lambda x: x['score'])
55
- return emotion
56
-
57
- @staticmethod
58
- def get_num_token(text):
59
- # return len(nltk.word_tokenize(text))
60
- return len(re.findall(r'\w+', text))
61
-
62
- @staticmethod
63
- def check_show_emotion(confidence_score, frequency, w):
64
- frequency_penalty = 1 - frequency
65
- probability_emote = w * confidence_score + (1-w) * frequency_penalty
66
- return probability_emote > np.random.random_sample()
67
-
68
- def story(self,
69
- story_till_now="Hello, I'm a language model,",
70
- num_generation=4,
71
- length=10):
72
- # last_length = 0
73
-
74
- for i in range(num_generation):
75
- last_length = len(story_till_now)
76
- genreate_robot_sentence = self.generator(story_till_now, max_length=self.get_num_token(story_till_now) +
77
- length, num_return_sequences=1)
78
- story_till_now = genreate_robot_sentence[0]['generated_text']
79
- new_sentence = story_till_now[last_length:]
80
- emotion = self.get_emotion(new_sentence)
81
- # printj.yellow(f'Sentence {i}:')
82
- # story_to_print = f'{printj.ColorText.cyan(story_till_now[:last_length])}{printj.ColorText.green(story_till_now[last_length:])}\n'
83
- # print(story_to_print)
84
- # printj.purple(f'Emotion: {emotion}')
85
- return story_till_now, emotion
86
-
87
- def next_sentence(self,
88
- story_till_now="Hello, I'm a language model,",
89
- length=10):
90
- last_length = len(story_till_now)
91
- genreate_robot_sentence = self.generator(story_till_now, max_length=self.get_num_token(story_till_now) +
92
- length, num_return_sequences=1)
93
- story_till_now = genreate_robot_sentence[0]['generated_text']
94
- new_sentence = story_till_now[last_length:]
95
- emotion = self.get_emotion(new_sentence)
96
- return story_till_now, emotion, new_sentence
97
-
98
-
99
- def auto_ist(self,
100
- story_till_now="Hello, I'm a language model,",
101
- num_generation=4,
102
- length=20, reaction_weight=0.5):
103
- stats_df = pd.DataFrame(data=[], columns=[])
104
- stats_dict = dict()
105
- num_reactions = 0
106
- reaction_frequency = 0
107
- emotion = self.get_emotion(story_till_now) # first line emotion
108
- story_data = [{
109
- 'sentence': story_till_now,
110
- 'turn': 'first',
111
- 'emotion': emotion['label'],
112
- 'confidence_score': emotion['score'],
113
- }]
114
- for i in range(num_generation):
115
- # Text generation for User
116
- last_length = len(story_till_now)
117
- printj.cyan(story_till_now)
118
- printj.red.bold_on_white(
119
- f'loop: {i}; generate user text; length: {last_length}')
120
- genreate_user_sentence = self.generator(story_till_now, max_length=self.get_num_token(
121
- story_till_now)+length, num_return_sequences=1)
122
- story_till_now = genreate_user_sentence[0]['generated_text']
123
- new_sentence_user = story_till_now[last_length:]
124
-
125
- printj.red.bold_on_white(f'loop: {i}; check emotion')
126
- # Emotion self.classifier for User
127
- emotion_user = self.get_emotion(new_sentence_user)
128
- if emotion_user['label'] == 'neutral':
129
- show_emotion_user = False
130
- else:
131
- reaction_frequency = num_reactions/(i+1)
132
- show_emotion_user = self.check_show_emotion(
133
- confidence_score=emotion_user['score'], frequency=reaction_frequency, w=reaction_weight)
134
- if show_emotion_user:
135
- num_reactions += 1
136
-
137
- story_data.append({
138
- 'sentence': new_sentence_user,
139
- 'turn': 'user',
140
- 'emotion': emotion_user['label'],
141
- 'confidence_score': emotion_user['score'],
142
- })
143
- stats_dict['sentence_no'] = i
144
- stats_dict['turn'] = 'user'
145
- stats_dict['sentence'] = new_sentence_user
146
- stats_dict['show_emotion'] = show_emotion_user
147
- stats_dict['emotion_label'] = emotion_user['label']
148
- stats_dict['emotion_score'] = emotion_user['score']
149
- stats_dict['num_reactions'] = num_reactions
150
- stats_dict['reaction_frequency'] = reaction_frequency
151
- stats_dict['reaction_weight'] = reaction_weight
152
- stats_df = pd.concat(
153
- [stats_df, pd.DataFrame(stats_dict, index=[f'idx_{i}'])])
154
- # Text generation for Robot
155
- last_length = len(story_till_now)
156
- printj.cyan(story_till_now)
157
- printj.red.bold_on_white(
158
- f'loop: {i}; generate robot text; length: {last_length}')
159
- genreate_robot_sentence = self.generator(story_till_now, max_length=self.get_num_token(
160
- story_till_now)+length, num_return_sequences=1)
161
- story_till_now = genreate_robot_sentence[0]['generated_text']
162
- new_sentence_robot = story_till_now[last_length:]
163
- emotion_robot = self.get_emotion(new_sentence_robot)
164
-
165
- story_data.append({
166
- 'sentence': new_sentence_robot,
167
- 'turn': 'robot',
168
- 'emotion': emotion_robot['label'],
169
- 'confidence_score': emotion_robot['score'],
170
- })
171
- stats_dict['sentence_no'] = i
172
- stats_dict['turn'] = 'robot'
173
- stats_dict['sentence'] = new_sentence_robot
174
- stats_dict['show_emotion'] = None
175
- stats_dict['emotion_label'] = emotion_robot['label']
176
- stats_dict['emotion_score'] = emotion_robot['score']
177
- stats_dict['num_reactions'] = None
178
- stats_dict['reaction_frequency'] = None
179
- stats_dict['reaction_weight'] = None
180
- stats_df = pd.concat(
181
- [stats_df, pd.DataFrame(stats_dict, index=[f'idx_{i}'])])
182
-
183
- return stats_df, story_till_now, story_data
184
-
185
- def get_stats(self,
186
- story_till_now="Hello, I'm a language model,",
187
- num_generation=4,
188
- length=20, reaction_weight=-1, num_tests=2):
189
- use_random_w = reaction_weight == -1
190
- # self.stories = []
191
- try:
192
- num_rows = max(self.stats_df.story_id)+1
193
- except Exception:
194
- num_rows = 0
195
- for story_id in range(num_tests):
196
- if use_random_w:
197
- # reaction_weight = np.random.random_sample()
198
- reaction_weight = np.round(np.random.random_sample(), 1)
199
- stats_df0, _story_till_now, story_data = self.auto_ist(
200
- story_till_now=story_till_now,
201
- num_generation=num_generations,
202
- length=length, reaction_weight=reaction_weight)
203
- stats_df0.insert(loc=0, column='story_id', value=story_id+num_rows)
204
-
205
- # stats_df0['story_id'] = story_id
206
- self.stats_df = pd.concat([self.stats_df, stats_df0])
207
- printj.yellow(f'story_id: {story_id}')
208
- printj.green(stats_df0)
209
- self.stories.append(_story_till_now)
210
- self.data.append(story_data)
211
- self.stats_df = self.stats_df.reset_index(drop=True)
212
- print(self.stats_df)
213
-
214
- def save_stats(self, path='pandas_simple.xlsx'):
215
- writer = pd.ExcelWriter(path, engine='xlsxwriter')
216
-
217
- # Convert the dataframe to an XlsxWriter Excel object.
218
- self.stats_df.to_excel(writer, sheet_name='IST')
219
-
220
- # Close the Pandas Excel writer and output the Excel file.
221
- writer.save()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
story_gen_test.py DELETED
@@ -1,34 +0,0 @@
1
- # %%
2
- import printj
3
- from story_gen import StoryGenerator
4
-
5
- gen = StoryGenerator()
6
- # # %%
7
- # story_till_now, emotion = gen.story(story_till_now='Hello, I\'m a language model,', num_generation=3, length=10)
8
- # printj.purple(story_till_now)
9
- # printj.yellow(emotion)
10
-
11
-
12
- # %%
13
- gen.get_stats(story_till_now="For myriad of eons i’ve forgotten who I really was, harvesting the essence of all existence.",
14
- length=10, num_generation=3, num_tests=50)
15
-
16
- # %%
17
- gen.save_stats('/home/jitesh/haru/ist/results/a.xlsx')
18
-
19
-
20
-
21
-
22
- # %%
23
- data=gen.stats_df[gen.stats_df.sentence_no==3]
24
- import seaborn as sns
25
- sns.set_theme(style="whitegrid")
26
- # ax = sns.violinplot(x="day", y="total_bill", data=tips)
27
- ax = sns.violinplot(x="reaction_weight", y="num_reactions", data=data).set_title('Analysing ProbabilityEmote (Max reactions=3)')
28
- # %%
29
-
30
- gen.stats_df[gen.stats_df.sentence_no==3]
31
- # %%
32
- import re
33
- len(re.findall(r'\w+', 'line ive '))
34
- # %%