Download src/streamlit_app.py from faiz3123/campus: direct link, hf CLI and curl.
- Browser
- Download file 16.2 kB
-
https://huggingface.co/spaces/faiz3123/campus/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/faiz3123/campus/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/faiz3123/campus/resolve/main/src/streamlit_app.py
16.2 kB
| import streamlit as st | |
| import pandas as pd | |
| import plotly.express as px | |
| import plotly.graph_objects as go | |
| import google.generativeai as genai | |
| import random | |
| from datetime import datetime, timedelta | |
| import json | |
| # Configure the page | |
| st.set_page_config( | |
| page_title="SkillSphere", | |
| page_icon="π", | |
| layout="wide", | |
| initial_sidebar_state="expanded" | |
| ) | |
| # Initialize Gemini | |
| def init_gemini(): | |
| try: | |
| # Using the provided API key | |
| genai.configure(api_key="AIzaSyCWxM6Ic9zs-hZiovnMU8a4UJko7ObqPqU") | |
| return genai.GenerativeModel('gemini-2.0-flash') | |
| except Exception as e: | |
| st.error(f"Error initializing Gemini: {e}") | |
| return None | |
| # Generate sample data | |
| def generate_sample_data(): | |
| departments = ["Computer Science", "Electrical Engineering", "Mechanical Engineering", "Civil Engineering", "Chemistry"] | |
| skills = ["Python", "Java", "C++", "Machine Learning", "Data Structures", "Algorithms", | |
| "Web Development", "Database Management", "Networking", "Cloud Computing"] | |
| students = [] | |
| for i in range(1, 21): | |
| students.append({ | |
| 'id': f'student_{i}', | |
| 'name': f'Student {i}', | |
| 'department': random.choice(departments), | |
| 'gpa': round(random.uniform(3.0, 4.0), 2), | |
| 'skills': random.sample(skills, random.randint(3, 6)) | |
| }) | |
| achievement_categories = ["Academic", "Technical", "Professional", "Extracurricular", "Volunteering"] | |
| achievements = [] | |
| for student in students: | |
| num_achievements = random.randint(3, 8) | |
| for i in range(num_achievements): | |
| achievement_date = datetime.now() - timedelta(days=random.randint(1, 180)) | |
| achievements.append({ | |
| 'id': f'ach_{len(achievements)+1}', | |
| 'student_id': student['id'], | |
| 'title': f'Achievement {len(achievements)+1}', | |
| 'category': random.choice(achievement_categories), | |
| 'description': f'Description for achievement {len(achievements)+1}', | |
| 'status': random.choices(['pending', 'verified', 'rejected'], weights=[0.2, 0.7, 0.1])[0], | |
| 'points': random.randint(5, 50), | |
| 'date': achievement_date.strftime('%Y-%m-%d'), | |
| 'verified_by': f'faculty_{random.randint(1, 5)}' if random.random() > 0.3 else None | |
| }) | |
| return students, achievements | |
| # Calculate scores for leaderboard | |
| def calculate_scores(students, achievements): | |
| leaderboard_data = [] | |
| for student in students: | |
| student_achievements = [a for a in achievements if a['student_id'] == student['id'] and a['status'] == 'verified'] | |
| total_points = sum(a['points'] for a in student_achievements) | |
| # GPA contributes to score | |
| gpa_score = student['gpa'] * 25 | |
| total_score = total_points + gpa_score | |
| leaderboard_data.append({ | |
| 'id': student['id'], | |
| 'name': student['name'], | |
| 'department': student['department'], | |
| 'gpa': student['gpa'], | |
| 'achievements_count': len(student_achievements), | |
| 'score': round(total_score, 2), | |
| 'skills': student['skills'] | |
| }) | |
| # Sort by score descending | |
| leaderboard_data.sort(key=lambda x: x['score'], reverse=True) | |
| # Add ranks | |
| for i, student in enumerate(leaderboard_data): | |
| student['rank'] = i + 1 | |
| return leaderboard_data | |
| # AI Functions | |
| def generate_ai_advice(gemini_model, user_context, user_question): | |
| try: | |
| prompt = f""" | |
| You are Cortex, an AI career guide for college students. Your goal is to give personalized, actionable advice. | |
| Here is the data for the student you are talking to: | |
| - Name: {user_context.get('name', 'N/A')} | |
| - GPA: {user_context.get('gpa', 'N/A')} | |
| - Department: {user_context.get('department', 'N/A')} | |
| - Skills: {', '.join(user_context.get('skills', []))} | |
| - Achievements: {user_context.get('achievements_count', 0)} verified achievements | |
| - Current Rank: #{user_context.get('rank', 'N/A')} | |
| - Total Score: {user_context.get('score', 'N/A')} | |
| The student asks: '{user_question}' | |
| Answer helpfully and specifically based ONLY on the data provided above. Be concise but informative. | |
| """ | |
| response = gemini_model.generate_content(prompt) | |
| return response.text | |
| except Exception as e: | |
| return f"I'm sorry, I encountered an error generating advice: {str(e)}" | |
| def generate_ai_rankings(gemini_model, leaderboard_data): | |
| try: | |
| # Prepare data for AI analysis | |
| ai_data = [] | |
| for student in leaderboard_data[:10]: # Just top 10 for efficiency | |
| ai_data.append({ | |
| 'name': student['name'], | |
| 'department': student['department'], | |
| 'gpa': student['gpa'], | |
| 'achievements_count': student['achievements_count'], | |
| 'score': student['score'], | |
| 'skills': student['skills'] | |
| }) | |
| prompt = f""" | |
| Analyze the following student data and provide insights about: | |
| 1. What makes the top-performing students successful | |
| 2. Patterns you notice in skills among high achievers | |
| 3. Recommendations for students who want to improve their ranking | |
| Student data: {json.dumps(ai_data, indent=2)} | |
| Provide your analysis in a structured format with clear sections. | |
| """ | |
| response = gemini_model.generate_content(prompt) | |
| return response.text | |
| except Exception as e: | |
| return f"Error generating AI analysis: {str(e)}" | |
| # UI Components | |
| def render_student_dashboard(gemini_model, student, achievements, leaderboard_data): | |
| st.header(f"Welcome, {student['name']}!") | |
| # Display student info | |
| col1, col2, col3, col4 = st.columns(4) | |
| with col1: | |
| st.metric("GPA", student['gpa']) | |
| with col2: | |
| verified_achievements = len([a for a in achievements if a['student_id'] == student['id'] and a['status'] == 'verified']) | |
| st.metric("Verified Achievements", verified_achievements) | |
| with col3: | |
| st.metric("Skills", len(student['skills'])) | |
| with col4: | |
| rank = next((s['rank'] for s in leaderboard_data if s['id'] == student['id']), "N/A") | |
| st.metric("Rank", f"#{rank}") | |
| # Display achievements | |
| st.subheader("Your Achievements") | |
| student_achievements = [a for a in achievements if a['student_id'] == student['id']] | |
| if student_achievements: | |
| for achievement in student_achievements: | |
| status_color = { | |
| 'verified': 'green', | |
| 'pending': 'orange', | |
| 'rejected': 'red' | |
| }.get(achievement.get('status', 'pending'), 'gray') | |
| with st.container(): | |
| col1, col2 = st.columns([3, 1]) | |
| with col1: | |
| st.write(f"**{achievement.get('title')}** ({achievement.get('category')}) - {achievement.get('date')}") | |
| st.write(achievement.get('description')) | |
| st.write(f"Points: {achievement.get('points')}") | |
| with col2: | |
| st.write(f"Status: :{status_color}[{achievement.get('status').title()}]") | |
| st.divider() | |
| else: | |
| st.info("You haven't added any achievements yet.") | |
| # Add new achievement form | |
| with st.expander("Add New Achievement"): | |
| with st.form("achievement_form"): | |
| title = st.text_input("Title*") | |
| category = st.selectbox("Category*", ["Academic", "Technical", "Professional", "Extracurricular", "Volunteering", "Other"]) | |
| description = st.text_area("Description*") | |
| points = st.slider("Points", 5, 50, 10) | |
| submitted = st.form_submit_button("Submit Achievement") | |
| if submitted: | |
| if title and category and description: | |
| new_achievement = { | |
| 'id': f'ach_{len(achievements)+1}', | |
| 'student_id': student['id'], | |
| 'title': title, | |
| 'category': category, | |
| 'description': description, | |
| 'status': 'pending', | |
| 'points': points, | |
| 'date': datetime.now().strftime('%Y-%m-%d'), | |
| 'verified_by': None | |
| } | |
| achievements.append(new_achievement) | |
| st.success("Achievement submitted for verification!") | |
| else: | |
| st.warning("Please fill in all required fields (marked with *)") | |
| def render_faculty_dashboard(students, achievements): | |
| st.header("Faculty Verification Dashboard") | |
| pending_achievements = [a for a in achievements if a['status'] == 'pending'] | |
| if not pending_achievements: | |
| st.info("No pending verifications at this time.") | |
| return | |
| for achievement in pending_achievements: | |
| student = next((s for s in students if s['id'] == achievement['student_id']), None) | |
| with st.container(): | |
| st.subheader(achievement['title']) | |
| if student: | |
| st.write(f"**Student:** {student['name']} ({student['department']})") | |
| st.write(f"**Category:** {achievement['category']}") | |
| st.write(f"**Description:** {achievement['description']}") | |
| st.write(f"**Points Claimed:** {achievement['points']}") | |
| st.write(f"**Date:** {achievement['date']}") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| if st.button("Verify", key=f"verify_{achievement['id']}"): | |
| achievement['status'] = 'verified' | |
| achievement['verified_by'] = 'Faculty_1' | |
| st.success("Achievement verified!") | |
| with col2: | |
| if st.button("Reject", key=f"reject_{achievement['id']}"): | |
| achievement['status'] = 'rejected' | |
| st.success("Achievement rejected.") | |
| st.divider() | |
| def render_leaderboard(gemini_model, leaderboard_data): | |
| st.header("Student Leaderboard") | |
| if not leaderboard_data: | |
| st.info("No leaderboard data available yet.") | |
| return | |
| # Display top 3 with special badges | |
| if len(leaderboard_data) >= 1: | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| st.metric("π₯ 1st Place", f"{leaderboard_data[0]['name']} ({leaderboard_data[0]['score']} pts)") | |
| with col2: | |
| if len(leaderboard_data) >= 2: | |
| st.metric("π₯ 2nd Place", f"{leaderboard_data[1]['name']} ({leaderboard_data[1]['score']} pts)") | |
| with col3: | |
| if len(leaderboard_data) >= 3: | |
| st.metric("π₯ 3rd Place", f"{leaderboard_data[2]['name']} ({leaderboard_data[2]['score']} pts)") | |
| # Display full leaderboard table | |
| df = pd.DataFrame(leaderboard_data) | |
| st.dataframe( | |
| df[['rank', 'name', 'department', 'gpa', 'achievements_count', 'score']], | |
| use_container_width=True, | |
| hide_index=True | |
| ) | |
| # Visualization | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| # Score distribution by department | |
| dept_scores = df.groupby('department')['score'].mean().reset_index() | |
| fig1 = px.bar( | |
| dept_scores, | |
| x='department', | |
| y='score', | |
| title='Average Score by Department', | |
| color='department' | |
| ) | |
| st.plotly_chart(fig1, use_container_width=True) | |
| with col2: | |
| # Score distribution chart | |
| fig2 = px.histogram( | |
| df, | |
| x='score', | |
| title='Score Distribution', | |
| nbins=10 | |
| ) | |
| st.plotly_chart(fig2, use_container_width=True) | |
| # AI-powered ranking analysis | |
| if st.button("Generate AI-Powered Ranking Analysis", type="secondary"): | |
| with st.spinner("Generating AI analysis..."): | |
| analysis = generate_ai_rankings(gemini_model, leaderboard_data) | |
| st.subheader("AI Analysis of Leaderboard") | |
| st.write(analysis) | |
| def render_ai_assistant(gemini_model, student, leaderboard_data): | |
| st.header("Cortex AI Assistant") | |
| # Find student's rank and score | |
| student_data = next((s for s in leaderboard_data if s['id'] == student['id']), {}) | |
| # Prepare user context | |
| user_context = { | |
| 'name': student['name'], | |
| 'gpa': student['gpa'], | |
| 'department': student['department'], | |
| 'skills': student['skills'], | |
| 'achievements_count': student_data.get('achievements_count', 0), | |
| 'rank': student_data.get('rank', 'N/A'), | |
| 'score': student_data.get('score', 'N/A') | |
| } | |
| # Initialize chat history | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] | |
| # Display chat messages from history | |
| for message in st.session_state.messages: | |
| with st.chat_message(message["role"]): | |
| st.markdown(message["content"]) | |
| # React to user input | |
| if prompt := st.chat_input("Ask Cortex for advice..."): | |
| # Display user message in chat message container | |
| with st.chat_message("user"): | |
| st.markdown(prompt) | |
| # Add user message to chat history | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| # Generate AI response | |
| with st.chat_message("assistant"): | |
| with st.spinner("Cortex is thinking..."): | |
| response = generate_ai_advice(gemini_model, user_context, prompt) | |
| st.markdown(response) | |
| # Add assistant response to chat history | |
| st.session_state.messages.append({"role": "assistant", "content": response}) | |
| def main(): | |
| # Initialize Gemini | |
| gemini_model = init_gemini() | |
| if not gemini_model: | |
| st.error("Failed to initialize Gemini. Please check your API key.") | |
| return | |
| # Generate sample data | |
| students, achievements = generate_sample_data() | |
| leaderboard_data = calculate_scores(students, achievements) | |
| # Sidebar navigation | |
| st.sidebar.title("SkillSphere π") | |
| st.sidebar.write("AI-Powered Student Portfolio & Leaderboard") | |
| # User selection | |
| user_options = {s['id']: s for s in students} | |
| user_options['faculty_1'] = {'id': 'faculty_1', 'name': 'Dr. Smith', 'role': 'faculty', 'department': 'Computer Science'} | |
| selected_user = st.sidebar.selectbox( | |
| "Select User:", | |
| options=list(user_options.keys()), | |
| format_func=lambda x: user_options[x]['name'] | |
| ) | |
| user_info = user_options[selected_user] | |
| st.sidebar.write(f"**Name:** {user_info['name']}") | |
| if 'department' in user_info: | |
| st.sidebar.write(f"**Department:** {user_info['department']}") | |
| if 'gpa' in user_info: | |
| st.sidebar.write(f"**GPA:** {user_info['gpa']}") | |
| # Navigation based on user role | |
| if selected_user.startswith('student'): | |
| pages = { | |
| "Dashboard": render_student_dashboard, | |
| "Leaderboard": render_leaderboard, | |
| "Cortex AI Assistant": render_ai_assistant | |
| } | |
| else: | |
| pages = { | |
| "Verification Dashboard": render_faculty_dashboard, | |
| "Leaderboard": render_leaderboard | |
| } | |
| selected_page = st.sidebar.selectbox("Navigation", options=list(pages.keys())) | |
| # Render the selected page | |
| if selected_page == "Dashboard": | |
| render_student_dashboard(gemini_model, user_info, achievements, leaderboard_data) | |
| elif selected_page == "Verification Dashboard": | |
| render_faculty_dashboard(students, achievements) | |
| elif selected_page == "Leaderboard": | |
| render_leaderboard(gemini_model, leaderboard_data) | |
| elif selected_page == "Cortex AI Assistant": | |
| render_ai_assistant(gemini_model, user_info, leaderboard_data) | |
| if __name__ == "__main__": | |
| main() |