Ashar086 commited on
Commit
e8548a4
·
verified ·
1 Parent(s): f04ba14

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -209
app.py CHANGED
@@ -1,219 +1,115 @@
1
  import streamlit as st
2
  import pandas as pd
3
- import numpy as np
4
- import matplotlib.pyplot as plt
5
  import seaborn as sns
6
-
7
- # Streamlit App
8
- st.set_page_config(page_title="Social Media Usage Dashboard", layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  # Sidebar Navigation
 
11
  st.sidebar.title("Navigation")
12
- page = st.sidebar.radio("Go to", ["Overview", "Time Analysis", "Demographics", "Behavior Analysis"])
13
-
14
- # Load dataset
15
- df = pd.read_csv("Dataset.csv")
16
-
17
- # Display the selected page
18
- if page == "Overview":
19
- st.title("📊 Overview: Social Media Usage Insights")
20
- st.write("This dashboard provides key insights into how people waste time on social media.")
21
-
22
- # Sidebar Filters
23
- st.sidebar.subheader("🔹 Filters")
24
- gender_filter = st.sidebar.multiselect("Select Gender:", options=df["Gender"].unique(), default=df["Gender"].unique())
25
- platform_filter = st.sidebar.multiselect("Select Platform:", options=df["Platform"].unique(), default=df["Platform"].unique())
26
-
27
- # Apply Filters
28
- filtered_df = df[(df["Gender"].isin(gender_filter)) & (df["Platform"].isin(platform_filter))]
29
-
30
- # Refresh Button
31
- if st.sidebar.button("Reset Filters"):
32
- gender_filter = df["Gender"].unique()
33
- platform_filter = df["Platform"].unique()
34
-
35
- # Display Key Metrics
36
- col1, col2, col3 = st.columns(3)
37
-
38
- with col1:
39
- total_time = filtered_df["Total Time Spent"].sum()
40
- st.metric(label=" Total Time Wasted", value=f"{total_time} minutes")
41
-
42
- with col2:
43
- most_used_platform = filtered_df["Platform"].mode()[0]
44
- st.metric(label="📱 Most Used Platform", value=most_used_platform)
45
-
46
- with col3:
47
- avg_session_time = filtered_df["Total Time Spent"].mean()
48
- st.metric(label="🕒 Avg. Session Time", value=f"{avg_session_time:.2f} minutes")
49
-
50
- # Visualizations
51
- st.subheader("📌 Time Wasted by Gender")
52
- fig, ax = plt.subplots()
53
- filtered_df.groupby("Gender")["Total Time Spent"].sum().plot(kind="pie", autopct="%1.1f%%", ax=ax)
54
- ax.set_ylabel("")
55
- st.pyplot(fig)
56
-
57
- st.subheader("📌 Most Used Social Media Platforms")
58
- fig, ax = plt.subplots()
59
- sns.countplot(x="Platform", data=filtered_df, order=filtered_df["Platform"].value_counts().index, palette="viridis", ax=ax)
60
- plt.xticks(rotation=45)
61
- ax.set_title("Most Used Social Media Platforms")
62
- st.pyplot(fig)
63
-
64
- st.subheader("📌 Time Spent Distribution")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  fig, ax = plt.subplots()
66
- sns.histplot(filtered_df["Total Time Spent"], bins=20, kde=True, color="blue", ax=ax)
67
- ax.set_title("Distribution of Time Spent on Social Media")
68
  st.pyplot(fig)
69
-
70
- # Interactive Button
71
- if st.button("📈 Show More Insights"):
72
- st.write("More analysis coming soon! 🚀")
73
-
74
- # Footer
75
- st.markdown("**🔹 Use the sidebar to filter data by gender and platform.**")
76
-
77
-
78
- elif page == "Time Analysis":
79
- st.title("⏳ Time-Based Trends")
80
- st.write("Analyze how people waste time on social media at different times of the day.")
81
-
82
- # Sidebar Filters
83
- st.sidebar.subheader("🔹 Filters")
84
- gender_filter = st.sidebar.multiselect("Select Gender:", options=df["Gender"].unique(), default=df["Gender"].unique())
85
- platform_filter = st.sidebar.multiselect("Select Platform:", options=df["Platform"].unique(), default=df["Platform"].unique())
86
-
87
- # Apply Filters
88
- filtered_df = df[(df["Gender"].isin(gender_filter)) & (df["Platform"].isin(platform_filter))]
89
-
90
- # Extract Watch Hour from Watch Time
91
- filtered_df["Watch Hour"] = pd.to_datetime(filtered_df["Watch Time"], errors="coerce").dt.hour
92
-
93
- # Toggle insights
94
- show_insights = st.checkbox("📊 Show Key Insights")
95
-
96
- # Key Insights
97
- if show_insights:
98
- peak_hour = filtered_df.groupby("Watch Hour")["Total Time Spent"].sum().idxmax()
99
- most_active_platform = filtered_df["Platform"].mode()[0]
100
-
101
- col1, col2 = st.columns(2)
102
- with col1:
103
- st.metric(label="⏰ Peak Hour of Usage", value=f"{peak_hour}:00")
104
- with col2:
105
- st.metric(label="📱 Most Active Platform", value=most_active_platform)
106
-
107
- # Line Chart: Time Spent Per Hour
108
- st.subheader("📌 Time Spent by Hour of the Day")
109
- fig, ax = plt.subplots()
110
- sns.lineplot(x="Watch Hour", y="Total Time Spent", data=filtered_df, marker="o", ax=ax)
111
- ax.set_title("Social Media Usage by Hour")
112
- ax.set_xticks(range(0, 24))
113
- st.pyplot(fig)
114
-
115
- # Heatmap: Hour vs. Platform
116
- st.subheader("📌 Time Spent by Hour & Platform")
117
- pivot_table = filtered_df.pivot_table(values="Total Time Spent", index="Watch Hour", columns="Platform", aggfunc="sum")
118
-
119
- fig, ax = plt.subplots(figsize=(8,6))
120
- sns.heatmap(pivot_table, cmap="coolwarm", annot=True, fmt=".1f", ax=ax)
121
- st.pyplot(fig)
122
-
123
- # Interactive Button
124
- if st.button("🔍 More Insights Coming Soon!"):
125
- st.write("Stay tuned for deeper analysis! 🚀")
126
-
127
- elif page == "Demographics":
128
- st.title("🧑‍🤝‍🧑 Demographics Analysis")
129
- st.write("Understand how different demographics engage with social media.")
130
-
131
- # Sidebar Filters
132
- st.sidebar.subheader("🔹 Filters")
133
- gender_filter = st.sidebar.multiselect("Select Gender:", options=df["Gender"].unique(), default=df["Gender"].unique())
134
- age_filter = st.sidebar.slider("Select Age Range:", int(df["Age"].min()), int(df["Age"].max()), (int(df["Age"].min()), int(df["Age"].max())))
135
- location_filter = st.sidebar.multiselect("Select Location:", options=df["Location"].unique(), default=df["Location"].unique())
136
-
137
- # Apply Filters
138
- filtered_df = df[(df["Gender"].isin(gender_filter)) &
139
- (df["Age"].between(age_filter[0], age_filter[1])) &
140
- (df["Location"].isin(location_filter))]
141
-
142
- # Toggle insights
143
- show_insights = st.checkbox("📊 Show Key Insights")
144
-
145
- # Key Insights
146
- if show_insights:
147
- most_active_age_group = filtered_df.groupby("Age")["Total Time Spent"].sum().idxmax()
148
- most_active_location = filtered_df.groupby("Location")["Total Time Spent"].sum().idxmax()
149
-
150
- col1, col2 = st.columns(2)
151
- with col1:
152
- st.metric(label="📅 Most Active Age Group", value=f"{most_active_age_group} years")
153
- with col2:
154
- st.metric(label="📍 Most Active Location", value=most_active_location)
155
-
156
- # Bar Chart: Time Spent by Age Group
157
- st.subheader("📌 Time Spent by Age Group")
158
- fig, ax = plt.subplots()
159
- sns.barplot(x="Age", y="Total Time Spent", data=filtered_df, palette="coolwarm", ax=ax)
160
- ax.set_title("Social Media Usage by Age Group")
161
- st.pyplot(fig)
162
-
163
- # Pie Chart: Time Wasted by Location
164
- st.subheader("📌 Time Wasted by Location")
165
- fig, ax = plt.subplots()
166
- filtered_df.groupby("Location")["Total Time Spent"].sum().plot(kind="pie", autopct="%1.1f%%", ax=ax)
167
- ax.set_ylabel("")
168
- st.pyplot(fig)
169
-
170
- # Interactive Button
171
- if st.button("🔍 More Insights Coming Soon!"):
172
- st.write("Stay tuned for deeper demographic analysis! 🚀")
173
- elif page == "Behavior Analysis":
174
- st.title("🧠 Behavior Analysis")
175
- st.write("Understand how social media affects engagement, addiction, and productivity.")
176
-
177
- # Sidebar Filters
178
- st.sidebar.subheader("🔹 Filters")
179
- gender_filter = st.sidebar.multiselect("Select Gender:", options=df["Gender"].unique(), default=df["Gender"].unique())
180
- platform_filter = st.sidebar.multiselect("Select Platform:", options=df["Platform"].unique(), default=df["Platform"].unique())
181
- engagement_filter = st.sidebar.slider("Select Engagement Level:", int(df["Engagement"].min()), int(df["Engagement"].max()), (int(df["Engagement"].min()), int(df["Engagement"].max())))
182
-
183
- # Apply Filters
184
- filtered_df = df[(df["Gender"].isin(gender_filter)) &
185
- (df["Platform"].isin(platform_filter)) &
186
- (df["Engagement"].between(engagement_filter[0], engagement_filter[1]))]
187
-
188
- # Toggle insights
189
- show_insights = st.checkbox("📊 Show Key Insights")
190
-
191
- # Key Insights
192
- if show_insights:
193
- highest_engagement_platform = filtered_df.groupby("Platform")["Engagement"].mean().idxmax()
194
- most_addictive_platform = filtered_df.groupby("Platform")["Addiction Level"].mean().idxmax()
195
-
196
- col1, col2 = st.columns(2)
197
- with col1:
198
- st.metric(label="🔥 Highest Engagement Platform", value=highest_engagement_platform)
199
- with col2:
200
- st.metric(label="⚠️ Most Addictive Platform", value=most_addictive_platform)
201
-
202
- # Bar Chart: Engagement Levels by Platform
203
- st.subheader("📌 Engagement Levels by Platform")
204
- fig, ax = plt.subplots()
205
- sns.barplot(x="Platform", y="Engagement", data=filtered_df, palette="viridis", ax=ax)
206
- ax.set_title("Average Engagement Level per Platform")
207
- plt.xticks(rotation=45)
208
- st.pyplot(fig)
209
-
210
- # Scatter Plot: Addiction Level vs. Productivity Loss
211
- st.subheader("📌 Addiction Level vs. Productivity Loss")
212
- fig, ax = plt.subplots()
213
- sns.scatterplot(x="Addiction Level", y="ProductivityLoss", hue="Platform", data=filtered_df, palette="coolwarm", ax=ax)
214
- ax.set_title("Impact of Addiction on Productivity Loss")
215
  st.pyplot(fig)
216
 
217
- # Interactive Button
218
- if st.button("🔍 More Insights Coming Soon!"):
219
- st.write("Stay tuned for deeper behavior analysis! 🚀")
 
1
  import streamlit as st
2
  import pandas as pd
3
+ import plotly.express as px
 
4
  import seaborn as sns
5
+ import matplotlib.pyplot as plt
6
+ import time
7
+ from wordcloud import WordCloud
8
+
9
+ # Load Data
10
+ df = pd.read_csv('Data/Time-Wasters on Social Media.csv')
11
+
12
+ # Custom CSS Styling
13
+ def local_css():
14
+ st.markdown("""
15
+ <style>
16
+ .main {background-color: #f5f7fa;}
17
+ h1 {color: #003366; text-align: center;}
18
+ h3 {color: #666666; text-align: center;}
19
+ .stButton>button {background-color: #003366; color: white; font-size: 18px;}
20
+ </style>
21
+ """, unsafe_allow_html=True)
22
+ local_css()
23
 
24
  # Sidebar Navigation
25
+ st.sidebar.image('assets/logo.png', width=200)
26
  st.sidebar.title("Navigation")
27
+ page = st.sidebar.radio("Go to", ['Home', 'Time Wasters', 'Engagement Levels', 'Addiction Levels'])
28
+
29
+ # Session Timer (Tracks time spent on dashboard)
30
+ start_time = time.time()
31
+ if 'start_time' not in st.session_state:
32
+ st.session_state['start_time'] = start_time
33
+ elapsed_time = time.time() - st.session_state['start_time']
34
+ st.sidebar.metric("Time Spent Here", f"{int(elapsed_time)} sec")
35
+
36
+ # Home Page
37
+ if page == 'Home':
38
+ st.title("📊 Welcome to the Time-Wasters Analytics Dashboard")
39
+ st.markdown("""
40
+ ### What you will explore:
41
+ 1. **Time-Wasting Trends on Social Media**
42
+ 2. **Engagement Levels & Productivity Loss**
43
+ 3. **Social Media Addiction Insights**
44
+ """)
45
+ st.image('assets/dashboard_preview.png')
46
+
47
+ # Time Wasters Analysis
48
+ elif page == 'Time Wasters':
49
+ st.title("📱 Time Wasters on Social Media")
50
+ col1, col2 = st.columns(2)
51
+ col1.metric("Total Users", len(df['UserID'].unique()))
52
+ col2.metric("Total Time Spent", int(df['Total Time Spent'].sum()))
53
+
54
+ # Filters
55
+ selected_country = st.selectbox("Select Country", df['Location'].unique())
56
+ selected_gender = st.selectbox("Select Gender", df['Gender'].unique())
57
+ selected_platform = st.selectbox("Select Platform", df['Platform'].unique())
58
+ age_range = st.slider("Select Age Range", int(df['Age'].min()), int(df['Age'].max()), (20, 40))
59
+
60
+ # Filter Data
61
+ filtered_data = df[(df['Location'] == selected_country) &
62
+ (df['Gender'] == selected_gender) &
63
+ (df['Age'].between(*age_range)) &
64
+ (df['Platform'] == selected_platform)]
65
+
66
+ avg_addiction_level = filtered_data['Addiction Level'].mean()
67
+ st.subheader(f"Average Addiction Level: {avg_addiction_level:.2f}")
68
+
69
+ # Animated Bar Chart
70
+ fig = px.histogram(filtered_data, x='Addiction Level', nbins=10, color_discrete_sequence=['teal'], animation_frame='Age')
71
+ st.plotly_chart(fig)
72
+
73
+ # Engagement Levels
74
+ elif page == 'Engagement Levels':
75
+ st.title("🎯 Engagement Levels on Social Media")
76
+ selected_country = st.selectbox("Select Country", df['Location'].unique(), key='engage_country')
77
+ selected_platform = st.selectbox("Select Platform", df['Platform'].unique(), key='engage_platform')
78
+
79
+ filtered_data = df[(df['Location'] == selected_country) & (df['Platform'] == selected_platform)]
80
+ avg_engagement = filtered_data['Engagement'].mean()
81
+ st.subheader(f"Average Engagement: {avg_engagement:.2f}")
82
+
83
+ # Word Cloud of Watch Reasons
84
+ text = ' '.join(filtered_data['Watch Reason'].dropna())
85
+ wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
86
+ st.image(wordcloud.to_array())
87
+
88
+ # Engagement Scatter Plot
89
+ fig = px.scatter(filtered_data, x='Engagement', y='ProductivityLoss', color='Platform', size='Total Time Spent')
90
+ st.plotly_chart(fig)
91
+
92
+ # Addiction Levels
93
+ elif page == 'Addiction Levels':
94
+ st.title("⚠️ Social Media Addiction Levels")
95
+ selected_country = st.selectbox("Select Country", df['Location'].unique(), key='addict_country')
96
+ selected_platform = st.selectbox("Select Platform", df['Platform'].unique(), key='addict_platform')
97
+
98
+ filtered_data = df[(df['Location'] == selected_country) & (df['Platform'] == selected_platform)]
99
+ avg_addiction = filtered_data['Addiction Level'].mean()
100
+ st.subheader(f"Average Addiction Level: {avg_addiction:.2f}")
101
+
102
+ # Addiction vs Age Line Chart
103
  fig, ax = plt.subplots()
104
+ sns.lineplot(data=filtered_data, x='Age', y='Addiction Level', marker='o', ax=ax)
105
+ ax.set_title("Addiction Level vs Age")
106
  st.pyplot(fig)
107
+
108
+ # Heatmap
109
+ st.subheader("Engagement & Addiction Heatmap")
110
+ heatmap_data = df.pivot_table(index='Location', columns='Platform', values='Addiction Level', aggfunc='mean')
111
+ fig, ax = plt.subplots(figsize=(10,6))
112
+ sns.heatmap(heatmap_data, cmap='coolwarm', annot=True, ax=ax)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  st.pyplot(fig)
114
 
115
+ st.sidebar.write("© 2025 Social Media Analytics Dashboard")