mojakob commited on
Commit
06dcd2d
·
verified ·
1 Parent(s): b27da9c

Delete Chatbot_new.py

Browse files
Files changed (1) hide show
  1. Chatbot_new.py +0 -920
Chatbot_new.py DELETED
@@ -1,920 +0,0 @@
1
- import os
2
- import openai
3
- import random
4
- import pandas as pd
5
- import uuid
6
- import pickle
7
-
8
- # Module seeds
9
- context_types = {
10
- "Work/Professional": [
11
- "Working on a project or task",
12
- "Attending a meeting or briefing",
13
- "Collaborating with colleagues or team members",
14
- "Presenting a proposal or idea",
15
- "Responding to client or customer feedback",
16
- "Managing or resolving a workplace conflict",
17
- "Negotiating a contract or agreement",
18
- "Performing routine tasks",
19
- "Handling unexpected challenges"
20
- ],
21
- "Social": [
22
- "Engaging in a social gathering or event",
23
- "Having a one-on-one conversation with a friend or acquaintance",
24
- "Participating in a group activity or hobby",
25
- "Sharing ideas or opinions in a casual discussion",
26
- "Dealing with a social conflict or disagreement",
27
- "Networking at a professional or social event"
28
- ],
29
- "Physical Activity": [
30
- "Participating in a team sport or physical competition",
31
- "Engaging in an outdoor activity",
32
- "Training or practicing with a coach or instructor",
33
- "Competing in a tournament or race",
34
- "Engaging in a personal fitness routine or challenge",
35
- "Performing a physical task that requires coordination or teamwork"
36
- ],
37
- "Reflection": [
38
- "Reflecting on a past decision or action",
39
- "Planning future goals or strategies",
40
- "Evaluating personal or professional progress",
41
- "Contemplating a challenging situation or conflict",
42
- "Revisiting a difficult conversation or interaction",
43
- "Assessing personal strengths, weaknesses, or skills"
44
- ],
45
- "Educational": [
46
- "Participating in a class, lecture, or seminar",
47
- "Collaborating on a study project or research",
48
- "Receiving feedback from a teacher or mentor",
49
- "Preparing for or taking an exam",
50
- "Engaging in group study or discussion",
51
- "Presenting academic work or research findings"
52
- ],
53
- "Creative": [
54
- "Working on a creative project",
55
- "Collaborating with others on a creative endeavor",
56
- "Receiving feedback on a creative piece",
57
- "Presenting a creative work to an audience",
58
- "Brainstorming or ideating new concepts",
59
- "Experimenting with new techniques or styles"
60
- ]
61
- }
62
-
63
- interaction_types = {
64
- "Authority Feedback": [
65
- "Receiving feedback or critique from a supervisor, boss, or mentor",
66
- "Listening to advice or guidance from a coach or teacher",
67
- "Engaging in a performance review or evaluation",
68
- "Responding to managerial decisions or directives"
69
- ],
70
- "Peer Reaction": [
71
- "Receiving input, advice, or reactions from a colleague, friend, or teammate",
72
- "Discussing ideas or opinions with peers in a group setting",
73
- "Addressing concerns, compliments, or criticisms from a peer",
74
- "Collaborating on a task or project with equal responsibility"
75
- ],
76
- "Group Dynamics": [
77
- "Participating in a group discussion or brainstorming session",
78
- "Leading or following in a team activity or project",
79
- "Managing group feedback or collective opinions",
80
- "Navigating differing opinions, conflicts, or agreements within a group"
81
- ],
82
- "Self-Reflection": [
83
- "Analyzing personal decisions, actions, or behaviors",
84
- "Contemplating improvements or changes based on past experiences",
85
- "Reflecting on feedback received from others",
86
- "Re-evaluating personal goals, priorities, or values"
87
- ],
88
- "Creative Feedback": [
89
- "Seeking opinions or critiques on a creative project from peers or mentors",
90
- "Engaging in a discussion about a creative piece's direction or style",
91
- "Presenting creative work to a group and receiving diverse reactions"
92
- ],
93
- "Social Participation": [
94
- "Engaging in a group activity or event related to a hobby or interest",
95
- "Discussing or sharing personal achievements or interests in a social setting",
96
- "Navigating group dynamics during a leisure activity or social gathering"
97
- ]
98
- }
99
-
100
- tones = ["Positive", "Negative"]
101
-
102
- actions_events = {
103
- "Work/Professional": [
104
- "Receiving feedback",
105
- "Observing reactions",
106
- "Presenting ideas",
107
- "Responding to a situation"
108
- ],
109
- "Creative/Personal Projects": [
110
- "Completing a creative project",
111
- "Seeking feedback",
112
- "Engaging in competition",
113
- "Sharing achievements"
114
- ],
115
- "Social/Leisure Activities": [
116
- "Socializing at an event",
117
- "Participating in a hobby",
118
- "Competing in a friendly match",
119
- "Celebrating an achievement"
120
- ]
121
- }
122
-
123
- outcomes_reveals = {
124
- "Feedback Becomes More Detailed": [
125
- "The feedback received becomes more specific, highlighting both strengths and weaknesses",
126
- "Additional information is provided about how your work or actions have been perceived"
127
- ],
128
- "Reactions Evolve": [
129
- "Others in the group or interaction begin to share their thoughts, leading to a broader or more complex discussion",
130
- "A different or unexpected perspective is introduced, challenging initial reactions or assumptions"
131
- ],
132
- "Situation Becomes More Complex": [
133
- "A new element or complication is introduced, adding layers to the initial problem or challenge",
134
- "Additional context or background information is revealed, shifting the interpretation of the situation"
135
- ],
136
- "Personal Reflection Deepens": [
137
- "You start to see patterns or broader implications of your actions or decisions",
138
- "A realization or new insight occurs that changes how you view the initial event or scenario"
139
- ]
140
- }
141
-
142
- def interpret_response(user_input, options_text, user_state):
143
- prompt = f"""
144
- You are tasked with interpreting user responses to multiple-choice questions.
145
- Options provided:
146
- {options_text}
147
- User's response: "{user_input}"
148
- Identify the matching option number (e.g., '1', '2', etc.) based on the options.
149
- Respond with the option number only.
150
- If the user's response is unclear or doesn't match any option, respond with "Please clarify.".
151
- """
152
-
153
- response = openai.chat.completions.create(
154
- model="gpt-4o-mini",
155
- messages=[{"role": "user", "content": prompt}],
156
- temperature=0.3,
157
- max_tokens=5
158
- )
159
-
160
- assistant_response = response.choices[0].message.content.strip()
161
- print(f"interpret_result() output: {assistant_response}")
162
-
163
- # Validate the response
164
- option_numbers = [str(i) for i in range(1, len(options_text.split('\n')) + 1)]
165
- if assistant_response in option_numbers:
166
- return assistant_response
167
- elif assistant_response.lower() == "please clarify.":
168
- return "Please clarify."
169
- else:
170
- return "Invalid response."
171
-
172
- def standardize_response(question, response):
173
- prompt = f"""
174
- Standardize the following user response for analysis:
175
- Question: "{question}"
176
- User Response: "{response}"
177
- Extract the key information relevant to the question and provide it as a standardized response.
178
- Examples:
179
- - Age: "I'm 25 years old" → "25"
180
- - Profession: "I work as a teacher" → "teacher"
181
- - Interests: "I enjoy hiking and painting" → "hiking, painting"
182
- Respond with only the standardized response. Do not include any additional text or explanations.
183
- """
184
-
185
- response = openai.chat.completions.create(
186
- model="gpt-4o-mini",
187
- messages=[
188
- {"role": "system", "content": "You are an assistant standardizing user responses for data analysis."},
189
- {"role": "user", "content": prompt}
190
- ],
191
- temperature=0.1
192
- )
193
-
194
- # Extract and validate the standardized response
195
- standardized_response = response.choices[0].message.content.strip()
196
- print(f"standardize_result() output: {standardized_response}")
197
-
198
- if standardized_response.lower().startswith("standardized response:"):
199
- standardized_response = standardized_response.split(":")[1].strip()
200
-
201
- # Validate the format based on the question type
202
- if "age" in question.lower() and standardized_response.isdigit():
203
- return int(standardized_response), user_state
204
- elif "profession" in question.lower():
205
- return standardized_response
206
- elif "interests" in question.lower():
207
- return standardized_response
208
- else:
209
- return standardized_response
210
-
211
- # def load_vignette_data(vignette_number, user_state):
212
- # """
213
- # Fetches the vignette and reveal for a given participant from the Excel file.
214
- # Arguments:
215
- # - vignette_number: The specific vignette number (1 to 16)
216
- # Returns:
217
- # - vignette_text: The text of the vignette for the selected participant
218
- # - tone: The tone associated with the vignette (e.g., Positive or Negative)
219
- # - first_reveal: The first reveal for the given vignette
220
- # """
221
-
222
- # # Load the Excel data
223
- # data = pd.read_excel("assessment_data.xlsx")
224
-
225
- # # Select a random user ID if it's not set yet
226
- # if selected_user_id is None:
227
- # user_ids = data['User ID'].unique()
228
- # if len(user_ids) == 0:
229
- # print("No User IDs found in the assessment data.")
230
- # return None, None, None
231
- # selected_user_id = random.choice(user_ids)
232
-
233
- # # Filter the data based on selected_user_id and vignette_number
234
- # user_data = data[(data['User ID'] == selected_user_id) & (data['Vignette Number'] == vignette_number)]
235
-
236
- # if not user_data.empty:
237
- # vignette_text = user_data['Vignette'].values[0]
238
- # tone = user_data['Tone'].values[0]
239
- # first_reveal = user_data['First Reveal'].values[0]
240
-
241
- # return vignette_text, tone, first_reveal
242
- # else:
243
- # print(f"No data found for user_id {selected_user_id} and vignette {vignette_number}")
244
- # return None, None, None
245
-
246
- # Function to generate the vignette
247
- def generate_vignette(chat_history, topic_choice, desired_tone, user_state):
248
- # Extract user profile from standardized data
249
- user_profile = user_state.get("standardized_data", {})
250
- user_age = user_profile.get("Age", "Unknown")
251
- user_profession = user_profile.get("Profession", "Unknown")
252
- user_interests = user_profile.get("Interests", "Unknown")
253
-
254
- # Build the prompt to select modules and generate the vignette
255
- prompt = f"""
256
- Based on the user's profile and preferences, create a vignette tailored to the following details:
257
- - Age: {user_age}
258
- - Profession: {user_profession}
259
- - Interests: {user_interests}
260
- - Chat history: {chat_history}
261
- Select the most appropriate modules from these categories to create a relatable situation:
262
- - Context type (Work/Professional, Social, Physical Activity, Reflection, Educational, Creative)
263
- - Interaction type (Authority Feedback, Peer Reaction, Group Dynamics, Creative Feedback, Social Participation, Conflict/Disagreement, Support Interaction)
264
- - Tone (Must be either clearly Positive or clearly Negative!)
265
- - Action/Event (Receiving Feedback, Observing Reactions, Presenting Ideas, Responding to a Situation, Completing a Creative Project, Seeking Feedback, Engaging in Competition, Sharing Achievements, Socializing at an Event, Competing in a Friendly Match, Celebrating an Achievement, Providing/Receiving Emotional Support, Conflict Resolution, Handling Unexpected Situations, Facing Disapproval)
266
- Use these selected modules to generate a vignette for a psychological assessment.
267
- Guidelines:
268
- - Analyze the conversation history to understand the user's age, profession, and interests.
269
- - **The user has chosen topic {topic_choice}:**
270
- - **If the user chose '1', focus on a situation related to their profession.**
271
- - **If the user chose '2', focus on a situation related to their personal interests.**
272
- - **If the user chose '3', focus on a situation related to their most recent input in the {chat_history}.**
273
- Only select one module per category.
274
-
275
- The selected tone should clearly shape the atmosphere of the scenario and remain consistent throughout the vignette.
276
-
277
- Avoid mixed tones.
278
-
279
- Keep the vignettes fresh and varied.
280
-
281
- Consider all clarifying information the user has provided throughout the {chat_history} when creating a vignette.
282
- Do not include the module names or categories in the output.
283
- Only provide the vignette text and do not include phrases like "Sure", "Here is your vignette", or any other extra text.
284
- Ensure that the vignette is directly related to the user's profile and context. **Focus on describing the external events without including any inner reflections, thoughts, or feelings.**
285
- **Do not mention how the user feels or thinks about the situation.**
286
- Describe the vignette in a second-person view.
287
- Keep the vignette concise, under a 50-token limit.
288
- Use neutral and professional but simple language suitable for a psychological assessment.
289
- Do not include any personal identifying information.
290
- """
291
-
292
- # Prepare the messages for the API call
293
- messages = [
294
- {"role": "system", "content": """
295
- You are tasked with selecting appropriate modules and generating a standardized vignette for a psychological assessment.
296
- The vignette should assess attribution styles across three dimensions: Internal-External, Stable-Unstable, and Global-Specific.
297
- """},
298
- {"role": "user", "content": prompt}
299
- ]
300
-
301
- # Append the conversation history to the messages
302
- for message in chat_history:
303
- messages.append(message)
304
-
305
- # Call the OpenAI API
306
- response = openai.chat.completions.create(
307
- model="gpt-4o-mini",
308
- messages=messages,
309
- temperature=0.3
310
- )
311
-
312
-
313
-
314
- # Extract the response content
315
- content = response.choices[0].message.content.strip()
316
-
317
- vignette = content
318
- tone = desired_tone
319
- return vignette, tone
320
-
321
- # Function to generate internal-external options
322
- def generate_internal_external_options(chat_history, vignette, user_state):
323
- prompt = f"""
324
- Based on the following scenario:
325
- "{vignette}"
326
- Provide two possible causes for why this situation occurred, focusing on **internal** and **external** factors that are directly related to the scenario.
327
- Ensure each explanation is **concise** and captures the essence of an internal or external cause, without excessive detail. The causes should be easy for the user to understand, without overwhelming them with too many specifics.
328
- Describe these explanations from the user's point of view, making them relatable and personal.
329
- Present the options in the following format exactly:
330
- 1. [Specific internal reason]
331
- 2. [Specific external reason]
332
- Do not include any additional text or explanation.
333
- Use simple, but neutral and professional language suitable for a psychological assessment.
334
- """
335
-
336
- response = openai.chat.completions.create(
337
- model="gpt-4o-mini",
338
- temperature=0.3,
339
- messages=[
340
- {"role": "system", "content": "You are assisting in generating attribution options based on a given scenario for a psychological assessment. Directly address the user. Present a single brief sentence for each option."},
341
- {"role": "user", "content": prompt},
342
- ],
343
- )
344
-
345
-
346
- return response.choices[0].message.content.strip()
347
-
348
- # Function to generate stable-unstable and global-specific options
349
- def generate_stable_unstable_options(chat_history, vignette, previous_choice, user_state):
350
- # Determine the attribution type based on the user's previous choice
351
- formatted_history = []
352
- for user_msg, assistant_msg in chat_history:
353
- if user_msg:
354
- formatted_history.append({"role": "user", "content": user_msg})
355
- if assistant_msg:
356
- formatted_history.append({"role": "assistant", "content": assistant_msg})
357
-
358
- if previous_choice == '1':
359
- attribution_type = 'Internal'
360
- elif previous_choice == '2':
361
- attribution_type = 'External'
362
- else:
363
- attribution_type = 'Internal' # Default to Internal if unexpected input
364
-
365
- prompt = f"""
366
- Based on the following scenario:
367
- "{vignette}"
368
- The user's previous attribution was of type "{attribution_type}".
369
- Now generate four distinct short statements explaining what might have led to this situation, covering:
370
- 1) Stable & Global
371
- 2) Stable & Specific
372
- 3) Unstable & Global
373
- 4) Unstable & Specific
374
- Ensure the response includes **exactly four options**, each on a new line.
375
- Do not add any further text or comments.
376
- Present the options in exactly the following format:
377
- 1. [Stable and Global] - Provide a concise, {attribution_type.lower()} cause that is consistent over time and impacts multiple areas.
378
- 2. [Stable and Specific] - Provide a concise, {attribution_type.lower()} cause that is consistent but affects only this situation.
379
- 3. [Unstable and Global] - Provide a concise, {attribution_type.lower()} cause that is temporary but has broader implications.
380
- 4. [Unstable and Specific] - Provide a concise, {attribution_type.lower()} cause that is temporary and limited to this particular situation.
381
- Each option should be concise and focus on the main idea without including excessive detail. Ensure the options are unique and clear, without overwhelming the user.
382
-
383
- Only present the four options without explicitly stating the associated dimensions (i.e., Stable, Unstable, Global, Specific). The options should be in simple sentences that are easy to understand.
384
- Ensure the options are directly relevant to the scenario, specific, and reflect the {attribution_type} attribution selected by the user.
385
- Use simple, but neutral and professional language suitable for a psychological assessment.
386
- Do not include any additional text or explanation.
387
- Do not include any personal identifying information.
388
- """
389
-
390
- messages = [
391
- {"role": "system", "content": "You are a helpful assistant."},
392
- {"role": "user", "content": prompt},
393
- ] + formatted_history # Append the formatted chat history
394
-
395
- response = openai.chat.completions.create(
396
- model="gpt-4o-mini",
397
- messages=messages,
398
- temperature=0.3,
399
- max_tokens=300
400
- )
401
-
402
- return response.choices[0].message.content.strip()
403
-
404
-
405
- # First reveal
406
- def generate_first_reveal(vignette, user_state):
407
- prompt = f"""
408
- Based on the following scenario:
409
- "{vignette}"
410
- Present a first reveal that adds complexity to the situation. The reveal should provide new information that challenges the user's previous attributions.
411
- Use neutral and professional language suitable for a psychological assessment.
412
- Keep the reveal concise.
413
-
414
- Only provide the vignette text and do not include phrases like "Sure", "Here is your vignette", or any other extra text.
415
- """
416
-
417
- response = openai.chat.completions.create(
418
- model="gpt-4o-mini",
419
- temperature=0.3,
420
- messages=[
421
- {"role": "system", "content": "You are assisting in generating attribution options based on a given scenario for a psychological assessment. Directly address the user. Present a single brief sentence for eacht option."},
422
- {"role": "user", "content": prompt},
423
- ],
424
- )
425
- return response.choices[0].message.content.strip()
426
-
427
- # Second reveal
428
- def generate_second_reveal(vignette, first_reveal):
429
- prompt = f"""
430
- Based on the following scenario:
431
- "{vignette}"
432
- And the first reveal:
433
- "{first_reveal}"
434
- Present a second reveal that significantly alters the user's interpretation of the situation. The reveal should provide additional context or details that prompt a re-evaluation of the initial attribution.
435
- Use neutral and professional language suitable for a psychological assessment.
436
- Keep the reveal concise.
437
- Only provide the vignette text and do not include phrases like "Sure", "Here is your vignette", or any other extra text.
438
- """
439
-
440
- response = openai.chat.completions.create(
441
- model="gpt-4o-mini",
442
- temperature=0.3,
443
- messages=[
444
- {"role": "system", "content": "You are assisting in generating attribution options based on a given scenario for a psychological assessment. Directly address the user. Present a single brief sentence for eacht option."},
445
- {"role": "user", "content": prompt},
446
- ],
447
- )
448
- return response.choices[0].message.content.strip()
449
-
450
-
451
- # Save to Excel
452
- def save_data_to_excel(data):
453
- # Read the existing Excel file
454
- df = pd.read_excel('assessment_data.xlsx')
455
-
456
- # Convert the data dictionary to a DataFrame
457
- new_entry = pd.DataFrame([data])
458
-
459
- # Append the new entry to the DataFrame
460
- df = pd.concat([df, new_entry], ignore_index=True)
461
-
462
- # Save the updated DataFrame back to the Excel file
463
- df.to_excel('assessment_data.xlsx', index=False)
464
-
465
- # Excel for control condition
466
- def save_data_to_control_excel(data):
467
- # Read the existing Excel file
468
- df = pd.read_excel('assessment_data_nonpersonal.xlsx')
469
-
470
- # Convert the data dictionary to a DataFrame
471
- new_entry = pd.DataFrame([data])
472
-
473
- # Append the new entry to the DataFrame
474
- df = pd.concat([df, new_entry], ignore_index=True)
475
-
476
- # Save the updated DataFrame back to the Excel file
477
- df.to_excel('assessment_data_nonpersonal.xlsx', index=False)
478
-
479
-
480
- # Save to Pickle
481
- def save_data_to_pickle(data):
482
- # Read the existing Excel file
483
- df = pd.read_pickle(pickle_file)
484
-
485
- # Convert the data dictionary to a DataFrame
486
- new_entry = pd.DataFrame([data])
487
-
488
- # Append the new entry to the DataFrame
489
- df = pd.concat([df, new_entry], ignore_index=True)
490
-
491
- # Save the updated DataFrame back to the Excel file
492
- df.to_pickle(pickle_file)
493
-
494
- # Pickle for control condition
495
- def save_data_to_control_pickle(data):
496
- # Read the existing Excel file
497
- df = pd.read_pickle(pickle_file2)
498
-
499
- # Convert the data dictionary to a DataFrame
500
- new_entry = pd.DataFrame([data])
501
-
502
- # Append the new entry to the DataFrame
503
- df = pd.concat([df, new_entry], ignore_index=True)
504
-
505
- # Save the updated DataFrame back to the Excel file
506
- df.to_pickle(pickle_file2)
507
-
508
-
509
- def chat(fn_print, fn_input):
510
- print("test")
511
- conversation_history = []
512
- user_responses = [] # List to store raw user responses
513
- standardized_data = {} # Dictionary to store standardized data for the Excel file
514
- stage = "start"
515
- user_id = str(uuid.uuid4()) # Generate a unique user ID
516
- topic_choice = None
517
-
518
- vignette_tones = ['Positive', 'Negative', 'Negative', 'Positive'] # Two positive and two negative
519
- vignette_counter = 1 # To keep track of the current vignette number
520
-
521
- while True:
522
- if stage == "start":
523
- fn_print("Welcome! Before we begin, please note that your responses will be used for research purposes. Your data will be kept confidential and anonymous.")
524
- options_text = "Yes\nNo"
525
- while True:
526
- user_input = fn_input("Do you consent to participate? (yes/no): ")
527
- user_responses.append({'stage': 'consent', 'response': user_input})
528
- conversation_history.append({"role": "user", "content": user_input})
529
- mapped_option = interpret_response(user_input, options_text)
530
- if mapped_option == '1' or user_input.strip().lower() in ['yes', 'y']:
531
- standardized_data['Consent'] = 'Yes'
532
- stage = "user_profile"
533
- break
534
- elif mapped_option == '2' or user_input.strip().lower() in ['no', 'n']:
535
- standardized_data['Consent'] = 'No'
536
- fn_print("Thank you for your time. Goodbye!")
537
- return conversation_history, user_responses # Exit the chat
538
- else:
539
- fn_print("Sorry, I couldn't understand your response. Please answer 'yes' or 'no'.")
540
-
541
- stage = "user_profile"
542
-
543
- elif stage == "user_profile":
544
- fn_print("""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.
545
-
546
- In order to provide you with situations that might be more relevant to you specifically,
547
- we need some general information about you. Don't worry, you will remain anonymous!
548
-
549
- Please tell us your age, profession and one of your personal interests.""")
550
- user_profile_response = fn_input("You: ")
551
- user_responses.append({'stage': 'user_profile', 'response': user_profile_response})
552
- conversation_history.append({"role": "user", "content": user_profile_response})
553
-
554
- standardized_data['Age'] = standardize_response("Please extract the user's age from the following input.", user_profile_response)
555
- standardized_data['Profession'] = standardize_response("Please extract the user's profession from the following input.", user_profile_response)
556
- standardized_data['Interests'] = standardize_response("Please extract the user's interests from the following input.", user_profile_response)
557
-
558
- stage = "topic_choice"
559
-
560
- elif stage == "topic_choice":
561
- fn_print("Let's create a scenario for you.")
562
- fn_print("Which topic would you prefer?")
563
- fn_print("1. A situation related to your profession.")
564
- fn_print("2. A situation related to your personal interests.")
565
- options_text = "1. A situation related to your profession.\n2. A situation related to your personal interests."
566
- while True:
567
- user_input = fn_input("You: ")
568
- user_responses.append({'stage': 'topic_choice', 'response': user_input})
569
- conversation_history.append({"role": "user", "content": user_input})
570
- mapped_option = interpret_response(user_input, options_text)
571
- if mapped_option in ['1', '2']:
572
- topic_choice_response = mapped_option
573
- standardized_data['Topic Choice'] = topic_choice_response
574
- topic_choice = topic_choice_response
575
- stage = "vignette"
576
- break
577
- else:
578
- fn_print("Sorry, I couldn't understand your response. Could you please specify your choice?")
579
-
580
- elif stage == "vignette":
581
- if vignette_counter > 4:
582
- # All vignettes have been presented
583
- fn_print("You have completed all scenarios. Thank you for your participation! You will now be redirected to Prolific. Please don't close the browser yet. Goodbye!")
584
- save_data_to_excel(standardized_data)
585
- fn_print(f"Total vignettes presented: {vignette_counter - 1}")
586
- break
587
-
588
- # Determine the desired tone for the current vignette
589
- desired_tone = vignette_tones[vignette_counter - 1]
590
-
591
- vignette, tone = generate_vignette(conversation_history, topic_choice, desired_tone)
592
- if vignette is None:
593
- fn_print("There was an error generating the vignette. Exiting the assessment.")
594
- break
595
-
596
- fn_print("Alright, please imagine you are witnessing the following scene:")
597
- fn_print(f"Chatbot: {vignette}")
598
- conversation_history.append({"role": "assistant", "content": vignette})
599
- user_responses.append({'stage': 'vignette', 'content': vignette, 'tone': tone})
600
-
601
- # Temporarily store the vignette and tone with a unique key per vignette
602
- standardized_data[f'Vignette{vignette_counter}'] = vignette
603
- standardized_data[f'Tone{vignette_counter}'] = tone
604
-
605
- stage = "vignette_usability_assessment"
606
-
607
- elif stage == "vignette_usability_assessment":
608
- fn_print(f"Vignette {vignette_counter} Usability Assessment:")
609
- fn_print("On a scale from 1 to 10, how relevant, immersive, or relatable is the depicted scenario to you personally? (1 = not at all, 10 = completely)")
610
- relevance_rating = fn_input("You: ")
611
- user_responses.append({'stage': 'vignette_usability_assessment', 'response': relevance_rating})
612
- conversation_history.append({"role": "user", "content": relevance_rating})
613
-
614
- # Store the initial relevance rating if not already stored
615
- if f'Initial Relevance Rating{vignette_counter}' not in standardized_data:
616
- standardized_data[f'Initial Relevance Rating{vignette_counter}'] = int(relevance_rating)
617
-
618
- if int(relevance_rating) >= 7:
619
- # Accept the vignette
620
- standardized_data[f'Vignette{vignette_counter}'] = vignette
621
- standardized_data[f'Tone{vignette_counter}'] = tone
622
- # Store the final relevance rating
623
- standardized_data[f'Final Relevance Rating{vignette_counter}'] = int(relevance_rating)
624
- stage = "internal_external"
625
- else:
626
- # Ask for further clarification
627
- fn_print("I'm sorry to hear that the scenario wasn't quite fitting. Could you please provide more details about your specific context, so we can come up with a better one?")
628
- additional_info = fn_input("You: ")
629
- user_responses.append({'stage': 'additional_info', 'response': additional_info})
630
- conversation_history.append({"role": "user", "content": additional_info})
631
- # Use the additional info to regenerate the vignette
632
-
633
- stage = "vignette_regeneration"
634
-
635
- elif stage == "vignette_regeneration":
636
- # Use the additional info in the conversation history to regenerate the vignette
637
- vignette, tone = generate_vignette(conversation_history, topic_choice, desired_tone)
638
- fn_print("Okay, let's try again. Please imagine you are witnessing the following scene:")
639
- fn_print(f"Chatbot: {vignette}")
640
- conversation_history.append({"role": "assistant", "content": vignette})
641
- user_responses.append({'stage': 'vignette_regenerated', 'content': vignette, 'tone': tone})
642
- # Temporarily store the new vignette and tone
643
- standardized_data[f'Vignette{vignette_counter}'] = vignette
644
- standardized_data[f'Tone{vignette_counter}'] = tone
645
-
646
- # Go back to usability assessment
647
- stage = "vignette_usability_assessment"
648
-
649
- elif stage == "internal_external":
650
- options_text = generate_internal_external_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'])
651
- fn_print("Based on the scenario above, which of the following explanations do you think is most likely?:")
652
- fn_print(f"Options:\n{options_text}")
653
- while True:
654
- user_input = fn_input("Your explanation: ")
655
- user_responses.append({'stage': 'internal_external', 'options': options_text, 'response': user_input})
656
- conversation_history.append({"role": "user", "content": user_input})
657
- mapped_option = interpret_response(user_input, options_text)
658
- if mapped_option in ['1', '2']:
659
- explanation_response = mapped_option
660
- break
661
- else:
662
- fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
663
- # Store the initial internal/external attribution numerically
664
- if explanation_response == '1':
665
- standardized_data[f'Initial Internal{vignette_counter}'] = 1
666
- standardized_data[f'Initial External{vignette_counter}'] = 0
667
- elif explanation_response == '2':
668
- standardized_data[f'Initial Internal{vignette_counter}'] = 0
669
- standardized_data[f'Initial External{vignette_counter}'] = 1
670
- else:
671
- standardized_data[f'Initial Internal{vignette_counter}'] = None
672
- standardized_data[f'Initial External{vignette_counter}'] = None
673
-
674
-
675
- stage = "stable_unstable_global_specific"
676
-
677
- elif stage == "stable_unstable_global_specific":
678
- previous_choice = explanation_response
679
- options_text = generate_stable_unstable_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'], previous_choice)
680
- fn_print("Now, considering your previous choice, please select which option best explains the situation:")
681
- fn_print(f"Options:\n{options_text}")
682
- while True:
683
- user_input = fn_input("Your explanation: ")
684
- user_responses.append({'stage': 'stable_unstable_global_specific', 'options': options_text, 'response': user_input})
685
- conversation_history.append({"role": "user", "content": user_input})
686
- mapped_option = interpret_response(user_input, options_text)
687
- if mapped_option in ['1', '2', '3', '4']:
688
- explanation_stable_unstable_response = mapped_option
689
- break
690
- else:
691
- fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
692
- # Store the initial stable/unstable and global/specific attributions numerically
693
- if explanation_stable_unstable_response == '1':
694
- standardized_data[f'Initial Stable{vignette_counter}'] = 1
695
- standardized_data[f'Initial Unstable{vignette_counter}'] = 0
696
- standardized_data[f'Initial Global{vignette_counter}'] = 1
697
- standardized_data[f'Initial Specific{vignette_counter}'] = 0
698
- elif explanation_stable_unstable_response == '2':
699
- standardized_data[f'Initial Stable{vignette_counter}'] = 1
700
- standardized_data[f'Initial Unstable{vignette_counter}'] = 0
701
- standardized_data[f'Initial Global{vignette_counter}'] = 0
702
- standardized_data[f'Initial Specific{vignette_counter}'] = 1
703
- elif explanation_stable_unstable_response == '3':
704
- standardized_data[f'Initial Stable{vignette_counter}'] = 0
705
- standardized_data[f'Initial Unstable{vignette_counter}'] = 1
706
- standardized_data[f'Initial Global{vignette_counter}'] = 1
707
- standardized_data[f'Initial Specific{vignette_counter}'] = 0
708
- elif explanation_stable_unstable_response == '4':
709
- standardized_data[f'Initial Stable{vignette_counter}'] = 0
710
- standardized_data[f'Initial Unstable{vignette_counter}'] = 1
711
- standardized_data[f'Initial Global{vignette_counter}'] = 0
712
- standardized_data[f'Initial Specific{vignette_counter}'] = 1
713
- else:
714
- standardized_data[f'Initial Stable{vignette_counter}'] = None
715
- standardized_data[f'Initial Unstable{vignette_counter}'] = None
716
- standardized_data[f'Initial Global{vignette_counter}'] = None
717
- standardized_data[f'Initial Specific{vignette_counter}'] = None
718
-
719
- stage = "first_reveal"
720
-
721
- elif stage == "first_reveal":
722
- first_reveal = generate_first_reveal(vignette)
723
- fn_print("Alright, noted. Now, please imagine the following:")
724
- fn_print(f"Chatbot: {first_reveal}")
725
- conversation_history.append({"role": "assistant", "content": first_reveal})
726
- user_responses.append({'stage': 'first_reveal', 'content': first_reveal})
727
- standardized_data[f'First Reveal{vignette_counter}'] = first_reveal
728
- stage = "internal_external_reassessment"
729
-
730
- elif stage == "internal_external_reassessment":
731
- options_text = generate_internal_external_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'])
732
- fn_print("Considering these new developments, please select which of these options seems more likely to you:")
733
- fn_print(f"Options:\n{options_text}")
734
- while True:
735
- user_input = fn_input("Your explanation: ")
736
- user_responses.append({'stage': 'internal_external_reassessment', 'options': options_text, 'response': user_input})
737
- conversation_history.append({"role": "user", "content": user_input})
738
- mapped_option = interpret_response(user_input, options_text)
739
- if mapped_option in ['1', '2']:
740
- assessment_internal_external_response = mapped_option
741
- break
742
- else:
743
- fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
744
-
745
- # Store the reassessment internal/external attribution numerically
746
- if assessment_internal_external_response == '1':
747
- standardized_data[f'Reassessment Internal{vignette_counter}'] = 1
748
- standardized_data[f'Reassessment External{vignette_counter}'] = 0
749
- elif assessment_internal_external_response == '2':
750
- standardized_data[f'Reassessment Internal{vignette_counter}'] = 0
751
- standardized_data[f'Reassessment External{vignette_counter}'] = 1
752
- else:
753
- standardized_data[f'Reassessment Internal{vignette_counter}'] = None
754
- standardized_data[f'Reassessment External{vignette_counter}'] = None
755
-
756
- stage = "stable_unstable_global_specific_reassessment"
757
-
758
- elif stage == "stable_unstable_global_specific_reassessment":
759
- previous_choice = assessment_internal_external_response
760
- options_text = generate_stable_unstable_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'], previous_choice)
761
- fn_print("Now, based on your previous choice, once again select, which option best explains the situation:")
762
- fn_print(f"Options:\n{options_text}")
763
- while True:
764
- user_input = fn_input("Your explanation: ")
765
- user_responses.append({'stage': 'stable_unstable_global_specific_reassessment', 'options': options_text, 'response': user_input})
766
- conversation_history.append({"role": "user", "content": user_input})
767
- mapped_option = interpret_response(user_input, options_text)
768
- if mapped_option in ['1', '2', '3', '4']:
769
- assessment_stable_unstable_response = mapped_option
770
- break
771
- else:
772
- fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
773
-
774
- # Store the reassessment stable/unstable and global/specific attributions numerically
775
- if assessment_stable_unstable_response == '1':
776
- standardized_data[f'Reassessment Stable{vignette_counter}'] = 1
777
- standardized_data[f'Reassessment Unstable{vignette_counter}'] = 0
778
- standardized_data[f'Reassessment Global{vignette_counter}'] = 1
779
- standardized_data[f'Reassessment Specific{vignette_counter}'] = 0
780
- elif assessment_stable_unstable_response == '2':
781
- standardized_data[f'Reassessment Stable{vignette_counter}'] = 1
782
- standardized_data[f'Reassessment Unstable{vignette_counter}'] = 0
783
- standardized_data[f'Reassessment Global{vignette_counter}'] = 0
784
- standardized_data[f'Reassessment Specific{vignette_counter}'] = 1
785
- elif assessment_stable_unstable_response == '3':
786
- standardized_data[f'Reassessment Stable{vignette_counter}'] = 0
787
- standardized_data[f'Reassessment Unstable{vignette_counter}'] = 1
788
- standardized_data[f'Reassessment Global{vignette_counter}'] = 1
789
- standardized_data[f'Reassessment Specific{vignette_counter}'] = 0
790
- elif assessment_stable_unstable_response == '4':
791
- standardized_data[f'Reassessment Stable{vignette_counter}'] = 0
792
- standardized_data[f'Reassessment Unstable{vignette_counter}'] = 1
793
- standardized_data[f'Reassessment Global{vignette_counter}'] = 0
794
- standardized_data[f'Reassessment Specific{vignette_counter}'] = 1
795
- else:
796
- standardized_data[f'Reassessment Stable{vignette_counter}'] = None
797
- standardized_data[f'Reassessment Unstable{vignette_counter}'] = None
798
- standardized_data[f'Reassessment Global{vignette_counter}'] = None
799
- standardized_data[f'Reassessment Specific{vignette_counter}'] = None
800
-
801
- stage = "second_reveal"
802
-
803
- elif stage == "second_reveal":
804
- second_reveal = generate_second_reveal(vignette, first_reveal)
805
- fn_print("Okay. Finally, please imagine this:")
806
- fn_print(f"Chatbot: {second_reveal}")
807
- conversation_history.append({"role": "assistant", "content": second_reveal})
808
- user_responses.append({'stage': 'second_reveal', 'content': second_reveal})
809
- standardized_data[f'Second Reveal{vignette_counter}'] = second_reveal
810
- stage = "evolved_internal_external"
811
-
812
- elif stage == "evolved_internal_external":
813
- options_text = generate_internal_external_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'] + " " + standardized_data[f'Second Reveal{vignette_counter}'])
814
- fn_print("With the new information, what do you think why the situation occurred:")
815
- fn_print(f"Options:\n{options_text}")
816
- while True:
817
- user_input = fn_input("Your explanation: ")
818
- user_responses.append({'stage': 'evolved_internal_external', 'options': options_text, 'response': user_input})
819
- conversation_history.append({"role": "user", "content": user_input})
820
- mapped_option = interpret_response(user_input, options_text)
821
- if mapped_option in ['1', '2']:
822
- evolved_internal_external_response = mapped_option
823
- break
824
- else:
825
- fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
826
-
827
- # Store the final internal/external attribution numerically
828
- if evolved_internal_external_response == '1':
829
- standardized_data[f'Final Internal{vignette_counter}'] = 1
830
- standardized_data[f'Final External{vignette_counter}'] = 0
831
- elif evolved_internal_external_response == '2':
832
- standardized_data[f'Final Internal{vignette_counter}'] = 0
833
- standardized_data[f'Final External{vignette_counter}'] = 1
834
- else:
835
- standardized_data[f'Final Internal{vignette_counter}'] = None
836
- standardized_data[f'Final External{vignette_counter}'] = None
837
-
838
- stage = "evolved_stable_unstable_global_specific"
839
-
840
- elif stage == "evolved_stable_unstable_global_specific":
841
- previous_choice = evolved_internal_external_response
842
- options_text = generate_stable_unstable_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'] + " " + standardized_data[f'Second Reveal{vignette_counter}'], previous_choice)
843
- fn_print("One last time, based on your previous choice, which option best explains the situation:")
844
- fn_print(f"Options:\n{options_text}")
845
- while True:
846
- user_input = fn_input("Your explanation: ")
847
- user_responses.append({'stage': 'evolved_stable_unstable_global_specific', 'options': options_text, 'response': user_input})
848
- conversation_history.append({"role": "user", "content": user_input})
849
- mapped_option = interpret_response(user_input, options_text)
850
- if mapped_option in ['1', '2', '3', '4']:
851
- evolved_stable_unstable_response = mapped_option
852
- break
853
- else:
854
- fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
855
-
856
- # Store the final stable/unstable and global/specific attributions numerically
857
- if evolved_stable_unstable_response == '1':
858
- standardized_data[f'Final Stable{vignette_counter}'] = 1
859
- standardized_data[f'Final Unstable{vignette_counter}'] = 0
860
- standardized_data[f'Final Global{vignette_counter}'] = 1
861
- standardized_data[f'Final Specific{vignette_counter}'] = 0
862
- elif evolved_stable_unstable_response == '2':
863
- standardized_data[f'Final Stable{vignette_counter}'] = 1
864
- standardized_data[f'Final Unstable{vignette_counter}'] = 0
865
- standardized_data[f'Final Global{vignette_counter}'] = 0
866
- standardized_data[f'Final Specific{vignette_counter}'] = 1
867
- elif evolved_stable_unstable_response == '3':
868
- standardized_data[f'Final Stable{vignette_counter}'] = 0
869
- standardized_data[f'Final Unstable{vignette_counter}'] = 1
870
- standardized_data[f'Final Global{vignette_counter}'] = 1
871
- standardized_data[f'Final Specific{vignette_counter}'] = 0
872
- elif evolved_stable_unstable_response == '4':
873
- standardized_data[f'Final Stable{vignette_counter}'] = 0
874
- standardized_data[f'Final Unstable{vignette_counter}'] = 1
875
- standardized_data[f'Final Global{vignette_counter}'] = 0
876
- standardized_data[f'Final Specific{vignette_counter}'] = 1
877
- else:
878
- standardized_data[f'Final Stable{vignette_counter}'] = None
879
- standardized_data[f'Final Unstable{vignette_counter}'] = None
880
- standardized_data[f'Final Global{vignette_counter}'] = None
881
- standardized_data[f'Final Specific{vignette_counter}'] = None
882
-
883
- stage = "likelihood_of_change"
884
-
885
- elif stage == "likelihood_of_change":
886
- fn_print("Think back to your initial interpretation of the scene. On a scale from 1 to 10, how likely are you to change that initial interpretation after receiving the new information? (1 = least likely, 10 = most likely)")
887
- user_input = fn_input("You: ")
888
- user_responses.append({'stage': 'likelihood_of_change', 'response': user_input})
889
- conversation_history.append({"role": "user", "content": user_input})
890
-
891
- # Interpret the user's response to extract the numerical rating
892
- prompt = f"""
893
- The user was asked to rate their likelihood of changing their initial interpretation on a scale from 1 to 10.
894
- The user responded: "{user_input}"
895
- Extract the numerical rating from the user's response. Provide the number only.
896
- If you cannot determine the rating, respond with "Unable to determine".
897
- """
898
-
899
- response = openai.chat.completions.create(
900
- model="gpt-4o-mini",
901
- messages=[{"role": "user", "content": prompt}],
902
- temperature=0.0,
903
- max_tokens=5
904
- )
905
-
906
- assistant_response = response.choices[0].message.content.strip()
907
- if assistant_response.isdigit() and 1 <= int(assistant_response) <= 10:
908
- standardized_data[f'Likelihood of Change{vignette_counter}'] = int(assistant_response)
909
- stage = "subsequent_vignettes"
910
- else:
911
- fn_print("Sorry, I couldn't understand your response. Please provide a number between 1 and 10.")
912
-
913
- elif stage == "subsequent_vignettes":
914
- fn_print("Thank you! We are now finished with this scene. In total you will be seeing four scenes.")
915
-
916
- vignette_counter += 1 # Move to the next vignette
917
-
918
- stage = "topic_choice" # Reset stage to process the next vignette
919
-
920
- return conversation_history, user_responses