Spaces:
Sleeping
Sleeping
renamed the variables in context file
Browse files- pages/2_Context-based_chatbot.py +83 -82
pages/2_Context-based_chatbot.py
CHANGED
@@ -14,13 +14,13 @@ from nltk.corpus import wordnet as wn
|
|
14 |
from nltk.tokenize import word_tokenize
|
15 |
|
16 |
@st.cache_resource
|
17 |
-
def
|
18 |
st.write('Loading the model...')
|
19 |
model = pipeline("fill-mask")
|
20 |
st.write("_The assistant is loaded and ready to use! :tada:_")
|
21 |
return model
|
22 |
|
23 |
-
|
24 |
|
25 |
def remove_punctuation(word):
|
26 |
# Create a translation table that maps all punctuation characters to None
|
@@ -31,7 +31,7 @@ def remove_punctuation(word):
|
|
31 |
|
32 |
return word_without_punctuation
|
33 |
|
34 |
-
def
|
35 |
|
36 |
if sentence[-1] != ".":
|
37 |
sentence = sentence + "."
|
@@ -41,7 +41,7 @@ def return_top_k(sentence, word=None, rels=False):
|
|
41 |
# else:
|
42 |
# inputs = [f"Description : {sentence} Word : "]
|
43 |
|
44 |
-
output =
|
45 |
output = [output[i]['token_str'].strip() for i in range(len(output))]
|
46 |
return output
|
47 |
|
@@ -72,7 +72,7 @@ def return_top_k(sentence, word=None, rels=False):
|
|
72 |
|
73 |
# return ", ".join(beam_preds[:num])
|
74 |
|
75 |
-
#if '
|
76 |
|
77 |
def get_text():
|
78 |
input_text = st.chat_input()
|
@@ -92,9 +92,9 @@ def write_bot(input, remember=True, blink=True):
|
|
92 |
time.sleep(0.5)
|
93 |
message_placeholder.markdown(full_response)
|
94 |
if remember == True:
|
95 |
-
st.session_state.
|
96 |
|
97 |
-
def
|
98 |
y = st.button('Yes!', key=60)
|
99 |
n = st.button('No...', key=61)
|
100 |
new = st.button('I have a new word', key=62)
|
@@ -103,22 +103,22 @@ def ask_if_helped():
|
|
103 |
again = st.button('Play again')
|
104 |
if again:
|
105 |
write_bot("Please describe your word!")
|
106 |
-
st.session_state.
|
107 |
elif n:
|
108 |
-
st.session_state.
|
109 |
-
st.session_state.
|
110 |
#cue_generation()
|
111 |
elif new:
|
112 |
write_bot("Please describe your word!")
|
113 |
-
st.session_state.
|
114 |
|
115 |
-
## removed: if st.session_state.
|
116 |
|
117 |
# JS
|
118 |
# def get_related_words_llama(relation, target, device, num=5):
|
119 |
-
#
|
120 |
|
121 |
-
# inputs = tokenizer([
|
122 |
# output = model.generate(
|
123 |
# **inputs, max_new_tokens=40, temperature=.75, early_stopping=True,
|
124 |
# )
|
@@ -172,25 +172,25 @@ def get_available_cues(target):
|
|
172 |
|
173 |
# JS: moved the cue generation further down
|
174 |
#def cue_generation():
|
175 |
-
# if st.session_state.
|
176 |
|
177 |
-
if '
|
178 |
-
st.session_state.
|
179 |
|
180 |
-
if '
|
181 |
-
st.session_state.
|
182 |
|
183 |
-
if '
|
184 |
-
st.session_state.
|
185 |
|
186 |
-
if '
|
187 |
-
st.session_state.
|
188 |
|
189 |
-
if '
|
190 |
-
st.session_state.
|
191 |
|
192 |
-
if '
|
193 |
-
st.session_state.
|
194 |
|
195 |
st.title("You name it! 🗣")
|
196 |
|
@@ -201,8 +201,8 @@ with st.chat_message('user'):
|
|
201 |
bot = st.chat_message('assistant')
|
202 |
bot.write("Hello human! Wanna practice naming some words?")
|
203 |
|
204 |
-
#for showing history of
|
205 |
-
for message in st.session_state.
|
206 |
if message['role'] == 'user':
|
207 |
with st.chat_message(message['role']):
|
208 |
st.markdown(message['content'])
|
@@ -211,61 +211,62 @@ for message in st.session_state.messages:
|
|
211 |
st.markdown(message['content'])
|
212 |
|
213 |
#display user message in chat message container
|
214 |
-
|
215 |
-
if
|
216 |
#JS: would replace Simon by some neutral character
|
217 |
with st.chat_message('user'):
|
218 |
-
st.markdown(
|
219 |
#add to history
|
220 |
-
st.session_state.
|
221 |
#TODO: replace it with zero-shot classifier
|
222 |
yes = ['yes', 'again', 'Yes', 'sure', 'new word', 'yes!', 'yep', 'yeah']
|
223 |
-
if
|
224 |
write_bot("Please give a sentence using a <mask> instead of the word you have in mind!")
|
225 |
-
elif
|
226 |
write_bot("Great! Let me think what it could be...")
|
227 |
time.sleep(3)
|
228 |
write_bot("Do you mean Saarland?")
|
229 |
-
#if previously we asked to give a
|
230 |
-
elif (st.session_state.
|
231 |
write_bot("Great! Let me think what it could be...")
|
232 |
-
st.session_state.
|
233 |
-
st.session_state.
|
234 |
-
st.session_state.
|
|
|
235 |
write_bot("I think I have some ideas. Do you want to see my guesses or do you want a cue?")
|
236 |
-
st.session_state.
|
237 |
|
238 |
-
if st.session_state.
|
239 |
col1, col2, col3, col4, col5 = st.columns(5)
|
240 |
with col1:
|
241 |
-
a1 = st.button('
|
242 |
with col2:
|
243 |
a2 = st.button('Cue', key=11)
|
244 |
if a1:
|
245 |
write_bot("Here are my guesses about your word:")
|
246 |
-
st.write(st.session_state.
|
247 |
time.sleep(1)
|
248 |
write_bot('Does it help you remember the word?', remember=False)
|
249 |
-
st.session_state.
|
250 |
elif a2:
|
251 |
-
#write_bot(f'The first letter is {st.session_state.
|
252 |
#time.sleep(1)
|
253 |
-
st.session_state.
|
254 |
#cue_generation()
|
255 |
#write_bot('Does it help you remember the word?', remember=False)
|
256 |
-
#st.session_state.
|
257 |
|
258 |
-
if st.session_state.
|
259 |
-
|
260 |
|
261 |
-
if st.session_state.
|
262 |
guessed = False
|
263 |
write_bot('What do you want to see?', remember=False, blink=False)
|
264 |
|
265 |
while guessed == False:
|
266 |
# JS
|
267 |
-
word_count = st.session_state.
|
268 |
-
target = st.session_state.
|
269 |
|
270 |
col1, col2, col3, col4, col5 = st.columns(5)
|
271 |
|
@@ -289,38 +290,38 @@ if st.session_state.actions[-1] == 'cue':
|
|
289 |
new = st.button('Play again', key=64, type='primary')
|
290 |
|
291 |
if b1:
|
292 |
-
st.session_state.
|
293 |
-
#word_count = st.session_state.
|
294 |
-
letter_count = st.session_state.
|
295 |
if letter_count < len(target):
|
296 |
-
write_bot(f'The word starts with {st.session_state.
|
297 |
-
#
|
298 |
-
st.session_state.
|
299 |
else:
|
300 |
write_bot(f'This is my predicted word: "{target}". Does this match your query?')
|
301 |
-
#
|
302 |
-
st.session_state.
|
303 |
|
304 |
elif b2:
|
305 |
-
rels =
|
306 |
write_bot(f'Here are words that are related to your word: {", ".join(rels)}. \n Does this help you remember the word?', remember=False)
|
307 |
-
#
|
308 |
-
st.session_state.
|
309 |
|
310 |
elif b3:
|
311 |
-
st.session_state.
|
312 |
-
letter_count = st.session_state.
|
313 |
-
st.session_state.
|
314 |
-
word_count = st.session_state.
|
315 |
-
#write_bot(f'The next word starts with {st.session_state.
|
316 |
if letter_count < len(target):
|
317 |
-
write_bot(f'The next word starts with {st.session_state.
|
318 |
-
#
|
319 |
-
st.session_state.
|
320 |
else:
|
321 |
write_bot(f'This is my predicted word: "{target}". Does this match your query?')
|
322 |
-
#
|
323 |
-
st.session_state.
|
324 |
|
325 |
#elif get_available_cues(target) and "Synonyms" in cues_buttons and cues_buttons['Synonyms']:
|
326 |
#write_bot(f'Here are synonyms for the current word: {", ".join(avail_cues["Synonyms"])}', remember=False)
|
@@ -335,12 +336,12 @@ if st.session_state.actions[-1] == 'cue':
|
|
335 |
#write_bot(f'Here are example contexts for the current word: {", ".join(avail_cues["Examples"])}', remember=False)
|
336 |
|
337 |
elif b4:
|
338 |
-
write_bot(f"Here are all my guesses about your word: {st.session_state.
|
339 |
|
340 |
elif b5:
|
341 |
write_bot("Yay! I am happy I could be of help!")
|
342 |
-
st.session_state.
|
343 |
-
st.session_state.
|
344 |
new = st.button('Play again', key=63)
|
345 |
if new:
|
346 |
write_bot("Please describe your word!")
|
@@ -350,14 +351,14 @@ if st.session_state.actions[-1] == 'cue':
|
|
350 |
|
351 |
elif b6:
|
352 |
write_bot("I am sorry I couldn't help you this time. See you soon!")
|
353 |
-
st.session_state.
|
354 |
-
st.session_state.
|
355 |
-
st.session_state.
|
356 |
|
357 |
if new:
|
358 |
write_bot("Please describe your word!")
|
359 |
-
st.session_state.
|
360 |
-
st.session_state.
|
361 |
|
362 |
break
|
363 |
|
|
|
14 |
from nltk.tokenize import word_tokenize
|
15 |
|
16 |
@st.cache_resource
|
17 |
+
def get_models_context(llama=False):
|
18 |
st.write('Loading the model...')
|
19 |
model = pipeline("fill-mask")
|
20 |
st.write("_The assistant is loaded and ready to use! :tada:_")
|
21 |
return model
|
22 |
|
23 |
+
model_context = get_models_context()
|
24 |
|
25 |
def remove_punctuation(word):
|
26 |
# Create a translation table that maps all punctuation characters to None
|
|
|
31 |
|
32 |
return word_without_punctuation
|
33 |
|
34 |
+
def return_top_k_context(sentence, word=None, rels=False):
|
35 |
|
36 |
if sentence[-1] != ".":
|
37 |
sentence = sentence + "."
|
|
|
41 |
# else:
|
42 |
# inputs = [f"Description : {sentence} Word : "]
|
43 |
|
44 |
+
output = model_context(sentence)
|
45 |
output = [output[i]['token_str'].strip() for i in range(len(output))]
|
46 |
return output
|
47 |
|
|
|
72 |
|
73 |
# return ", ".join(beam_preds[:num])
|
74 |
|
75 |
+
#if 'messages_context' not in st.session_state:
|
76 |
|
77 |
def get_text():
|
78 |
input_text = st.chat_input()
|
|
|
92 |
time.sleep(0.5)
|
93 |
message_placeholder.markdown(full_response)
|
94 |
if remember == True:
|
95 |
+
st.session_state.messages_context.append({'role': 'assistant', 'content': full_response})
|
96 |
|
97 |
+
def ask_if_helped_context():
|
98 |
y = st.button('Yes!', key=60)
|
99 |
n = st.button('No...', key=61)
|
100 |
new = st.button('I have a new word', key=62)
|
|
|
103 |
again = st.button('Play again')
|
104 |
if again:
|
105 |
write_bot("Please describe your word!")
|
106 |
+
st.session_state.is_helpful_context['ask'] = False
|
107 |
elif n:
|
108 |
+
st.session_state.actions_context.append('cue')
|
109 |
+
st.session_state.is_helpful_context['ask'] = False
|
110 |
#cue_generation()
|
111 |
elif new:
|
112 |
write_bot("Please describe your word!")
|
113 |
+
st.session_state.is_helpful_context['ask'] = False
|
114 |
|
115 |
+
## removed: if st.session_state.actions_context[-1] == "result":
|
116 |
|
117 |
# JS
|
118 |
# def get_related_words_llama(relation, target, device, num=5):
|
119 |
+
# prompt_context = f"Provide {num} {relation}s for the word '{target}'. Your answer consists of these {num} words only. Do not include the word '{target}' itself in your answer"
|
120 |
|
121 |
+
# inputs = tokenizer([prompt_context], return_tensors='pt').to(device)
|
122 |
# output = model.generate(
|
123 |
# **inputs, max_new_tokens=40, temperature=.75, early_stopping=True,
|
124 |
# )
|
|
|
172 |
|
173 |
# JS: moved the cue generation further down
|
174 |
#def cue_generation():
|
175 |
+
# if st.session_state.actions_context[-1] == 'cue':
|
176 |
|
177 |
+
if 'messages_context' not in st.session_state:
|
178 |
+
st.session_state.messages_context = []
|
179 |
|
180 |
+
if 'results_context' not in st.session_state:
|
181 |
+
st.session_state.results_context = {'results_context': False, 'results_context_print': False}
|
182 |
|
183 |
+
if 'actions_context' not in st.session_state:
|
184 |
+
st.session_state.actions_context = [""]
|
185 |
|
186 |
+
if 'counter_context' not in st.session_state:
|
187 |
+
st.session_state.counter_context = {"letter_count": 0, "word_count": 0}
|
188 |
|
189 |
+
if 'is_helpful_context' not in st.session_state:
|
190 |
+
st.session_state.is_helpful_context = {'ask':False}
|
191 |
|
192 |
+
if 'descriptions_context' not in st.session_state:
|
193 |
+
st.session_state.descriptions_context = []
|
194 |
|
195 |
st.title("You name it! 🗣")
|
196 |
|
|
|
201 |
bot = st.chat_message('assistant')
|
202 |
bot.write("Hello human! Wanna practice naming some words?")
|
203 |
|
204 |
+
#for showing history of messages_context
|
205 |
+
for message in st.session_state.messages_context:
|
206 |
if message['role'] == 'user':
|
207 |
with st.chat_message(message['role']):
|
208 |
st.markdown(message['content'])
|
|
|
211 |
st.markdown(message['content'])
|
212 |
|
213 |
#display user message in chat message container
|
214 |
+
prompt_context = get_text()
|
215 |
+
if prompt_context:
|
216 |
#JS: would replace Simon by some neutral character
|
217 |
with st.chat_message('user'):
|
218 |
+
st.markdown(prompt_context)
|
219 |
#add to history
|
220 |
+
st.session_state.messages_context.append({'role': 'user', 'content': prompt_context})
|
221 |
#TODO: replace it with zero-shot classifier
|
222 |
yes = ['yes', 'again', 'Yes', 'sure', 'new word', 'yes!', 'yep', 'yeah']
|
223 |
+
if prompt_context in yes:
|
224 |
write_bot("Please give a sentence using a <mask> instead of the word you have in mind!")
|
225 |
+
elif prompt_context == 'it is similar to the best place on earth':
|
226 |
write_bot("Great! Let me think what it could be...")
|
227 |
time.sleep(3)
|
228 |
write_bot("Do you mean Saarland?")
|
229 |
+
#if previously we asked to give a prompt_context
|
230 |
+
elif (st.session_state.messages_context[-2]['content'] == "Please give a sentence using a <mask> instead of the word you have in mind!") & (st.session_state.messages_context[-1]['content'] != "no"):
|
231 |
write_bot("Great! Let me think what it could be...")
|
232 |
+
st.session_state.descriptions_context.append(prompt_context)
|
233 |
+
st.session_state.results_context['results_context'] = return_top_k_context
|
234 |
+
(st.session_state.descriptions_context[-1])
|
235 |
+
st.session_state.results_context['results_context_print'] = dict(zip(range(1, 11), st.session_state.results_context['results_context']))
|
236 |
write_bot("I think I have some ideas. Do you want to see my guesses or do you want a cue?")
|
237 |
+
st.session_state.actions_context.append("result")
|
238 |
|
239 |
+
if st.session_state.actions_context[-1] == "result":
|
240 |
col1, col2, col3, col4, col5 = st.columns(5)
|
241 |
with col1:
|
242 |
+
a1 = st.button('results_context', key=10)
|
243 |
with col2:
|
244 |
a2 = st.button('Cue', key=11)
|
245 |
if a1:
|
246 |
write_bot("Here are my guesses about your word:")
|
247 |
+
st.write(st.session_state.results_context['results_context_print'])
|
248 |
time.sleep(1)
|
249 |
write_bot('Does it help you remember the word?', remember=False)
|
250 |
+
st.session_state.is_helpful_context['ask'] = True
|
251 |
elif a2:
|
252 |
+
#write_bot(f'The first letter is {st.session_state.results_context["results_context"][0][0]}.')
|
253 |
#time.sleep(1)
|
254 |
+
st.session_state.actions_context.append('cue')
|
255 |
#cue_generation()
|
256 |
#write_bot('Does it help you remember the word?', remember=False)
|
257 |
+
#st.session_state.is_helpful_context['ask'] = True
|
258 |
|
259 |
+
if st.session_state.is_helpful_context['ask']:
|
260 |
+
ask_if_helped_context()
|
261 |
|
262 |
+
if st.session_state.actions_context[-1] == 'cue':
|
263 |
guessed = False
|
264 |
write_bot('What do you want to see?', remember=False, blink=False)
|
265 |
|
266 |
while guessed == False:
|
267 |
# JS
|
268 |
+
word_count = st.session_state.counter_context["word_count"]
|
269 |
+
target = st.session_state.results_context["results_context"][word_count]
|
270 |
|
271 |
col1, col2, col3, col4, col5 = st.columns(5)
|
272 |
|
|
|
290 |
new = st.button('Play again', key=64, type='primary')
|
291 |
|
292 |
if b1:
|
293 |
+
st.session_state.counter_context["letter_count"] += 1
|
294 |
+
#word_count = st.session_state.counter_context["word_count"]
|
295 |
+
letter_count = st.session_state.counter_context["letter_count"]
|
296 |
if letter_count < len(target):
|
297 |
+
write_bot(f'The word starts with {st.session_state.results_context["results_context"][word_count][:letter_count]}. \n Does this help you remember the word?', remember=False)
|
298 |
+
#ask_if_helped_context()
|
299 |
+
st.session_state.is_helpful_context['ask'] = True
|
300 |
else:
|
301 |
write_bot(f'This is my predicted word: "{target}". Does this match your query?')
|
302 |
+
#ask_if_helped_context()
|
303 |
+
st.session_state.is_helpful_context['ask'] = True
|
304 |
|
305 |
elif b2:
|
306 |
+
rels = return_top_k_context(st.session_state.descriptions_context[-1], word=target, rels=True)
|
307 |
write_bot(f'Here are words that are related to your word: {", ".join(rels)}. \n Does this help you remember the word?', remember=False)
|
308 |
+
#ask_if_helped_context()
|
309 |
+
st.session_state.is_helpful_context['ask'] = True
|
310 |
|
311 |
elif b3:
|
312 |
+
st.session_state.counter_context["letter_count"] = 1
|
313 |
+
letter_count = st.session_state.counter_context["letter_count"]
|
314 |
+
st.session_state.counter_context["word_count"] += 1
|
315 |
+
word_count = st.session_state.counter_context["word_count"]
|
316 |
+
#write_bot(f'The next word starts with {st.session_state.results_context["results_context"][word_count][:letter_count]}', remember=False)
|
317 |
if letter_count < len(target):
|
318 |
+
write_bot(f'The next word starts with {st.session_state.results_context["results_context"][word_count][:letter_count]}. \n Does this help you remember the word?', remember=False)
|
319 |
+
#ask_if_helped_context()
|
320 |
+
st.session_state.is_helpful_context['ask'] = True
|
321 |
else:
|
322 |
write_bot(f'This is my predicted word: "{target}". Does this match your query?')
|
323 |
+
#ask_if_helped_context()
|
324 |
+
st.session_state.is_helpful_context['ask'] = True
|
325 |
|
326 |
#elif get_available_cues(target) and "Synonyms" in cues_buttons and cues_buttons['Synonyms']:
|
327 |
#write_bot(f'Here are synonyms for the current word: {", ".join(avail_cues["Synonyms"])}', remember=False)
|
|
|
336 |
#write_bot(f'Here are example contexts for the current word: {", ".join(avail_cues["Examples"])}', remember=False)
|
337 |
|
338 |
elif b4:
|
339 |
+
write_bot(f"Here are all my guesses about your word: {st.session_state.results_context['results_context_print']}")
|
340 |
|
341 |
elif b5:
|
342 |
write_bot("Yay! I am happy I could be of help!")
|
343 |
+
st.session_state.counter_context["word_count"] = 0
|
344 |
+
st.session_state.counter_context["letter_count"] = 0
|
345 |
new = st.button('Play again', key=63)
|
346 |
if new:
|
347 |
write_bot("Please describe your word!")
|
|
|
351 |
|
352 |
elif b6:
|
353 |
write_bot("I am sorry I couldn't help you this time. See you soon!")
|
354 |
+
st.session_state.counter_context["word_count"] = 0
|
355 |
+
st.session_state.counter_context["letter_count"] = 0
|
356 |
+
st.session_state.actions_context.append('cue')
|
357 |
|
358 |
if new:
|
359 |
write_bot("Please describe your word!")
|
360 |
+
st.session_state.counter_context["word_count"] = 0
|
361 |
+
st.session_state.counter_context["letter_count"] = 0
|
362 |
|
363 |
break
|
364 |
|