NursNurs commited on
Commit
ec07c0a
1 Parent(s): 28bf522

Full model

Browse files
Files changed (2) hide show
  1. app.py +375 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ from tqdm import tqdm
4
+ from peft import PeftModel, PeftConfig
5
+ from transformers import AutoModelForSeq2SeqLM
6
+ from transformers import AutoTokenizer
7
+ import numpy as np
8
+ import time
9
+
10
+
11
+ @st.cache_resource
12
+ def get_models():
13
+ st.write('Loading the model...')
14
+ config = PeftConfig.from_pretrained("NursNurs/T5ForReverseDictionary")
15
+ model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-large")
16
+ model = PeftModel.from_pretrained(model, "NursNurs/T5ForReverseDictionary")
17
+
18
+ tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-large")
19
+
20
+ st.session_state.model['model'] = model
21
+ st.session_state.model['tokenizer'] = tokenizer
22
+
23
+ st.write("The assistant is loaded and ready to use!")
24
+
25
+ def return_top_k(sentence, k=10):
26
+
27
+ model, tokenizer = st.session_state.model['model'], st.session_state.model['tokenizer']
28
+
29
+ if sentence[-1] != ".":
30
+ sentence = sentence + "."
31
+
32
+ inputs = [f"Descripton : {sentence}. Word : "]
33
+
34
+ inputs = tokenizer(
35
+ inputs,
36
+ padding=True, truncation=True,
37
+ return_tensors="pt",
38
+ )
39
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
40
+ model.to(device)
41
+
42
+ with torch.no_grad():
43
+ inputs = {k: v.to(device) for k, v in inputs.items()}
44
+ output_sequences = model.generate(input_ids=inputs["input_ids"], max_new_tokens=10, num_beams=k+5, num_return_sequences=k+5, #max_length=3,
45
+ top_p = 50, output_scores=True, return_dict_in_generate=True) #repetition_penalty=10000.0
46
+
47
+ logits = output_sequences['sequences_scores'].clone().detach()
48
+ decoded_probabilities = torch.softmax(logits, dim=0)
49
+
50
+
51
+ #all word predictions
52
+ predictions = [tokenizer.decode(tokens, skip_special_tokens=True) for tokens in output_sequences['sequences']]
53
+ probabilities = [round(float(prob), 2) for prob in decoded_probabilities]
54
+
55
+ for pred in predictions:
56
+ if len(pred) < 2:
57
+ predictions.pop(predictions.index(pred))
58
+
59
+ return predictions[:10]
60
+
61
+
62
+ if 'messages' not in st.session_state:
63
+ st.session_state.messages = []
64
+
65
+ if 'results' not in st.session_state:
66
+ st.session_state.results = {'results': False, 'results_print': False}
67
+
68
+ if 'actions' not in st.session_state:
69
+ st.session_state.actions = [""]
70
+
71
+ if 'counters' not in st.session_state:
72
+ st.session_state.counters = {"letter_count": 1, "word_count": 0}
73
+
74
+ if 'is_helpful' not in st.session_state:
75
+ st.session_state.is_helpful = {'ask':False}
76
+
77
+ if 'model' not in st.session_state:
78
+ st.session_state.model = {'model': False, 'tokenizer': False}
79
+
80
+ if st.session_state.model['model'] == False:
81
+ get_models()
82
+
83
+ st.title("You name it!")
84
+
85
+ with st.chat_message('user'):
86
+ st.write("Hey assistant!")
87
+
88
+ bot = st.chat_message('assistant')
89
+ bot.write("Hello human! Wanna practice naming some words?")
90
+
91
+ #for showing history of messages
92
+ for message in st.session_state.messages:
93
+ with st.chat_message(message['role']):
94
+ st.markdown(message['content'])
95
+
96
+ def get_text():
97
+ input_text = st.chat_input()
98
+ return input_text
99
+
100
+ def write_bot(input, remember=True):
101
+ with st.chat_message('assistant'):
102
+ message_placeholder = st.empty()
103
+ full_response = input
104
+ response = ''
105
+ for chunk in full_response.split():
106
+ response += chunk + " "
107
+ time.sleep(0.05)
108
+ # Add a blinking cursor to simulate typing
109
+ message_placeholder.markdown(response + "▌")
110
+ time.sleep(0.5)
111
+ message_placeholder.markdown(full_response)
112
+ if remember == True:
113
+ st.session_state.messages.append({'role': 'assistant', 'content': full_response})
114
+
115
+ def ask_if_helped():
116
+ if st.session_state.is_helpful['ask'] == True:
117
+ y = st.button('Yes!', key=60)
118
+ n = st.button('No...', key=61)
119
+ if y:
120
+ write_bot("I am happy to help!")
121
+ elif n:
122
+ st.session_state.actions.append('cue')
123
+
124
+ if st.session_state.actions[-1] == "result":
125
+ a1 = st.button('Results', key=10)
126
+ a2 = st.button('Cue', key=11)
127
+ if a1:
128
+ write_bot("Here are my guesses about your word:")
129
+ st.write(st.session_state.results['results_print'])
130
+ time.sleep(2)
131
+ write_bot('Does it help you remember the word?', remember=False)
132
+ st.session_state.is_helpful['ask'] = True
133
+ elif a2:
134
+ write_bot(f'The first letter is {st.session_state.results["results"][0][0]}.')
135
+ time.sleep(2)
136
+ write_bot('Does it help you remember the word?', remember=False)
137
+ st.session_state.is_helpful['ask'] = True
138
+
139
+
140
+ ask_if_helped()
141
+
142
+
143
+ if st.session_state.actions[-1] == 'cue':
144
+ guessed = False
145
+ write_bot('What do you want to see?', remember=False)
146
+ b1 = st.button("Next letter", key="1")
147
+ b2 = st.button("Next word", key="2")
148
+ b3 = st.button("All words", key="3")
149
+ b4 = st.button("I remembered the word!", key="4", type='primary')
150
+ b5 = st.button("Exit", key="5", type='primary')
151
+ while guessed == False:
152
+ if b1:
153
+ st.session_state.counters["letter_count"] += 1
154
+ word_count = st.session_state.counters["word_count"]
155
+ letter_count = st.session_state.counters["letter_count"]
156
+ write_bot(f'The word starts with {st.session_state.results["results"][word_count][:letter_count]}')
157
+
158
+ elif b2:
159
+ st.session_state.counters["letter_count"] = 1
160
+ letter_count = st.session_state.counters["letter_count"]
161
+ st.session_state.counters["word_count"] += 1
162
+ word_count = st.session_state.counters["word_count"]
163
+ write_bot(f'The next word starts with {st.session_state.results["results"][word_count][:letter_count]}')
164
+
165
+ elif b3:
166
+ write_bot(f"Here are all my guesses about your word: {st.session_state.results['results_print']}")
167
+
168
+ elif b4:
169
+ write_bot("Yay! I am happy I could be of help!")
170
+ guessed = True
171
+ break
172
+
173
+ elif b5:
174
+ write_bot("I am sorry I couldn't help you this time. See you soon!")
175
+ st.session_state.actions.append('cue')
176
+ break
177
+
178
+ #display user message in chat message container
179
+ prompt = get_text()
180
+ if prompt:
181
+ with st.chat_message('user'):
182
+ st.markdown(prompt)
183
+ #add to history
184
+ st.session_state.messages.append({'role': 'user', 'content': prompt})
185
+ yes = "YesyesYes!Sure!sure"
186
+ if prompt == "yes":
187
+ write_bot("Please describe your word!")
188
+ #if previously we asked to give a prompt
189
+ elif (st.session_state.messages[-2]['content'] == "Please describe your word!") & (st.session_state.messages[-1]['content'] != "no"):
190
+ write_bot("Great! Let me think what it could be...")
191
+ st.session_state.results['results'] = return_top_k(prompt)
192
+ st.session_state.results['results_print'] = dict(zip(range(1, 11), st.session_state.results['results']))
193
+ write_bot("I think I have some ideas. Do you want to see my guesses or do you want a cue?")
194
+ st.session_state.actions.append("result")
195
+
196
+ # elif prompt == 'results':
197
+ # st.text("results")
198
+ # st.write("results")
199
+ # st.session_state.actions.append({'result': True})
200
+ # st.write(st.session_state.actions)
201
+ # with st.chat_message('user'):
202
+ # custom_response = "Results"
203
+ # st.markdown(custom_response)
204
+ # st.session_state.messages.append({'role': 'user', 'content': custom_response})
205
+
206
+ # with st.chat_message('assistant'):
207
+ # message_placeholder = st.empty()
208
+ # response = f"Here are my guesses about your word: {result_print}"
209
+ # message_placeholder.markdown(response + "|")
210
+ # st.session_state.messages.append({'role': 'assistant', 'content': response})
211
+ # elif st.button('Cue'):
212
+ # response = "Cue"
213
+ # with st.chat_message('user'):
214
+ # st.markdown(response)
215
+ # st.session_state.messages.append({'role': 'user', 'content': response})
216
+ # text = f'The first letter is {result[0][0]}.'
217
+ # bot.write(text)
218
+ # st.session_state.messages.append({'role': 'assistant', 'content': text})
219
+ # letter_count = 1
220
+ # word_count = 0
221
+ # elif prompt == 'Results':
222
+ # with st.chat_message('assistant'):
223
+ # message_placeholder = st.empty()
224
+ # response = f"Here are my guesses about your word: {result_print}"
225
+ # message_placeholder.markdown(response + "|")
226
+ # st.session_state.messages.append({'role': 'assistant', 'content': response})
227
+
228
+ # #if you don't wanna practice word naming
229
+ # else:
230
+ # with st.chat_message('assistant'):
231
+ # message_placeholder = st.empty()
232
+ # response = "See you next time!"
233
+ # message_placeholder.markdown(response + "|")
234
+ # st.session_state.messages.append({'role': 'assistant', 'content': response})
235
+
236
+
237
+
238
+ # if st.button('Results'):
239
+ # bot.write("Here are my guesses about your word:")
240
+ # bot.write(result_print)
241
+ # elif st.button('Cue'):
242
+ # bot.write(f'The first letter is {result[0][0]}.')
243
+ # letter_count = 1
244
+ # word_count = 0
245
+ # answer = st.chat_input('Does it help you remember the word? Type yes or no')
246
+ # if answer == "no":
247
+ # bot.write("What do you want to see?")
248
+ # if st.button('Next letter'):
249
+ # letter_count += 1
250
+ # bot.write(f'The word starts with {result[word_count][:letter_count]}')
251
+ # elif st.button('Next word'):
252
+ # letter_count = 1
253
+ # bot.write(f'The next word starts with {result[word_count][:letter_count]}')
254
+ # word_count += 1
255
+ # elif st.button('All words'):
256
+ # bot.write("Here are all my guesses about your word:")
257
+ # bot.write(result_print)
258
+ # bot.write("Does this help you remember your word?")
259
+ # answer = st.chat_input('Type yes/no/exit')
260
+ # if answer == 'Exit':
261
+ # st.write("I am sorry I couldn't help you. See you next time!")
262
+
263
+
264
+ #write down assistant's responses
265
+ #response = f'Echo: {prompt}' #echoes prompt
266
+ # with st.chat_message('assistant'):
267
+ # message_placeholder = st.empty()
268
+ # full_response = "yeee"
269
+ # #here insert the loop with the model answers (for response in...)
270
+ # #this to imitate a cursor
271
+ # message_placeholder.markdown(full_response + "|")
272
+
273
+ # #add to history
274
+ # st.session_state.messages.append({'role': 'assistant', 'content': full_response})
275
+
276
+
277
+
278
+ ##TODO: a button to delete history
279
+ # if prompt == 'Yes':
280
+ # bot.write("Great! Please describe the word you have in mind.")
281
+ # sent = st.chat_input('Description of your word')
282
+
283
+
284
+ # # adding the text that will show in the text box as default
285
+ # default_value = "Type the description of the word you have in mind!"
286
+
287
+ # sent = st.text_area("Text", default_value, height = 50)
288
+ # result = return_top_k(sent)
289
+ # result = ['animal', 'monster', 'creature', 'bird', 'cat', 'human', 'dog', 'spider', 'alien', 'meow']
290
+ # result = return_top_k(sent)
291
+ # result_print = dict(zip(range(1, 11), result))
292
+
293
+ # if st.button('Results'):
294
+ # st.write("Here are my guesses about your word:")
295
+ # st.write(result_print)
296
+ # elif st.button('Cue'):
297
+ # st.write(f'The first letter is {result[0][0]}.')
298
+ # letter_count = 1
299
+ # word_count = 0
300
+ # answer = st.text_area("Text", 'Does it help you remember the word? Type yes or no', height = 50)
301
+ # if answer == 'No':
302
+ # while answer == 'No':
303
+ # option = st.selectbox(
304
+ # 'What do you want to see?',
305
+ # ('Next letter', 'Next word', 'All words'))
306
+ # if option == 'Next letter':
307
+ # letter_count += 1
308
+ # st.write(f'The word starts with {result[word_count][:letter_count]}')
309
+ # elif option == 'Next word':
310
+ # letter_count = 1
311
+ # st.write(f'The next word starts with {result[word_count][:letter_count]}')
312
+ # word_count += 1
313
+ # else:
314
+ # st.write("Here are all my guesses about your word:")
315
+ # st.write(result_print)
316
+ # answer = st.selectbox(
317
+ # 'Does it help you remember the word??',
318
+ # ('Yes', 'No', 'Exit'))
319
+ # if answer == 'Exit':
320
+ # st.write("I am sorry I couldn't help you. See you next time!")
321
+ # break
322
+ # else:
323
+ # st.write("I am happy I could be of help!")
324
+ # else:
325
+ # st.write('Do you want to see my guesses or do you want a cue?')
326
+
327
+
328
+ #2
329
+
330
+ # option = st.selectbox(
331
+ # 'Do you want to see my guesses or do you want a cue?',
332
+ # ('Results', 'Cue'))
333
+
334
+ # st.write('You selected:', option)
335
+
336
+ # if option == 'Results':
337
+ # st.write("Here are my guesses about your word:")
338
+ # st.write(result_print)
339
+ # elif option == 'Cue':
340
+ # st.write(f'The first letter is {result[0][0]}.')
341
+ # letter_count = 1
342
+ # word_count = 0
343
+ # answer = st.selectbox(
344
+ # 'Does it help you remember the word??',
345
+ # ('Yes', 'No'))
346
+ # if answer == 'No':
347
+ # while answer == 'No':
348
+ # option = st.selectbox(
349
+ # 'What do you want to see?',
350
+ # ('Next letter', 'Next word', 'All words'))
351
+ # if option == 'Next letter':
352
+ # letter_count += 1
353
+ # st.write(f'The word starts with {result[word_count][:letter_count]}')
354
+ # elif option == 'Next word':
355
+ # letter_count = 1
356
+ # st.write(f'The next word starts with {result[word_count][:letter_count]}')
357
+ # word_count += 1
358
+ # else:
359
+ # st.write("Here are all my guesses about your word:")
360
+ # st.write(result_print)
361
+ # answer = st.selectbox(
362
+ # 'Does it help you remember the word??',
363
+ # ('Yes', 'No', 'Exit'))
364
+ # if answer == 'Exit':
365
+ # st.write("I am sorry I couldn't help you. See you next time!")
366
+ # break
367
+ # else:
368
+ # st.write("I am happy I could be of help!")
369
+
370
+
371
+
372
+
373
+
374
+
375
+
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ numpy==1.23.5
2
+ peft==0.5.0
3
+ streamlit==1.26.0
4
+ torch==1.13.1
5
+ tqdm==4.64.1
6
+ transformers==4.33.2