Wanswan commited on
Commit
ed1e7f2
·
verified ·
1 Parent(s): eec0b80

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +237 -0
app.py CHANGED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from openai import OpenAI
3
+ import os
4
+ import random
5
+ import asyncio
6
+
7
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
8
+
9
+ DEFAULT_LANGUAGE = "English"
10
+ WELCOME_MESSAGE_EN = "Hi! I'm your friendly assistant 🤖 Let's begin!\n\nPlease tell me which language you'd like to use."
11
+
12
+ # === Normal Question Bank ===
13
+ NORMAL_SET_I = [
14
+ "When was the last time you walked for more than an hour? Describe where you went and what you saw.",
15
+ "What is the best gift you have ever received? Why?",
16
+ "If you had to leave California, where would you move to? What do you miss most about California?",
17
+ "How did you celebrate Halloween last year?",
18
+ "Do you read newspapers often? Which newspapers do you like? Why?",
19
+ "What is the ideal number of students to share a house with? Why?",
20
+ "If you could invent a new flavor of ice cream, what flavor would you create?",
21
+ "What is the best restaurant you have been to in the past month that your partner has not been to? Describe it to your partner.",
22
+ "Describe the pet you last got.",
23
+ "What is your favorite holiday? Why?",
24
+ "Tell your partner the funniest thing that happened when you were with a child."
25
+ ]
26
+ NORMAL_SET_II = [
27
+ "What gift did you get on your last birthday?",
28
+ "Describe your last trip to the zoo.",
29
+ "Name and age of your family members, including grandparents, uncles and aunts, and where they were born (to the extent known).",
30
+ "One person says a word, and the next person says a word starting with the last letter of the previous word. Continue for 50 words. No need to form sentences.",
31
+ "Do you like to wake up early or stay up late? Has anything interesting ever happened to you because of this?",
32
+ "Where are you from? List all the places you have lived.",
33
+ "What is your favorite class at UC Santa Cruz? Why?",
34
+ "What did you do this summer?",
35
+ "What gifts did you receive last Christmas/Hanukkah?",
36
+ "Who is your favorite same-sex actor? Describe a great scene he or she starred in.",
37
+ "What was your impression of UC Santa Cruz when you first came to it?",
38
+ "What is the best TV show you have seen in the past month that your partner has not seen? Describe it to your partner.",
39
+ "What is your favorite holiday? Why?"
40
+ ]
41
+ NORMAL_SET_III = [
42
+ "Where did you go to high school? What was it like?",
43
+ "What is the best book you have read in the past three months that your partner has not read? Describe it to your partner.",
44
+ "What country would you most like to visit? What attracts you to it?",
45
+ "Do you prefer digital or analog watches/clocks? Why?",
46
+ "Describe your mother's best friend.",
47
+ "What are the pros and cons of artificial Christmas trees?",
48
+ "How often do you get your hair cut? Where do you go? Have you ever had a bad haircut?",
49
+ "Did you have a class pet in elementary school? Do you remember its name?",
50
+ "Do you think left-handed people are more creative than right-handed people?",
51
+ "What was the last concert you attended? How many albums of the band do you have? Have you seen them perform before? Where?",
52
+ "What magazines do you subscribe to? What have you subscribed to in the past?",
53
+ "Have you ever participated in a school play? What role did you play? What was the plot? Did anything funny happen during the play?"
54
+ ]
55
+
56
+ def generate_question_set():
57
+ return random.sample(NORMAL_SET_I, 3) + random.sample(NORMAL_SET_II, 3) + random.sample(NORMAL_SET_III, 3)
58
+
59
+ async def gpt_translate(text, target_lang):
60
+ if target_lang == "English":
61
+ return text
62
+ prompt = f"Translate the following into {target_lang}:\n\n{text}"
63
+ response = client.chat.completions.create(
64
+ model="gpt-3.5-turbo",
65
+ messages=[{"role": "user", "content": prompt}],
66
+ temperature=0.3
67
+ )
68
+ return response.choices[0].message.content.strip()
69
+
70
+ async def respond(user_input, history, step, language, questions, followup_mode):
71
+ history.append({"role": "user", "content": user_input})
72
+ if language == "":
73
+ user_language = user_input.strip().capitalize()
74
+ questions_en = generate_question_set()
75
+ translated_questions = [await gpt_translate(q, user_language) for q in questions_en]
76
+ welcome = await gpt_translate("Great! We will now continue in your selected language.", user_language)
77
+ history.append({"role": "assistant", "content": f"{welcome}\n\n1. {translated_questions[0]}"})
78
+ return history, "", 1, user_language, translated_questions, False
79
+ if step >= len(questions):
80
+ thank_you = await gpt_translate("Thank you for your response!", language)
81
+ end_note = await gpt_translate("This concludes our questions. Please proceed with the rest of the survey. 📝", language)
82
+ history.append({"role": "assistant", "content": thank_you})
83
+ history.append({"role": "assistant", "content": end_note})
84
+ return history, "", step, language, questions, False
85
+ if followup_mode:
86
+ comment_prompt = [
87
+ {"role": "system", "content": f"Write a short, empathetic comment in {language} responding to the user's last answer."},
88
+ history[-2],
89
+ history[-1]
90
+ ]
91
+ comment_response = client.chat.completions.create(
92
+ model="gpt-3.5-turbo",
93
+ messages=comment_prompt,
94
+ temperature=0.7
95
+ )
96
+ comment = comment_response.choices[0].message.content.strip()
97
+ history.append({"role": "assistant", "content": ""})
98
+ for c in comment:
99
+ history[-1]["content"] += c
100
+ await asyncio.sleep(0.03)
101
+ next_question = f"{step+1}. {questions[step]}"
102
+ history.append({"role": "assistant", "content": ""})
103
+ for c in next_question:
104
+ history[-1]["content"] += c
105
+ await asyncio.sleep(0.03)
106
+ return history, "", step + 1, language, questions, False
107
+
108
+ comment_prompt = [
109
+ {"role": "system", "content": f"You are a friendly and witty assistant. Write a short, personalized comment on the user's answer in {language}. Add a light emoji at the end."},
110
+ history[-2],
111
+ history[-1]
112
+ ]
113
+ comment_response = client.chat.completions.create(
114
+ model="gpt-3.5-turbo",
115
+ messages=comment_prompt,
116
+ temperature=0.8
117
+ )
118
+ bot_reply = comment_response.choices[0].message.content.strip()
119
+
120
+ followup_count = 0
121
+ rand = random.random()
122
+ if rand < 0.1:
123
+ followup_count = 2
124
+ elif rand < 0.5:
125
+ followup_count = 1
126
+
127
+ if followup_count > 0:
128
+ followup_prompt = [
129
+ {"role": "system", "content": f"Ask {followup_count} open-ended follow-up question(s) based on the user's last answer in {language}."},
130
+ history[-2],
131
+ history[-1]
132
+ ]
133
+ followup_response = client.chat.completions.create(
134
+ model="gpt-3.5-turbo",
135
+ messages=followup_prompt,
136
+ temperature=0.7
137
+ )
138
+ bot_reply += "\n\n" + followup_response.choices[0].message.content.strip()
139
+ history.append({"role": "assistant", "content": ""})
140
+ for c in bot_reply:
141
+ history[-1]["content"] += c
142
+ await asyncio.sleep(0.03)
143
+ return history, "", step, language, questions, True
144
+
145
+ history.append({"role": "assistant", "content": ""})
146
+ for c in bot_reply:
147
+ history[-1]["content"] += c
148
+ await asyncio.sleep(0.03)
149
+ next_question = f"{step+1}. {questions[step]}"
150
+ history.append({"role": "assistant", "content": ""})
151
+ for c in next_question:
152
+ history[-1]["content"] += c
153
+ await asyncio.sleep(0.03)
154
+ return history, "", step + 1, language, questions, False
155
+
156
+ def init():
157
+ return [{"role": "assistant", "content": WELCOME_MESSAGE_EN}], 0, "", [], False
158
+
159
+ with gr.Blocks(css="""
160
+ .send-btn {
161
+ background-color: #25D366 !important;
162
+ color: white !important;
163
+ border: none;
164
+ border-radius: 24px;
165
+ font-size: 20px;
166
+ padding: 8px 20px;
167
+ height: 48px;
168
+ width: 60px;
169
+ margin-left: 8px;
170
+ cursor: pointer;
171
+ }
172
+ #chatbox .avatar-container {
173
+ width: 64px !important;
174
+ height: 64px !important;
175
+ min-width: 64px !important;
176
+ min-height: 64px !important;
177
+ background-size: 100% 100% !important;
178
+ background-position: center center !important;
179
+ border-radius: 50% !important;
180
+ padding: 0 !important;
181
+ margin: 0 !important;
182
+ border: none !important;
183
+ box-shadow: none !important;
184
+ background-color: transparent !important;
185
+ }
186
+ #chatbox .message.user { background-color: #DCF8C6 !important; }
187
+ #chatbox .message.assistant { background-color: #ffffff !important; }
188
+ """) as demo:
189
+ gr.HTML("""
190
+ <script>
191
+ const waitForChatbox = () => {
192
+ const chatbox = document.getElementById("chatbox");
193
+ if (chatbox) {
194
+ const observer = new MutationObserver(() => {
195
+ chatbox.scrollTop = chatbox.scrollHeight;
196
+ });
197
+ observer.observe(chatbox, { childList: true, subtree: true });
198
+ } else {
199
+ setTimeout(waitForChatbox, 500);
200
+ }
201
+ };
202
+ waitForChatbox();
203
+ </script>
204
+ """)
205
+
206
+ chatbot = gr.Chatbot(
207
+ elem_id="chatbox",
208
+ label="",
209
+ avatar_images=["user_avatar.jpg", "humanlike_avatar.png"],
210
+ bubble_full_width=False,
211
+ height=500,
212
+ show_copy_button=False,
213
+ type="messages"
214
+ )
215
+
216
+ with gr.Row():
217
+ user_input = gr.Textbox(
218
+ show_label=False,
219
+ placeholder="Type your message here and press send...",
220
+ container=True,
221
+ scale=10
222
+ )
223
+ send_btn = gr.Button(value="➤", elem_classes="send-btn")
224
+
225
+ state = gr.State([])
226
+ step = gr.State(0)
227
+ language = gr.State("")
228
+ questions = gr.State([])
229
+ followup_mode = gr.State(False)
230
+
231
+ demo.load(fn=init, outputs=[chatbot, step, language, questions, followup_mode])
232
+ user_input.submit(respond, [user_input, state, step, language, questions, followup_mode],
233
+ [chatbot, user_input, step, language, questions, followup_mode])
234
+ send_btn.click(respond, [user_input, state, step, language, questions, followup_mode],
235
+ [chatbot, user_input, step, language, questions, followup_mode])
236
+
237
+ demo.queue().launch()