Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,91 +1,98 @@
|
|
1 |
# app.py
|
2 |
import streamlit as st
|
3 |
-
from groq import Groq
|
4 |
import torch
|
5 |
-
|
|
|
|
|
|
|
6 |
from reportlab.lib.pagesizes import letter
|
7 |
from reportlab.pdfgen import canvas
|
8 |
import io
|
9 |
-
import
|
10 |
-
from
|
11 |
|
12 |
-
# Initialize
|
13 |
try:
|
14 |
groq_client = Groq(api_key=st.secrets["GROQ_API_KEY"])
|
15 |
-
|
16 |
-
st.error("GROQ_API_KEY missing in secrets! Add it in Hugging Face settings.")
|
17 |
-
st.stop()
|
18 |
-
|
19 |
-
# Load personality model
|
20 |
-
try:
|
21 |
-
model = AutoModelForSequenceClassification.from_pretrained(
|
22 |
-
"KevSun/Personality_LM",
|
23 |
-
ignore_mismatched_sizes=True
|
24 |
-
)
|
25 |
tokenizer = AutoTokenizer.from_pretrained("KevSun/Personality_LM")
|
26 |
except Exception as e:
|
27 |
-
st.error(f"
|
28 |
st.stop()
|
29 |
|
30 |
# Configure Streamlit
|
31 |
-
st.set_page_config(page_title="π§
|
32 |
|
33 |
# Custom CSS
|
34 |
st.markdown("""
|
35 |
<style>
|
36 |
-
@keyframes
|
37 |
-
|
38 |
-
|
39 |
-
40% { color: #ffff00; }
|
40 |
-
60% { color: #00ff00; }
|
41 |
-
80% { color: #0000ff; }
|
42 |
-
100% { color: #ff00ff; }
|
43 |
}
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
.social-post {
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
}
|
55 |
</style>
|
56 |
""", unsafe_allow_html=True)
|
57 |
|
58 |
-
# Personality
|
59 |
OCEAN_TRAITS = ["agreeableness", "openness", "conscientiousness", "extraversion", "neuroticism"]
|
60 |
-
|
61 |
-
# Enhanced question bank with mix of serious and funny questions
|
62 |
QUESTION_BANK = [
|
63 |
-
{"text": "If
|
64 |
-
{"text": "Describe your ideal
|
65 |
-
{"text": "How would you survive a
|
66 |
-
{"text": "What's your spirit animal during
|
67 |
-
{"text": "Plan a perfect
|
68 |
-
{"text": "If
|
69 |
-
{"text": "What would your
|
70 |
-
{"text": "Describe your
|
71 |
-
{"text": "
|
72 |
-
{"text": "What's your superpower in
|
73 |
]
|
74 |
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
|
|
|
|
82 |
|
83 |
-
|
84 |
-
|
85 |
-
prompt =
|
86 |
-
{traits}
|
87 |
-
Include relevant emojis and make it {platform}-appropriate. Keep it under 280 characters."""
|
88 |
-
|
89 |
response = groq_client.chat.completions.create(
|
90 |
model="mixtral-8x7b-32768",
|
91 |
messages=[{"role": "user", "content": prompt}],
|
@@ -93,121 +100,166 @@ Include relevant emojis and make it {platform}-appropriate. Keep it under 280 ch
|
|
93 |
)
|
94 |
return response.choices[0].message.content
|
95 |
|
96 |
-
def
|
97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
buffer = io.BytesIO()
|
99 |
p = canvas.Canvas(buffer, pagesize=letter)
|
100 |
-
|
101 |
p.setFont("Helvetica-Bold", 16)
|
102 |
-
p.drawString(100, 750, "π Psychological
|
103 |
p.setFont("Helvetica", 12)
|
104 |
|
105 |
y_position = 700
|
106 |
-
|
107 |
-
f"
|
108 |
-
|
109 |
-
"Personality Traits:",
|
110 |
-
*[f"- {trait.upper()}: {score:.2f}" for trait, score in report['traits'].items()],
|
111 |
-
"",
|
112 |
-
"Personalized Quote:",
|
113 |
-
report['quote'],
|
114 |
-
]
|
115 |
-
|
116 |
-
for line in content:
|
117 |
-
p.drawString(100, y_position, line)
|
118 |
-
y_position -= 15
|
119 |
|
|
|
|
|
120 |
p.save()
|
121 |
buffer.seek(0)
|
122 |
return buffer
|
123 |
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
# Main UI
|
133 |
-
st.title("π§ Mind Mapper Pro")
|
134 |
-
st.markdown("### Your Advanced Psychology Assistant πβ¨")
|
135 |
-
|
136 |
-
# Progress tracker
|
137 |
-
progress = st.session_state.current_q / 5
|
138 |
-
st.markdown(f"""
|
139 |
-
<div style="background: #f0f2f6; border-radius: 15px; padding: 5px;">
|
140 |
-
<div style="width: {progress*100}%; height: 25px; border-radius: 15px; background: linear-gradient(90deg, #FF6B6B 0%, #4ECDC4 100%);"></div>
|
141 |
-
</div>
|
142 |
-
""", unsafe_allow_html=True)
|
143 |
-
|
144 |
-
# Question flow
|
145 |
-
if st.session_state.current_q < 5:
|
146 |
-
q = st.session_state.selected_questions[st.session_state.current_q]
|
147 |
-
|
148 |
-
with st.chat_message("assistant"):
|
149 |
-
st.markdown(f"### {q['text']}")
|
150 |
-
user_input = st.text_input("Your response:", key=f"q{st.session_state.current_q}")
|
151 |
-
|
152 |
-
if st.button("Next β‘οΈ"):
|
153 |
-
st.session_state.responses.append(user_input)
|
154 |
-
st.session_state.current_q += 1
|
155 |
-
st.rerun()
|
156 |
-
else:
|
157 |
-
# Generate report
|
158 |
-
combined_text = "\n".join(st.session_state.responses)
|
159 |
-
traits = analyze_psychology(combined_text)
|
160 |
-
|
161 |
-
report = {
|
162 |
-
"traits": traits,
|
163 |
-
"quote": generate_social_post("general", traits) # Initial quote
|
164 |
}
|
|
|
|
|
|
|
|
|
165 |
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
with st.expander("𧩠Personality Breakdown"):
|
171 |
-
cols = st.columns(5)
|
172 |
-
for i, (trait, score) in enumerate(report['traits'].items()):
|
173 |
-
cols[i].metric(label=trait.upper(), value=f"{score:.2f}")
|
174 |
-
|
175 |
-
# Social Media Post Generation
|
176 |
-
st.markdown("### π± Create Social Media Post")
|
177 |
-
platform = st.selectbox("Choose platform:", ["LinkedIn", "Instagram", "Facebook", "WhatsApp"])
|
178 |
-
|
179 |
-
if st.button("Generate Post π"):
|
180 |
-
post = generate_social_post(platform, report['traits'])
|
181 |
-
st.session_state.post = post
|
182 |
-
|
183 |
-
if 'post' in st.session_state:
|
184 |
-
st.markdown(f"""
|
185 |
-
<div class="social-post">
|
186 |
-
{st.session_state.post}
|
187 |
-
</div>
|
188 |
-
""", unsafe_allow_html=True)
|
189 |
-
st.button("π Copy Post", on_click=lambda: st.write(st.session_state.post))
|
190 |
-
|
191 |
-
# PDF Report
|
192 |
-
pdf_buffer = create_pdf_report(report)
|
193 |
-
st.download_button(
|
194 |
-
"π₯ Download Full Report",
|
195 |
-
data=pdf_buffer,
|
196 |
-
file_name="personality_profile.pdf",
|
197 |
-
mime="application/pdf"
|
198 |
)
|
|
|
199 |
|
200 |
-
#
|
201 |
-
|
202 |
-
st.markdown("
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
# app.py
|
2 |
import streamlit as st
|
|
|
3 |
import torch
|
4 |
+
import random
|
5 |
+
import altair as alt
|
6 |
+
import pandas as pd
|
7 |
+
from datetime import datetime
|
8 |
from reportlab.lib.pagesizes import letter
|
9 |
from reportlab.pdfgen import canvas
|
10 |
import io
|
11 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
12 |
+
from groq import Groq
|
13 |
|
14 |
+
# Initialize components
|
15 |
try:
|
16 |
groq_client = Groq(api_key=st.secrets["GROQ_API_KEY"])
|
17 |
+
model = AutoModelForSequenceClassification.from_pretrained("KevSun/Personality_LM", ignore_mismatched_sizes=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
tokenizer = AutoTokenizer.from_pretrained("KevSun/Personality_LM")
|
19 |
except Exception as e:
|
20 |
+
st.error(f"Initialization error: {str(e)}")
|
21 |
st.stop()
|
22 |
|
23 |
# Configure Streamlit
|
24 |
+
st.set_page_config(page_title="π§ PersonaCraft", layout="wide", page_icon="π")
|
25 |
|
26 |
# Custom CSS
|
27 |
st.markdown("""
|
28 |
<style>
|
29 |
+
@keyframes fadeIn {
|
30 |
+
from { opacity: 0; }
|
31 |
+
to { opacity: 1; }
|
|
|
|
|
|
|
|
|
32 |
}
|
33 |
+
|
34 |
+
.quote-box {
|
35 |
+
animation: fadeIn 1s ease-in;
|
36 |
+
border-left: 5px solid #4CAF50;
|
37 |
+
padding: 20px;
|
38 |
+
margin: 20px 0;
|
39 |
+
background: #f8fff9;
|
40 |
+
border-radius: 10px;
|
41 |
+
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
42 |
}
|
43 |
+
|
44 |
+
.tip-card {
|
45 |
+
padding: 15px;
|
46 |
+
margin: 10px 0;
|
47 |
+
background: #fff3e0;
|
48 |
+
border-radius: 10px;
|
49 |
+
border: 1px solid #ffab40;
|
50 |
+
}
|
51 |
+
|
52 |
.social-post {
|
53 |
+
background: #e3f2fd;
|
54 |
+
padding: 20px;
|
55 |
+
border-radius: 15px;
|
56 |
+
margin: 15px 0;
|
57 |
+
}
|
58 |
+
|
59 |
+
.viz-box {
|
60 |
+
background: white;
|
61 |
+
padding: 20px;
|
62 |
+
border-radius: 15px;
|
63 |
+
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
64 |
}
|
65 |
</style>
|
66 |
""", unsafe_allow_html=True)
|
67 |
|
68 |
+
# Personality configuration
|
69 |
OCEAN_TRAITS = ["agreeableness", "openness", "conscientiousness", "extraversion", "neuroticism"]
|
|
|
|
|
70 |
QUESTION_BANK = [
|
71 |
+
{"text": "If your personality was a pizza topping, what would it be? π", "trait": "openness"},
|
72 |
+
{"text": "Describe your ideal alarm clock vs reality β°", "trait": "conscientiousness"},
|
73 |
+
{"text": "How would you survive a surprise party? π", "trait": "neuroticism"},
|
74 |
+
{"text": "What's your spirit animal during deadlines? πΎ", "trait": "agreeableness"},
|
75 |
+
{"text": "Plan a perfect day... for your nemesis! π", "trait": "extraversion"},
|
76 |
+
{"text": "If stress was a color, what's your current shade? π¨", "trait": "neuroticism"},
|
77 |
+
{"text": "What would your browser history say about you? π", "trait": "openness"},
|
78 |
+
{"text": "Describe your phone's home screen as a poem π±", "trait": "conscientiousness"},
|
79 |
+
{"text": "React to 'Your idea is interesting, but...' π‘", "trait": "agreeableness"},
|
80 |
+
{"text": "What's your superpower in awkward situations? π¦Έ", "trait": "extraversion"}
|
81 |
]
|
82 |
|
83 |
+
# Session state management
|
84 |
+
if 'started' not in st.session_state:
|
85 |
+
st.session_state.started = False
|
86 |
+
if 'current_q' not in st.session_state:
|
87 |
+
st.session_state.current_q = 0
|
88 |
+
if 'responses' not in st.session_state:
|
89 |
+
st.session_state.responses = []
|
90 |
+
if 'page' not in st.session_state:
|
91 |
+
st.session_state.page = "π Home"
|
92 |
|
93 |
+
# Functions
|
94 |
+
def generate_quote():
|
95 |
+
prompt = "Generate a fresh motivational quote about self-discovery with an emoji"
|
|
|
|
|
|
|
96 |
response = groq_client.chat.completions.create(
|
97 |
model="mixtral-8x7b-32768",
|
98 |
messages=[{"role": "user", "content": prompt}],
|
|
|
100 |
)
|
101 |
return response.choices[0].message.content
|
102 |
|
103 |
+
def analyze_personality(text):
|
104 |
+
encoded_input = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=64)
|
105 |
+
with torch.no_grad():
|
106 |
+
outputs = model(**encoded_input)
|
107 |
+
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
108 |
+
return {trait: score.item() for trait, score in zip(OCEAN_TRAITS, predictions[0])}
|
109 |
+
|
110 |
+
def create_pdf_report(traits, quote):
|
111 |
buffer = io.BytesIO()
|
112 |
p = canvas.Canvas(buffer, pagesize=letter)
|
|
|
113 |
p.setFont("Helvetica-Bold", 16)
|
114 |
+
p.drawString(100, 750, "π PersonaCraft Psychological Report π")
|
115 |
p.setFont("Helvetica", 12)
|
116 |
|
117 |
y_position = 700
|
118 |
+
for trait, score in traits.items():
|
119 |
+
p.drawString(100, y_position, f"{trait.upper()}: {score:.2f}")
|
120 |
+
y_position -= 20
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
121 |
|
122 |
+
p.drawString(100, y_position-40, "Motivational Quote:")
|
123 |
+
p.drawString(100, y_position-60, quote)
|
124 |
p.save()
|
125 |
buffer.seek(0)
|
126 |
return buffer
|
127 |
|
128 |
+
def generate_social_post(platform, traits):
|
129 |
+
platform_formats = {
|
130 |
+
"LinkedIn": "professional tone with industry hashtags",
|
131 |
+
"Instagram": "visual storytelling with emojis",
|
132 |
+
"Facebook": "friendly community-oriented style",
|
133 |
+
"WhatsApp": "casual conversational format",
|
134 |
+
"Twitter": "concise with trending hashtags"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
}
|
136 |
+
prompt = f"""Create a {platform} post about personal growth with these personality traits:
|
137 |
+
{traits}
|
138 |
+
Format: {platform_formats[platform]}
|
139 |
+
Include relevant emojis and keep under 280 characters."""
|
140 |
|
141 |
+
response = groq_client.chat.completions.create(
|
142 |
+
model="mixtral-8x7b-32768",
|
143 |
+
messages=[{"role": "user", "content": prompt}],
|
144 |
+
temperature=0.7
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
)
|
146 |
+
return response.choices[0].message.content
|
147 |
|
148 |
+
# Main UI
|
149 |
+
if not st.session_state.started:
|
150 |
+
st.markdown(f"""
|
151 |
+
<div class="quote-box">
|
152 |
+
<h2>π Welcome to PersonaCraft! π</h2>
|
153 |
+
<h3>{generate_quote()}</h3>
|
154 |
+
</div>
|
155 |
+
""", unsafe_allow_html=True)
|
156 |
|
157 |
+
if st.button("π Start Personality Journey!", use_container_width=True):
|
158 |
+
st.session_state.started = True
|
159 |
+
st.session_state.selected_questions = random.sample(QUESTION_BANK, 5)
|
160 |
+
st.rerun()
|
161 |
+
else:
|
162 |
+
# Sidebar navigation
|
163 |
+
with st.sidebar:
|
164 |
+
st.title("π§ Navigation")
|
165 |
+
st.session_state.page = st.radio("Choose Section:", [
|
166 |
+
"π Personality Report",
|
167 |
+
"π Visual Analysis",
|
168 |
+
"π± Social Media Post",
|
169 |
+
"π‘ Success Tips",
|
170 |
+
"π₯ Download Report"
|
171 |
+
])
|
172 |
+
|
173 |
+
# Question flow
|
174 |
+
if st.session_state.current_q < 5:
|
175 |
+
q = st.session_state.selected_questions[st.session_state.current_q]
|
176 |
+
st.progress(st.session_state.current_q/5, text="Assessment Progress")
|
177 |
+
|
178 |
+
with st.chat_message("assistant"):
|
179 |
+
st.markdown(f"### {q['text']}")
|
180 |
+
user_input = st.text_input("Your response:", key=f"q{st.session_state.current_q}")
|
181 |
+
|
182 |
+
if st.button("Next β‘οΈ"):
|
183 |
+
st.session_state.responses.append(user_input)
|
184 |
+
st.session_state.current_q += 1
|
185 |
+
st.rerun()
|
186 |
+
else:
|
187 |
+
# Process responses
|
188 |
+
traits = analyze_personality("\n".join(st.session_state.responses))
|
189 |
+
quote = generate_quote()
|
190 |
+
|
191 |
+
# Current page display
|
192 |
+
if st.session_state.page == "π Personality Report":
|
193 |
+
st.header("π Personality Breakdown")
|
194 |
+
cols = st.columns(5)
|
195 |
+
for i, (trait, score) in enumerate(traits.items()):
|
196 |
+
cols[i].metric(label=trait.upper(), value=f"{score:.2f}")
|
197 |
+
|
198 |
+
st.divider()
|
199 |
+
st.header("π Emotional Landscape")
|
200 |
+
emotion_data = pd.DataFrame({
|
201 |
+
"Trait": traits.keys(),
|
202 |
+
"Score": traits.values()
|
203 |
+
})
|
204 |
+
st.altair_chart(alt.Chart(emotion_data).mark_bar().encode(
|
205 |
+
x="Trait",
|
206 |
+
y="Score",
|
207 |
+
color=alt.Color("Trait", legend=None)
|
208 |
+
), use_container_width=True)
|
209 |
+
|
210 |
+
elif st.session_state.page == "π Visual Analysis":
|
211 |
+
st.header("π Personality Visualization")
|
212 |
+
radar_data = pd.DataFrame({
|
213 |
+
"Trait": list(traits.keys()) * 2,
|
214 |
+
"Score": list(traits.values()) * 2,
|
215 |
+
"Type": ["Base"]*5 + ["Current"]*5
|
216 |
+
})
|
217 |
+
st.altair_chart(alt.Chart(radar_data).mark_line().encode(
|
218 |
+
theta="Trait",
|
219 |
+
r="Score",
|
220 |
+
color="Type"
|
221 |
+
).project(type='radial'), use_container_width=True)
|
222 |
+
|
223 |
+
elif st.session_state.page == "π± Social Media Post":
|
224 |
+
st.header("π± Create Social Post")
|
225 |
+
platform = st.selectbox("Select Platform:", ["LinkedIn", "Instagram", "Facebook", "WhatsApp", "Twitter"])
|
226 |
+
|
227 |
+
if st.button("Generate Post π"):
|
228 |
+
post = generate_social_post(platform, traits)
|
229 |
+
st.session_state.post = post
|
230 |
+
|
231 |
+
if 'post' in st.session_state:
|
232 |
+
st.markdown(f"""
|
233 |
+
<div class="social-post">
|
234 |
+
<p>{st.session_state.post}</p>
|
235 |
+
</div>
|
236 |
+
""", unsafe_allow_html=True)
|
237 |
+
st.button("οΏ½οΏ½οΏ½ Copy to Clipboard", on_click=lambda: st.write(st.session_state.post))
|
238 |
+
|
239 |
+
elif st.session_state.page == "π‘ Success Tips":
|
240 |
+
st.header("π‘ Personality Success Tips")
|
241 |
+
tips = [
|
242 |
+
"π± Practice daily self-reflection journaling",
|
243 |
+
"π€ Seek diverse social interactions weekly",
|
244 |
+
"π― Set SMART goals for personal development",
|
245 |
+
"π§βοΈ Incorporate mindfulness practices daily",
|
246 |
+
"π Engage in cross-disciplinary learning",
|
247 |
+
"π£οΈ Practice active listening techniques",
|
248 |
+
"π Embrace constructive feedback regularly",
|
249 |
+
"βοΈ Maintain work-life harmony",
|
250 |
+
"π Develop emotional granularity skills",
|
251 |
+
"π Challenge comfort zones monthly"
|
252 |
+
]
|
253 |
+
for tip in tips:
|
254 |
+
st.markdown(f"<div class='tip-card'>{tip}</div>", unsafe_allow_html=True)
|
255 |
+
|
256 |
+
elif st.session_state.page == "π₯ Download Report":
|
257 |
+
st.header("π₯ Download Complete Report")
|
258 |
+
pdf_buffer = create_pdf_report(traits, quote)
|
259 |
+
st.download_button(
|
260 |
+
"β¬οΈ Download PDF Report",
|
261 |
+
data=pdf_buffer,
|
262 |
+
file_name="personacraft_report.pdf",
|
263 |
+
mime="application/pdf",
|
264 |
+
use_container_width=True
|
265 |
+
)
|