Spaces:
Running
Running
File size: 12,339 Bytes
f13c4f4 be4f650 f64656d f13c4f4 f64656d d675e08 f64656d 7b64bbd f64656d dc01735 be4f650 dc01735 7b64bbd be4f650 491f880 7b64bbd 09b864a 7b64bbd be4f650 7b64bbd 634bf96 be4f650 634bf96 be4f650 634bf96 7b64bbd 634bf96 be4f650 634bf96 7b64bbd 634bf96 33718ef 634bf96 f64656d 634bf96 33718ef 634bf96 dc01735 634bf96 33718ef 634bf96 33718ef 634bf96 33718ef 634bf96 d09a5db 634bf96 33718ef 634bf96 bb2d1c0 634bf96 7b64bbd bb2d1c0 7b64bbd 33718ef bb2d1c0 33718ef bb2d1c0 33718ef 7b64bbd 33718ef 7b64bbd 33718ef 7b64bbd bb2d1c0 33718ef bb2d1c0 33718ef bb2d1c0 33718ef 7b64bbd 33718ef bb2d1c0 95965a1 bb2d1c0 95965a1 bb2d1c0 7b64bbd 95965a1 bb2d1c0 95965a1 7b64bbd 33718ef 7b64bbd 33718ef 7b64bbd 33718ef 7b64bbd 33718ef 7b64bbd bb2d1c0 7b64bbd 33718ef 7b64bbd 33718ef bb2d1c0 f55e2b1 2063026 fd9459a 2063026 f55e2b1 fd9459a f55e2b1 fd9459a f55e2b1 fd9459a f55e2b1 fd9459a 2063026 f55e2b1 7b64bbd 2063026 f55e2b1 fd9459a f55e2b1 2063026 f55e2b1 2063026 fd9459a 2063026 fd9459a 2063026 f55e2b1 7b64bbd fd9459a 7b64bbd 33718ef 7b64bbd 33718ef bb2d1c0 33718ef bb2d1c0 |
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 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 |
from __future__ import annotations
import time
import uuid
import re
from pathlib import Path
import streamlit as st
from config import AVATAR_DIR
from storage import Profile, ProfileStore
from utils import normalize_skill_list, make_prompt_for_matching
from groq_client import ask_groq_for_matches
from matching import calculate_local_matches
from feedback import save_feedback
from ui_styles import BASE_CSS
# ----------------------------------------------
# Streamlit Config
# ----------------------------------------------
st.set_page_config(
page_title="AI Skill Swap",
page_icon="π€",
layout="wide",
)
st.markdown(f"<style>{BASE_CSS}</style>", unsafe_allow_html=True)
store = ProfileStore()
# ----------------------------------------------
# Header Section
# ----------------------------------------------
col_logo, col_title = st.columns([1, 6])
with col_logo:
try:
st.image("logo.jpg", width=90)
except:
st.image("https://via.placeholder.com/100x100/4F46E5/FFFFFF?text=π€", width=90)
with col_title:
st.title("AI Skill Swap")
st.caption("Teach what you know β’ Learn what you love β’ Match intelligently")
# ----------------------------------------------
# Sidebar: Profile Management
# ----------------------------------------------
with st.sidebar:
st.header("π€ Profile Manager")
profiles = store.load_all()
usernames = [p.username for p in profiles]
selected_user = st.selectbox(
"Select profile",
["β Create New β"] + usernames,
key="selected_user"
)
st.markdown("### π Profile Details")
username = st.text_input(
"Username",
value="" if selected_user == "β Create New β" else selected_user,
key="username_input"
)
offers_text = st.text_area(
"Skills you can teach",
height=90,
value=st.session_state.get("offers_text", ""),
placeholder="Python, React, Data Science",
key="offers_input"
)
wants_text = st.text_area(
"Skills you want to learn",
height=90,
value=st.session_state.get("wants_text", ""),
placeholder="LLMs, DevOps, UI Design",
key="wants_input"
)
availability = st.text_input(
"Availability",
placeholder="Evenings / Weekends",
value=st.session_state.get("availability", ""),
key="availability_input"
)
preferences = st.text_input(
"Language / Preferences",
placeholder="English, Hindi, Urdu",
value=st.session_state.get("preferences", ""),
key="preferences_input"
)
avatar_file = st.file_uploader(
"Upload Avatar (Max 800KB)",
type=["png", "jpg", "jpeg"],
key="avatar_uploader"
)
# Avatar Preview & Size Check
if avatar_file:
st.image(avatar_file, width=150, caption="Preview Avatar")
if avatar_file.size > 800 * 1024:
st.error("File exceeds 800KB!")
avatar_file = None
st.markdown("---")
col_create, col_update = st.columns(2)
# Create Button
with col_create:
if st.button("β Create", key="create_button", use_container_width=True):
if not username.strip():
st.error("Username is required!")
elif store.find_by_username(username):
st.error("Already exists β use Update!")
else:
avatar_path = None
if avatar_file:
safe = re.sub(r"[^A-Za-z0-9_.-]", "_", username)
ext = Path(avatar_file.name).suffix
avatar_path = str(
AVATAR_DIR / f"{safe}_{int(time.time())}{ext}"
)
with open(avatar_path, "wb") as f:
f.write(avatar_file.getbuffer())
profile = Profile(
id=str(uuid.uuid4()),
username=username.strip(),
offers=normalize_skill_list(offers_text),
wants=normalize_skill_list(wants_text),
availability=availability.strip(),
preferences=preferences.strip(),
avatar=avatar_path,
)
ok, msg = store.add_or_update(profile)
if ok:
st.success(msg)
# Clear fields on create
for key in ["offers_text", "wants_text", "availability", "preferences"]:
if key in st.session_state:
del st.session_state[key]
if "avatar_uploader" in st.session_state:
del st.session_state["avatar_uploader"]
# Clear previous matches
st.session_state["matches"] = []
st.rerun()
else:
st.error(msg)
# Update Button
with col_update:
if st.button("πΎ Update", key="update_button", use_container_width=True):
existing = store.find_by_username(username)
if not existing:
st.error("Profile does not exist.")
else:
existing.offers = normalize_skill_list(offers_text)
existing.wants = normalize_skill_list(wants_text)
existing.availability = availability.strip()
existing.preferences = preferences.strip()
if avatar_file:
safe = re.sub(r"[^A-Za-z0-9_.-]", "_", username)
ext = Path(avatar_file.name).suffix
avatar_path = str(
AVATAR_DIR / f"{safe}_{int(time.time())}{ext}"
)
with open(avatar_path, "wb") as f:
f.write(avatar_file.getbuffer())
existing.avatar = avatar_path
store.add_or_update(existing)
st.success("Profile updated")
if "avatar_uploader" in st.session_state:
del st.session_state["avatar_uploader"]
st.rerun()
# Delete Button
if selected_user != "β Create New β":
if st.button("ποΈ Delete Profile", key="delete_button", type="secondary"):
ok, msg = store.delete(selected_user)
if ok:
st.warning(msg)
# Clear sidebar fields
for key in ["username_input", "offers_input", "wants_input", "availability_input", "preferences_input"]:
if key in st.session_state:
del st.session_state[key]
if "avatar_uploader" in st.session_state:
del st.session_state["avatar_uploader"]
st.rerun()
else:
st.error(msg)
# ----------------------------------------------
# Main Content - Community Profiles
# ----------------------------------------------
left, right = st.columns([2, 3])
with left:
st.subheader("π Community Profiles")
profiles = store.load_all()
if not profiles:
st.info("No profiles yet. Create one above.")
else:
for p in profiles:
st.markdown("<div class='card'>", unsafe_allow_html=True)
cols = st.columns([1, 4])
with cols[0]:
if p.avatar and Path(p.avatar).exists():
st.image(p.avatar, width=120)
else:
st.image("https://via.placeholder.com/120", width=120)
with cols[1]:
st.markdown(f"**{p.username}**")
st.caption(f"{p.availability} β’ {p.preferences}")
st.markdown(f"π§ **Offers:** {', '.join(p.offers) or 'β'}")
st.markdown(f"π― **Wants:** {', '.join(p.wants) or 'β'}")
st.markdown("</div>", unsafe_allow_html=True)
# ----------------------------------------------
# AI Matchmaking
# ----------------------------------------------
with right:
st.subheader("π€ AI Matchmaking")
if not profiles:
st.info("Add profiles to enable matchmaking.")
else:
pick = st.selectbox(
"Match for profile",
[p.username for p in profiles],
key="matchmaking_select"
)
if st.button("β¨ Find Best Matches", key="find_matches_button"):
with st.spinner("Finding best matches..."):
current = store.find_by_username(pick)
try:
sys_msg, user_msg = make_prompt_for_matching(
current, profiles, 3
)
raw_matches = ask_groq_for_matches(sys_msg, user_msg)
except Exception as e:
st.info(
f"Using local matching due to: {str(e)[:100]}..."
)
raw_matches = calculate_local_matches(
current,
[p for p in profiles if p.id != current.id],
3,
)
enriched = []
for rm in raw_matches:
prof = store.find_by_username(rm.get("username", ""))
if not prof:
continue
# π SAFE SCORE HANDLING
try:
raw_score = float(rm.get("score", 0))
except (ValueError, TypeError):
raw_score = 0.0
raw_score = max(0.0, min(raw_score, 1.0))
enriched.append({
"username": prof.username,
"offers": prof.offers,
"wants": prof.wants,
"avatar": prof.avatar,
"score": raw_score, # ALWAYS 0β1
"reason": rm.get("reason", "AI Match")
})
st.session_state["matches"] = enriched
matches_list = st.session_state.get("matches", [])
if matches_list:
st.markdown(
f"### π― Top {len(matches_list)} Matches for {pick}"
)
for m in matches_list:
st.markdown("<div class='card'>", unsafe_allow_html=True)
cols = st.columns([1, 4])
with cols[0]:
if m.get("avatar") and Path(m["avatar"]).exists():
st.image(m["avatar"], width=120)
else:
st.image(
"https://via.placeholder.com/120",
width=120
)
with cols[1]:
st.markdown(f"### {m['username']}")
score_float = m["score"] # 0β1
score_percent = int(score_float * 100)
st.progress(score_float)
st.caption(f"Match Score: {score_percent}%")
st.markdown(
f"π§ **Offers:** "
f"{', '.join(m['offers']) or 'β'}"
)
st.markdown(
f"π― **Wants:** "
f"{', '.join(m['wants']) or 'β'}"
)
st.markdown(f"*{m['reason']}*")
st.markdown("</div>", unsafe_allow_html=True)
# ----------------------------------------------
# Feedback
# ----------------------------------------------
with st.sidebar:
st.markdown("---")
with st.expander("π¬ Feedback"):
fb = st.text_area("Your feedback", key="feedback_text")
if st.button("Submit Feedback", key="submit_feedback_button"):
if fb.strip():
save_feedback({
"timestamp": time.time(),
"feedback": fb,
"username": username if username.strip() else "anonymous",
})
st.success("Thank you!")
if "feedback_text" in st.session_state:
del st.session_state["feedback_text"]
st.rerun()
else:
st.warning("Please write feedback.") |