mojakob commited on
Commit
cfbfa67
·
verified ·
1 Parent(s): 23934a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -97
app.py CHANGED
@@ -177,120 +177,155 @@ EXCLUSION_THRESHOLD = 20
177
  # Storing / Uploading Functions
178
  ##############################################################################
179
 
180
- def generate_custom_vignette(conversation_history, topic_choice, desired_tone, app_state=None):
 
 
 
 
 
 
 
 
181
  """
182
- Creates a concise, neutral, second-person vignette based on:
183
- - user profile (age, profession, interests),
184
- - topic choice (1=profession, 2=interests, 3=other from conversation_history),
185
- - desired tone (Positive/Negative).
186
-
187
- Returns:
188
- vignette_text (str): The generated scenario
189
- final_tone (str): The validated tone used in the scenario
 
 
 
 
 
 
 
 
190
  """
191
 
192
  if app_state is None:
193
  raise ValueError("app_state must be passed to generate_custom_vignette().")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
- # ----------------------------
196
- # 1) Extract user profile
197
- # ----------------------------
198
- user_age = app_state["standardized_data"].get("Age", "Unknown")
199
- user_profession = app_state["standardized_data"].get("Profession", "Unknown")
200
- user_interests = app_state["standardized_data"].get("Interests", "Unknown")
201
-
202
- # ----------------------------
203
- # 2) Determine the topic
204
- # ----------------------------
205
- # For topic_choice == "3", we look at the last user entry in the conversation for hints
206
- if topic_choice == "1":
207
- chosen_topic = f"your profession as a {user_profession}"
208
- elif topic_choice == "2":
209
- chosen_topic = f"your personal interests (e.g., {user_interests})"
210
- else:
211
- # If there's recent user input, we use that. Otherwise fall back to user_interests.
212
- recent_input = None
213
- if conversation_history:
214
- # Look for the last user message that might reveal another hobby/activity
215
- # e.g., "I also like cooking"
216
- # We'll just grab the last user’s content.
217
- for msg in reversed(conversation_history):
218
- if msg.get("role") == "user":
219
- recent_input = msg.get("content")
220
- break
221
- if recent_input:
222
- chosen_topic = f"the additional hobby or activity you mentioned: '{recent_input}'"
223
- else:
224
- chosen_topic = f"another activity you enjoy, such as {user_interests}"
225
 
226
- # ----------------------------
227
- # 3) Validate desired_tone
228
- # ----------------------------
229
- if desired_tone not in ["Positive", "Negative"]:
230
- final_tone = "Positive"
231
- else:
232
- final_tone = desired_tone
233
-
234
- # ----------------------------
235
- # 4) System prompt (role=system)
236
- # ----------------------------
237
- system_prompt = (
238
- "You are a helpful assistant generating short, second-person vignettes "
239
- "for a psychological assessment. Use neutral language focusing on external events, "
240
- "avoiding any mention of the user's internal thoughts or emotions. The scenario "
241
- "should remain under ~70 tokens. "
242
- "The user is participating in a study comparing standard versus personalized vignettes."
243
- )
244
 
245
- # ----------------------------
246
- # 5) User prompt (role=user)
247
- # ----------------------------
248
- # We keep it short, mention the user’s profile, the chosen topic, and the desired tone
249
- user_prompt = f"""
250
- The user has the following profile:
251
- - Age: {user_age}
252
- - Profession: {user_profession}
253
- - Interests: {user_interests}
254
 
255
- They have selected a scenario focusing on {chosen_topic}.
256
- They want a clearly {final_tone} external situation, described in second-person format.
257
- No internal commentary; only outward, observable events.
258
 
259
  Instructions:
260
- - Use neutral, simple language suitable for a psychological questionnaire.
261
- - Keep it short (~70 tokens).
262
- - If {final_tone} = Positive, it should center on a pleasant/rewarding outcome.
263
- - If {final_tone} = Negative, it should center on an unpleasant/confrontational outcome.
264
- - Avoid personal identifiers. Do not include inner thoughts or feelings.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
 
266
- Example (Positive tone):
267
- "You arrive at the office for a routine meeting. A coworker praises your recent progress,
268
- and you briefly discuss next steps before finalizing the agenda."
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
- Now produce the vignette. Avoid any additional text or comments.
271
- """
 
 
272
 
273
- # 5) Make the OpenAI API call
274
  try:
275
  response = openai.chat.completions.create(
276
- model="gpt-4o-mini",
277
- messages=[
278
- {"role": "system", "content": system_prompt},
279
- {"role": "user", "content": user_prompt},
280
- ],
281
  temperature=0.3,
282
- max_tokens=100, # Enough to allow ~70 tokens plus overhead
283
  )
284
-
285
- # 6) Extract the resulting vignette
286
- vignette_text = response.choices[0].message.content.strip()
287
-
288
  except Exception as e:
289
  print(f"Error calling OpenAI API for vignette: {e}")
290
  return None, None
291
 
292
- # 7) Return the final scenario + the tone we used
293
- return vignette_text, final_tone
 
 
 
 
 
 
 
294
 
295
  def upload_file_to_space(local_file_path, repo_id, hf_token, path_in_repo=None):
296
  """
@@ -612,10 +647,13 @@ def new_chat_input(message, history, app_state=None, *args, **kwargs):
612
 
613
  app_state["desired_tone"] = vignette_tones[app_state["vignette_counter"] - 1]
614
  vignette, tone = generate_custom_vignette(
615
- app_state["conversation_history"],
616
- app_state["standardized_data"].get("Topic Choice"),
617
- app_state.get("desired_tone"),
618
- app_state
 
 
 
619
  )
620
  app_state["vignette"] = vignette
621
  app_state["tone"] = tone
@@ -729,7 +767,7 @@ def new_chat_input(message, history, app_state=None, *args, **kwargs):
729
  app_state["user_responses"].append({'app_state["stage"]': 'additional_info', 'response': additional_info})
730
  app_state["conversation_history"].append({"role": "user", "content": additional_info})
731
  # Use the additional info in the conversation history to regenerate the vignette
732
- app_state["vignette"], app_state["tone"] = generate_custom_vignette(app_state["conversation_history"], app_state["topic_choice"], app_state["desired_tone"])
733
  app_state["conversation_history"].append({"role": "assistant", "content": app_state["vignette"]})
734
  app_state["user_responses"].append({'app_state["stage"]': 'vignette_regenerated', 'content': app_state["vignette"], 'tone': app_state["tone"]})
735
  # Temporarily store the new vignette and tone
 
177
  # Storing / Uploading Functions
178
  ##############################################################################
179
 
180
+ def generate_custom_vignette(
181
+ conversation_history,
182
+ topic_choice,
183
+ desired_tone,
184
+ app_state=None,
185
+ context_types=None,
186
+ interaction_types=None,
187
+ actions_events=None
188
+ ):
189
  """
190
+ Based on the provided user profile, topic choice and desired_tone create a concise vignette by selecting exactly one module from:
191
+ - context_types
192
+ - interaction_types
193
+ - actions_events
194
+ to create a relatable scenario for them, featuring events that might happen during their provided profession or interests.
195
+
196
+ The final text should:
197
+ - Remain a short second-person vignette (< 50 tokens).
198
+ - Reflect the chosen modules (context, interaction, action).
199
+ - Avoid mentioning the module names or categories themselves.
200
+ - Stay purely external (no inner feelings).
201
+ - Maintain a clearly Positive or Negative atmosphere (desired_tone).
202
+ - Follow the user's topic choice:
203
+ 1 => profession-related
204
+ 2 => personal interests
205
+ 3 => something referencing the last user input in conversation_history
206
  """
207
 
208
  if app_state is None:
209
  raise ValueError("app_state must be passed to generate_custom_vignette().")
210
+ if context_types is None or interaction_types is None or actions_events is None:
211
+ raise ValueError("Please provide the modular seeds: context_types, interaction_types, actions_events.")
212
+
213
+ # Extract user profile
214
+ user_profile = app_state.get("standardized_data", {})
215
+ user_age = user_profile.get("Age", "Unknown")
216
+ user_profession = user_profile.get("Profession", "Unknown")
217
+ user_interests = user_profile.get("Interests", "Unknown")
218
+
219
+ # Build the main user prompt, referencing the dictionaries and the user profile
220
+ # We instruct the LLM to pick one module from each category:
221
+ # - context_types
222
+ # - interaction_types
223
+ # - actions_events
224
+ # Also specify how to handle topic_choice, tone, and the minimal length requirement.
225
+
226
+ # Convert your dictionaries into a short text so the model "knows" the available modules:
227
+ # (We keep them brief. If you prefer, you can provide them in a simpler bullet format.)
228
+ context_types_text = "\n".join(
229
+ f"{key}: {values}" for key, values in context_types.items()
230
+ )
231
+ interaction_types_text = "\n".join(
232
+ f"{key}: {values}" for key, values in interaction_types.items()
233
+ )
234
+ actions_events_text = "\n".join(
235
+ f"{key}: {values}" for key, values in actions_events.items()
236
+ )
237
 
238
+ # We want to ensure the LLM sees these references but does NOT spit them out.
239
+ # We'll say "Do not reveal the categories or modules themselves in the final text."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
 
241
+ prompt = f"""
242
+ You have three dictionaries of modular seeds for constructing short, second-person vignettes:
243
+ 1) context_types:
244
+ {context_types_text}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
+ 2) interaction_types:
247
+ {interaction_types_text}
 
 
 
 
 
 
 
248
 
249
+ 3) actions_events:
250
+ {actions_events_text}
 
251
 
252
  Instructions:
253
+ - Pick exactly ONE item from each dictionary (context, interaction, action) to form a scenario.
254
+ - Base your selection on the user's profile and the conversation details below.
255
+ - The user profile is:
256
+ Age: {user_age}
257
+ Profession: {user_profession}
258
+ Interests: {user_interests}
259
+
260
+ - The user has chosen topic {topic_choice}:
261
+ 1 = a situation related to their profession
262
+ 2 = a situation related to their personal interests
263
+ 3 = a scenario referencing the user's most recent input in the conversation history
264
+
265
+ - The user wants a scenario with a tone that is clearly {desired_tone}.
266
+ (Must be "Positive" or "Negative" in atmosphere. No mixed tone.)
267
+
268
+ - You must keep your final text under 50 tokens.
269
+ - Do NOT include the module names or categories in your final text.
270
+ - Only provide a short second-person vignette describing external events,
271
+ with no mention of the user’s internal thoughts or feelings.
272
+ - Do not add any extra lines like "Tone: ...".
273
+ - Do not say "Here is your vignette."
274
+ - Keep it neutral and professional, describing only outward actions or occurrences.
275
+
276
+ Below is the conversation history, which may include clarifications or references from the user:
277
+ {conversation_history}
278
+
279
+ Now:
280
+ 1) Select the best modules from each dictionary (one context, one interaction, one action).
281
+ 2) Ensure the final text is concise (<50 tokens).
282
+ 3) Remain in second-person, external focus, matching the chosen tone.
283
+ 4) Output only the short scenario text, nothing else.
284
+ """
285
 
286
+ # Prepare the messages for the OpenAI call
287
+ messages = [
288
+ {
289
+ "role": "system",
290
+ "content": (
291
+ "You are an assistant that creates standardized short vignettes "
292
+ "for a psychological assessment, focusing on outward events, "
293
+ "avoiding internal states or feelings."
294
+ ),
295
+ },
296
+ {
297
+ "role": "user",
298
+ "content": prompt,
299
+ },
300
+ ]
301
 
302
+ # Optionally append the entire conversation history as separate messages
303
+ # if you want the LLM to read them as distinct user/assistant messages:
304
+ for msg in conversation_history:
305
+ messages.append(msg)
306
 
307
+ # Make the OpenAI API call
308
  try:
309
  response = openai.chat.completions.create(
310
+ model="gpt-4o-mini", # or your chosen model
311
+ messages=messages,
 
 
 
312
  temperature=0.3,
313
+ max_tokens=150, # Enough overhead for a short vignette
314
  )
315
+ content = response.choices[0].message.content.strip()
 
 
 
316
  except Exception as e:
317
  print(f"Error calling OpenAI API for vignette: {e}")
318
  return None, None
319
 
320
+ # Final text is the entire content; the tone we used is desired_tone (or fallback)
321
+ # If desired_tone is not strictly "Positive"/"Negative," you might default to "Positive."
322
+ final_tone = desired_tone
323
+ if final_tone not in ["Positive", "Negative"]:
324
+ final_tone = "Positive"
325
+
326
+ # Return the raw content + final_tone
327
+ return content, final_tone
328
+
329
 
330
  def upload_file_to_space(local_file_path, repo_id, hf_token, path_in_repo=None):
331
  """
 
647
 
648
  app_state["desired_tone"] = vignette_tones[app_state["vignette_counter"] - 1]
649
  vignette, tone = generate_custom_vignette(
650
+ conversation_history=app_state["conversation_history"],
651
+ topic_choice=app_state["topic_choice"],
652
+ desired_tone=app_state["desired_tone"],
653
+ app_state=app_state,
654
+ context_types=context_types,
655
+ interaction_types=interaction_types,
656
+ actions_events=actions_events
657
  )
658
  app_state["vignette"] = vignette
659
  app_state["tone"] = tone
 
767
  app_state["user_responses"].append({'app_state["stage"]': 'additional_info', 'response': additional_info})
768
  app_state["conversation_history"].append({"role": "user", "content": additional_info})
769
  # Use the additional info in the conversation history to regenerate the vignette
770
+ 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"], app_state=app_state, context_types=context_types, interaction_types=interaction_types, actions_events=actions_events)
771
  app_state["conversation_history"].append({"role": "assistant", "content": app_state["vignette"]})
772
  app_state["user_responses"].append({'app_state["stage"]': 'vignette_regenerated', 'content': app_state["vignette"], 'tone': app_state["tone"]})
773
  # Temporarily store the new vignette and tone