File size: 11,075 Bytes
7077f97
81379ec
7e297f6
0e2ff7b
 
 
 
44faf53
 
 
0e2ff7b
 
6a3132f
0e2ff7b
76fd838
6a3132f
0e2ff7b
fe3a4fa
6a3132f
0e2ff7b
76fd838
 
 
0e2ff7b
6a3132f
76fd838
7077f97
 
0e2ff7b
 
 
7077f97
0e2ff7b
 
 
 
 
 
 
 
 
7077f97
0e2ff7b
 
 
 
 
 
 
 
 
74a4cc4
0e2ff7b
 
 
 
 
 
 
 
 
 
 
463559d
d682964
 
 
 
 
7077f97
 
 
0e2ff7b
fe3a4fa
11a490b
0e2ff7b
 
 
 
 
 
 
 
 
 
44faf53
 
0e2ff7b
 
 
 
 
 
 
 
 
1e1fdd9
0e2ff7b
 
 
f2f526f
 
 
 
 
 
 
0e2ff7b
 
 
 
 
 
 
 
fe3a4fa
 
 
0e2ff7b
fe3a4fa
 
 
0e2ff7b
 
 
fe3a4fa
0e2ff7b
 
fe3a4fa
 
 
 
0e2ff7b
 
 
 
 
 
 
fe3a4fa
0e2ff7b
 
 
 
f2f526f
0e2ff7b
 
 
 
fe3a4fa
0e2ff7b
7e297f6
0e2ff7b
 
 
 
 
 
 
 
fe3a4fa
0e2ff7b
 
 
 
 
 
 
 
d682964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e2ff7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d682964
0e2ff7b
d682964
 
 
0e2ff7b
d682964
 
 
 
 
 
 
 
 
0e2ff7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py
import streamlit as st
import torch
import random
import altair as alt
import pandas as pd
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import io
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from groq import Groq

# Initialize components
try:
    groq_client = Groq(api_key=st.secrets["GROQ_API_KEY"])
    model = AutoModelForSequenceClassification.from_pretrained("KevSun/Personality_LM", ignore_mismatched_sizes=True)
    tokenizer = AutoTokenizer.from_pretrained("KevSun/Personality_LM")
except Exception as e:
    st.error(f"Initialization error: {str(e)}")
    st.stop()

# Configure Streamlit
st.set_page_config(page_title="🧠 PersonaCraft", layout="wide", page_icon="🌟")

# Custom CSS
st.markdown("""
<style>
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.quote-box {
    animation: fadeIn 1s ease-in;
    border-left: 5px solid #4CAF50;
    padding: 20px;
    margin: 20px 0;
    background: #f8fff9;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.tip-card {
    padding: 15px;
    margin: 10px 0;
    background: #fff3e0;
    border-radius: 10px;
    border: 1px solid #ffab40;
}

.social-post {
    background: #e3f2fd;
    padding: 20px;
    border-radius: 15px;
    margin: 15px 0;
}

.viz-box {
    background: white;
    padding: 20px;
    border-radius: 15px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.nav-btn {
    margin: 8px 0;
    width: 100%;
}
</style>
""", unsafe_allow_html=True)

# Personality configuration
OCEAN_TRAITS = ["agreeableness", "openness", "conscientiousness", "extraversion", "neuroticism"]
QUESTION_BANK = [
    {"text": "If your personality was a pizza topping, what would it be? πŸ•", "trait": "openness"},
    {"text": "Describe your ideal alarm clock vs reality ⏰", "trait": "conscientiousness"},
    {"text": "How would you survive a surprise party? πŸŽ‰", "trait": "neuroticism"},
    {"text": "What's your spirit animal during deadlines? 🐾", "trait": "agreeableness"},
    {"text": "Plan a perfect day... for your nemesis! 😈", "trait": "extraversion"},
    {"text": "If stress was a color, what's your current shade? 🎨", "trait": "neuroticism"},
    {"text": "What would your browser history say about you? 🌐", "trait": "openness"},
    {"text": "Describe your phone's home screen as a poem πŸ“±", "trait": "conscientiousness"},
    {"text": "React to 'Your idea is interesting, but...' πŸ’‘", "trait": "agreeableness"},
    {"text": "What's your superpower in awkward situations? 🦸", "trait": "extraversion"}
]

# Session state management
if 'started' not in st.session_state:
    st.session_state.started = False
if 'current_q' not in st.session_state:
    st.session_state.current_q = 0
if 'responses' not in st.session_state:
    st.session_state.responses = []
if 'page' not in st.session_state:
    st.session_state.page = "🏠 Home"

# Functions
def generate_quote():
    prompt = "Generate a fresh motivational quote about self-discovery with 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 analyze_personality(text):
    encoded_input = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=64)
    with torch.no_grad():
        outputs = model(**encoded_input)
    predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
    return {trait: score.item() for trait, score in zip(OCEAN_TRAITS, predictions[0])}

def create_pdf_report(traits, quote):
    buffer = io.BytesIO()
    p = canvas.Canvas(buffer, pagesize=letter)
    p.setFont("Helvetica-Bold", 16)
    p.drawString(100, 750, "🌟 PersonaCraft Psychological Report 🌟")
    p.setFont("Helvetica", 12)
    
    y_position = 700
    for trait, score in traits.items():
        p.drawString(100, y_position, f"{trait.upper()}: {score:.2f}")
        y_position -= 20
    
    p.drawString(100, y_position-40, "Motivational Quote:")
    p.drawString(100, y_position-60, quote)
    p.save()
    buffer.seek(0)
    return buffer

def generate_social_post(platform, traits):
    platform_formats = {
        "LinkedIn": "professional tone with industry hashtags",
        "Instagram": "visual storytelling with emojis",
        "Facebook": "friendly community-oriented style",
        "WhatsApp": "casual conversational format",
        "Twitter": "concise with trending hashtags"
    }
    prompt = f"""Create a {platform} post about personal growth with these personality traits:
{traits}
Format: {platform_formats[platform]}
Include relevant emojis and keep under 280 characters."""
    
    response = groq_client.chat.completions.create(
        model="mixtral-8x7b-32768",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.7
    )
    return response.choices[0].message.content

# Main UI
if not st.session_state.started:
    st.markdown(f"""
    <div class="quote-box">
        <h2>🌟 Welcome to PersonaCraft! 🌟</h2>
        <h3>{generate_quote()}</h3>
    </div>
    """, unsafe_allow_html=True)
    
    if st.button("πŸš€ Start Personality Journey!", use_container_width=True):
        st.session_state.started = True
        st.session_state.selected_questions = random.sample(QUESTION_BANK, 5)
        st.rerun()
else:
    # Sidebar navigation
    with st.sidebar:
        st.title("🧭 Navigation")
        st.markdown("---")
        if st.button("πŸ“‹ Personality Report", key="btn1", use_container_width=True, 
                    help="View your detailed personality analysis"):
            st.session_state.page = "πŸ“‹ Personality Report"
        
        if st.button("πŸ“Š Visual Analysis", key="btn2", use_container_width=True,
                    help="Explore visual representations of your personality"):
            st.session_state.page = "πŸ“Š Visual Analysis"
        
        if st.button("πŸ“± Social Media Post", key="btn3", use_container_width=True,
                    help="Generate personalized social media posts"):
            st.session_state.page = "πŸ“± Social Media Post"
        
        if st.button("πŸ’‘ Success Tips", key="btn4", use_container_width=True,
                    help="Discover personalized improvement tips"):
            st.session_state.page = "πŸ’‘ Success Tips"
        
        if st.button("πŸ“₯ Download Report", key="btn5", use_container_width=True,
                    help="Download your complete personality report"):
            st.session_state.page = "πŸ“₯ Download Report"

    # Question flow
    if st.session_state.current_q < 5:
        q = st.session_state.selected_questions[st.session_state.current_q]
        st.progress(st.session_state.current_q/5, text="Assessment Progress")
        
        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:
        # Process responses
        traits = analyze_personality("\n".join(st.session_state.responses))
        quote = generate_quote()
        
        # Current page display
        if st.session_state.page == "πŸ“‹ Personality Report":
            st.header("πŸ“‹ Personality Breakdown")
            cols = st.columns(5)
            for i, (trait, score) in enumerate(traits.items()):
                cols[i].metric(label=trait.upper(), value=f"{score:.2f}")
            
            st.divider()
            st.header("🎭 Emotional Landscape")
            emotion_data = pd.DataFrame({
                "Trait": traits.keys(),
                "Score": traits.values()
            })
            st.altair_chart(alt.Chart(emotion_data).mark_bar().encode(
                x="Trait",
                y="Score",
                color=alt.Color("Trait", legend=None)
            ), use_container_width=True)

        elif st.session_state.page == "πŸ“Š Visual Analysis":
            st.header("πŸ“Š Personality Visualization")
            # Fix radar chart encoding
            radar_data = pd.DataFrame({
                "Trait": list(traits.keys()),
                "Score": list(traits.values()),
                "Angle": [i*(360/5) for i in range(5)]
            })
            
            chart = alt.Chart(radar_data).mark_line(point=True).encode(
                theta=alt.Theta("Angle:Q", stack=True),
                radius=alt.Radius("Score:Q", scale=alt.Scale(type='linear', zero=True)),
                color=alt.value("#4CAF50"),
                tooltip=["Trait", "Score"]
            ).project(type='radial')
            
            st.altair_chart(chart, use_container_width=True)

        elif st.session_state.page == "πŸ“± Social Media Post":
            st.header("πŸ“± Create Social Post")
            platform = st.selectbox("Select Platform:", ["LinkedIn", "Instagram", "Facebook", "WhatsApp", "Twitter"])
            
            if st.button("Generate Post πŸš€"):
                post = generate_social_post(platform, traits)
                st.session_state.post = post
            
            if 'post' in st.session_state:
                st.markdown(f"""
                <div class="social-post">
                    <p>{st.session_state.post}</p>
                </div>
                """, unsafe_allow_html=True)
                st.button("πŸ“‹ Copy to Clipboard", on_click=lambda: st.write(st.session_state.post))

        elif st.session_state.page == "πŸ’‘ Success Tips":
            st.header("πŸ’‘ Personality Success Tips")
            tips = [
                "🌱 Practice daily self-reflection journaling",
                "🀝 Seek diverse social interactions weekly",
                "🎯 Set SMART goals for personal development",
                "πŸ§˜β™‚οΈ Incorporate mindfulness practices daily",
                "πŸ“š Engage in cross-disciplinary learning",
                "πŸ—£οΈ Practice active listening techniques",
                "πŸ”„ Embrace constructive feedback regularly",
                "βš–οΈ Maintain work-life harmony",
                "🌟 Develop emotional granularity skills",
                "πŸš€ Challenge comfort zones monthly"
            ]
            for tip in tips:
                st.markdown(f"<div class='tip-card'>{tip}</div>", unsafe_allow_html=True)

        elif st.session_state.page == "πŸ“₯ Download Report":
            st.header("πŸ“₯ Download Complete Report")
            pdf_buffer = create_pdf_report(traits, quote)
            st.download_button(
                "⬇️ Download PDF Report",
                data=pdf_buffer,
                file_name="personacraft_report.pdf",
                mime="application/pdf",
                use_container_width=True
            )