File size: 10,619 Bytes
7077f97
81379ec
7077f97
bd3a27a
11a490b
7077f97
11a490b
116c6ba
44faf53
 
 
6a3132f
76fd838
 
6a3132f
76fd838
 
 
6a3132f
706a81d
6a3132f
706a81d
 
 
 
 
 
 
 
db0155e
 
 
6a3132f
76fd838
 
 
 
706a81d
6a3132f
76fd838
7077f97
 
11a490b
 
 
 
 
 
 
7077f97
11a490b
 
 
7077f97
 
44faf53
 
11a490b
7077f97
c10c05c
 
 
 
 
 
 
7077f97
 
 
706a81d
 
 
 
 
 
 
 
 
11a490b
706a81d
 
 
 
 
44faf53
 
706a81d
 
 
 
 
11a490b
f2f526f
706a81d
 
f2f526f
 
706a81d
f2f526f
 
706a81d
f2f526f
 
 
 
 
 
 
 
 
7337843
f2f526f
7337843
 
f2f526f
7337843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2f526f
7337843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2f526f
 
76fd838
f2f526f
 
 
 
706a81d
f2f526f
 
 
 
 
 
706a81d
 
f2f526f
 
 
 
 
 
 
 
c10c05c
 
f2f526f
 
 
 
 
 
 
 
116c6ba
11a490b
44faf53
 
11a490b
 
44faf53
f2f526f
706a81d
 
f2f526f
 
706a81d
f2f526f
 
 
 
 
44faf53
706a81d
 
 
11a490b
f2f526f
 
 
11a490b
f2f526f
 
 
76fd838
f2f526f
706a81d
 
 
 
f2f526f
706a81d
 
 
 
 
 
 
 
 
f2f526f
706a81d
 
f2f526f
706a81d
 
f2f526f
 
706a81d
f2f526f
 
 
 
706a81d
f2f526f
 
706a81d
f2f526f
 
c10c05c
 
 
 
 
 
 
f2f526f
706a81d
f2f526f
 
 
 
706a81d
f2f526f
 
c10c05c
f2f526f
 
 
 
706a81d
 
 
 
f2f526f
706a81d
 
 
 
76fd838
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# app.py
import streamlit as st
from groq import Groq
from textblob import TextBlob
from transformers import pipeline
import re
import random
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import io

# Initialize components with proper error handling
try:
    groq_client = Groq(api_key=st.secrets["GROQ_API_KEY"])
except KeyError:
    st.error("GROQ_API_KEY missing in secrets! Add it in Hugging Face settings.")
    st.stop()

# Initialize psychological models using verified public models
try:
    # Personality insights using zero-shot classification
    personality_analyzer = pipeline(
        "zero-shot-classification",
        model="facebook/bart-large-mnli"
    )
    
    # Emotion detection model
    emotion_classifier = pipeline(
        "text-classification", 
        model="j-hartmann/emotion-english-distilroberta-base"
    )
except Exception as e:
    st.error(f"Model loading error: {str(e)}")
    st.stop()

# Configure Streamlit
st.set_page_config(page_title="🧠 Mind Mapper", layout="wide", page_icon="πŸ€–")

# Custom CSS
st.markdown("""
<style>
@keyframes rainbow {
  0% { color: #ff0000; }
  20% { color: #ff8000; }
  40% { color: #ffff00; }
  60% { color: #00ff00; }
  80% { color: #0000ff; }
  100% { color: #ff00ff; }
}
.personality-title {
  animation: rainbow 3s infinite;
  font-size: 2.5em !important;
}
.progress-bar {
  height: 25px;
  border-radius: 15px;
  background: linear-gradient(90deg, #FF6B6B 0%, #4ECDC4 100%);
}
.tip-box {
  border-left: 4px solid #4CAF50;
  padding: 10px 15px;
  margin: 10px 0;
  background: #f8f9fa;
  border-radius: 5px;
}
</style>
""", unsafe_allow_html=True)

# Personality traits and questions
OCEAN_TRAITS = {
    "openness": ["curious", "creative", "adventurous"],
    "conscientiousness": ["organized", "responsible", "disciplined"],
    "extraversion": ["outgoing", "energetic", "sociable"],
    "agreeableness": ["friendly", "compassionate", "cooperative"],
    "neuroticism": ["sensitive", "nervous", "emotional"]
}

QUESTION_BANK = [
    {"text": "How do you typically approach new experiences? 🌍", "trait": "openness"},
    {"text": "Describe your ideal weekend vs reality 🏝️", "trait": "conscientiousness"},
    {"text": "How do you recharge after social events? πŸͺ«", "trait": "extraversion"},
    {"text": "Your reaction to someone disagreeing with you? πŸ’’", "trait": "agreeableness"},
    {"text": "How do you handle unexpected changes? πŸŒ€", "trait": "neuroticism"}
]

def analyze_psychology(text):
    """Analyze personality traits using zero-shot classification"""
    candidate_labels = list(OCEAN_TRAITS.keys())
    result = personality_analyzer(text, candidate_labels, multi_label=True)
    return {label: score for label, score in zip(result['labels'], result['scores'])}

def analyze_emotions(text):
    """Detect emotional tone"""
    return emotion_classifier(text[:512])

def generate_quote(traits):
    """Generate personality-specific quote"""
    prompt = f"""Create a motivational quote for someone with these traits:
{traits}
Make it inspirational and include an emoji."""
    
    response = groq_client.chat.completions.create(
        model="mixtral-8x7b-32768",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.7
    )
    return response.choices[0].message.content

def generate_tips(traits):
    """Generate evidence-based psychological tips for all traits"""
    tips = []
    
    # Openness
    if traits.get('openness', 0) > 0.7:
        tips.extend([
            "🎨 Creative boost: Try 'morning pages' - write 3 stream-of-consciousness pages each morning",
            "🌍 Novelty diet: Schedule one new experience weekly (new route, food, or activity)"
        ])
    else:
        tips.append("πŸ“š Structured exploration: Try a 'learning hour' weekly on a fixed schedule about random topics")

    # Conscientiousness
    if traits.get('conscientiousness', 0) > 0.6:
        tips.extend([
            "⏱️ Time boxing: Use the 52/17 rule (52 mins work, 17 mins break) for optimal productivity",
            "πŸ“¦ Declutter challenge: Remove 10 unnecessary items from your workspace daily"
        ])
    else:
        tips.extend([
            "🎯 Micro-goals: Break tasks into 5-minute chunks with immediate rewards",
            "πŸ“… Habit stacking: Attach new habits to existing routines (e.g., meditate after brushing teeth)"
        ])

    # Extraversion
    if traits.get('extraversion', 0) > 0.6:
        tips.extend([
            "πŸ‘₯ Energy sharing: Schedule weekly 'idea exchanges' with friends",
            "🎀 Social charging: Host monthly themed dinners to fuel your social battery"
        ])
    else:
        tips.extend([
            "πŸ“” Reflection ritual: Keep an 'insight journal' for deep thinking sessions",
            "🧠 Solo innovation: Try monthly 'solo design sprints' for personal projects"
        ])

    # Agreeableness
    if traits.get('agreeableness', 0) > 0.6:
        tips.extend([
            "πŸ›‘οΈ Boundary practice: Start sentences with 'I choose to...' instead of 'I have to...'",
            "πŸ’ͺ Diplomatic assertiveness: Use the 'DESC' script (Describe, Express, Specify, Consequences)"
        ])
    else:
        tips.extend([
            "🀝 Perspective walks: Have weekly conversations where you only ask questions",
            "❀️ Compassion training: Practice daily '3-good-things' gratitude journaling"
        ])

    # Neuroticism
    if traits.get('neuroticism', 0) > 0.6:
        tips.extend([
            "πŸ›‘ Anxiety containment: Create a 'worry window' (15 mins/day dedicated to problem-solving)",
            "🌊 Emotional surfing: Practice observing feelings like waves (notice-name-allow technique)"
        ])
    else:
        tips.extend([
            "🎭 Vulnerability practice: Share one authentic feeling daily with someone",
            "🚧 Comfort zone challenges: Do something mildly uncomfortable weekly"
        ])

    # General well-being tips
    tips.extend([
        "πŸ’€ Sleep hygiene: Follow 10-3-2-1-0 formula (10h before bed: caffeine, 3h: food, 2h: work, 1h: screens, 0 snooze)",
        "🧠 Cognitive refueling: Practice 20-20-20 rule (every 20 mins, look 20 ft away for 20 sec)",
        "❀️ Self-compassion break: When stressed, say 'This is hard, but I'm doing my best'"
    ])

    return tips[:15]  # Return top 15 most relevant tips

def create_pdf_report(report):
    """Generate downloadable PDF report"""
    buffer = io.BytesIO()
    p = canvas.Canvas(buffer, pagesize=letter)
    
    p.setFont("Helvetica-Bold", 16)
    p.drawString(100, 750, "🌟 Psychological Profile Report 🌟")
    p.setFont("Helvetica", 12)
    
    y_position = 700
    content = [
        f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M')}",
        "",
        "Personality Traits:",
        *[f"- {trait.upper()}: {score:.2f}" for trait, score in report['traits'].items()],
        "",
        "Emotional Analysis:",
        *[f"- {emo['label']}: {emo['score']:.2f}" for emo in report['emotions']],
        "",
        "Personalized Quote:",
        report['quote'],
        "",
        "Growth Tips:",
        *[f"{i+1}. {tip}" for i, tip in enumerate(report['tips'])]
    ]
    
    for line in content:
        p.drawString(100, y_position, line)
        y_position -= 15
    
    p.save()
    buffer.seek(0)
    return buffer

# Session state management
if 'responses' not in st.session_state:
    st.session_state.responses = []
if 'current_q' not in st.session_state:
    st.session_state.current_q = 0

# Main UI
st.title("🧠 Mind Mapper")
st.markdown("### Your Personal Psychology Assistant πŸ”βœ¨")

# Progress tracker
progress = st.session_state.current_q / len(QUESTION_BANK)
st.markdown(f"""
<div style="background: #f0f2f6; border-radius: 15px; padding: 5px;">
    <div class="progress-bar" style="width: {progress*100}%; height: 25px;"></div>
</div>
""", unsafe_allow_html=True)

# Question flow
if st.session_state.current_q < len(QUESTION_BANK):
    q = QUESTION_BANK[st.session_state.current_q]
    
    with st.chat_message("assistant"):
        st.markdown(f"### {q['text']}")
        user_input = st.text_input("Your response:", key=f"q{st.session_state.current_q}")
        
        if st.button("Next ➑️"):
            st.session_state.responses.append(user_input)
            st.session_state.current_q += 1
            st.rerun()
else:
    # Generate report
    combined_text = "\n".join(st.session_state.responses)
    traits = analyze_psychology(combined_text)
    emotions = analyze_emotions(combined_text)
    
    report = {
        "traits": traits,
        "emotions": emotions,
        "quote": generate_quote(traits),
        "tips": generate_tips(traits)
    }
    
    st.balloons()
    st.markdown(f"## <div class='personality-title'>🌟 Your Psychological Profile 🌟</div>", unsafe_allow_html=True)
    
    # Trait Visualization
    with st.expander("🧩 Personality Breakdown"):
        cols = st.columns(5)
        for i, (trait, score) in enumerate(report['traits'].items()):
            cols[i].metric(label=trait.upper(), value=f"{score:.0%}")
    
    # Emotional Analysis
    with st.expander("🎭 Emotional Landscape"):
        emotion = max(report['emotions'], key=lambda x: x['score'])
        st.markdown(f"**Dominant Emotion**: {emotion['label']} ({emotion['score']:.0%})")
        st.progress(emotion['score'])
    
    # Recommendations
    col1, col2 = st.columns(2)
    with col1:
        st.markdown("### πŸ’¬ Personalized Wisdom")
        st.success(f'"{report["quote"]}"')
    with col2:
        st.markdown("### πŸ› οΈ Actionable Psychology Hacks")
        for i, tip in enumerate(report['tips']):
            st.markdown(f"""
            <div class="tip-box">
                <strong>#{i+1}</strong> {tip}
            </div>
            """, unsafe_allow_html=True)
    
    # PDF Report
    pdf_buffer = create_pdf_report(report)
    st.download_button(
        "πŸ“₯ Download Full Report", 
        data=pdf_buffer, 
        file_name="psych_profile.pdf",
        mime="application/pdf"
    )

# Sidebar
with st.sidebar:
    st.markdown("## 🌈 How It Works")
    st.markdown("""
    1. Answer 5 psychology-based questions
    2. Get instant personality analysis
    3. Receive emotional insights
    4. Download personalized report
    
    **Science Behind It:**
    - Zero-shot personality classification
    - Emotion recognition (RoBERTa)
    - Cognitive behavioral therapy principles
    """)