sunbal7 commited on
Commit
0e2ff7b
Β·
verified Β·
1 Parent(s): fe3a4fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -160
app.py CHANGED
@@ -1,91 +1,98 @@
1
  # app.py
2
  import streamlit as st
3
- from groq import Groq
4
  import torch
5
- from transformers import AutoModelForSequenceClassification, AutoTokenizer
 
 
 
6
  from reportlab.lib.pagesizes import letter
7
  from reportlab.pdfgen import canvas
8
  import io
9
- import random
10
- from datetime import datetime
11
 
12
- # Initialize Groq client
13
  try:
14
  groq_client = Groq(api_key=st.secrets["GROQ_API_KEY"])
15
- except KeyError:
16
- st.error("GROQ_API_KEY missing in secrets! Add it in Hugging Face settings.")
17
- st.stop()
18
-
19
- # Load personality model
20
- try:
21
- model = AutoModelForSequenceClassification.from_pretrained(
22
- "KevSun/Personality_LM",
23
- ignore_mismatched_sizes=True
24
- )
25
  tokenizer = AutoTokenizer.from_pretrained("KevSun/Personality_LM")
26
  except Exception as e:
27
- st.error(f"Model loading error: {str(e)}")
28
  st.stop()
29
 
30
  # Configure Streamlit
31
- st.set_page_config(page_title="🧠 Mind Mapper Pro", layout="wide", page_icon="πŸ€–")
32
 
33
  # Custom CSS
34
  st.markdown("""
35
  <style>
36
- @keyframes rainbow {
37
- 0% { color: #ff0000; }
38
- 20% { color: #ff8000; }
39
- 40% { color: #ffff00; }
40
- 60% { color: #00ff00; }
41
- 80% { color: #0000ff; }
42
- 100% { color: #ff00ff; }
43
  }
44
- .personality-title {
45
- animation: rainbow 3s infinite;
46
- font-size: 2.5em !important;
 
 
 
 
 
 
47
  }
 
 
 
 
 
 
 
 
 
48
  .social-post {
49
- border: 2px solid #4CAF50;
50
- border-radius: 15px;
51
- padding: 20px;
52
- margin: 15px 0;
53
- background: #f8fff9;
 
 
 
 
 
 
54
  }
55
  </style>
56
  """, unsafe_allow_html=True)
57
 
58
- # Personality traits
59
  OCEAN_TRAITS = ["agreeableness", "openness", "conscientiousness", "extraversion", "neuroticism"]
60
-
61
- # Enhanced question bank with mix of serious and funny questions
62
  QUESTION_BANK = [
63
- {"text": "If you were a kitchen appliance, which would you be and why? πŸ₯„", "trait": "openness"},
64
- {"text": "Describe your ideal Sunday vs your actual last Sunday πŸ“†", "trait": "conscientiousness"},
65
- {"text": "How would you survive a zombie apocalypse? 🧟", "trait": "neuroticism"},
66
- {"text": "What's your spirit animal during tax season? 🦁", "trait": "agreeableness"},
67
- {"text": "Plan a perfect date... with yourself! πŸ’ƒ", "trait": "extraversion"},
68
- {"text": "If emotions were weather patterns, what's your forecast? β›…", "trait": "neuroticism"},
69
- {"text": "What would your childhood toy say about you? 🧸", "trait": "openness"},
70
- {"text": "Describe your email inbox as a movie title πŸ“§", "trait": "conscientiousness"},
71
- {"text": "How do you react when someone says 'We need to talk'? 😬", "trait": "agreeableness"},
72
- {"text": "What's your superpower in group projects? 🦸", "trait": "extraversion"}
73
  ]
74
 
75
- def analyze_psychology(text):
76
- """Analyze personality traits using the specified model"""
77
- encoded_input = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=64)
78
- with torch.no_grad():
79
- outputs = model(**encoded_input)
80
- predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
81
- return {trait: score.item() for trait, score in zip(OCEAN_TRAITS, predictions[0])}
 
 
82
 
83
- def generate_social_post(platform, traits):
84
- """Generate platform-specific social media post"""
85
- prompt = f"""Create a {platform} post about personal growth based on these personality scores:
86
- {traits}
87
- Include relevant emojis and make it {platform}-appropriate. Keep it under 280 characters."""
88
-
89
  response = groq_client.chat.completions.create(
90
  model="mixtral-8x7b-32768",
91
  messages=[{"role": "user", "content": prompt}],
@@ -93,121 +100,166 @@ Include relevant emojis and make it {platform}-appropriate. Keep it under 280 ch
93
  )
94
  return response.choices[0].message.content
95
 
96
- def create_pdf_report(report):
97
- """Generate downloadable PDF report"""
 
 
 
 
 
 
98
  buffer = io.BytesIO()
99
  p = canvas.Canvas(buffer, pagesize=letter)
100
-
101
  p.setFont("Helvetica-Bold", 16)
102
- p.drawString(100, 750, "🌟 Psychological Profile Report 🌟")
103
  p.setFont("Helvetica", 12)
104
 
105
  y_position = 700
106
- content = [
107
- f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M')}",
108
- "",
109
- "Personality Traits:",
110
- *[f"- {trait.upper()}: {score:.2f}" for trait, score in report['traits'].items()],
111
- "",
112
- "Personalized Quote:",
113
- report['quote'],
114
- ]
115
-
116
- for line in content:
117
- p.drawString(100, y_position, line)
118
- y_position -= 15
119
 
 
 
120
  p.save()
121
  buffer.seek(0)
122
  return buffer
123
 
124
- # Session state management
125
- if 'responses' not in st.session_state:
126
- st.session_state.responses = []
127
- if 'current_q' not in st.session_state:
128
- st.session_state.current_q = 0
129
- if 'selected_questions' not in st.session_state:
130
- st.session_state.selected_questions = random.sample(QUESTION_BANK, 5)
131
-
132
- # Main UI
133
- st.title("🧠 Mind Mapper Pro")
134
- st.markdown("### Your Advanced Psychology Assistant πŸ”βœ¨")
135
-
136
- # Progress tracker
137
- progress = st.session_state.current_q / 5
138
- st.markdown(f"""
139
- <div style="background: #f0f2f6; border-radius: 15px; padding: 5px;">
140
- <div style="width: {progress*100}%; height: 25px; border-radius: 15px; background: linear-gradient(90deg, #FF6B6B 0%, #4ECDC4 100%);"></div>
141
- </div>
142
- """, unsafe_allow_html=True)
143
-
144
- # Question flow
145
- if st.session_state.current_q < 5:
146
- q = st.session_state.selected_questions[st.session_state.current_q]
147
-
148
- with st.chat_message("assistant"):
149
- st.markdown(f"### {q['text']}")
150
- user_input = st.text_input("Your response:", key=f"q{st.session_state.current_q}")
151
-
152
- if st.button("Next ➑️"):
153
- st.session_state.responses.append(user_input)
154
- st.session_state.current_q += 1
155
- st.rerun()
156
- else:
157
- # Generate report
158
- combined_text = "\n".join(st.session_state.responses)
159
- traits = analyze_psychology(combined_text)
160
-
161
- report = {
162
- "traits": traits,
163
- "quote": generate_social_post("general", traits) # Initial quote
164
  }
 
 
 
 
165
 
166
- st.balloons()
167
- st.markdown(f"## <div class='personality-title'>🌟 Your Personality Profile 🌟</div>", unsafe_allow_html=True)
168
-
169
- # Trait Visualization
170
- with st.expander("🧩 Personality Breakdown"):
171
- cols = st.columns(5)
172
- for i, (trait, score) in enumerate(report['traits'].items()):
173
- cols[i].metric(label=trait.upper(), value=f"{score:.2f}")
174
-
175
- # Social Media Post Generation
176
- st.markdown("### πŸ“± Create Social Media Post")
177
- platform = st.selectbox("Choose platform:", ["LinkedIn", "Instagram", "Facebook", "WhatsApp"])
178
-
179
- if st.button("Generate Post πŸš€"):
180
- post = generate_social_post(platform, report['traits'])
181
- st.session_state.post = post
182
-
183
- if 'post' in st.session_state:
184
- st.markdown(f"""
185
- <div class="social-post">
186
- {st.session_state.post}
187
- </div>
188
- """, unsafe_allow_html=True)
189
- st.button("πŸ“‹ Copy Post", on_click=lambda: st.write(st.session_state.post))
190
-
191
- # PDF Report
192
- pdf_buffer = create_pdf_report(report)
193
- st.download_button(
194
- "πŸ“₯ Download Full Report",
195
- data=pdf_buffer,
196
- file_name="personality_profile.pdf",
197
- mime="application/pdf"
198
  )
 
199
 
200
- # Sidebar
201
- with st.sidebar:
202
- st.markdown("## 🌈 Features Overview")
203
- st.markdown("""
204
- - **Enhanced Personality Assessment**
205
- - **Social Media Post Generator**
206
- - **Interactive Question Flow**
207
- - **PDF Report Download**
208
 
209
- **New Features:**
210
- - 🎭 Fun psychological questions
211
- - πŸ“± Platform-specific post crafting
212
- - 🧠 Advanced personality modeling
213
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # app.py
2
  import streamlit as st
 
3
  import torch
4
+ import random
5
+ import altair as alt
6
+ import pandas as pd
7
+ from datetime import datetime
8
  from reportlab.lib.pagesizes import letter
9
  from reportlab.pdfgen import canvas
10
  import io
11
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
12
+ from groq import Groq
13
 
14
+ # Initialize components
15
  try:
16
  groq_client = Groq(api_key=st.secrets["GROQ_API_KEY"])
17
+ model = AutoModelForSequenceClassification.from_pretrained("KevSun/Personality_LM", ignore_mismatched_sizes=True)
 
 
 
 
 
 
 
 
 
18
  tokenizer = AutoTokenizer.from_pretrained("KevSun/Personality_LM")
19
  except Exception as e:
20
+ st.error(f"Initialization error: {str(e)}")
21
  st.stop()
22
 
23
  # Configure Streamlit
24
+ st.set_page_config(page_title="🧠 PersonaCraft", layout="wide", page_icon="🌟")
25
 
26
  # Custom CSS
27
  st.markdown("""
28
  <style>
29
+ @keyframes fadeIn {
30
+ from { opacity: 0; }
31
+ to { opacity: 1; }
 
 
 
 
32
  }
33
+
34
+ .quote-box {
35
+ animation: fadeIn 1s ease-in;
36
+ border-left: 5px solid #4CAF50;
37
+ padding: 20px;
38
+ margin: 20px 0;
39
+ background: #f8fff9;
40
+ border-radius: 10px;
41
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
42
  }
43
+
44
+ .tip-card {
45
+ padding: 15px;
46
+ margin: 10px 0;
47
+ background: #fff3e0;
48
+ border-radius: 10px;
49
+ border: 1px solid #ffab40;
50
+ }
51
+
52
  .social-post {
53
+ background: #e3f2fd;
54
+ padding: 20px;
55
+ border-radius: 15px;
56
+ margin: 15px 0;
57
+ }
58
+
59
+ .viz-box {
60
+ background: white;
61
+ padding: 20px;
62
+ border-radius: 15px;
63
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
64
  }
65
  </style>
66
  """, unsafe_allow_html=True)
67
 
68
+ # Personality configuration
69
  OCEAN_TRAITS = ["agreeableness", "openness", "conscientiousness", "extraversion", "neuroticism"]
 
 
70
  QUESTION_BANK = [
71
+ {"text": "If your personality was a pizza topping, what would it be? πŸ•", "trait": "openness"},
72
+ {"text": "Describe your ideal alarm clock vs reality ⏰", "trait": "conscientiousness"},
73
+ {"text": "How would you survive a surprise party? πŸŽ‰", "trait": "neuroticism"},
74
+ {"text": "What's your spirit animal during deadlines? 🐾", "trait": "agreeableness"},
75
+ {"text": "Plan a perfect day... for your nemesis! 😈", "trait": "extraversion"},
76
+ {"text": "If stress was a color, what's your current shade? 🎨", "trait": "neuroticism"},
77
+ {"text": "What would your browser history say about you? 🌐", "trait": "openness"},
78
+ {"text": "Describe your phone's home screen as a poem πŸ“±", "trait": "conscientiousness"},
79
+ {"text": "React to 'Your idea is interesting, but...' πŸ’‘", "trait": "agreeableness"},
80
+ {"text": "What's your superpower in awkward situations? 🦸", "trait": "extraversion"}
81
  ]
82
 
83
+ # Session state management
84
+ if 'started' not in st.session_state:
85
+ st.session_state.started = False
86
+ if 'current_q' not in st.session_state:
87
+ st.session_state.current_q = 0
88
+ if 'responses' not in st.session_state:
89
+ st.session_state.responses = []
90
+ if 'page' not in st.session_state:
91
+ st.session_state.page = "🏠 Home"
92
 
93
+ # Functions
94
+ def generate_quote():
95
+ prompt = "Generate a fresh motivational quote about self-discovery with an emoji"
 
 
 
96
  response = groq_client.chat.completions.create(
97
  model="mixtral-8x7b-32768",
98
  messages=[{"role": "user", "content": prompt}],
 
100
  )
101
  return response.choices[0].message.content
102
 
103
+ def analyze_personality(text):
104
+ encoded_input = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=64)
105
+ with torch.no_grad():
106
+ outputs = model(**encoded_input)
107
+ predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
108
+ return {trait: score.item() for trait, score in zip(OCEAN_TRAITS, predictions[0])}
109
+
110
+ def create_pdf_report(traits, quote):
111
  buffer = io.BytesIO()
112
  p = canvas.Canvas(buffer, pagesize=letter)
 
113
  p.setFont("Helvetica-Bold", 16)
114
+ p.drawString(100, 750, "🌟 PersonaCraft Psychological Report 🌟")
115
  p.setFont("Helvetica", 12)
116
 
117
  y_position = 700
118
+ for trait, score in traits.items():
119
+ p.drawString(100, y_position, f"{trait.upper()}: {score:.2f}")
120
+ y_position -= 20
 
 
 
 
 
 
 
 
 
 
121
 
122
+ p.drawString(100, y_position-40, "Motivational Quote:")
123
+ p.drawString(100, y_position-60, quote)
124
  p.save()
125
  buffer.seek(0)
126
  return buffer
127
 
128
+ def generate_social_post(platform, traits):
129
+ platform_formats = {
130
+ "LinkedIn": "professional tone with industry hashtags",
131
+ "Instagram": "visual storytelling with emojis",
132
+ "Facebook": "friendly community-oriented style",
133
+ "WhatsApp": "casual conversational format",
134
+ "Twitter": "concise with trending hashtags"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  }
136
+ prompt = f"""Create a {platform} post about personal growth with these personality traits:
137
+ {traits}
138
+ Format: {platform_formats[platform]}
139
+ Include relevant emojis and keep under 280 characters."""
140
 
141
+ response = groq_client.chat.completions.create(
142
+ model="mixtral-8x7b-32768",
143
+ messages=[{"role": "user", "content": prompt}],
144
+ temperature=0.7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  )
146
+ return response.choices[0].message.content
147
 
148
+ # Main UI
149
+ if not st.session_state.started:
150
+ st.markdown(f"""
151
+ <div class="quote-box">
152
+ <h2>🌟 Welcome to PersonaCraft! 🌟</h2>
153
+ <h3>{generate_quote()}</h3>
154
+ </div>
155
+ """, unsafe_allow_html=True)
156
 
157
+ if st.button("πŸš€ Start Personality Journey!", use_container_width=True):
158
+ st.session_state.started = True
159
+ st.session_state.selected_questions = random.sample(QUESTION_BANK, 5)
160
+ st.rerun()
161
+ else:
162
+ # Sidebar navigation
163
+ with st.sidebar:
164
+ st.title("🧭 Navigation")
165
+ st.session_state.page = st.radio("Choose Section:", [
166
+ "πŸ“‹ Personality Report",
167
+ "πŸ“Š Visual Analysis",
168
+ "πŸ“± Social Media Post",
169
+ "πŸ’‘ Success Tips",
170
+ "πŸ“₯ Download Report"
171
+ ])
172
+
173
+ # Question flow
174
+ if st.session_state.current_q < 5:
175
+ q = st.session_state.selected_questions[st.session_state.current_q]
176
+ st.progress(st.session_state.current_q/5, text="Assessment Progress")
177
+
178
+ with st.chat_message("assistant"):
179
+ st.markdown(f"### {q['text']}")
180
+ user_input = st.text_input("Your response:", key=f"q{st.session_state.current_q}")
181
+
182
+ if st.button("Next ➑️"):
183
+ st.session_state.responses.append(user_input)
184
+ st.session_state.current_q += 1
185
+ st.rerun()
186
+ else:
187
+ # Process responses
188
+ traits = analyze_personality("\n".join(st.session_state.responses))
189
+ quote = generate_quote()
190
+
191
+ # Current page display
192
+ if st.session_state.page == "πŸ“‹ Personality Report":
193
+ st.header("πŸ“‹ Personality Breakdown")
194
+ cols = st.columns(5)
195
+ for i, (trait, score) in enumerate(traits.items()):
196
+ cols[i].metric(label=trait.upper(), value=f"{score:.2f}")
197
+
198
+ st.divider()
199
+ st.header("🎭 Emotional Landscape")
200
+ emotion_data = pd.DataFrame({
201
+ "Trait": traits.keys(),
202
+ "Score": traits.values()
203
+ })
204
+ st.altair_chart(alt.Chart(emotion_data).mark_bar().encode(
205
+ x="Trait",
206
+ y="Score",
207
+ color=alt.Color("Trait", legend=None)
208
+ ), use_container_width=True)
209
+
210
+ elif st.session_state.page == "πŸ“Š Visual Analysis":
211
+ st.header("πŸ“Š Personality Visualization")
212
+ radar_data = pd.DataFrame({
213
+ "Trait": list(traits.keys()) * 2,
214
+ "Score": list(traits.values()) * 2,
215
+ "Type": ["Base"]*5 + ["Current"]*5
216
+ })
217
+ st.altair_chart(alt.Chart(radar_data).mark_line().encode(
218
+ theta="Trait",
219
+ r="Score",
220
+ color="Type"
221
+ ).project(type='radial'), use_container_width=True)
222
+
223
+ elif st.session_state.page == "πŸ“± Social Media Post":
224
+ st.header("πŸ“± Create Social Post")
225
+ platform = st.selectbox("Select Platform:", ["LinkedIn", "Instagram", "Facebook", "WhatsApp", "Twitter"])
226
+
227
+ if st.button("Generate Post πŸš€"):
228
+ post = generate_social_post(platform, traits)
229
+ st.session_state.post = post
230
+
231
+ if 'post' in st.session_state:
232
+ st.markdown(f"""
233
+ <div class="social-post">
234
+ <p>{st.session_state.post}</p>
235
+ </div>
236
+ """, unsafe_allow_html=True)
237
+ st.button("οΏ½οΏ½οΏ½ Copy to Clipboard", on_click=lambda: st.write(st.session_state.post))
238
+
239
+ elif st.session_state.page == "πŸ’‘ Success Tips":
240
+ st.header("πŸ’‘ Personality Success Tips")
241
+ tips = [
242
+ "🌱 Practice daily self-reflection journaling",
243
+ "🀝 Seek diverse social interactions weekly",
244
+ "🎯 Set SMART goals for personal development",
245
+ "πŸ§˜β™‚οΈ Incorporate mindfulness practices daily",
246
+ "πŸ“š Engage in cross-disciplinary learning",
247
+ "πŸ—£οΈ Practice active listening techniques",
248
+ "πŸ”„ Embrace constructive feedback regularly",
249
+ "βš–οΈ Maintain work-life harmony",
250
+ "🌟 Develop emotional granularity skills",
251
+ "πŸš€ Challenge comfort zones monthly"
252
+ ]
253
+ for tip in tips:
254
+ st.markdown(f"<div class='tip-card'>{tip}</div>", unsafe_allow_html=True)
255
+
256
+ elif st.session_state.page == "πŸ“₯ Download Report":
257
+ st.header("πŸ“₯ Download Complete Report")
258
+ pdf_buffer = create_pdf_report(traits, quote)
259
+ st.download_button(
260
+ "⬇️ Download PDF Report",
261
+ data=pdf_buffer,
262
+ file_name="personacraft_report.pdf",
263
+ mime="application/pdf",
264
+ use_container_width=True
265
+ )