-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatbot_frontend.py
396 lines (330 loc) Β· 15.7 KB
/
chatbot_frontend.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import streamlit as st
import chatbot_backend as glib
import time
import random
import re
# random.seed(46)
st.set_page_config(page_title="Vaccine Echo Chamberπ")
def set_sidebar_width(width):
st.markdown(
f"""
<style>
.css-1d391kg {{
width: {width}px;
}}
</style>
""",
unsafe_allow_html=True
)
set_sidebar_width(400)
assistants = [
{"name": "Mr.Dinosaur", "avatar": 'π¦'},
{"name": "Ms.Bird", "avatar": 'π€'},
{"name": "Mrs.Tiger", "avatar": 'π―'},
{"name": "Dr.Panda", "avatar": 'πΌ'},
{"name": "Dr.Robot", "avatar": 'π€'},
{"name": "Dr.Unicorn", "avatar": 'π¦'},
{"name": "Mr.Elephant", "avatar": 'π'},
{"name": "Ms.Butterfly", "avatar": 'π¦'},
{"name": "Mrs.Dolphin", "avatar": 'π¬'},
{"name": "Dr.Owl", "avatar": 'π¦'},
{"name": "Mr.Kangaroo", "avatar": 'π¦'},
{"name": "Ms.Penguin", "avatar": 'π§'},
{"name": "Mrs.Koala", "avatar": 'π¨'},
{"name": "Dr.Flamingo", "avatar": 'π¦©'},
{"name": "Mr.Giraffe", "avatar": 'π¦'},
{"name": "Ms.Hedgehog", "avatar": 'π¦'},
{"name": "Mrs.Raccoon", "avatar": 'π¦'},
{"name": "Dr.Sloth", "avatar": 'π¦₯'},
{"name": "Mr.Hippo", "avatar": 'π¦'},
{"name": "Ms.Parrot", "avatar": 'π¦'}
]
if 'gpt' not in st.session_state.keys():
st.session_state.gpt = glib.get_gpt()
if 'phi2' not in st.session_state.keys():
st.session_state.phi2 = glib.get_phi2()
if 'memory' not in st.session_state.keys():
st.session_state.memory = glib.get_memory(st.session_state.gpt)
# chat_history: {"type":'message'/'warning', "name":assistant['name'], "text":comment, "avatar":assistant["avatar"], "quote":''}
if 'chat_history' not in st.session_state.keys():
st.session_state.chat_history = []
if 'user_name' not in st.session_state.keys():
st.session_state.user_name = None
def add_sign_input(input_text):
if input_text and not input_text[-1] in '.!?':
input_text += '.'
return input_text
def get_last_sentence_part(remarker):
# ori_string = st.session_state.chat_history[-1]['text'][:length]
# parts = ori_string.split('.')
# parts = [part for part in parts if part.strip()]
# if len(parts) <= 1:
# return ori_string
# selected_part = random.choice(parts[:-1]).strip() + '.'
# return selected_part
remarker_name = remarker['name']
for message in st.session_state.chat_history[::-1]:
if message['type'] == 'message':
if remarker_name != message['name'] and len(message['text']) > 20:
return message["text"]
def identity_changing(question):
new_question = question.replace("i ", "I ")
new_question = new_question.replace("I am ", "Someone is ")
new_question = new_question.replace("i am ", "Someone is ")
new_question = new_question.replace("I'm ", "Someone is ")
new_question = new_question.replace("i'm ", "Someone is ")
new_question = new_question.replace("Im ", "Someone is")
new_question = new_question.replace("im ", "Someone is ")
new_question = new_question.replace("my ", "Someone's ")
new_question = new_question.replace("My ", "Someone's ")
new_question = new_question.replace("I ", "Someone ")
return new_question
def do_a_static_comment(comment, assistant):
placeholder = st.empty()
with placeholder.container():
with st.chat_message(assistant["name"], avatar = assistant["avatar"]):
with st.spinner(assistant['name'] + " is typing..."):
st.session_state.chat_history.append({"type":'message', "name":assistant['name'], "text":comment, "avatar":assistant["avatar"], "quote":None})
time.sleep(1.5)
st.markdown(comment)
def do_a_direct_response(question, responser):
placeholder = st.empty()
with placeholder.container():
with st.chat_message(responser['name'], avatar = responser["avatar"]):
with st.spinner(responser['name'] + " is typing..."):
print(question)
new_question = identity_changing(question)
print(new_question)
chat_response = glib.get_bad_vaccine_response(input_text=new_question, phi2=st.session_state.phi2, memory=st.session_state.memory)
sentences = re.split(r'[,.!?]+', chat_response)
sentences = [sentence.strip() for sentence in sentences if sentence.strip()]
placeholder.empty()
for i in range(len(sentences)):
sentence = sentences[i]
placeholder = st.empty()
with placeholder.container():
with st.chat_message(responser["name"], avatar = responser["avatar"]):
with st.spinner(responser['name'] + " is typing..."):
if i == 0:
sentence = sentence.replace(new_question, "emmm...")
st.session_state.chat_history.append({"type":'message', "name": responser["name"], "text": sentence, "avatar": responser["avatar"], "quote":question})
st.markdown(f"\>\>\>''*{question}*''")
else:
st.session_state.chat_history.append({"type":'message', "name": responser["name"], "text": sentence, "avatar": responser["avatar"], "quote":None})
time.sleep(random.uniform(1, 2))
placeholder = st.empty()
full_response = ''
for item in sentence.split():
full_response += item + ' '
placeholder.markdown(full_response)
time.sleep(random.uniform(0, 0.5))
placeholder.markdown(full_response)
def do_a_last_sentence_remark(remarker, times):
placeholder = st.empty()
with placeholder.container():
with st.chat_message(remarker["name"], avatar = remarker["avatar"]):
with st.spinner(remarker['name'] + " is typing..."):
last_sentence_part = get_last_sentence_part(remarker)
chat_remark = glib.get_bad_vaccine_remark(message=last_sentence_part, times=times, phi2=st.session_state.phi2, memory=st.session_state.memory)
sentences = re.split(r'[,.!?]+', chat_remark)
sentences = [sentence.strip() for sentence in sentences if sentence.strip()]
placeholder.empty()
for i in range(len(sentences)):
sentence = sentences[i]
placeholder = st.empty()
with placeholder.container():
with st.chat_message("assistant", avatar = remarker["avatar"]):
with st.spinner(remarker['name'] + " is typing..."):
if i == 0:
if sentence.startswith(last_sentence_part):
sentence = sentence.replace(last_sentence_part, 'I agree.')
st.session_state.chat_history.append({"type":'message', "name": remarker["name"], "text": sentence, "avatar": remarker["avatar"], "quote":last_sentence_part})
st.markdown(f"\>\>\>''*{last_sentence_part}*''")
else:
st.session_state.chat_history.append({"type":'message', "name": remarker["name"], "text": sentence, "avatar": remarker["avatar"], "quote":None})
time.sleep(random.uniform(1, 2))
placeholder = st.empty()
full_remark = ''
for item in sentence.split():
full_remark += item + ' '
placeholder.markdown(full_remark)
time.sleep(random.uniform(0, 0.5))
placeholder.markdown(full_remark)
def do_a_funny_remark(assistant):
placeholder = st.empty()
with placeholder.container():
with st.chat_message(assistant['name'], avatar = assistant["avatar"]):
with st.spinner(assistant['name'] + " is typing..."):
chat_remark = glib.get_funny_remark()
st.session_state.chat_history.append({"type":'message', "name": assistant['name'], "text": chat_remark, "avatar": assistant["avatar"], "quote":None})
time.sleep(2)
placeholder = st.empty()
full_remark = ''
for item in chat_remark.split():
full_remark += item + ' '
placeholder.markdown(full_remark)
time.sleep(random.uniform(0, 0.1))
placeholder.markdown(full_remark)
def do_a_dummy_agree():
if random.randint(0,1) < 0.4: return
print('>>>>>>>>>>DUMMY<<<<<<<<<<<')
agree_template = [
f'yes you are right.',
f'really?',
f'Yeah',
f'Yes',
f'Oh, wtf?',
f'yes I agree',
f'Agree',
f'Oh My God',
f'Oh My Gosh',
f'That\'s right',
f'serious??',
f'Ohhhhh',
f'wow really?',
f'that\'s correct',
f'fair enough',
f'that makes sense',
f'oh god',
f'what??'
]
assistant = random.choice(assistants)
hidden_assistant = random.choice(assistants)
index = random.randint(0, len(agree_template) - 1)
hidden_index = random.randint(0, len(agree_template) - 1)
placeholder = st.empty()
with placeholder.container():
with st.chat_message(assistant["name"], avatar = assistant["avatar"]):
with st.spinner(assistant['name'] + " is typing..."):
content = get_last_sentence_part(assistant)
st.session_state.chat_history.append({"type":'message', "name":assistant['name'], "text":agree_template[index], "avatar":assistant["avatar"], "quote":content})
st.session_state.chat_history.append({"type":'message', "name":hidden_assistant['name'], "text":agree_template[hidden_index], "avatar":hidden_assistant["avatar"], "quote":content})
time.sleep(1.5)
st.markdown(f"\>\>\>''*{content}*''")
st.markdown(agree_template[index])
with st.sidebar:
# st.title('Welcome to the Vaccine Echo Chamber πππ')
st.sidebar.markdown("<h1 style='margin-top: -50px;'>Welcome to the Vaccine Echo Chamber πππ</h1>", unsafe_allow_html=True)
st.success('Successfully Connected! Talk anything related to the vaccines!', icon='β
')
st.warning('Only for research purpose! Do not trust anyone!!!', icon='β')
st.subheader('Chat Examples')
example_questions = [
"Tell me your attitude about vaccines.",
"Describe how you feel about the effectiveness of vaccines.",
"Explain any hesitations you have about getting certain vaccines.",
"Tell me about your experience with receiving your vaccine.",
"Share any stories or experiences you've had with vaccinations.",
]
for question in example_questions:
st.markdown(f"- {question}")
people = st.sidebar.slider('Max People', min_value=5, max_value=10, value=7, step=1)
# add a backgroung image
st.image("background.png", use_column_width=True)
st.warning('Please end your input with a punctuation mark (., !, or ?).')
# print all of the historical conversations
for message in st.session_state.chat_history:
if message["type"] == 'message':
with st.chat_message(message["name"], avatar = message["avatar"]):
if message["quote"] != None:
quote = message["quote"]
st.markdown(f"\>\>\>''*{quote}*''")
st.markdown(message["text"])
elif message["type"] == 'warning':
st.success('Message Send Successfully! Do not trust anyone in the room!', icon='β
')
else:
continue
# clear all of hte chat history
def clear_chat_history():
st.session_state.chat_history = []
st.sidebar.button('Clear Chat History', on_click=clear_chat_history)
# saving all of the chat history
def save_chat_history():
chat_string = ""
for message in st.session_state.chat_history:
if message['type'] == 'message':
chat_string += f"{message['name']}: {message['text']}\n"
time_stamp = time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime(time.time()))
file_path = f'.../echo_chamber/experiment/results/{st.session_state.user_name}_{time_stamp}.txt'
with open(file_path, 'w') as file:
file.write(chat_string)
user_name = st.sidebar.text_input('β¬οΈ Please input your nickname here')
if user_name:
st.session_state.user_name = user_name
st.sidebar.button('Save Chat History', on_click=save_chat_history)
# initialize input box
input_text = st.chat_input("Chat with others here")
###########################################################################################################
# auto: 1 question, 1 answer, 2 remarks;
# general: 1 question, 1 answer, 2-3 remarks, 1 answer(or funny), 2-3 remarks;
# beginning Auto conversation
if 'start' not in st.session_state.keys():
# if 'start' not in st.session_state.keys() and st.session_state.user_name != None:
st.session_state.start = True
# time.sleep(3.5)
asker = random.choice(assistants)
responser = random.choice(assistants)
while(asker == responser): responser = random.choice(assistants)
static_question = 'Hi, tell me your attitude toward vaccines.'
do_a_static_comment(static_question, asker)
do_a_direct_response(static_question, responser)
do_a_dummy_agree()
# generate remarks randomly
times = random.randint(2, 2)
for i in range(times):
assistant = random.choice(assistants)
do_a_last_sentence_remark(assistant, i)
do_a_dummy_agree()
time.sleep(random.uniform(0.5, 2))
# if user input sth
if input_text:
# add signs
# input_text = add_sign_input(input_text)
st.success('Message Send Successfully! Do not trust anyone in the room!', icon='β
')
st.session_state.chat_history.append({"type":'warning', "name":None, "text":None, "avatar":None, "quote":None})
with st.chat_message("user", avatar='π€'):
st.markdown(input_text)
st.session_state.chat_history.append({"type":'message', "name":"user", "text":input_text, "avatar":'π€', "quote":None})
# generate response randomly
time.sleep(1.5)
assistant = random.choice(assistants)
do_a_direct_response(input_text, assistant)
do_a_dummy_agree()
# st.write(f"Response generated in {elapsed_time:.2f} seconds.")
# generate remarks randomly
times = random.randint(2, 3)
for i in range(times):
assistant = random.choice(assistants)
# functions = [
# lambda: do_a_direct_response(input_text, assistant),
# lambda: do_a_last_sentence_remark(assistant)
# ]
# p = [0.2, 0.8]
# selected_callable = random.choices(functions, p, k=1)[0]
# selected_callable()
do_a_last_sentence_remark(assistant, i)
time.sleep(random.uniform(0.5, 1))
do_a_dummy_agree()
# generate response randomly
time.sleep(1)
assistant = random.choice(assistants)
do_a_direct_response(input_text, assistant)
do_a_dummy_agree()
# generate funny remarks
p = random.uniform(0, 1)
if p > 0.5:
assistant = random.choice(assistants)
do_a_funny_remark(assistant)
# generate remarks randomly
times = random.randint(2, 3)
for i in range(times):
assistant = random.choice(assistants)
# functions = [
# lambda: do_a_direct_response(input_text, assistant),
# lambda: do_a_last_sentence_remark(assistant)
# ]
# p = [0.2, 0.8]
# selected_callable = random.choices(functions, p, k=1)[0]
# selected_callable()
do_a_last_sentence_remark(assistant, i)
do_a_dummy_agree()
time.sleep(random.uniform(0.5, 1))