File size: 7,585 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
 
 
 
706a81d
 
 
 
 
 
 
 
 
11a490b
706a81d
 
 
 
 
44faf53
 
706a81d
 
 
 
 
11a490b
f2f526f
706a81d
 
f2f526f
 
706a81d
f2f526f
 
706a81d
f2f526f
 
 
 
 
 
 
 
 
76fd838
f2f526f
 
706a81d
f2f526f
706a81d
 
f2f526f
 
76fd838
f2f526f
 
 
 
706a81d
f2f526f
 
 
 
 
 
706a81d
 
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
 
706a81d
 
f2f526f
 
706a81d
f2f526f
 
 
 
706a81d
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
# 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%);
}
</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"""
    tips = []
    if traits.get('openness', 0) > 0.7:
        tips.append("🎨 Try creative cross-training: Write a short story about your day")
    if traits.get('neuroticism', 0) > 0.6:
        tips.append("🧘 Practice 4-7-8 breathing: Inhale 4s, hold 7s, exhale 8s")
    return tips[:5]

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 Tips")
        for tip in report['tips']:
            st.markdown(f"- {tip}")
    
    # 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
    """)