mojakob commited on
Commit
3213410
·
verified ·
1 Parent(s): 0093c77

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1365 -0
app.py ADDED
@@ -0,0 +1,1365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import openai
3
+ import gradio as gr
4
+ import pandas as pd
5
+ from Chatbot_new import (
6
+ generate_first_reveal, generate_internal_external_options,
7
+ generate_second_reveal, generate_stable_unstable_options,
8
+ generate_vignette, interpret_response, save_data_to_pickle,
9
+ standardize_response, save_data_to_excel
10
+ )
11
+ import uuid
12
+ from dotenv import load_dotenv
13
+ from huggingface_hub import HfApi, HfFolder
14
+ import datetime
15
+ import logging
16
+ #logging.basicConfig(level=logging.DEBUG)
17
+
18
+ write_token = os.getenv("write_token")
19
+
20
+ # Load environment variables
21
+ load_dotenv()
22
+
23
+ # Module seeds
24
+ context_types = {
25
+ "Work/Professional": [
26
+ "Working on a project or task",
27
+ "Attending a meeting or briefing",
28
+ "Collaborating with colleagues or team members",
29
+ "Presenting a proposal or idea",
30
+ "Responding to client or customer feedback",
31
+ "Managing or resolving a workplace conflict",
32
+ "Negotiating a contract or agreement",
33
+ "Performing routine tasks",
34
+ "Handling unexpected challenges"
35
+ ],
36
+ "Social": [
37
+ "Engaging in a social gathering or event",
38
+ "Having a one-on-one conversation with a friend or acquaintance",
39
+ "Participating in a group activity or hobby",
40
+ "Sharing ideas or opinions in a casual discussion",
41
+ "Dealing with a social conflict or disagreement",
42
+ "Networking at a professional or social event"
43
+ ],
44
+ "Physical Activity": [
45
+ "Participating in a team sport or physical competition",
46
+ "Engaging in an outdoor activity",
47
+ "Training or practicing with a coach or instructor",
48
+ "Competing in a tournament or race",
49
+ "Engaging in a personal fitness routine or challenge",
50
+ "Performing a physical task that requires coordination or teamwork"
51
+ ],
52
+
53
+ "Educational": [
54
+ "Participating in a class, lecture, or seminar",
55
+ "Collaborating on a study project or research",
56
+ "Receiving feedback from a teacher or mentor",
57
+ "Preparing for or taking an exam",
58
+ "Engaging in group study or discussion",
59
+ "Presenting academic work or research findings"
60
+ ],
61
+ "Creative": [
62
+ "Working on a creative project",
63
+ "Collaborating with others on a creative endeavor",
64
+ "Receiving feedback on a creative piece",
65
+ "Presenting a creative work to an audience",
66
+ "Brainstorming or ideating new concepts",
67
+ "Experimenting with new techniques or styles"
68
+ ]
69
+ }
70
+
71
+ interaction_types = {
72
+ "Authority Feedback": [
73
+ "Receiving feedback or critique from a supervisor, boss, or mentor",
74
+ "Listening to advice or guidance from a coach or teacher",
75
+ "Engaging in a performance review or evaluation",
76
+ "Responding to managerial decisions or directives"
77
+ ],
78
+ "Peer Reaction": [
79
+ "Receiving input, advice, or reactions from a colleague, friend, or teammate",
80
+ "Discussing ideas or opinions with peers in a group setting",
81
+ "Addressing concerns, compliments, or criticisms from a peer",
82
+ "Collaborating on a task or project with equal responsibility"
83
+ ],
84
+ "Group Dynamics": [
85
+ "Participating in a group discussion or brainstorming session",
86
+ "Leading or following in a team activity or project",
87
+ "Managing group feedback or collective opinions",
88
+ "Navigating differing opinions, conflicts, or agreements within a group"
89
+ ],
90
+ "Self-Reflection": [
91
+ "Analyzing personal decisions, actions, or behaviors",
92
+ "Contemplating improvements or changes based on past experiences",
93
+ "Reflecting on feedback received from others",
94
+ "Re-evaluating personal goals, priorities, or values"
95
+ ],
96
+ "Creative Feedback": [
97
+ "Seeking opinions or critiques on a creative project from peers or mentors",
98
+ "Engaging in a discussion about a creative piece's direction or style",
99
+ "Presenting creative work to a group and receiving diverse reactions"
100
+ ],
101
+ "Social Participation": [
102
+ "Engaging in a group activity or event related to a hobby or interest",
103
+ "Discussing or sharing personal achievements or interests in a social setting",
104
+ "Navigating group dynamics during a leisure activity or social gathering"
105
+ ]
106
+ }
107
+
108
+ actions_events = {
109
+ "Work/Professional": [
110
+ "Receiving feedback",
111
+ "Observing reactions",
112
+ "Presenting ideas",
113
+ "Responding to a situation"
114
+ ],
115
+ "Creative/Personal Projects": [
116
+ "Completing a creative project",
117
+ "Seeking feedback",
118
+ "Engaging in competition",
119
+ "Sharing achievements"
120
+ ],
121
+ "Social/Leisure Activities": [
122
+ "Socializing at an event",
123
+ "Participating in a hobby",
124
+ "Competing in a friendly match",
125
+ "Celebrating an achievement"
126
+ ]
127
+ }
128
+ ##############################################################################
129
+ # File paths & Initialization
130
+ ##############################################################################
131
+
132
+ excel_file = "assessment_data.xlsx"
133
+ pickle_file = "assessment_data.pkl"
134
+
135
+ # Make sure your Excel file has the PHQ/GAD columns:
136
+ if not os.path.exists(excel_file):
137
+ pd.DataFrame(columns=[
138
+ 'Prolific ID', 'Age', 'Profession', 'Interests', 'Topic Choice',
139
+ 'Vignette Number', 'Vignette', 'Tone', 'First Reveal', 'Initial Internal',
140
+ 'Initial External', 'Initial Stable', 'Initial Unstable', 'Initial Global',
141
+ 'Initial Specific', 'Reassessment Internal', 'Reassessment External',
142
+ 'Initial Relevance Rating', 'Final Relevance Rating', 'Emotional Relevance',
143
+ 'Positive Valence', 'Negative Valence', 'Likelihood of Change', "Ease of Use",
144
+ "Clarity of Instructions", "Engagement Level", "Satisfaction with Assessment",
145
+ "Cognitive Load", "Additional Comments", 'PHQ-9 Score', 'GAD-7 Score'
146
+ ]).to_excel(excel_file, index=False, engine="openpyxl")
147
+
148
+
149
+ # Same for the pickle file:
150
+ if not os.path.exists(pickle_file):
151
+ pd.DataFrame(columns=[
152
+ 'Prolific ID', 'Age', 'Profession', 'Interests', 'Topic Choice',
153
+ 'Vignette Number', 'Vignette', 'Tone', 'First Reveal', 'Initial Internal',
154
+ 'Initial External', 'Initial Stable', 'Initial Unstable', 'Initial Global',
155
+ 'Initial Specific', 'Reassessment Internal', 'Reassessment External',
156
+ 'Initial Relevance Rating', 'Final Relevance Rating', 'Emotional Relevance',
157
+ 'Positive Valence', 'Negative Valence', 'Likelihood of Change', "Ease of Use",
158
+ "Clarity of Instructions", "Engagement Level", "Satisfaction with Assessment",
159
+ "Cognitive Load", "Additional Comments", 'PHQ-9 Score', 'GAD-7 Score'
160
+ ]).to_pickle(pickle_file)
161
+
162
+ ##############################################################################
163
+ # Shared app_state & Constants
164
+ ##############################################################################
165
+
166
+ app_state = {
167
+ "prolific_id": None,
168
+ "phq_score": 0,
169
+ "gad_score": 0,
170
+ "eligible": False,
171
+ "standardized_data": {
172
+ "Prolific ID": None,
173
+ "Raw Age": None,
174
+ "Raw Profession": None,
175
+ "Raw Interests": None,
176
+ "Age": None,
177
+ "Profession": None,
178
+ "Interests": None,
179
+ "Topic Choice": None,
180
+ "Vignette Number": None,
181
+ "Vignette": None,
182
+ "Tone": None,
183
+ "First Reveal": None,
184
+ "Initial Internal": None,
185
+ 'Initial External': None,
186
+ 'Initial Stable': None,
187
+ 'Initial Unstable': None,
188
+ 'Initial Global': None,
189
+ 'Initial Specific': None,
190
+ 'Reassessment Internal': None,
191
+ 'Reassessment External': None,
192
+ 'Initial Relevance Rating': None,
193
+ 'Final Relevance Rating': None,
194
+ 'Emotional Relevance': None,
195
+ 'Positive Valence': None,
196
+ 'Negative Valence': None,
197
+ 'Likelihood of Change': None,
198
+ 'PHQ-9 Score': None,
199
+ 'GAD-7 Score': None,
200
+ "Second Reveal": None,
201
+ "Explanation Response": None,
202
+ "Assessment Internal External Response": None,
203
+ "Evolved Internal External Response": None,
204
+ },
205
+ "conversation_history": [],
206
+ "stage": "prestart",
207
+ "user_responses": [],
208
+ "vignette_counter": 1,
209
+ "topic_choice": None,
210
+ "options_text": None,
211
+ "desired_tone": None,
212
+ "usability_question_counter": 0,
213
+ "usability_feedback": {
214
+ "Ease of Use": None,
215
+ "Clarity of Instructions": None,
216
+ "Engagement Level": None,
217
+ "Satisfaction with Assessment": None,
218
+ "Cognitive Load": None,
219
+ "Additional Comments": None
220
+ }
221
+ }
222
+
223
+
224
+ EXCLUSION_THRESHOLD = 20
225
+
226
+ ##############################################################################
227
+ # Storing / Uploading Functions
228
+ ##############################################################################
229
+ def generate_custom_vignette(conversation_history, topic_choice, desired_tone):
230
+ """
231
+ Generates a personalized vignette for psychological assessment based on user preferences.
232
+ """
233
+ global app_state
234
+ # Extract user profile from conversation history
235
+ user_age = "Unknown"
236
+ user_profession = "Unknown"
237
+ user_interests = "Unknown"
238
+
239
+ # Parse the conversation history for profile details
240
+ for message in app_state["conversation_history"]:
241
+ if message["role"] == "user" and "User's age:" in message["content"]:
242
+ # Split and extract relevant parts
243
+ content_parts = message["content"].split(",")
244
+ for part in content_parts:
245
+ if "age:" in part:
246
+ user_age = part.split("age:")[1].strip()
247
+ elif "profession:" in part:
248
+ user_profession = part.split("profession:")[1].strip()
249
+ elif "interests:" in part:
250
+ user_interests = part.split("interests:")[1].strip()
251
+
252
+ # Determine topic context
253
+ if topic_choice == "1":
254
+ topic_context = f"a relatable situation directly related to the user's profession ({user_profession})"
255
+ elif topic_choice == "2":
256
+ topic_context = f"a relatable situation reflecting one of the user's personal interests ({user_interests})"
257
+ elif topic_choice == "3":
258
+ recent_context = (
259
+ app_state["conversation_history"][-1]["content"]
260
+ if app_state["conversation_history"] and "content" in app_state["conversation_history"][-1]
261
+ else "general activities or interests"
262
+ )
263
+ topic_context = f"a scenario inspired by the user's recent input ({recent_context})"
264
+ else:
265
+ topic_context = "a general context based on the user's profile"
266
+
267
+ # Define tone
268
+ if desired_tone == "Positive":
269
+ tone_context = "a pleasant and rewarding situation, highlighting success, collaboration, or enjoyable experiences."
270
+ elif desired_tone == "Negative":
271
+ tone_context = "an unpleasant or confrontational situation, involving conflict, challenges, or setbacks."
272
+ else:
273
+ tone_context = "a neutral situation."
274
+
275
+ # Build the prompt
276
+ prompt = f"""
277
+ You are tasked with generating short, personalized vignettes for a psychological assessment.
278
+ Each vignette should immerse the user in a specific, relatable scenario based on their profile.
279
+ User Profile:
280
+ - Age: {user_age}
281
+ - Profession: {user_profession}
282
+ - Interests: {user_interests}
283
+ Scenario Details:
284
+ - The topic of the vignette is {topic_context}.
285
+ - The tone of the vignette should reflect {tone_context}.
286
+ - The vignette should include:
287
+ - A clear context type (e.g., work, social, physical activity, educational, or creative).
288
+ - A specific interaction (e.g., feedback from authority, peer collaboration, or group dynamics).
289
+ - A defined event or action (e.g., presenting an idea, resolving a conflict, or completing a project).
290
+ Guidelines:
291
+ - The vignette must describe external events only, without referencing thoughts, emotions, or internal reflections.
292
+ - Use second-person language to immerse the user ("You...").
293
+ - Keep the vignette concise, no longer than 50 tokens.
294
+ - Use neutral and professional language suitable for a psychological assessment.
295
+ - Do not include personal identifying information.
296
+ Example:
297
+ Example User Profile:
298
+ - Profession: Software Developer
299
+ - Interest: Painting
300
+ Positive Example:
301
+ "As a software developer, you successfully present a new application feature during a team meeting. "
302
+ "Your manager compliments your innovative thinking, and the team celebrates the milestone with a round of applause."
303
+
304
+ Negative Example:
305
+ "While attending a local art exhibition, one of your paintings is critiqued harshly by a visitor. "
306
+ "Their comments spark a tense conversation, leaving you questioning the audience's preferences."
307
+ Now generate the vignette:
308
+ """
309
+
310
+ # Call the OpenAI API
311
+ try:
312
+ response = openai.chat.completions.create(
313
+ model="gpt-4o",
314
+ messages=[
315
+ {"role": "system", "content": "You are an assistant generating tailored psychological assessment scenarios."},
316
+ {"role": "user", "content": prompt},
317
+ ],
318
+ temperature=0.5,
319
+ max_tokens=100
320
+ )
321
+ content = response.choices[0].message.content.strip()
322
+ return content, desired_tone
323
+
324
+ except KeyError as ke:
325
+ print(f"KeyError accessing app_state: {ke}")
326
+ return None, None
327
+ except Exception as e:
328
+ print(f"Error generating vignette: {e}")
329
+ return None, None
330
+
331
+
332
+ def upload_file_to_space(local_file_path, repo_id, hf_token, path_in_repo=None):
333
+ """
334
+ Uploads `local_file_path` to the given Hugging Face Space and removes older versions.
335
+
336
+ :param local_file_path: Path to your local file (e.g. "assessment_data.xlsx").
337
+ :param repo_id: e.g. "username/your-space-name".
338
+ :param hf_token: Your Hugging Face token (with write access).
339
+ :param path_in_repo: Optional path/filename in the Space's git repo
340
+ (defaults to the same as local_file_path).
341
+ """
342
+
343
+ api = HfApi()
344
+ if path_in_repo is None:
345
+ path_in_repo = local_file_path
346
+
347
+ # 1. Delete previous versions of the file in the Space
348
+ all_files = api.list_repo_files(repo_id, repo_type="space")
349
+ for file in all_files:
350
+ if file.startswith(path_in_repo): # Match by file name prefix
351
+ api.delete_file(path_in_repo=file, repo_id=repo_id, repo_type="space", token=hf_token)
352
+ print(f"Deleted old file: {file}")
353
+
354
+ # 2. Upload the new version
355
+ api.upload_file(
356
+ path_or_fileobj=local_file_path,
357
+ path_in_repo=path_in_repo,
358
+ repo_id=repo_id,
359
+ repo_type="space",
360
+ token=hf_token,
361
+ commit_message="Upload latest version of the data file"
362
+ )
363
+ print(f"Uploaded {local_file_path} -> {repo_id}/{path_in_repo}")
364
+
365
+ def save_to_excel(new_row):
366
+ global app_state
367
+ # Add usability data from the app_state (if available)
368
+ usability_data = app_state.get("usability_feedback", {})
369
+ new_row.update(usability_data) # Merge usability data into the main row
370
+
371
+ try:
372
+ # Load the existing DataFrame
373
+ df = pd.read_excel(excel_file, engine="openpyxl")
374
+
375
+ # Save the updated DataFrame
376
+ print("New row data being saved:", new_row)
377
+ print("App state before saving:", app_state)
378
+ df.to_excel(excel_file, index=False, engine="openpyxl")
379
+
380
+ # Upload the updated file
381
+ hf_token = os.getenv("write_token")
382
+ repo_id = "mojakob/condition1"
383
+ if hf_token and repo_id:
384
+ upload_file_to_space(
385
+ local_file_path=excel_file,
386
+ repo_id=repo_id,
387
+ hf_token=hf_token,
388
+ path_in_repo="assessment_data.xlsx"
389
+ )
390
+ except Exception as e:
391
+ print(f"Error in save_to_excel: {e}")
392
+ raise
393
+
394
+
395
+
396
+ def save_to_pickle(standardized_data):
397
+ existing_df = pd.read_pickle(pickle_file)
398
+ # ._append is slightly different in newer pandas; you might use .concat instead:
399
+ new_df = existing_df._append(pd.DataFrame([standardized_data]), ignore_index=True)
400
+ new_df.to_pickle(pickle_file)
401
+
402
+ # Upload after writing
403
+ hf_token = os.getenv("write_token")
404
+ repo_id = "mojakob/condition1"
405
+ if hf_token and repo_id:
406
+ upload_file_to_space(
407
+ local_file_path=pickle_file,
408
+ repo_id=repo_id,
409
+ hf_token=hf_token
410
+ )
411
+
412
+ ##############################################################################
413
+ # Functions for Gradio Flow
414
+ ##############################################################################
415
+
416
+ def store_pid(manual_pid):
417
+ global app_state
418
+ pid = manual_pid.strip()
419
+ if not pid:
420
+ return "Error: Please enter your Prolific ID."
421
+ app_state["prolific_id"] = pid
422
+ return f"Prolific ID {pid} has been recorded."
423
+
424
+ def process_phq9(*scores):
425
+ global app_state
426
+ total_score = sum(scores)
427
+ app_state["phq_score"] = total_score
428
+ return f"PHQ-9 completed. Score: {total_score}. Proceed to GAD-7."
429
+
430
+ def process_gad7(*scores):
431
+ global app_state
432
+ total_score = sum(scores)
433
+ app_state["gad_score"] = total_score
434
+ combined_score = app_state["phq_score"] + total_score
435
+
436
+ if combined_score > EXCLUSION_THRESHOLD:
437
+ return "Your combined score exceeds the threshold. You do not meet the inclusion criteria."
438
+ else:
439
+ app_state["eligible"] = True
440
+
441
+ # We append these columns to the same Excel used for other scenario data:
442
+ #save_to_excel({
443
+ # "Prolific ID": app_state["prolific_id"],
444
+ # # If you want to store consent, age, etc. here, you can.
445
+ # "PHQ-9 Score": app_state["phq_score"],
446
+ # "GAD-7 Score": total_score
447
+ #})
448
+ return "You meet the inclusion criteria. Proceeding to the chatbot assessment."
449
+
450
+
451
+ def store_user_profile(age, profession, interest):
452
+ global app_state
453
+
454
+ """
455
+ Stores raw user inputs for age, profession, interest, and appends them to the conversation_history.
456
+ """
457
+ # Keep 'Raw' fields
458
+ app_state["standardized_data"]["Raw Age"] = age.strip()
459
+ app_state["standardized_data"]["Raw Profession"] = profession.strip()
460
+ app_state["standardized_data"]["Raw Interests"] = interest.strip()
461
+
462
+ # Optionally store "final" fields or keep them for a separate step
463
+ app_state["standardized_data"]["Age"] = age.strip()
464
+ app_state["standardized_data"]["Profession"] = profession.strip()
465
+ app_state["standardized_data"]["Interests"] = interest.strip()
466
+
467
+ # Add to conversation history
468
+ app_state["conversation_history"].append({
469
+ "role": "user",
470
+ "content": f"User's age: {age}, profession: {profession}, interests: {interest}"
471
+ })
472
+
473
+ print(f"app_state at the end of store_user_profile(): {app_state}")
474
+
475
+ return "Profile stored successfully."
476
+
477
+
478
+
479
+
480
+ def process_feedback(ease, clarity, engagement, satisfaction, cognitive_load, comments):
481
+ global app_state
482
+ app_state["usability_feedback"] = {
483
+ "Ease of Use": ease,
484
+ "Clarity of Instructions": clarity,
485
+ "Engagement Level": engagement,
486
+ "Satisfaction with Assessment": satisfaction,
487
+ "Cognitive Load": cognitive_load,
488
+ "Additional Comments": comments
489
+ }
490
+
491
+ return "Thank you for your feedback! It has been recorded."
492
+
493
+ ### Chat Flow ##############################################################
494
+ def new_chat_input(message, history, *args, **kwargs):
495
+ global app_state
496
+ print(f"app_state at start of new_chat_input: {app_state}")
497
+
498
+ # = app_state.copy()
499
+
500
+ print(f"message received: {message}")
501
+ print(f"history received: {history}")
502
+
503
+ vignette_tones = ['Positive', 'Negative', 'Negative', 'Positive', 'Positive', 'Negative', 'Negative', 'Positive',
504
+ 'Positive', 'Negative', 'Negative', 'Positive', 'Positive', 'Negative', 'Negative',
505
+ 'Positive'] # Total of 16 vignettes
506
+
507
+ # if "conversation_history" not in app_state:
508
+ # app_state["conversation_history"] = []
509
+ # if "user_responses" not in app_state:
510
+ # app_state["user_responses"] = []
511
+ # if "standardized_data" not in app_state:
512
+ # app_state["standardized_data"] = {
513
+ # "Raw Age": None,
514
+ # "Raw Profession": None,
515
+ # "Raw Interests": None,
516
+ # "Age": None,
517
+ # "Profession": None,
518
+ # "Interests": None,
519
+ # "Vignette": None,
520
+ # "Tone": None,
521
+ # "First Reveal": None,
522
+ # "Second Reveal": None,
523
+ # "Explanation Response": None,
524
+ # "Assessment Internal External Response": None,
525
+ # "Evolved Internal External Response": None,
526
+ # }
527
+ # if "vignette_counter" not in app_state:
528
+ # app_state["vignette_counter"] = 1
529
+ # if "stage" not in app_state:
530
+ # app_state["stage"] = "prestart"
531
+ # if "topic_choice" not in app_state:
532
+ # app_state["topic_choice"] = None
533
+ # if "options_text" not in app_state:
534
+ # app_state["options_text"] = None
535
+ # if "desired_tone" not in app_state:
536
+ # app_state["desired_tone"] = None
537
+
538
+ print(f"user entered {message}")
539
+ app_state["conversation_history"].append({"role": "user", "content": message})
540
+
541
+ if app_state["stage"] == "usability_feedback":
542
+ print("Transitioning to usability_feedback stage.")
543
+ #save_to_pickle(app_state["standardized_data"])
544
+ #save_to_excel(app_state["standardized_data"])
545
+ feedback_questions = [
546
+ """Thank you for completing all the scenarios. We just have a few more questions before you leave.
547
+
548
+ How easy was it to complete the assessment? (1 = Not at all, 10 = Very much)""",
549
+ "How clear were the instructions? (1 = Not at all, 10 = Very much)",
550
+ "How engaging was the assessment experience? (1 = Not at all, 10 = Very much)",
551
+ "How satisfied are you with this assessment? (1 = Not at all, 10 = Very much)",
552
+ "How mentally demanding was the assessment? (1 = Not at all, 10 = Very much)",
553
+ ]
554
+
555
+ # Initialize counter only once
556
+ # if "usability_question_counter" not in app_state:
557
+ # app_state["usability_question_counter"] = 0
558
+
559
+ # Check if we've finished all questions
560
+ if app_state["usability_question_counter"] >= len(feedback_questions):
561
+ app_state["stage"] = "completed"
562
+ save_to_excel({
563
+ 'Prolific ID': app_state["prolific_id"],
564
+ 'Age': app_state["standardized_data"].get("Age", None),
565
+ 'Profession': app_state["standardized_data"].get("Profession", None),
566
+ 'Interests': app_state["standardized_data"].get("Interests", None),
567
+ 'Topic Choice': app_state["standardized_data"].get("Topic Choice", None),
568
+ 'Vignette Number': app_state["standardized_data"].get("Vignette Number", None),
569
+ 'Vignette': app_state["standardized_data"].get("Vignette", None),
570
+ 'Tone': app_state["standardized_data"].get("Tone", None),
571
+ 'First Reveal': app_state["standardized_data"].get("First Reveal", None),
572
+ 'Initial Internal': app_state["standardized_data"].get("Initial Internal", None),
573
+ 'Initial External': app_state["standardized_data"].get("Initial External", None),
574
+ 'Initial Stable': app_state["standardized_data"].get("Initial Stable", None),
575
+ 'Initial Unstable': app_state["standardized_data"].get("Initial Unstable", None),
576
+ 'Initial Global': app_state["standardized_data"].get("Initial Global", None),
577
+ 'Initial Specific': app_state["standardized_data"].get("Initial Specific", None),
578
+ 'Reassessment Internal': app_state["standardized_data"].get("Reassessment Internal", None),
579
+ 'Reassessment External': app_state["standardized_data"].get("Reassessment External", None),
580
+ 'Initial Relevance Rating': app_state["standardized_data"].get("Initial Relevance Rating", None),
581
+ 'Final Relevance Rating': app_state["standardized_data"].get("Final Relevance Rating", None),
582
+ 'Emotional Relevance': app_state["standardized_data"].get("Emotional Relevance", None),
583
+ 'Positive Valence': app_state["standardized_data"].get("Positive Valence", None),
584
+ 'Negative Valence': app_state["standardized_data"].get("Negative Valence", None),
585
+ 'Likelihood of Change': app_state["standardized_data"].get("Likelihood of Change", None),
586
+ "Ease of Use": app_state["standardized_data"].get("Ease of Use", None),
587
+ "Clarity of Instructions": app_state["standardized_data"].get("Clarity of Instructions", None),
588
+ "Engagement Level": app_state["standardized_data"].get("Engagement Level", None),
589
+ "Satisfaction with Assessment": app_state["standardized_data"].get("Satisfaction with Assessment", None),
590
+ "Cognitive Load": app_state["standardized_data"].get("Cognitive Load", None),
591
+ "Additional Comments": app_state["standardized_data"].get("Additional Comments", None),
592
+ 'PHQ-9 Score': app_state["phq_score"],
593
+ 'GAD-7 Score': app_state["gad_score"]
594
+ })
595
+ return "Thank you for your feedback! Please use the following link to submit your results: https://app.prolific.com/submissions/complete?cc=CBQG85HO"
596
+
597
+ # Validate user input for the current question
598
+ try:
599
+ standardized_response = int(message)
600
+ except ValueError:
601
+ return "Please provide a number between 1 and 10."
602
+
603
+ if standardized_response not in range(1, 11):
604
+ return "Please provide a number between 1 and 10."
605
+
606
+ # Store the response
607
+ question_key = [
608
+ "Ease of Use",
609
+ "Clarity of Instructions",
610
+ "Engagement Level",
611
+ "Satisfaction",
612
+ "Cognitive Load"
613
+ ][app_state["usability_question_counter"]]
614
+ app_state["usability_feedback"][question_key] = standardized_response
615
+
616
+ # Move to the next question
617
+ app_state["usability_question_counter"] += 1
618
+
619
+ # If there are more questions, ask the next one
620
+ if app_state["usability_question_counter"] < len(feedback_questions):
621
+ return feedback_questions[app_state["usability_question_counter"]]
622
+
623
+ # If all questions are complete, transition to the next stage
624
+ app_state["stage"] = "completed"
625
+ save_to_excel({
626
+ 'Prolific ID': app_state["prolific_id"],
627
+ 'Age': app_state["standardized_data"].get("Age", None),
628
+ 'Profession': app_state["standardized_data"].get("Profession", None),
629
+ 'Interests': app_state["standardized_data"].get("Interests", None),
630
+ 'Topic Choice': app_state["standardized_data"].get("Topic Choice", None),
631
+ 'Vignette Number': app_state["standardized_data"].get("Vignette Number", None),
632
+ 'Vignette': app_state["standardized_data"].get("Vignette", None),
633
+ 'Tone': app_state["standardized_data"].get("Tone", None),
634
+ 'First Reveal': app_state["standardized_data"].get("First Reveal", None),
635
+ 'Initial Internal': app_state["standardized_data"].get("Initial Internal", None),
636
+ 'Initial External': app_state["standardized_data"].get("Initial External", None),
637
+ 'Initial Stable': app_state["standardized_data"].get("Initial Stable", None),
638
+ 'Initial Unstable': app_state["standardized_data"].get("Initial Unstable", None),
639
+ 'Initial Global': app_state["standardized_data"].get("Initial Global", None),
640
+ 'Initial Specific': app_state["standardized_data"].get("Initial Specific", None),
641
+ 'Reassessment Internal': app_state["standardized_data"].get("Reassessment Internal", None),
642
+ 'Reassessment External': app_state["standardized_data"].get("Reassessment External", None),
643
+ 'Initial Relevance Rating': app_state["standardized_data"].get("Initial Relevance Rating", None),
644
+ 'Final Relevance Rating': app_state["standardized_data"].get("Final Relevance Rating", None),
645
+ 'Emotional Relevance': app_state["standardized_data"].get("Emotional Relevance", None),
646
+ 'Positive Valence': app_state["standardized_data"].get("Positive Valence", None),
647
+ 'Negative Valence': app_state["standardized_data"].get("Negative Valence", None),
648
+ 'Likelihood of Change': app_state["standardized_data"].get("Likelihood of Change", None),
649
+ "Ease of Use": app_state["standardized_data"].get("Ease of Use", None),
650
+ "Clarity of Instructions": app_state["standardized_data"].get("Clarity of Instructions", None),
651
+ "Engagement Level": app_state["standardized_data"].get("Engagement Level", None),
652
+ "Satisfaction with Assessment": app_state["standardized_data"].get("Satisfaction with Assessment", None),
653
+ "Cognitive Load": app_state["standardized_data"].get("Cognitive Load", None),
654
+ "Additional Comments": app_state["standardized_data"].get("Additional Comments", None),
655
+ 'PHQ-9 Score': app_state["phq_score"],
656
+ 'GAD-7 Score': app_state["gad_score"]
657
+ })
658
+ return "Thank you for your feedback! Please use the following link to submit your results: https://app.prolific.com/submissions/complete?cc=CBQG85HO"
659
+
660
+ # elif app_state["stage"] == "usability_response":
661
+ # # Standardize and save the response
662
+ # question_index = app_state["usability_question_counter"] - 1
663
+ # usability_questions_keys = [
664
+ # "Ease of Use", "Clarity of Instructions", "Engagement Level",
665
+ # "Satisfaction", "Cognitive Load", "Additional Comments"
666
+ # ]
667
+
668
+ # Map response to the corresponding question key
669
+ # if question_index < len(usability_questions_keys):
670
+ # response_key = usability_questions_keys[question_index]
671
+ # standardized_response = interpret_response(message)
672
+ # app_state["standardized_data"][response_key] = standardized_response
673
+
674
+ # # Return to usability feedback stage
675
+ # app_state["stage"] = "usability_feedback"
676
+ # return "Got it, thank you!"
677
+
678
+
679
+ #return f"Vignette {app_state['vignette_counter']}: Response processed.", False # Keep button hidden
680
+ if app_state["stage"] == "prestart":
681
+ app_state["standardized_data"]['Prolific ID'] = app_state["prolific_id"]
682
+ # Retrieve the "Raw" fields first
683
+ raw_age = app_state["standardized_data"].get("Raw Age", "Unknown")
684
+ raw_profession = app_state["standardized_data"].get("Raw Profession", "Unknown")
685
+ raw_interests = app_state["standardized_data"].get("Raw Interests", "Unknown")
686
+
687
+ # Optionally parse or standardize them here if needed:
688
+ #app_state["standardized_data"]["Age"] = standardize_response("Extract age from:", raw_age)
689
+ #app_state["standardized_data"]["Profession"] = standardize_response("Extract profession from:", raw_profession)
690
+ #app_state["standardized_data"]["Interests"] = standardize_response("Extract interests from:", raw_interests)
691
+
692
+ # Add to conversation history
693
+ app_state["conversation_history"].append({"role": "user", "content": f"Age: {app_state['standardized_data']['Age']}"})
694
+ app_state["conversation_history"].append({"role": "user", "content": f"Profession: {app_state['standardized_data']['Profession']}"})
695
+ app_state["conversation_history"].append({"role": "user", "content": f"Interests: {app_state['standardized_data']['Interests']}"})
696
+
697
+ required_fields = ["Age", "Profession", "Interests"]
698
+ for field in required_fields:
699
+ if field not in app_state["standardized_data"]:
700
+ raise KeyError(f"Missing field '{field}' in app_state['standardized_data'].")
701
+
702
+ """
703
+ Let's create a scenario for you.
704
+ Which topic would you prefer?
705
+ 1. A situation related to your profession.
706
+ 2. A situation related to your personal interests.
707
+ 3. Something else about me. (Add another activity or interest that is important to you by saying "I also like...")
708
+ """
709
+ app_state["stage"] = "topic_choice"
710
+ print(f"app_state during initial topic_choice: {app_state}")
711
+ return """
712
+ Let's create a scenario for you.
713
+ Which topic would you prefer?
714
+ 1. A situation related to your profession.
715
+ 2. A situation related to your personal interests.
716
+ 3. Something else about me. (Add another activity or interest that is important to you by saying "I also like...")
717
+ """
718
+
719
+ elif app_state["stage"] == "topic_choice":
720
+ print("topic_choice block successfully entered")
721
+ print(f"User entered message: {message}")
722
+ app_state['options_text'] = '1. A situation related to your profession.\n2. A situation related to your personal interests.\n3. Something else about me (Add another activity or interest that is important to you by saying "I also like...")'
723
+ user_input = message #fn_input("You: ")
724
+ app_state["user_responses"].append({"stage": "topic_choice", "response": user_input})
725
+ app_state["conversation_history"].append({"role": "user", "content": user_input})
726
+ print(f"user input was: {user_input}, user responses after storing it are: {app_state['user_responses']}")
727
+ app_state.update(app_state)
728
+ mapped_option1 = standardize_response("Please extract the user's chosen topic.", user_input)
729
+ mapped_option2 = interpret_response(mapped_option1, app_state['options_text'])
730
+
731
+ print(f"Before Topic Choice Update: {app_state['standardized_data']}")
732
+ app_state["standardized_data"]["Topic Choice"] = mapped_option2
733
+ print(f"After Topic Choice Update: {app_state['standardized_data']}")
734
+
735
+
736
+ print(f"User Input: {user_input}")
737
+ print(f"Mapped Option 1: {mapped_option1}, Mapped Option 2: {mapped_option2}")
738
+
739
+ if mapped_option2 in ['1', '2', '3']:
740
+ topic_choice_response = mapped_option2
741
+ app_state["standardized_data"]['Vignette Number'] = app_state["vignette_counter"]
742
+ app_state["standardized_data"]['Topic Choice'] = topic_choice_response
743
+ app_state["topic_choice"] = topic_choice_response
744
+
745
+ app_state["desired_tone"] = vignette_tones[app_state["vignette_counter"] - 1] if app_state["vignette_counter"] - 1 < len(vignette_tones) else "Neutral"
746
+ vignette, tone = generate_custom_vignette(
747
+ conversation_history=app_state["conversation_history"],
748
+ topic_choice=app_state["topic_choice"],
749
+ desired_tone=app_state["desired_tone"]
750
+ )
751
+ if vignette is None:
752
+ app_state["stage"] = "error"
753
+ return "Error generating vignette. Please restart."
754
+
755
+ app_state["vignette"] = vignette
756
+ app_state["tone"] = tone
757
+
758
+ print(f"Generated Vignette: {app_state['vignette']}, Tone: {app_state['tone']}")
759
+
760
+ if app_state["vignette"] is None:
761
+ app_state["stage"] = "error"
762
+ return "There was an error generating the vignette. Exiting the assessment."
763
+
764
+ app_state["conversation_history"].append({"role": "assistant", "content": app_state["vignette"]})
765
+ app_state["user_responses"].append({
766
+ 'app_state["stage"]': 'vignette',
767
+ 'content': app_state["vignette"],
768
+ 'tone': app_state["tone"]
769
+ })
770
+
771
+ app_state["standardized_data"]['Vignette'] = app_state["vignette"]
772
+ app_state["standardized_data"]['Tone'] = app_state["tone"]
773
+ app_state["stage"] = "vignette_usability_assessment"
774
+ print(f"Stage updated to: {app_state['stage']}")
775
+
776
+ return f"""Alright, please imagine you are witnessing the following scene:
777
+
778
+ {app_state["vignette"]}
779
+
780
+ Before we proceed, on a scale from 0 to 10, how relevant, immersive, or relatable is the depicted scenario to you personally? (1 = not at all, 10 = completely)
781
+ """
782
+ else:
783
+ return "Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?"
784
+
785
+ elif app_state["stage"] == "vignette_usability_assessment":
786
+ relevance_rating = standardize_response("Please extract the user's rating on a scale from 0 to 10.", message)
787
+ app_state["user_responses"].append({'app_state["stage"]': 'vignette_usability_assessment', 'response': relevance_rating})
788
+ app_state["conversation_history"].append({"role": "user", "content": relevance_rating})
789
+ if relevance_rating not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']:
790
+ return "Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?"
791
+
792
+ # Store the initial relevance rating if not already stored
793
+ if f'Initial Relevance Rating' not in app_state["standardized_data"]:
794
+ app_state["standardized_data"][f'Initial Relevance Rating'] = int(relevance_rating)
795
+
796
+ if int(relevance_rating) < 5:
797
+ # Ask for further clarification
798
+ # Use the additional info to regenerate the vignette
799
+ app_state["stage"] = "vignette_regeneration"
800
+ return """I'm sorry to hear that the scenario wasn't quite fitting. I might have misunderstood some of your responses.
801
+
802
+ Could you please briefly clarify why the scenario felt off, so we can come up with a better one?"""
803
+
804
+ # Accept the vignette
805
+ app_state["standardized_data"][f'Vignette'] = app_state["vignette"]
806
+ app_state["standardized_data"][f'Tone'] = app_state["tone"]
807
+ # Store the final relevance rating
808
+ app_state["standardized_data"][f'Final Relevance Rating'] = int(relevance_rating)
809
+ app_state["stage"] = "emotional_relevance"
810
+ # Emotional relevance rating
811
+ return f"""How strongly did you feel any emotions while imagining this scenario? (0 = No emotional reaction, 10 = Very strong emotional reaction)"""
812
+
813
+ elif app_state["stage"] == "emotional_relevance":
814
+ emotional_relevance = standardize_response("Please extract the user's rating on a scale from 0 to 10.", message)
815
+ app_state["user_responses"].append(
816
+ {'app_state["stage"]': 'emotional_relevance', 'response': emotional_relevance})
817
+ app_state["conversation_history"].append({"role": "user", "content": emotional_relevance})
818
+ if emotional_relevance not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']:
819
+ return "Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?"
820
+
821
+ # Store emotional relevance rating
822
+ if f'Emotional Relevance' not in app_state["standardized_data"]:
823
+ app_state["standardized_data"][f'Emotional Relevance'] = int(emotional_relevance)
824
+ app_state["stage"] = "positive_valence"
825
+ # Positive Valence
826
+ return f"""How strongly did you feel any sense of joy, excitement, or satisfaction while reading the scenario? (0 = Not at all, 10 = A lot)"""
827
+
828
+ elif app_state["stage"] == "positive_valence":
829
+ positive_valence = standardize_response("Please extract the user's rating on a scale from 0 to 10.", message)
830
+ app_state["user_responses"].append(
831
+ {'app_state["stage"]': 'positive_valence', 'response': positive_valence})
832
+ app_state["conversation_history"].append({"role": "user", "content": positive_valence})
833
+ if positive_valence not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']:
834
+ return "Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?"
835
+
836
+ # Store positive valence rating
837
+ if f'Positive Valence' not in app_state["standardized_data"]:
838
+ app_state["standardized_data"][f'Positive Valence'] = int(positive_valence)
839
+ app_state["stage"] = "negative_valence"
840
+
841
+ # Negative Valence
842
+ return f"""How strongly did you feel any discomfort or tension while reading the scenario? (0 = Not at all, 10 = A lot)"""
843
+
844
+ elif app_state["stage"] == "negative_valence":
845
+ negative_valence = standardize_response("Please extract the user's rating on a scale from 0 to 10.", message)
846
+ app_state["user_responses"].append(
847
+ {'app_state["stage"]': 'negative_valence', 'response': negative_valence})
848
+ app_state["conversation_history"].append({"role": "user", "content": negative_valence})
849
+ if negative_valence not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']:
850
+ return "Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?"
851
+
852
+ # Store negative valence rating
853
+ if f'Negative Valence' not in app_state["standardized_data"]:
854
+ app_state["standardized_data"][f'Negative Valence'] = int(negative_valence)
855
+
856
+ # Move to next stage
857
+ app_state["stage"] = "internal_external"
858
+ app_state['options_text'] = generate_internal_external_options(app_state["conversation_history"], app_state["standardized_data"][f'Vignette'])
859
+ return f"""Based on the scenario above, which of the following statements do you personally think is most likely?:
860
+ \n{app_state['options_text']}"""
861
+
862
+ elif app_state["stage"] == "vignette_regeneration":
863
+ # additional_info = fn_input("You: ")
864
+ additional_info = message
865
+ app_state["user_responses"].append({'app_state["stage"]': 'additional_info', 'response': additional_info})
866
+ app_state["conversation_history"].append({"role": "user", "content": additional_info})
867
+ # Use the additional info in the conversation history to regenerate the vignette
868
+ app_state["vignette"], app_state["tone"] = generate_custom_vignette(conversation_history=app_state["conversation_history"], topic_choice=app_state["topic_choice"], desired_tone=app_state["desired_tone"])
869
+ app_state["conversation_history"].append({"role": "assistant", "content": app_state["vignette"]})
870
+ app_state["user_responses"].append({'app_state["stage"]': 'vignette_regenerated', 'content': app_state["vignette"], 'tone': app_state["tone"]})
871
+ # Temporarily store the new vignette and tone
872
+ app_state["standardized_data"][f'Vignette'] = app_state["vignette"]
873
+ app_state["standardized_data"][f'Tone'] = app_state["tone"]
874
+ # Go back to usability assessment
875
+ app_state["stage"] = "vignette_usability_assessment"
876
+ return f"""Okay, let's try again. Please imagine you are witnessing the following scene:
877
+
878
+ {app_state["vignette"]}
879
+
880
+ Before we proceed, on a scale from 0 to 10, how relevant, immersive, or relatable is the depicted scenario to you personally? (0 = not at all, 10 = completely)
881
+ """
882
+
883
+ elif app_state["stage"] == "internal_external":
884
+ # user_input = fn_input("Your explanation: ")
885
+ user_input = message
886
+ app_state["user_responses"].append({'app_state["stage"]': 'internal_external', 'options': app_state['options_text'], 'response': user_input})
887
+ app_state["conversation_history"].append({"role": "user", "content": user_input})
888
+ mapped_option = interpret_response(user_input, app_state['options_text'])
889
+ if mapped_option not in ['1', '2']:
890
+ return "Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?"
891
+ app_state["explanation_response"] = mapped_option
892
+ # Store the initial internal/external attribution numerically
893
+ if app_state["explanation_response"] == '1':
894
+ app_state["standardized_data"][f'Initial Internal'] = 1
895
+ app_state["standardized_data"][f'Initial External'] = 0
896
+ elif app_state["explanation_response"] == '2':
897
+ app_state["standardized_data"][f'Initial Internal'] = 0
898
+ app_state["standardized_data"][f'Initial External'] = 1
899
+ else:
900
+ print("initial internal/external unknown response")
901
+ app_state["standardized_data"][f'Initial Internal'] = None
902
+ app_state["standardized_data"][f'Initial External'] = None
903
+
904
+
905
+ app_state["stage"] = "stable_unstable_global_specific"
906
+ previous_choice = app_state["explanation_response"]
907
+ app_state['options_text'] = generate_stable_unstable_options(app_state["conversation_history"], app_state["standardized_data"][f'Vignette'], previous_choice)
908
+ return f"""Now, considering your previous choice, please select the option that - in your eyes - best describes what might have led to this situation:
909
+ \n{app_state['options_text']}"""
910
+ elif app_state["stage"] == "stable_unstable_global_specific":
911
+ # user_input = fn_input("Your explanation: ")
912
+ user_input = message
913
+ app_state["user_responses"].append({'app_state["stage"]': 'stable_unstable_global_specific', 'options': app_state['options_text'], 'response': user_input})
914
+ app_state["conversation_history"].append({"role": "user", "content": user_input})
915
+ mapped_option = interpret_response(user_input, app_state['options_text'])
916
+ if mapped_option not in ['1', '2', '3', '4']:
917
+ return "Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?"
918
+ app_state["explanation_stable_unstable_response"] = mapped_option
919
+ # Store the initial stable/unstable and global/specific attributions numerically
920
+ if app_state["explanation_stable_unstable_response"] == '1':
921
+ app_state["standardized_data"][f'Initial Stable'] = 1
922
+ app_state["standardized_data"][f'Initial Unstable'] = 0
923
+ app_state["standardized_data"][f'Initial Global'] = 1
924
+ app_state["standardized_data"][f'Initial Specific'] = 0
925
+ elif app_state["explanation_stable_unstable_response"] == '2':
926
+ app_state["standardized_data"][f'Initial Stable'] = 1
927
+ app_state["standardized_data"][f'Initial Unstable'] = 0
928
+ app_state["standardized_data"][f'Initial Global'] = 0
929
+ app_state["standardized_data"][f'Initial Specific'] = 1
930
+ elif app_state["explanation_stable_unstable_response"] == '3':
931
+ app_state["standardized_data"][f'Initial Stable'] = 0
932
+ app_state["standardized_data"][f'Initial Unstable'] = 1
933
+ app_state["standardized_data"][f'Initial Global'] = 1
934
+ app_state["standardized_data"][f'Initial Specific'] = 0
935
+ elif app_state["explanation_stable_unstable_response"] == '4':
936
+ app_state["standardized_data"][f'Initial Stable'] = 0
937
+ app_state["standardized_data"][f'Initial Unstable'] = 1
938
+ app_state["standardized_data"][f'Initial Global'] = 0
939
+ app_state["standardized_data"][f'Initial Specific'] = 1
940
+ else:
941
+ print("initial stable/global unknown response")
942
+ app_state["standardized_data"][f'Initial Stable'] = None
943
+ app_state["standardized_data"][f'Initial Unstable'] = None
944
+ app_state["standardized_data"][f'Initial Global'] = None
945
+ app_state["standardized_data"][f'Initial Specific'] = None
946
+
947
+
948
+ app_state["first_reveal"] = generate_first_reveal(app_state["vignette"])
949
+ app_state["conversation_history"].append({"role": "assistant", "content": app_state["first_reveal"]})
950
+ app_state["user_responses"].append({'app_state["stage"]': 'first_reveal', 'content': app_state["first_reveal"]})
951
+ app_state["standardized_data"][f'First Reveal'] = app_state["first_reveal"]
952
+ app_state["stage"] = "internal_external_reassessment"
953
+
954
+ app_state['options_text'] = generate_internal_external_options(app_state["conversation_history"], app_state["standardized_data"][f'Vignette'] + " " + app_state["standardized_data"][f'First Reveal'])
955
+ return f"""Alright, noted. Now, please imagine the following:
956
+
957
+ {app_state["first_reveal"]}
958
+
959
+ Considering these new developments, please select which of these options seems more likely to you:
960
+ \n{app_state['options_text']}"""
961
+
962
+ elif app_state["stage"] == "internal_external_reassessment":
963
+ # user_input = fn_input("Your explanation: ")
964
+ user_input = message
965
+ app_state["user_responses"].append({'app_state["stage"]': 'internal_external_reassessment', 'options': app_state['options_text'], 'response': user_input})
966
+ app_state["conversation_history"].append({"role": "user", "content": user_input})
967
+ mapped_option = interpret_response(user_input, app_state['options_text'])
968
+ if mapped_option not in ['1', '2']:
969
+ return "Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?"
970
+ app_state["assessment_internal_external_response"] = mapped_option
971
+
972
+ # Store the reassessment internal/external attribution numerically
973
+ if app_state["assessment_internal_external_response"] == '1':
974
+ app_state["standardized_data"][f'Reassessment Internal'] = 1
975
+ app_state["standardized_data"][f'Reassessment External'] = 0
976
+ elif app_state["assessment_internal_external_response"] == '2':
977
+ app_state["standardized_data"][f'Reassessment Internal'] = 0
978
+ app_state["standardized_data"][f'Reassessment External'] = 1
979
+ else:
980
+ print("reassessment internal unknown response")
981
+ app_state["standardized_data"][f'Reassessment Internal'] = None
982
+ app_state["standardized_data"][f'Reassessment External'] = None
983
+
984
+ app_state["stage"] = "likelihood_of_change"
985
+ return "Think back to your initial interpretation of the scene. On a scale from 0 to 10, how likely are you to change that initial interpretation after receiving the new information? (0 = least likely, 10 = most likely)"
986
+
987
+ elif app_state["stage"] == "likelihood_of_change":
988
+ # user_input = fn_input("You: ")
989
+ user_input = standardize_response("Please extract the user's rating on a scale from 0 to 10.", message)
990
+ app_state["user_responses"].append({'app_state["stage"]': 'likelihood_of_change', 'response': user_input})
991
+ app_state["conversation_history"].append({"role": "user", "content": user_input})
992
+ if user_input not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']:
993
+ return "Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?"
994
+
995
+ # Interpret the user's response to extract the numerical rating
996
+ # rating_prompt = f"""
997
+ # The user was asked to rate their likelihood of changing their initial interpretation on a scale from 1 to 10.
998
+ #
999
+ # The user responded: "{user_input}"
1000
+ #
1001
+ # Extract the numerical rating from the user's response. Provide the number only.
1002
+ #
1003
+ # If you cannot determine the rating, respond with "Unable to determine".
1004
+ # """
1005
+ #
1006
+ # response = openai.chat.completions.create(
1007
+ # model="gpt-4o-mini",
1008
+ # messages=[{"role": "user", "content": rating_prompt}],
1009
+ # temperature=0.0,
1010
+ # max_tokens=5
1011
+ # )
1012
+
1013
+ # assistant_response = response.choices[0].message.content.strip()
1014
+ # if assistant_response.isdigit() and 1 <= int(assistant_response) <= 10:
1015
+ app_state["standardized_data"][f'Likelihood of Change'] = int(user_input)
1016
+ app_state["vignette_counter"] += 1 # Move to the next vignette
1017
+
1018
+ # If all vignettes are complete, transition to usability feedback
1019
+ if app_state["vignette_counter"] > 2:
1020
+ print("All vignettes completed. Moving to usability feedback.")
1021
+ # save_to_pickle(app_state["standardized_data"])
1022
+ # save_to_excel(app_state["standardized_data"])
1023
+ app_state["stage"] = "usability_feedback"
1024
+ app_state["usability_question_counter"] = 0
1025
+ return "How easy was it to complete the assessment? (1 = Not at all, 10 = Very much)"
1026
+ else:
1027
+ # Save data and reset for the next vignette
1028
+ app_state["stage"] = "topic_choice"
1029
+ # save_to_pickle(app_state["standardized_data"])
1030
+ # save_to_excel(app_state["standardized_data"])
1031
+ # app_state["standardized_data"] = {} # Clear standardized data for the next vignette
1032
+ # app_state["standardized_data"]['Prolific ID'] = app_state["prolific_id"]
1033
+ return f"Thank you! We are now finished with scene {app_state['vignette_counter'] - 1}. In total you will be seeing 2 scenes.\n\nWhat would you like for your next round?\n1. A situation related to your profession.\n2. A situation related to your personal interests.\n3. Something else about me. (Add another activity or interest that is important to you by saying 'I also like...')"
1034
+ else:
1035
+ print(f"Unexpected app_state or input: stage={app_state['stage']}, message={message}")
1036
+ return "An unexpected error occurred. Please try again or contact support."
1037
+
1038
+
1039
+
1040
+ return app_state["conversation_history"], app_state["user_responses"]
1041
+
1042
+ # Gradio app
1043
+ css = """
1044
+ #app {
1045
+ margin: 0 auto;
1046
+ max-width: 100%;
1047
+ padding: 0;
1048
+ height: 100vh;
1049
+ display: flex;
1050
+ justify-content: center;
1051
+ align-items: center;
1052
+ }
1053
+ body {
1054
+ overflow-y: auto; /* Allows vertical scrolling */;
1055
+ margin: 0;
1056
+ }
1057
+ """
1058
+
1059
+ with gr.Blocks(css=css) as app:
1060
+ ########################################################################
1061
+ # Page 1: Get Prolific ID + PHQ-9
1062
+ ########################################################################
1063
+ with gr.Row(visible=True) as page_1:
1064
+ with gr.Column():
1065
+ # (A) Manual ID entry
1066
+ gr.Markdown("### Enter Your Prolific ID:")
1067
+ pid_input = gr.Textbox(label="Prolific ID (required)")
1068
+ pid_output = gr.Markdown()
1069
+ pid_button = gr.Button("Store ID")
1070
+
1071
+ pid_button.click(
1072
+ fn=store_pid,
1073
+ inputs=pid_input,
1074
+ outputs=pid_output)
1075
+
1076
+ # (B) PHQ-9
1077
+ gr.Markdown("""## Pretest: PHQ-9
1078
+ Over the last 2 weeks, how often have you been bothered by
1079
+ any of the following problems (0 = "Never", 3 = "Very often")?
1080
+ """)
1081
+ q1 = gr.Slider(0, 3, step=1, label="Little interest or pleasure in doing things?")
1082
+ q2 = gr.Slider(0, 3, step=1, label="Feeling down, depressed, or hopeless?")
1083
+ q3 = gr.Slider(0, 3, step=1, label="Trouble falling or staying asleep, or sleeping too much?")
1084
+ q4 = gr.Slider(0, 3, step=1, label="Feeling tired or having little energy?")
1085
+ q5 = gr.Slider(0, 3, step=1, label="Poor appetite or overeating?")
1086
+ q6 = gr.Slider(0, 3, step=1, label="Feeling bad about yourself?")
1087
+ q7 = gr.Slider(0, 3, step=1, label="Trouble concentrating?")
1088
+ q8 = gr.Slider(0, 3, step=1, label="Moving or speaking so slowly people noticed?")
1089
+ q9 = gr.Slider(0, 3, step=1, label="Thoughts that you would be better off dead?")
1090
+ phq_result = gr.Markdown()
1091
+ next_button = gr.Button("Next")
1092
+
1093
+ ########################################################################
1094
+ # Page 2: GAD-7
1095
+ ########################################################################
1096
+ with gr.Row(visible=False) as page_2:
1097
+ with gr.Column():
1098
+ gr.Markdown("""## Pretest: GAD-7
1099
+ Over the last 2 weeks, how often have you been bothered by
1100
+ any of the following problems (0 = "Never", 3 = "Very often")?
1101
+ """)
1102
+ g1 = gr.Slider(0, 3, step=1, label="Feeling nervous, anxious, or on edge?")
1103
+ g2 = gr.Slider(0, 3, step=1, label="Not being able to stop or control worrying?")
1104
+ g3 = gr.Slider(0, 3, step=1, label="Worrying too much about different things?")
1105
+ g4 = gr.Slider(0, 3, step=1, label="Trouble relaxing?")
1106
+ g5 = gr.Slider(0, 3, step=1, label="Being so restless that it’s hard to sit still?")
1107
+ g6 = gr.Slider(0, 3, step=1, label="Becoming easily annoyed or irritable?")
1108
+ g7 = gr.Slider(0, 3, step=1, label="Feeling afraid as if something awful might happen?")
1109
+ gad_result = gr.HTML()
1110
+ finish_button = gr.Button("Finish")
1111
+
1112
+ ########################################################################
1113
+ # Page 3: Chatbot
1114
+ ########################################################################
1115
+ # Page 3a: Briefing/Instructions before Chatbot
1116
+ with gr.Row(visible=False) as page_3a:
1117
+ with gr.Column():
1118
+ gr.Markdown("## Briefing & Informed Consent")
1119
+ gr.Markdown("""
1120
+ By participating in this study, you will be asked to imagine yourself in various fictional scenarios
1121
+ and answer questions about your thoughts or feelings. Your data will remain anonymous and will be used
1122
+ solely for research purposes.
1123
+
1124
+ **If you consent to participate, please click 'Continue' below.**
1125
+ """)
1126
+ # Consent by pressing the button
1127
+ briefing_start_button = gr.Button("Continue")
1128
+
1129
+ # Page 3b: User Profile
1130
+ with gr.Row(visible=False) as page_3b:
1131
+ with gr.Column():
1132
+ gr.Markdown("## Tell Us About Yourself")
1133
+ gr.Markdown("""Great! During the course of this assessment you will be confronted with descriptions of fictional everyday situations. Please try to immerse yourself in these scenarios as if they were happening to you personally.
1134
+
1135
+ In order to provide you with situations that might be more relevant to you specifically,
1136
+ we need some general information about you. Don't worry, you will remain anonymous!
1137
+
1138
+ Please tell us your age, profession and one of your personal interests.""")
1139
+ age_input = gr.Textbox(label="Age", placeholder="Enter your age")
1140
+ profession_input = gr.Textbox(label="Profession", placeholder="Enter your profession")
1141
+ interest_input = gr.Textbox(label="One personal interest", placeholder="Enter a hobby or interest")
1142
+
1143
+ user_profile_button = gr.Button("Submit Profile")
1144
+ user_profile_output = gr.Markdown()
1145
+
1146
+ # Page 3: Chatbot Assessment
1147
+ with gr.Row(visible=False) as page_3:
1148
+ with gr.Column():
1149
+ gr.ChatInterface(type="messages",
1150
+ fn=new_chat_input,
1151
+ description= "Interact with the chatbot to start the assessment.",
1152
+ title="Chat Assessment",
1153
+ )
1154
+ # gr.Markdown("## Chatbot Assessment")
1155
+ # chatbot = gr.Chatbot(type="messages")
1156
+ # user_message = gr.Textbox(label="Your Message")
1157
+ # send_button = gr.Button("Send")
1158
+
1159
+ # def handle_chat(message, history):
1160
+ # global app_state # Use the global app_state
1161
+
1162
+ # # Call new_chat_input to process the user's message and get a response
1163
+ # response = new_chat_input(message, history)
1164
+
1165
+ # # Append the user's message and assistant's response to history
1166
+ # history.append({"role": "user", "content": message})
1167
+ # history.append({"role": "assistant", "content": response})
1168
+
1169
+ # return history # Return the updated history
1170
+
1171
+ # send_button.click(
1172
+ # fn=handle_chat,
1173
+ # inputs=[user_message, chatbot],
1174
+ # outputs=chatbot
1175
+ # )
1176
+
1177
+ # user_message.submit(
1178
+ # fn=handle_chat,
1179
+ # inputs=[user_message, chatbot],
1180
+ # outputs=chatbot
1181
+ # )
1182
+
1183
+ ######################################################################
1184
+ # Page 4: Usability Questionnaire
1185
+ ######################################################################
1186
+ # with gr.Row(visible=False) as page_4:
1187
+ # with gr.Column():
1188
+ # gr.Markdown("## Usability / Feedback")
1189
+ # gr.Markdown("""
1190
+ # Thank you for completing the assessment.
1191
+ # Please answer the following questions on a scale from 1 (= "Not at all") to 10 (= "Very much").
1192
+ # """)
1193
+ #
1194
+ # # Sliders/Textboxes
1195
+ # ease = gr.Slider(label="How easy was it to complete the assessment?", minimum=1, maximum=10, step=1)
1196
+ # clarity = gr.Slider(label="How clear were the instructions?", minimum=1, maximum=10, step=1)
1197
+ # engagement = gr.Slider(label="How engaging was the assessment experience?", minimum=1, maximum=10, step=1)
1198
+ # satisfaction = gr.Slider(label="How satisfied are you with this assessment?", minimum=1, maximum=10, step=1)
1199
+ # cognitive_load = gr.Slider(label="How mentally demanding was the assessment?", minimum=1, maximum=10, step=1)
1200
+ # comments = gr.Textbox(label="Additional Comments (Optional)", lines=4)
1201
+ #
1202
+ # submit_button = gr.Button("Submit")
1203
+ # output_message = gr.Markdown(visible=False)
1204
+ # link_message = gr.Markdown(visible=False)
1205
+ #
1206
+ # # You might have a separate local app_state:
1207
+ # usability_app_state = gr.BrowserState({"completed": False})
1208
+ #
1209
+ # # Link the "Submit" button to process_feedback
1210
+ # submit_button.click(
1211
+ # fn=process_feedback,
1212
+ # inputs=[ease, clarity, engagement, satisfaction, cognitive_load, comments, usability_app_state],
1213
+ # outputs=[output_message, link_message]
1214
+ # )
1215
+ #
1216
+ # # Display the Prolific link after feedback is submitted
1217
+ # submit_button.click(
1218
+ # fn=redirect_to_prolific,
1219
+ # inputs=None,
1220
+ # outputs=link_message
1221
+ # )
1222
+
1223
+ ######################################################################
1224
+ # Transition Logic
1225
+ ######################################################################
1226
+
1227
+ # 1) After finishing PHQ-9, go to GAD-7
1228
+ def show_gad7(*_):
1229
+ return gr.update(visible=False), gr.update(visible=True)
1230
+
1231
+ next_button.click(
1232
+ fn=process_phq9,
1233
+ inputs=[q1, q2, q3, q4, q5, q6, q7, q8, q9],
1234
+ outputs=phq_result
1235
+ )
1236
+ next_button.click(show_gad7, inputs=[], outputs=[page_1, page_2])
1237
+
1238
+
1239
+ # 2) After finishing GAD-7, go to Briefing Page
1240
+ def show_briefing(*_):
1241
+ return gr.update(visible=False), gr.update(visible=True)
1242
+
1243
+ finish_button.click(
1244
+ fn=process_gad7,
1245
+ inputs=[g1, g2, g3, g4, g5, g6, g7],
1246
+ outputs=gad_result,
1247
+ )
1248
+ finish_button.click(show_briefing, inputs=[], outputs=[page_2, page_3a])
1249
+
1250
+
1251
+ # 3) After Briefing, go to User Profile
1252
+ def show_user_profile(*_):
1253
+ return gr.update(visible=False), gr.update(visible=True)
1254
+
1255
+ briefing_start_button.click(show_user_profile, inputs=[], outputs=[page_3a, page_3b])
1256
+
1257
+
1258
+ # 4) After User Profile, go to Chatbot
1259
+ def show_chatbot_after_profile(age, profession, interest):
1260
+ global app_state
1261
+ # Debug inputs
1262
+ if not age or not profession or not interest:
1263
+ raise ValueError(f"Missing input values: Age={age}, Profession={profession}, Interest={interest}")
1264
+
1265
+ # Update app_state
1266
+ if app_state:
1267
+ if not app_state["standardized_data"].get("Age"):
1268
+ app_state["standardized_data"]["Age"] = age.strip()
1269
+ if not app_state["standardized_data"].get("Profession"):
1270
+ app_state["standardized_data"]["Profession"] = profession.strip()
1271
+ if not app_state["standardized_data"].get("Interests"):
1272
+ app_state["standardized_data"]["Interests"] = interest.strip()
1273
+
1274
+ # Check app_state updates
1275
+ if not app_state["standardized_data"]["Raw Age"] or not app_state["standardized_data"]["Raw Profession"] or not app_state["standardized_data"]["Raw Interests"]:
1276
+ raise ValueError(f"app_state['standardized_data'] not updated correctly: {app_state['standardized_data']}")
1277
+
1278
+ # Debugging output
1279
+ print(f"app_state at the end of show_chatbot_after_profile: {app_state}")
1280
+
1281
+ # Return Gradio updates
1282
+ return (
1283
+ gr.update(visible=False), # Hide profile page
1284
+ gr.update(visible=True), # Show chatbot page
1285
+ "Profile submitted successfully. Proceeding to the chatbot." # Feedback message
1286
+ )
1287
+
1288
+ def transition_to_chat(age, profession, interest):
1289
+ """
1290
+ Handles the transition from the profile page to the chatbot.
1291
+ Updates app_state with the user profile and ensures it's passed correctly.
1292
+ """
1293
+ global app_state
1294
+ # Update the app_state with the profile information
1295
+ app_state["standardized_data"]["Raw Age"] = age.strip()
1296
+ app_state["standardized_data"]["Raw Profession"] = profession.strip()
1297
+ app_state["standardized_data"]["Raw Interests"] = interest.strip()
1298
+ app_state["standardized_data"]["Age"] = age.strip()
1299
+ app_state["standardized_data"]["Profession"] = profession.strip()
1300
+ app_state["standardized_data"]["Interests"] = interest.strip()
1301
+
1302
+ # Log for debugging
1303
+ print(f"Updated app_state in transition_to_chat: {app_state}")
1304
+
1305
+ # Return UI updates and app_state for the chatbot page
1306
+ return (
1307
+ gr.update(visible=False), # Hide the profile page
1308
+ gr.update(visible=True), # Show the chatbot page
1309
+ "Profile submitted successfully. Proceeding to the chatbot.", # Confirmation message
1310
+ app_state
1311
+ )
1312
+
1313
+ def process_user_profile(age, profession, interest):
1314
+ """
1315
+ Handles user profile input and transitions to the chatbot.
1316
+ Combines app_state updates and UI transitions.
1317
+ """
1318
+ global app_state
1319
+
1320
+ # Step 1: Update app_state with user profile
1321
+ store_user_profile(age, profession, interest)
1322
+
1323
+ # Debugging log
1324
+ print("app_state after store_user_profile:", app_state)
1325
+
1326
+ # Step 2: Transition to Chatbot
1327
+ return (
1328
+ gr.update(visible=False), # Hide the profile page
1329
+ gr.update(visible=True), # Show the chatbot page
1330
+ "Profile submitted successfully. Proceeding to the chatbot.", # Confirmation message
1331
+ app_state
1332
+ )
1333
+
1334
+ user_profile_button.click(
1335
+ fn=process_user_profile,
1336
+ inputs=[age_input, profession_input, interest_input],
1337
+ outputs=[page_3b, page_3, user_profile_output]
1338
+ )
1339
+
1340
+ # 5) After chatbot is done, go to Usability (button initially hidden)
1341
+ def go_to_usability():
1342
+ return gr.update(visible=False), gr.update(visible=True)
1343
+
1344
+ # Transition to usability page after chatbot
1345
+ # chatbot_done.click(
1346
+ # fn=lambda: (gr.update(visible=False), gr.update(visible=True)),
1347
+ # inputs=None,
1348
+ # outputs=[page_3, page_4]
1349
+ # )
1350
+
1351
+ # 6) Finish usability
1352
+ # submit_button.click(
1353
+ # fn=process_feedback,
1354
+ # inputs=[ease, clarity, engagement, satisfaction, cognitive_load, comments, usability_app_state],
1355
+ # outputs=[output_message, link_message]
1356
+ # )
1357
+
1358
+ # Display the Prolific link after feedback is submitted
1359
+ # submit_button.click(
1360
+ # fn=redirect_to_prolific,
1361
+ # inputs=None,
1362
+ # outputs=link_message
1363
+ # )
1364
+
1365
+ app.launch(share=True)