Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
21 |
try:
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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="π§
|
37 |
|
38 |
# Custom CSS
|
39 |
st.markdown("""
|
@@ -58,50 +60,38 @@ st.markdown("""
|
|
58 |
</style>
|
59 |
""", unsafe_allow_html=True)
|
60 |
|
61 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
QUESTION_BANK = [
|
63 |
-
{"text": "
|
64 |
-
{"text": "
|
65 |
-
{"text": "
|
66 |
-
{"text": "
|
67 |
-
{"text": "How do you
|
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
|
76 |
-
"""
|
77 |
-
|
78 |
-
|
79 |
-
|
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
|
98 |
-
return
|
99 |
|
100 |
def generate_quote(traits):
|
101 |
-
"""Generate personality-specific quote
|
102 |
prompt = f"""Create a motivational quote for someone with these traits:
|
103 |
{traits}
|
104 |
-
Make it inspirational
|
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.
|
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.
|
123 |
-
|
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, "π
|
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 |
-
"
|
155 |
-
*[f"- {trait.upper()}: {score:.2f}" for trait, score in report['
|
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("π§
|
185 |
-
st.markdown("### Your
|
186 |
|
187 |
# Progress tracker
|
188 |
-
progress = st.session_state.current_q / len(
|
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 |
-
#
|
196 |
-
if st.session_state.current_q < len(
|
197 |
-
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
|
217 |
-
|
218 |
-
|
|
|
219 |
|
220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
221 |
|
222 |
-
#
|
223 |
-
with st.expander("
|
224 |
cols = st.columns(5)
|
225 |
-
|
226 |
-
|
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
|
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 |
-
#
|
237 |
col1, col2 = st.columns(2)
|
238 |
with col1:
|
239 |
-
st.markdown("### π¬
|
240 |
st.success(f'"{report["quote"]}"')
|
241 |
with col2:
|
242 |
-
st.markdown("### π οΈ
|
243 |
-
for tip in report['tips']
|
244 |
st.markdown(f"- {tip}")
|
245 |
|
246 |
-
#
|
247 |
pdf_buffer = create_pdf_report(report)
|
248 |
st.download_button(
|
249 |
"π₯ Download Full Report",
|
250 |
data=pdf_buffer,
|
251 |
-
file_name="
|
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
|
260 |
-
2. Get
|
261 |
-
3. Receive
|
262 |
-
4. Download
|
263 |
|
264 |
-
**
|
265 |
-
-
|
266 |
-
- Emotion
|
267 |
-
- Cognitive
|
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 |
""")
|