KomalDeep355/Gen-ZStressAnalyzer
0
1"""2Gen Z Social Media & Academic Performance Analytics โ Streamlit Dashboard3Deployable on Hugging Face Spaces (SDK: streamlit).4"""5 6import sqlite37 8import matplotlib.pyplot as plt9import numpy as np10import pandas as pd11import seaborn as sns12import streamlit as st13from sklearn.ensemble import GradientBoostingClassifier, RandomForestRegressor14from sklearn.preprocessing import LabelEncoder15 16st.set_page_config(17 page_title="Gen Z Social Media & Academic Performance",18 page_icon="๐ฑ",19 layout="wide",20)21 22# ---------------------------------------------------------------------23# DATA LOADING24# ---------------------------------------------------------------------25@st.cache_data26def load_data():27 df = pd.read_csv("data/student_social_media_data.csv")28 return df29 30 31@st.cache_resource32def train_models(df):33 df_ml = df.copy()34 le_platform = LabelEncoder()35 le_year = LabelEncoder()36 le_gender = LabelEncoder()37 df_ml["platform_enc"] = le_platform.fit_transform(df_ml["platform_preference"])38 df_ml["year_enc"] = le_year.fit_transform(df_ml["year"])39 df_ml["gender_enc"] = le_gender.fit_transform(df_ml["gender"])40 41 features = ["daily_screen_time_hrs", "study_hours", "sleep_hours",42 "attendance_pct", "assignment_completion_pct",43 "platform_enc", "year_enc", "gender_enc"]44 45 X = df_ml[features]46 rf = RandomForestRegressor(n_estimators=300, max_depth=8, random_state=42)47 rf.fit(X, df_ml["cgpa"])48 49 gb = GradientBoostingClassifier(n_estimators=200, max_depth=3, random_state=42)50 gb.fit(X, df_ml["at_risk"])51 52 return rf, gb, le_platform, le_year, le_gender, features53 54 55df = load_data()56rf_model, gb_model, le_platform, le_year, le_gender, FEATURES = train_models(df)57 58# ---------------------------------------------------------------------59# SIDEBAR60# ---------------------------------------------------------------------61st.sidebar.title("๐ฑ Filters")62platforms_sel = st.sidebar.multiselect(63 "Platform", sorted(df["platform_preference"].unique()),64 default=sorted(df["platform_preference"].unique())65)66years_sel = st.sidebar.multiselect(67 "Year", sorted(df["year"].unique()), default=sorted(df["year"].unique())68)69screen_range = st.sidebar.slider(70 "Daily Screen Time (hrs)",71 float(df["daily_screen_time_hrs"].min()),72 float(df["daily_screen_time_hrs"].max()),73 (float(df["daily_screen_time_hrs"].min()), float(df["daily_screen_time_hrs"].max()))74)75 76filtered = df[77 df["platform_preference"].isin(platforms_sel)78 & df["year"].isin(years_sel)79 & df["daily_screen_time_hrs"].between(*screen_range)80]81 82# ---------------------------------------------------------------------83# HEADER84# ---------------------------------------------------------------------85st.title("๐ฑ Gen Z Social Media & Academic Performance Analytics")86st.caption("Does Screen Time Really Hurt Your CGPA? โ Built on simulated student behavioral data.")87 88c1, c2, c3, c4 = st.columns(4)89c1.metric("Students (filtered)", len(filtered))90c2.metric("Avg CGPA", f"{filtered['cgpa'].mean():.2f}")91c3.metric("Avg Screen Time", f"{filtered['daily_screen_time_hrs'].mean():.1f} hrs/day")92c4.metric("Avg Exam Score", f"{filtered['exam_score'].mean():.1f}")93 94st.divider()95 96# ---------------------------------------------------------------------97# TABS98# ---------------------------------------------------------------------99tab1, tab2, tab3, tab4 = st.tabs(100 ["๐ EDA Dashboard", "๐งฎ SQL Explorer", "๐ค CGPA Predictor", "โ ๏ธ Risk Classifier"]101)102 103with tab1:104 col1, col2 = st.columns(2)105 106 with col1:107 st.subheader("Screen Time Distribution")108 fig, ax = plt.subplots(figsize=(5, 3.2))109 sns.histplot(filtered["daily_screen_time_hrs"], bins=20, kde=True, ax=ax, color="#6C5CE7")110 st.pyplot(fig)111 112 st.subheader("Average CGPA by Platform")113 avg_plat = filtered.groupby("platform_preference")["cgpa"].mean().sort_values(ascending=False)114 st.bar_chart(avg_plat)115 116 with col2:117 st.subheader("Correlation Heatmap")118 num_cols = ["daily_screen_time_hrs", "study_hours", "sleep_hours",119 "attendance_pct", "assignment_completion_pct", "exam_score", "cgpa"]120 fig2, ax2 = plt.subplots(figsize=(5, 4))121 sns.heatmap(filtered[num_cols].corr(), annot=True, fmt=".2f", cmap="coolwarm", ax=ax2)122 st.pyplot(fig2)123 124 st.subheader("CGPA by Screen Time Group")125 order = ["<2h", "2-4h", "4-6h", "6-8h", "8h+"]126 avg_group = (filtered.groupby("screen_time_group", observed=True)["cgpa"]127 .mean().reindex(order))128 st.bar_chart(avg_group)129 130with tab2:131 st.subheader("Run SQL Queries Against the Dataset")132 st.caption("Table name: `students`")133 default_query = """SELECT platform_preference AS platform,134 ROUND(AVG(cgpa), 2) AS avg_cgpa,135 ROUND(AVG(exam_score), 1) AS avg_exam_score,136 COUNT(*) AS n_students137FROM students138GROUP BY platform_preference139ORDER BY avg_cgpa DESC;"""140 query = st.text_area("SQL query", value=default_query, height=160)141 142 if st.button("Run Query"):143 try:144 conn = sqlite3.connect(":memory:")145 filtered.to_sql("students", conn, index=False, if_exists="replace")146 result = pd.read_sql(query, conn)147 st.dataframe(result, use_container_width=True)148 except Exception as e:149 st.error(f"Query error: {e}")150 151with tab3:152 st.subheader("Predict CGPA from Behavioral Inputs")153 colA, colB, colC = st.columns(3)154 with colA:155 in_screen = st.slider("Daily screen time (hrs)", 0.0, 14.0, 5.5)156 in_study = st.slider("Study hours (hrs/day)", 0.0, 9.0, 3.0)157 with colB:158 in_sleep = st.slider("Sleep hours", 3.0, 10.0, 7.0)159 in_attendance = st.slider("Attendance %", 40.0, 100.0, 85.0)160 with colC:161 in_assignment = st.slider("Assignment completion %", 10.0, 100.0, 70.0)162 in_platform = st.selectbox("Platform preference", sorted(df["platform_preference"].unique()))163 in_year = st.selectbox("Year", sorted(df["year"].unique()))164 in_gender = st.selectbox("Gender", sorted(df["gender"].unique()))165 166 if st.button("Predict CGPA"):167 row = pd.DataFrame([{168 "daily_screen_time_hrs": in_screen,169 "study_hours": in_study,170 "sleep_hours": in_sleep,171 "attendance_pct": in_attendance,172 "assignment_completion_pct": in_assignment,173 "platform_enc": le_platform.transform([in_platform])[0],174 "year_enc": le_year.transform([in_year])[0],175 "gender_enc": le_gender.transform([in_gender])[0],176 }])[FEATURES]177 pred_cgpa = rf_model.predict(row)[0]178 st.success(f"Predicted CGPA: **{pred_cgpa:.2f}** / 10")179 180 importances = pd.Series(rf_model.feature_importances_, index=FEATURES).sort_values()181 st.caption("Model: Random Forest Regressor โ feature importances below")182 st.bar_chart(importances)183 184with tab4:185 st.subheader("Academic Risk Classifier")186 st.caption("Flags students in the bottom ~20% CGPA band based on behavioral inputs.")187 colA, colB, colC = st.columns(3)188 with colA:189 r_screen = st.slider("Daily screen time (hrs) ", 0.0, 14.0, 7.0, key="r1")190 r_study = st.slider("Study hours (hrs/day) ", 0.0, 9.0, 1.5, key="r2")191 with colB:192 r_sleep = st.slider("Sleep hours ", 3.0, 10.0, 6.0, key="r3")193 r_attendance = st.slider("Attendance % ", 40.0, 100.0, 70.0, key="r4")194 with colC:195 r_assignment = st.slider("Assignment completion % ", 10.0, 100.0, 50.0, key="r5")196 r_platform = st.selectbox("Platform preference ", sorted(df["platform_preference"].unique()), key="r6")197 r_year = st.selectbox("Year ", sorted(df["year"].unique()), key="r7")198 r_gender = st.selectbox("Gender ", sorted(df["gender"].unique()), key="r8")199 200 if st.button("Assess Risk"):201 row = pd.DataFrame([{202 "daily_screen_time_hrs": r_screen,203 "study_hours": r_study,204 "sleep_hours": r_sleep,205 "attendance_pct": r_attendance,206 "assignment_completion_pct": r_assignment,207 "platform_enc": le_platform.transform([r_platform])[0],208 "year_enc": le_year.transform([r_year])[0],209 "gender_enc": le_gender.transform([r_gender])[0],210 }])[FEATURES]211 proba = gb_model.predict_proba(row)[0][1]212 label = "โ ๏ธ At Risk" if proba >= 0.5 else "โ
On Track"213 st.metric("Risk Probability", f"{proba*100:.1f}%", label)214 215st.divider()216st.caption(217 "Note: This dataset is simulated for demonstration purposes. "218 "Relationships shown illustrate analytics/ML workflow, not verified real-world findings."219)