Wanswan commited on
Commit
e07d4e9
·
verified ·
1 Parent(s): c637927

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -52
app.py CHANGED
@@ -1,73 +1,232 @@
1
-
2
  import gradio as gr
3
- import random
4
  import os
 
5
  import asyncio
6
  import urllib.parse
7
- from openai import OpenAI
8
 
9
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
10
 
 
11
  WELCOME_MESSAGE_EN = "Hi! I'm your friendly assistant 🤖 Let's begin!\n\nPlease tell me which language you'd like to use."
12
 
13
- # 简化的问题题库
14
- ARON_SET = ["What's something you're proud of?", "What makes a good friendship?"]
15
- NORMAL_SET = ["What's your favorite color?", "Do you enjoy walking outside?"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- def get_questions(group):
18
- if group in ["A", "C"]:
19
- return random.sample(ARON_SET, 2)
20
- else:
21
- return random.sample(NORMAL_SET, 2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- def get_avatar(group):
24
- if group in ["A", "B"]:
25
- return "humanlike_avatar.png"
26
  else:
27
- return "robot_avatar.png"
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  def get_group_from_url(request: gr.Request):
30
  query = urllib.parse.parse_qs(request.query_string.decode())
31
  group = query.get("group", [None])[0]
32
  if group not in ["A", "B", "C", "D"]:
33
  group = random.choice(["A", "B", "C", "D"])
34
- return group
35
-
36
- async def respond(user_input, history, step, questions, group):
37
- history.append((user_input, None))
38
-
39
- if step < len(questions):
40
- response = questions[step]
41
- history[-1] = (user_input, response)
42
- return history, step + 1, questions, group
43
- else:
44
- history.append(("", "Thanks for chatting!"))
45
- return history, step, questions, group
46
 
47
- with gr.Blocks() as demo:
48
- chatbot = gr.Chatbot()
49
- user_input = gr.Textbox(show_label=False, placeholder="Type your message here...", scale=10)
50
- send_btn = gr.Button("")
51
-
52
- state_history = gr.State([])
53
- state_step = gr.State(0)
54
- state_questions = gr.State([])
55
- state_group = gr.State("A")
56
-
57
- def init(request: gr.Request):
58
- group = get_group_from_url(request)
59
- questions = get_questions(group)
60
- welcome = [(None, WELCOME_MESSAGE_EN)]
61
- return welcome, 0, questions, group
62
-
63
- demo.load(init, inputs=None, outputs=[state_history, state_step, state_questions, state_group])
64
- user_input.submit(
65
- fn=respond,
66
- inputs=[user_input, state_history, state_step, state_questions, state_group],
67
- outputs=[chatbot, state_step, state_questions, state_group]
 
 
 
 
 
 
68
  )
69
- send_btn.click(
70
- fn=respond,
71
- inputs=[user_input, state_history, state_step, state_questions, state_group],
72
- outputs=[chatbot, state_step, state_questions, state_group]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from openai import OpenAI
3
  import os
4
+ import random
5
  import asyncio
6
  import urllib.parse
 
7
 
8
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
9
 
10
+ DEFAULT_LANGUAGE = "English"
11
  WELCOME_MESSAGE_EN = "Hi! I'm your friendly assistant 🤖 Let's begin!\n\nPlease tell me which language you'd like to use."
12
 
13
+ # === Aron Question Bank ===
14
+ ARON_SET_I = [
15
+ "Given the choice of anyone in the world, whom would you want as a dinner guest?",
16
+ "Would you like to be famous? In what way?",
17
+ "Before making a telephone call, do you ever rehearse what you are going to say? Why?",
18
+ "What would constitute a 'perfect' day for you?",
19
+ "When did you last sing to yourself? To someone else?",
20
+ "If you were able to live to the age of 90 and retain either the mind or body of a 30-year-old for the last 60 years of your life, which would you want?",
21
+ "Do you have a secret hunch about how you will die?",
22
+ "Name three things you and me appear to have in common.",
23
+ "For what in your life do you feel most grateful?",
24
+ "If you could change anything about the way you were raised, what would it be?",
25
+ "Take one minute and tell me your life story in as much detail as possible.",
26
+ "If you could wake up tomorrow having gained any one quality or ability, what would it be?"
27
+ ]
28
+ ARON_SET_II = [
29
+ "If a crystal ball could tell you the truth about yourself, your life, the future or anything else, what would you want to know?",
30
+ "Is there something that you\u2019ve dreamed of doing for a long time? Why haven\u2019t you done it?",
31
+ "What is the greatest accomplishment of your life?",
32
+ "What do you value most in a friendship?",
33
+ "What is your most treasured memory?",
34
+ "What is your most terrible memory?",
35
+ "If you knew that in one year you would die suddenly, would you change anything about the way you are now living? Why?",
36
+ "What does friendship mean to you?",
37
+ "What roles do love and affection play in your life?",
38
+ "Alternate sharing something you consider a positive characteristic of me. Share a total of three items.",
39
+ "How close and warm is your family? Do you feel your childhood was happier than most other people\u2019s?",
40
+ "How do you feel about your relationship with your mother?"
41
+ ]
42
+ ARON_SET_III = [
43
+ "Make three true 'we' statements each. For instance, 'We are both in this chatroom feeling ...'",
44
+ "Complete this sentence: 'I wish I had someone with whom I could share ...'",
45
+ "If you were going to become a close friend with me, please share what would be important for me to know.",
46
+ "Tell me what you like about me; be very honest this time, saying things that you might not say to someone you\u2019ve just met.",
47
+ "Share with me an embarrassing moment in your life.",
48
+ "When did you last cry in front of another person? By yourself?",
49
+ "Tell me something that you like about me already.",
50
+ "What, if anything, is too serious to be joked about?",
51
+ "If you were to die this evening with no opportunity to communicate with anyone, what would you most regret not having told someone? Why haven\u2019t you told them yet?",
52
+ "Your house, containing everything you own, catches fire. After saving your loved ones and pets, you have time to safely make a final dash to save any one item. What would it be? Why?",
53
+ "Of all the people in your family, whose death would you find most disturbing? Why?",
54
+ "Share a personal problem and ask my advice on how I might handle it. Also, ask me to reflect back to you how you seem to be feeling about the problem you have chosen."
55
+ ]
56
 
57
+ # === Normal Question Bank ===
58
+ NORMAL_SET_I = [
59
+ "When was the last time you walked for more than an hour? Describe where you went and what you saw.",
60
+ "What is the best gift you have ever received? Why?",
61
+ "If you had to leave California, where would you move to? What do you miss most about California?",
62
+ "How did you celebrate Halloween last year?",
63
+ "Do you read newspapers often? Which newspapers do you like? Why?",
64
+ "What is the ideal number of students to share a house with? Why?",
65
+ "If you could invent a new flavor of ice cream, what flavor would you create?",
66
+ "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.",
67
+ "Describe the pet you last got.",
68
+ "What is your favorite holiday? Why?",
69
+ "Tell your partner the funniest thing that happened when you were with a child."
70
+ ]
71
+ NORMAL_SET_II = [
72
+ "What gift did you get on your last birthday?",
73
+ "Describe your last trip to the zoo.",
74
+ "Name and age of your family members, including grandparents, uncles and aunts, and where they were born (to the extent known).",
75
+ "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.",
76
+ "Do you like to wake up early or stay up late? Has anything interesting ever happened to you because of this?",
77
+ "Where are you from? List all the places you have lived.",
78
+ "What is your favorite class at UC Santa Cruz? Why?",
79
+ "What did you do this summer?",
80
+ "What gifts did you receive last Christmas/Hanukkah?",
81
+ "Who is your favorite same-sex actor? Describe a great scene he or she starred in.",
82
+ "What was your impression of UC Santa Cruz when you first came to it?",
83
+ "What is the best TV show you have seen in the past month that your partner has not seen? Describe it to your partner.",
84
+ "What is your favorite holiday? Why?"
85
+ ]
86
+ NORMAL_SET_III = [
87
+ "Where did you go to high school? What was it like?",
88
+ "What is the best book you have read in the past three months that your partner has not read? Describe it to your partner.",
89
+ "What country would you most like to visit? What attracts you to it?",
90
+ "Do you prefer digital or analog watches/clocks? Why?",
91
+ "Describe your mother's best friend.",
92
+ "What are the pros and cons of artificial Christmas trees?",
93
+ "How often do you get your hair cut? Where do you go? Have you ever had a bad haircut?",
94
+ "Did you have a class pet in elementary school? Do you remember its name?",
95
+ "Do you think left-handed people are more creative than right-handed people?",
96
+ "What was the last concert you attended? How many albums of the band do you have? Have you seen them perform before? Where?",
97
+ "What magazines do you subscribe to? What have you subscribed to in the past?",
98
+ "Have you ever participated in a school play? What role did you play? What was the plot? Did anything funny happen during the play?"
99
+ ]
100
 
101
+ def generate_question_set(question_type):
102
+ if question_type == "aron":
103
+ return random.sample(ARON_SET_I, 3) + random.sample(ARON_SET_II, 3) + random.sample(ARON_SET_III, 3)
104
  else:
105
+ return random.sample(NORMAL_SET_I, 3) + random.sample(NORMAL_SET_II, 3) + random.sample(NORMAL_SET_III, 3)
106
+
107
+ async def gpt_translate(text, target_lang):
108
+ if target_lang == "English":
109
+ return text
110
+ prompt = f"Translate the following into {target_lang}:\n\n{text}"
111
+ response = client.chat.completions.create(
112
+ model="gpt-3.5-turbo",
113
+ messages=[{"role": "user", "content": prompt}],
114
+ temperature=0.3
115
+ )
116
+ return response.choices[0].message.content.strip()
117
 
118
  def get_group_from_url(request: gr.Request):
119
  query = urllib.parse.parse_qs(request.query_string.decode())
120
  group = query.get("group", [None])[0]
121
  if group not in ["A", "B", "C", "D"]:
122
  group = random.choice(["A", "B", "C", "D"])
123
+ humanlike = group in ["A", "B"]
124
+ question_type = "aron" if group in ["A", "C"] else "normal"
125
+ return group, humanlike, question_type
 
 
 
 
 
 
 
 
 
126
 
127
+ async def respond(user_input, history, step, language, questions, followup_mode, followup_total_count, group, humanlike, question_type):
128
+ history.append({"role": "user", "content": user_input})
129
+
130
+ if language == "":
131
+ user_language = user_input.strip()
132
+ questions_en = generate_question_set(question_type)
133
+ translated_questions = [await gpt_translate(q, user_language) for q in questions_en]
134
+ welcome = await gpt_translate("Great! We will now continue in your selected language.", user_language)
135
+ history.append({"role": "assistant", "content": f"{welcome}\n\n1. {translated_questions[0]}"} )
136
+ return history, "", 1, user_language, translated_questions, False, 0, group, humanlike, question_type
137
+
138
+ if step >= len(questions):
139
+ thank_you = await gpt_translate("Thank you for your response!", language)
140
+ end_note = await gpt_translate("This concludes our questions. Please proceed with the rest of the survey. 📝", language)
141
+ history.append({"role": "assistant", "content": thank_you})
142
+ history.append({"role": "assistant", "content": end_note})
143
+ return history, "", step, language, questions, False, 0, group, humanlike, question_type
144
+
145
+ # 评论
146
+ comment_prompt = [
147
+ {"role": "system", "content": f"You are a helpful, attentive assistant. Always respond in {language}. Use natural, short, respectful replies."},
148
+ history[-2], history[-1]
149
+ ]
150
+ comment_response = client.chat.completions.create(
151
+ model="gpt-3.5-turbo",
152
+ messages=comment_prompt,
153
+ temperature=0.7
154
  )
155
+ comment = comment_response.choices[0].message.content.strip()
156
+ history.append({"role": "assistant", "content": comment})
157
+ await asyncio.sleep(0.02)
158
+
159
+ if followup_mode:
160
+ if followup_total_count == 1 and random.random() < 0.1:
161
+ # 第二次追问
162
+ followup_prompt = [
163
+ {"role": "system", "content": f"Ask 1 more open-ended follow-up question in {language}, unnumbered."},
164
+ history[-4], history[-3], history[-2], history[-1]
165
+ ]
166
+ followup_response = client.chat.completions.create(
167
+ model="gpt-3.5-turbo",
168
+ messages=followup_prompt,
169
+ temperature=0.9
170
+ )
171
+ second_followup = followup_response.choices[0].message.content.strip()
172
+ history.append({"role": "assistant", "content": second_followup})
173
+ return history, "", step, language, questions, True, 2, group, humanlike, question_type
174
+
175
+ # 追问结束 → 进入下一主问题
176
+ next_question = f"{step+1}. {questions[step]}"
177
+ history.append({"role": "assistant", "content": next_question})
178
+ return history, "", step + 1, language, questions, False, 0, group, humanlike, question_type
179
+
180
+ if random.random() < 0.4:
181
+ # 第一次追问
182
+ followup_prompt = [
183
+ {"role": "system", "content": f"Ask 1 open-ended follow-up question in {language}, based on user's response."},
184
+ history[-2], history[-1]
185
+ ]
186
+ followup_response = client.chat.completions.create(
187
+ model="gpt-3.5-turbo",
188
+ messages=followup_prompt,
189
+ temperature=0.9
190
+ )
191
+ first_followup = followup_response.choices[0].message.content.strip()
192
+ history.append({"role": "assistant", "content": first_followup})
193
+ return history, "", step, language, questions, True, 1, group, humanlike, question_type
194
+
195
+ # 没有追问,直接提问
196
+ next_question = f"{step+1}. {questions[step]}"
197
+ history.append({"role": "assistant", "content": next_question})
198
+ return history, "", step + 1, language, questions, False, 0, group, humanlike, question_type
199
+
200
+ def init():
201
+ return [{"role": "assistant", "content": WELCOME_MESSAGE_EN}], 0, "", [], False, 0
202
+
203
+ with gr.Blocks() as demo:
204
+ chatbot = gr.Chatbot(
205
+ label="", elem_id="chatbox",
206
+ avatar_images=["user_avatar.jpg", "humanlike_avatar.png"],
207
+ bubble_full_width=False,
208
+ height=500, show_copy_button=False, type="messages"
209
  )
210
+
211
+ with gr.Row():
212
+ user_input = gr.Textbox(show_label=False, placeholder="Type your message here...", container=True, scale=10)
213
+ send_btn = gr.Button(value="➤")
214
+
215
+ state = gr.State([])
216
+ step = gr.State(0)
217
+ language = gr.State("")
218
+ questions = gr.State([])
219
+ followup_mode = gr.State(False)
220
+ followup_total_count = gr.State(0)
221
+ group = gr.State()
222
+ humanlike = gr.State()
223
+ question_type = gr.State()
224
+
225
+ demo.load(get_group_from_url, None, [group, humanlike, question_type], queue=False)
226
+ demo.load(init, None, [state, step, language, questions, followup_mode, followup_total_count])
227
+ user_input.submit(respond, [user_input, state, step, language, questions, followup_mode, followup_total_count, group, humanlike, question_type],
228
+ [chatbot, user_input, step, language, questions, followup_mode, followup_total_count, group, humanlike, question_type])
229
+ send_btn.click(respond, [user_input, state, step, language, questions, followup_mode, followup_total_count, group, humanlike, question_type],
230
+ [chatbot, user_input, step, language, questions, followup_mode, followup_total_count, group, humanlike, question_type])
231
+
232
+ demo.queue().launch()