sunbal7 commited on
Commit
706a81d
Β·
verified Β·
1 Parent(s): f5a0f8b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -110
app.py CHANGED
@@ -17,23 +17,25 @@ except KeyError:
17
  st.error("GROQ_API_KEY missing in secrets! Add it in Hugging Face settings.")
18
  st.stop()
19
 
20
- # Initialize models with verified working versions
21
  try:
22
- personality_classifier = pipeline(
 
 
 
 
 
 
 
23
  "text-classification",
24
  model="j-hartmann/emotion-english-distilroberta-base"
25
  )
26
- big5_model = pipeline(
27
- "text-classification",
28
- model="m3hrdadfi/bigfive-personality-traits",
29
- top_k=5
30
- )
31
  except Exception as e:
32
  st.error(f"Model loading error: {str(e)}")
33
  st.stop()
34
 
35
  # Configure Streamlit
36
- st.set_page_config(page_title="🧠 Personality Prodigy", layout="wide", page_icon="πŸ€–")
37
 
38
  # Custom CSS
39
  st.markdown("""
@@ -58,50 +60,38 @@ st.markdown("""
58
  </style>
59
  """, unsafe_allow_html=True)
60
 
61
- # Dynamic questions pool
 
 
 
 
 
 
 
 
62
  QUESTION_BANK = [
63
- {"text": "What's your most creative procrastination method? πŸŽ¨πŸ›Œ", "trait": "openness"},
64
- {"text": "How do you react when plans change suddenly? πŸŒͺοΈπŸ€”", "trait": "neuroticism"},
65
- {"text": "Describe your ideal weekend vs reality πŸοΈπŸ› οΈ", "trait": "extraversion"},
66
- {"text": "What's your 'guilty pleasure' productivity hack? πŸ«πŸ“ˆ", "trait": "conscientiousness"},
67
- {"text": "How do you comfort a stressed friend? πŸ€—πŸ’¬", "trait": "agreeableness"},
68
- {"text": "What would you do if you were invisible for a day? πŸ‘»πŸŽ­", "trait": "openness"},
69
- {"text": "Your reaction to unexpected criticism? πŸ₯ŠπŸ’‘", "trait": "neuroticism"},
70
- {"text": "Plan a party vs enjoy quiet night? πŸŽ‰πŸ“š", "trait": "extraversion"},
71
- {"text": "How do you handle missed deadlines? βŒ›πŸ€·", "trait": "conscientiousness"},
72
- {"text": "Describe your perfect collaboration πŸ‘₯✨", "trait": "agreeableness"}
73
  ]
74
 
75
- def analyze_big5(text):
76
- """Process Big Five personality traits from model output"""
77
- results = big5_model(text[:512])
78
- trait_map = {
79
- 'EXTRAVERSION': 'extraversion',
80
- 'NEUROTICISM': 'neuroticism',
81
- 'CONSCIENTIOUSNESS': 'conscientiousness',
82
- 'OPENNESS': 'openness',
83
- 'AGREEABLENESS': 'agreeableness'
84
- }
85
- return {trait_map[res['label']]: res['score'] for res in results}
86
-
87
- def get_dynamic_questions(responses):
88
- """Select questions based on personality patterns"""
89
- if not responses:
90
- return random.sample(QUESTION_BANK, 5)
91
-
92
- traits = analyze_big5("\n".join(responses))
93
- dominant_trait = max(traits, key=traits.get)
94
- return [q for q in QUESTION_BANK if q['trait'] == dominant_trait][:3] + random.sample(QUESTION_BANK, 2)
95
 
96
  def analyze_emotions(text):
97
- """Detect emotional tone using RoBERTa"""
98
- return personality_classifier(text[:512])
99
 
100
  def generate_quote(traits):
101
- """Generate personality-specific quote using Groq/Mistral"""
102
  prompt = f"""Create a motivational quote for someone with these traits:
103
  {traits}
104
- Make it inspirational, funny, and include an emoji."""
105
 
106
  response = groq_client.chat.completions.create(
107
  model="mixtral-8x7b-32768",
@@ -114,45 +104,26 @@ def generate_tips(traits):
114
  """Generate evidence-based psychological tips"""
115
  tips = []
116
  if traits.get('openness', 0) > 0.7:
117
- tips.extend([
118
- "🎨 Try creative cross-training (write a poem about your work)",
119
- "🌍 Learn something new daily about different cultures"
120
- ])
121
  if traits.get('neuroticism', 0) > 0.6:
122
- tips.extend([
123
- "🧘 Practice box breathing: 4s in, 4s hold, 4s out",
124
- "πŸ“ Keep a worry journal to externalize anxieties"
125
- ])
126
- return tips[:10]
127
-
128
- def create_personality_report(responses):
129
- """Generate comprehensive personality analysis"""
130
- text = "\n".join(responses)
131
- big5_results = analyze_big5(text)
132
- return {
133
- "big5": big5_results,
134
- "emotions": analyze_emotions(text),
135
- "quote": generate_quote(big5_results),
136
- "tips": generate_tips(big5_results)
137
- }
138
 
139
  def create_pdf_report(report):
140
  """Generate downloadable PDF report"""
141
  buffer = io.BytesIO()
142
  p = canvas.Canvas(buffer, pagesize=letter)
143
 
144
- # Header
145
  p.setFont("Helvetica-Bold", 16)
146
- p.drawString(100, 750, "🌟 Personality Prodigy Report 🌟")
147
  p.setFont("Helvetica", 12)
148
 
149
- # Content
150
  y_position = 700
151
  content = [
152
  f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M')}",
153
  "",
154
- "Big Five Personality Traits:",
155
- *[f"- {trait.upper()}: {score:.2f}" for trait, score in report['big5'].items()],
156
  "",
157
  "Emotional Analysis:",
158
  *[f"- {emo['label']}: {emo['score']:.2f}" for emo in report['emotions']],
@@ -162,7 +133,6 @@ def create_pdf_report(report):
162
  "",
163
  "Growth Tips:",
164
  *[f"{i+1}. {tip}" for i, tip in enumerate(report['tips'])]
165
- ] # Fixed missing closing bracket
166
 
167
  for line in content:
168
  p.drawString(100, y_position, line)
@@ -177,78 +147,75 @@ if 'responses' not in st.session_state:
177
  st.session_state.responses = []
178
  if 'current_q' not in st.session_state:
179
  st.session_state.current_q = 0
180
- if 'questions' not in st.session_state:
181
- st.session_state.questions = get_dynamic_questions([])
182
 
183
  # Main UI
184
- st.title("🧠 Personality Prodigy")
185
- st.markdown("### Your AI-Powered Mirror for Self-Discovery πŸ”βœ¨")
186
 
187
  # Progress tracker
188
- progress = st.session_state.current_q / len(st.session_state.questions)
189
  st.markdown(f"""
190
  <div style="background: #f0f2f6; border-radius: 15px; padding: 5px;">
191
  <div class="progress-bar" style="width: {progress*100}%; height: 25px;"></div>
192
  </div>
193
  """, unsafe_allow_html=True)
194
 
195
- # Dynamic question flow
196
- if st.session_state.current_q < len(st.session_state.questions):
197
- q = st.session_state.questions[st.session_state.current_q]
198
 
199
  with st.chat_message("assistant"):
200
  st.markdown(f"### {q['text']}")
201
- st.markdown(f"*What's your answer?* {'πŸ€”' if q['trait'] in ['neuroticism','conscientiousness'] else 'πŸ˜„'}")
202
-
203
  user_input = st.text_input("Your response:", key=f"q{st.session_state.current_q}")
204
 
205
  if st.button("Next ➑️"):
206
  st.session_state.responses.append(user_input)
207
  st.session_state.current_q += 1
208
-
209
- # Update questions based on responses
210
- if st.session_state.current_q == len(st.session_state.questions):
211
- st.session_state.questions = get_dynamic_questions(st.session_state.responses)
212
- st.session_state.current_q = 0
213
-
214
  st.rerun()
215
  else:
216
- # Generate and display report
217
- report = create_personality_report(st.session_state.responses)
218
- st.balloons()
 
219
 
220
- st.markdown(f"## <div class='personality-title'>🌟 Your Personality Report 🌟</div>", unsafe_allow_html=True)
 
 
 
 
 
 
 
 
221
 
222
- # Big Five Traits Visualization
223
- with st.expander("πŸ” Big Five Personality Traits"):
224
  cols = st.columns(5)
225
- traits = report['big5']
226
- for i, (trait, score) in enumerate(traits.items()):
227
- cols[i].metric(label=trait.upper(), value=f"{score:.0%}",
228
- help=f"{['Low','Moderate','High'][int(score//0.33)]} {trait}")
229
 
230
  # Emotional Analysis
231
- with st.expander("🎭 Emotional Tone Analysis"):
232
  emotion = max(report['emotions'], key=lambda x: x['score'])
233
  st.markdown(f"**Dominant Emotion**: {emotion['label']} ({emotion['score']:.0%})")
234
  st.progress(emotion['score'])
235
 
236
- # Personalized Content
237
  col1, col2 = st.columns(2)
238
  with col1:
239
- st.markdown("### πŸ’¬ Your Personality Quote")
240
  st.success(f'"{report["quote"]}"')
241
  with col2:
242
- st.markdown("### πŸ› οΈ Growth Strategies")
243
- for tip in report['tips'][:5]:
244
  st.markdown(f"- {tip}")
245
 
246
- # Downloadable Report
247
  pdf_buffer = create_pdf_report(report)
248
  st.download_button(
249
  "πŸ“₯ Download Full Report",
250
  data=pdf_buffer,
251
- file_name="personality_report.pdf",
252
  mime="application/pdf"
253
  )
254
 
@@ -256,13 +223,13 @@ else:
256
  with st.sidebar:
257
  st.markdown("## 🌈 How It Works")
258
  st.markdown("""
259
- 1. Answer dynamic personality questions
260
- 2. Get real-time psychological analysis
261
- 3. Receive personalized growth strategies
262
- 4. Download/share your unique report
263
 
264
- **Scientific Backing:**
265
- - Big Five Personality Model (OCEAN)
266
- - Emotion Recognition (RoBERTa)
267
- - Cognitive Behavioral Therapy (CBT)
268
  """)
 
17
  st.error("GROQ_API_KEY missing in secrets! Add it in Hugging Face settings.")
18
  st.stop()
19
 
20
+ # Initialize psychological models using verified public models
21
  try:
22
+ # Personality insights using zero-shot classification
23
+ personality_analyzer = pipeline(
24
+ "zero-shot-classification",
25
+ model="facebook/bart-large-mnli"
26
+ )
27
+
28
+ # Emotion detection model
29
+ emotion_classifier = pipeline(
30
  "text-classification",
31
  model="j-hartmann/emotion-english-distilroberta-base"
32
  )
 
 
 
 
 
33
  except Exception as e:
34
  st.error(f"Model loading error: {str(e)}")
35
  st.stop()
36
 
37
  # Configure Streamlit
38
+ st.set_page_config(page_title="🧠 Mind Mapper", layout="wide", page_icon="πŸ€–")
39
 
40
  # Custom CSS
41
  st.markdown("""
 
60
  </style>
61
  """, unsafe_allow_html=True)
62
 
63
+ # Personality traits and questions
64
+ OCEAN_TRAITS = {
65
+ "openness": ["curious", "creative", "adventurous"],
66
+ "conscientiousness": ["organized", "responsible", "disciplined"],
67
+ "extraversion": ["outgoing", "energetic", "sociable"],
68
+ "agreeableness": ["friendly", "compassionate", "cooperative"],
69
+ "neuroticism": ["sensitive", "nervous", "emotional"]
70
+ }
71
+
72
  QUESTION_BANK = [
73
+ {"text": "How do you typically approach new experiences? 🌍", "trait": "openness"},
74
+ {"text": "Describe your ideal weekend vs reality 🏝️", "trait": "conscientiousness"},
75
+ {"text": "How do you recharge after social events? πŸͺ«", "trait": "extraversion"},
76
+ {"text": "Your reaction to someone disagreeing with you? πŸ’’", "trait": "agreeableness"},
77
+ {"text": "How do you handle unexpected changes? πŸŒ€", "trait": "neuroticism"}
 
 
 
 
 
78
  ]
79
 
80
+ def analyze_psychology(text):
81
+ """Analyze personality traits using zero-shot classification"""
82
+ candidate_labels = list(OCEAN_TRAITS.keys())
83
+ result = personality_analyzer(text, candidate_labels, multi_label=True)
84
+ return {label: score for label, score in zip(result['labels'], result['scores'])}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  def analyze_emotions(text):
87
+ """Detect emotional tone"""
88
+ return emotion_classifier(text[:512])
89
 
90
  def generate_quote(traits):
91
+ """Generate personality-specific quote"""
92
  prompt = f"""Create a motivational quote for someone with these traits:
93
  {traits}
94
+ Make it inspirational and include an emoji."""
95
 
96
  response = groq_client.chat.completions.create(
97
  model="mixtral-8x7b-32768",
 
104
  """Generate evidence-based psychological tips"""
105
  tips = []
106
  if traits.get('openness', 0) > 0.7:
107
+ tips.append("🎨 Try creative cross-training: Write a short story about your day")
 
 
 
108
  if traits.get('neuroticism', 0) > 0.6:
109
+ tips.append("🧘 Practice 4-7-8 breathing: Inhale 4s, hold 7s, exhale 8s")
110
+ return tips[:5]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  def create_pdf_report(report):
113
  """Generate downloadable PDF report"""
114
  buffer = io.BytesIO()
115
  p = canvas.Canvas(buffer, pagesize=letter)
116
 
 
117
  p.setFont("Helvetica-Bold", 16)
118
+ p.drawString(100, 750, "🌟 Psychological Profile Report 🌟")
119
  p.setFont("Helvetica", 12)
120
 
 
121
  y_position = 700
122
  content = [
123
  f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M')}",
124
  "",
125
+ "Personality Traits:",
126
+ *[f"- {trait.upper()}: {score:.2f}" for trait, score in report['traits'].items()],
127
  "",
128
  "Emotional Analysis:",
129
  *[f"- {emo['label']}: {emo['score']:.2f}" for emo in report['emotions']],
 
133
  "",
134
  "Growth Tips:",
135
  *[f"{i+1}. {tip}" for i, tip in enumerate(report['tips'])]
 
136
 
137
  for line in content:
138
  p.drawString(100, y_position, line)
 
147
  st.session_state.responses = []
148
  if 'current_q' not in st.session_state:
149
  st.session_state.current_q = 0
 
 
150
 
151
  # Main UI
152
+ st.title("🧠 Mind Mapper")
153
+ st.markdown("### Your Personal Psychology Assistant πŸ”βœ¨")
154
 
155
  # Progress tracker
156
+ progress = st.session_state.current_q / len(QUESTION_BANK)
157
  st.markdown(f"""
158
  <div style="background: #f0f2f6; border-radius: 15px; padding: 5px;">
159
  <div class="progress-bar" style="width: {progress*100}%; height: 25px;"></div>
160
  </div>
161
  """, unsafe_allow_html=True)
162
 
163
+ # Question flow
164
+ if st.session_state.current_q < len(QUESTION_BANK):
165
+ q = QUESTION_BANK[st.session_state.current_q]
166
 
167
  with st.chat_message("assistant"):
168
  st.markdown(f"### {q['text']}")
 
 
169
  user_input = st.text_input("Your response:", key=f"q{st.session_state.current_q}")
170
 
171
  if st.button("Next ➑️"):
172
  st.session_state.responses.append(user_input)
173
  st.session_state.current_q += 1
 
 
 
 
 
 
174
  st.rerun()
175
  else:
176
+ # Generate report
177
+ combined_text = "\n".join(st.session_state.responses)
178
+ traits = analyze_psychology(combined_text)
179
+ emotions = analyze_emotions(combined_text)
180
 
181
+ report = {
182
+ "traits": traits,
183
+ "emotions": emotions,
184
+ "quote": generate_quote(traits),
185
+ "tips": generate_tips(traits)
186
+ }
187
+
188
+ st.balloons()
189
+ st.markdown(f"## <div class='personality-title'>🌟 Your Psychological Profile 🌟</div>", unsafe_allow_html=True)
190
 
191
+ # Trait Visualization
192
+ with st.expander("🧩 Personality Breakdown"):
193
  cols = st.columns(5)
194
+ for i, (trait, score) in enumerate(report['traits'].items()):
195
+ cols[i].metric(label=trait.upper(), value=f"{score:.0%}")
 
 
196
 
197
  # Emotional Analysis
198
+ with st.expander("🎭 Emotional Landscape"):
199
  emotion = max(report['emotions'], key=lambda x: x['score'])
200
  st.markdown(f"**Dominant Emotion**: {emotion['label']} ({emotion['score']:.0%})")
201
  st.progress(emotion['score'])
202
 
203
+ # Recommendations
204
  col1, col2 = st.columns(2)
205
  with col1:
206
+ st.markdown("### πŸ’¬ Personalized Wisdom")
207
  st.success(f'"{report["quote"]}"')
208
  with col2:
209
+ st.markdown("### πŸ› οΈ Actionable Tips")
210
+ for tip in report['tips']:
211
  st.markdown(f"- {tip}")
212
 
213
+ # PDF Report
214
  pdf_buffer = create_pdf_report(report)
215
  st.download_button(
216
  "πŸ“₯ Download Full Report",
217
  data=pdf_buffer,
218
+ file_name="psych_profile.pdf",
219
  mime="application/pdf"
220
  )
221
 
 
223
  with st.sidebar:
224
  st.markdown("## 🌈 How It Works")
225
  st.markdown("""
226
+ 1. Answer 5 psychology-based questions
227
+ 2. Get instant personality analysis
228
+ 3. Receive emotional insights
229
+ 4. Download personalized report
230
 
231
+ **Science Behind It:**
232
+ - Zero-shot personality classification
233
+ - Emotion recognition (RoBERTa)
234
+ - Cognitive behavioral therapy principles
235
  """)