|
|
|
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 |
|
|
|
|
|
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() |
|
|
|
|
|
try: |
|
|
|
personality_analyzer = pipeline( |
|
"zero-shot-classification", |
|
model="facebook/bart-large-mnli" |
|
) |
|
|
|
|
|
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() |
|
|
|
|
|
st.set_page_config(page_title="π§ Mind Mapper", layout="wide", page_icon="π€") |
|
|
|
|
|
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) |
|
|
|
|
|
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 |
|
|
|
|
|
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 |
|
|
|
|
|
st.title("π§ Mind Mapper") |
|
st.markdown("### Your Personal Psychology Assistant πβ¨") |
|
|
|
|
|
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) |
|
|
|
|
|
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: |
|
|
|
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) |
|
|
|
|
|
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%}") |
|
|
|
|
|
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']) |
|
|
|
|
|
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_buffer = create_pdf_report(report) |
|
st.download_button( |
|
"π₯ Download Full Report", |
|
data=pdf_buffer, |
|
file_name="psych_profile.pdf", |
|
mime="application/pdf" |
|
) |
|
|
|
|
|
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 |
|
""") |