Spaces:
Sleeping
Sleeping
Update app.py
Browse filesdownload process report via zip
app.py
CHANGED
|
@@ -1,288 +1,280 @@
|
|
| 1 |
-
import pandas as pd
|
| 2 |
-
import os
|
| 3 |
-
import gradio as gr
|
| 4 |
-
import plotly.express as px
|
| 5 |
-
from typing import Tuple, List, Union
|
| 6 |
-
import traceback
|
| 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 |
-
user_info
|
| 46 |
-
user_info['
|
| 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 |
-
user_info
|
| 72 |
-
user_info
|
| 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 |
-
worksheet
|
| 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 |
-
.gr-button-secondary:
|
| 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 |
-
clear_btn.click(
|
| 282 |
-
clear_outputs,
|
| 283 |
-
inputs=[],
|
| 284 |
-
outputs=[output_msg, csv_location, summary_stats, users_activity_chart, users_courses_chart, scatter_plot, user_table]
|
| 285 |
-
)
|
| 286 |
-
|
| 287 |
-
if __name__ == "__main__":
|
| 288 |
iface.launch()
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import os
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import plotly.express as px
|
| 5 |
+
from typing import Tuple, List, Union
|
| 6 |
+
import traceback
|
| 7 |
+
import io
|
| 8 |
+
import zipfile
|
| 9 |
+
|
| 10 |
+
# NTU Singapore colors
|
| 11 |
+
NTU_BLUE = "#003D7C"
|
| 12 |
+
NTU_RED = "#C11E38"
|
| 13 |
+
NTU_GOLD = "#E7B820"
|
| 14 |
+
|
| 15 |
+
def process_data(file: gr.File, progress=gr.Progress()) -> Tuple[str, str, pd.DataFrame, Union[io.BytesIO, None]]:
|
| 16 |
+
try:
|
| 17 |
+
# Check if file is uploaded
|
| 18 |
+
if file is None:
|
| 19 |
+
raise ValueError("No file uploaded. Please upload an Excel file.")
|
| 20 |
+
|
| 21 |
+
# Check file extension
|
| 22 |
+
if not file.name.lower().endswith(('.xls', '.xlsx')):
|
| 23 |
+
raise ValueError("Invalid file format. Please upload an Excel file (.xls or .xlsx).")
|
| 24 |
+
|
| 25 |
+
# Load the raw Excel file
|
| 26 |
+
try:
|
| 27 |
+
raw_data = pd.read_excel(file.name)
|
| 28 |
+
except Exception as e:
|
| 29 |
+
raise ValueError(f"Error reading Excel file: {str(e)}")
|
| 30 |
+
|
| 31 |
+
# Check if required columns are present
|
| 32 |
+
required_columns = ['user_id', 'lastname', 'course_id']
|
| 33 |
+
missing_columns = [col for col in required_columns if col not in raw_data.columns]
|
| 34 |
+
if missing_columns:
|
| 35 |
+
raise ValueError(f"Missing required columns: {', '.join(missing_columns)}")
|
| 36 |
+
|
| 37 |
+
# Extract filename without extension
|
| 38 |
+
base_filename = os.path.splitext(os.path.basename(file.name))[0]
|
| 39 |
+
|
| 40 |
+
# Define output paths
|
| 41 |
+
final_file_path = f'mailmerge {base_filename}.xlsx'
|
| 42 |
+
base_path = 'mailmerge'
|
| 43 |
+
|
| 44 |
+
# Step 1: Extract User Information
|
| 45 |
+
user_info = raw_data[['user_id', 'lastname']].drop_duplicates().copy()
|
| 46 |
+
user_info['Username'] = user_info['user_id']
|
| 47 |
+
user_info['Name'] = user_info['lastname']
|
| 48 |
+
user_info['Email'] = user_info['user_id'] + '@ntu.edu.sg'
|
| 49 |
+
|
| 50 |
+
progress(0.2, desc="Extracting user information")
|
| 51 |
+
|
| 52 |
+
# Step 2: Calculate Course Count
|
| 53 |
+
course_counts = raw_data.groupby('user_id')['course_id'].nunique().reset_index()
|
| 54 |
+
course_counts.columns = ['Username', 'Courses']
|
| 55 |
+
user_info = user_info.merge(course_counts, on='Username', how='left')
|
| 56 |
+
|
| 57 |
+
progress(0.4, desc="Calculating course counts")
|
| 58 |
+
|
| 59 |
+
# Step 3: Calculate Grand Total
|
| 60 |
+
event_counts = raw_data.groupby('user_id').size().reset_index(name='Grand Total')
|
| 61 |
+
event_counts.columns = ['Username', 'Grand Total']
|
| 62 |
+
user_info = user_info.merge(event_counts, on='Username', how='left')
|
| 63 |
+
|
| 64 |
+
progress(0.6, desc="Calculating grand totals")
|
| 65 |
+
|
| 66 |
+
# Step 4: Generate Filenames and Paths
|
| 67 |
+
user_info['File'] = 'User_' + user_info['Username'] + '_data.csv'
|
| 68 |
+
user_info['Path'] = user_info['File'].apply(lambda x: os.path.join(base_path, x))
|
| 69 |
+
|
| 70 |
+
# Remove extra columns and summary rows
|
| 71 |
+
user_info = user_info[['Username', 'Name', 'Courses', 'Grand Total', 'Email', 'File', 'Path']]
|
| 72 |
+
user_info = user_info[user_info['Username'].notna()]
|
| 73 |
+
user_info.drop_duplicates(subset=['Username'], inplace=True)
|
| 74 |
+
user_info.sort_values(by='Username', inplace=True)
|
| 75 |
+
|
| 76 |
+
progress(0.8, desc="Generating individual CSV files")
|
| 77 |
+
|
| 78 |
+
# Generate individual CSV files for each user
|
| 79 |
+
required_columns = ['course_id', 'course_pk1', 'data', 'event_type', 'internal_handle', 'lastname', 'session_id', 'timestamp', 'user_id', 'system_role']
|
| 80 |
+
missing_columns = [col for col in required_columns if col not in raw_data.columns]
|
| 81 |
+
if missing_columns:
|
| 82 |
+
raise ValueError(f"Missing columns for individual CSV files: {', '.join(missing_columns)}")
|
| 83 |
+
|
| 84 |
+
# Create a BytesIO object to store the zip file
|
| 85 |
+
zip_buffer = io.BytesIO()
|
| 86 |
+
|
| 87 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 88 |
+
# Save individual CSV files
|
| 89 |
+
for user_id in user_info['Username'].unique():
|
| 90 |
+
user_data = raw_data[raw_data['user_id'] == user_id][required_columns]
|
| 91 |
+
user_file_path = f'{base_path}/User_{user_id}_data.csv'
|
| 92 |
+
zip_file.writestr(user_file_path, user_data.to_csv(index=False))
|
| 93 |
+
|
| 94 |
+
# Save the final Excel file
|
| 95 |
+
excel_buffer = io.BytesIO()
|
| 96 |
+
with pd.ExcelWriter(excel_buffer, engine='xlsxwriter') as writer:
|
| 97 |
+
user_info.to_excel(writer, index=False, sheet_name='Sheet1')
|
| 98 |
+
workbook = writer.book
|
| 99 |
+
worksheet = writer.sheets['Sheet1']
|
| 100 |
+
|
| 101 |
+
last_row = len(user_info) + 1
|
| 102 |
+
worksheet.write(f'B{last_row + 1}', 'Total')
|
| 103 |
+
worksheet.write(f'C{last_row + 1}', user_info['Courses'].sum())
|
| 104 |
+
worksheet.write(f'D{last_row + 1}', user_info['Grand Total'].sum())
|
| 105 |
+
|
| 106 |
+
zip_file.writestr(final_file_path, excel_buffer.getvalue())
|
| 107 |
+
|
| 108 |
+
zip_buffer.seek(0)
|
| 109 |
+
progress(1.0, desc="Processing complete")
|
| 110 |
+
return "Processing complete. You can now download the results.", "Results are packaged in the zip file below.", user_info, zip_buffer
|
| 111 |
+
except Exception as e:
|
| 112 |
+
error_msg = f"Error: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
| 113 |
+
return error_msg, "Processing failed", pd.DataFrame(), None
|
| 114 |
+
|
| 115 |
+
def create_summary_stats(df: pd.DataFrame) -> dict:
|
| 116 |
+
try:
|
| 117 |
+
return {
|
| 118 |
+
"Total Users": len(df),
|
| 119 |
+
"Total Courses": df['Courses'].sum(),
|
| 120 |
+
"Total Activity": df['Grand Total'].sum(),
|
| 121 |
+
"Avg Courses per User": df['Courses'].mean(),
|
| 122 |
+
"Avg Activity per User": df['Grand Total'].mean()
|
| 123 |
+
}
|
| 124 |
+
except Exception as e:
|
| 125 |
+
return {"Error": f"Failed to create summary stats: {str(e)}"}
|
| 126 |
+
|
| 127 |
+
def create_bar_chart(df: pd.DataFrame, x: str, y: str, title: str) -> Union[px.bar, None]:
|
| 128 |
+
try:
|
| 129 |
+
if df.empty:
|
| 130 |
+
return None
|
| 131 |
+
fig = px.bar(df, x=x, y=y, title=title)
|
| 132 |
+
fig.update_layout(
|
| 133 |
+
plot_bgcolor='white',
|
| 134 |
+
paper_bgcolor='white',
|
| 135 |
+
font_color=NTU_BLUE
|
| 136 |
+
)
|
| 137 |
+
fig.update_traces(marker_color=NTU_BLUE)
|
| 138 |
+
return fig
|
| 139 |
+
except Exception as e:
|
| 140 |
+
print(f"Error creating bar chart: {str(e)}")
|
| 141 |
+
return None
|
| 142 |
+
|
| 143 |
+
def create_scatter_plot(df: pd.DataFrame) -> Union[px.scatter, None]:
|
| 144 |
+
try:
|
| 145 |
+
if df.empty:
|
| 146 |
+
return None
|
| 147 |
+
fig = px.scatter(df, x='Courses', y='Grand Total', title='Courses vs. Activity Level',
|
| 148 |
+
hover_data=['Username', 'Name'])
|
| 149 |
+
fig.update_layout(
|
| 150 |
+
plot_bgcolor='white',
|
| 151 |
+
paper_bgcolor='white',
|
| 152 |
+
font_color=NTU_BLUE
|
| 153 |
+
)
|
| 154 |
+
fig.update_traces(marker_color=NTU_RED)
|
| 155 |
+
return fig
|
| 156 |
+
except Exception as e:
|
| 157 |
+
print(f"Error creating scatter plot: {str(e)}")
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
def update_insights(df: pd.DataFrame, zip_file: Union[io.BytesIO, None]) -> List[Union[gr.components.Component, None]]:
|
| 161 |
+
try:
|
| 162 |
+
if df.empty:
|
| 163 |
+
return [gr.Markdown("No data available. Please upload and process a file first.")] + [None] * 5
|
| 164 |
+
|
| 165 |
+
stats = create_summary_stats(df)
|
| 166 |
+
stats_md = gr.Markdown("\n".join([f"**{k}**: {v:.2f}" for k, v in stats.items()]))
|
| 167 |
+
|
| 168 |
+
users_activity_chart = create_bar_chart(df, 'Username', 'Grand Total', 'User Activity Levels')
|
| 169 |
+
users_courses_chart = create_bar_chart(df, 'Username', 'Courses', 'Courses per User')
|
| 170 |
+
scatter_plot = create_scatter_plot(df)
|
| 171 |
+
|
| 172 |
+
user_table = gr.DataFrame(value=df)
|
| 173 |
+
|
| 174 |
+
download_button = gr.File(value=zip_file, visible=(zip_file is not None), label="Download Results")
|
| 175 |
+
|
| 176 |
+
return [stats_md, users_activity_chart, users_courses_chart, scatter_plot, user_table, download_button]
|
| 177 |
+
except Exception as e:
|
| 178 |
+
error_msg = f"Error updating insights: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
| 179 |
+
return [gr.Markdown(error_msg)] + [None] * 5
|
| 180 |
+
|
| 181 |
+
def process_and_update(file):
|
| 182 |
+
try:
|
| 183 |
+
result_msg, csv_loc, df, zip_file = process_data(file)
|
| 184 |
+
insights = update_insights(df, zip_file)
|
| 185 |
+
return [result_msg, csv_loc] + insights
|
| 186 |
+
except Exception as e:
|
| 187 |
+
error_msg = f"Error in process_and_update: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
| 188 |
+
return [error_msg, "Processing failed"] + [gr.Markdown(error_msg)] + [None] * 5
|
| 189 |
+
|
| 190 |
+
def clear_outputs():
|
| 191 |
+
return [""] * 2 + [None] * 6 # 2 text outputs and 6 graph/table/file outputs
|
| 192 |
+
|
| 193 |
+
# Create a custom theme
|
| 194 |
+
custom_theme = gr.themes.Base().set(
|
| 195 |
+
body_background_fill="#E6F3FF",
|
| 196 |
+
body_text_color="#003D7C",
|
| 197 |
+
button_primary_background_fill="#C11E38",
|
| 198 |
+
button_primary_background_fill_hover="#A5192F",
|
| 199 |
+
button_primary_text_color="white",
|
| 200 |
+
block_title_text_color="#003D7C",
|
| 201 |
+
block_label_background_fill="#E6F3FF",
|
| 202 |
+
input_background_fill="white",
|
| 203 |
+
input_border_color="#003D7C",
|
| 204 |
+
input_border_color_focus="#C11E38",
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
# Custom CSS
|
| 208 |
+
custom_css = """
|
| 209 |
+
.gr-button-secondary {
|
| 210 |
+
background-color: #F0F0F0;
|
| 211 |
+
color: #003D7C;
|
| 212 |
+
border: 1px solid #003D7C;
|
| 213 |
+
border-radius: 12px;
|
| 214 |
+
padding: 8px 16px;
|
| 215 |
+
font-size: 16px;
|
| 216 |
+
font-weight: bold;
|
| 217 |
+
cursor: pointer;
|
| 218 |
+
transition: background-color 0.3s, color 0.3s, border-color 0.3s;
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
.gr-button-secondary:hover {
|
| 222 |
+
background-color: #003D7C;
|
| 223 |
+
color: white;
|
| 224 |
+
border-color: #003D7C;
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
.gr-button-secondary:active {
|
| 228 |
+
transform: translateY(1px);
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
.app-title {
|
| 232 |
+
color: #003D7C;
|
| 233 |
+
font-size: 24px;
|
| 234 |
+
font-weight: bold;
|
| 235 |
+
text-align: center;
|
| 236 |
+
margin-bottom: 20px;
|
| 237 |
+
}
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
with gr.Blocks(theme=custom_theme, css=custom_css) as iface:
|
| 241 |
+
gr.Markdown("# Gradebook Data Processor", elem_classes=["app-title"])
|
| 242 |
+
|
| 243 |
+
with gr.Tabs():
|
| 244 |
+
with gr.TabItem("1. File Upload and Processing"):
|
| 245 |
+
gr.Markdown("## Step 1: Upload your Excel file and process the data")
|
| 246 |
+
file_input = gr.File(label="Upload Excel File")
|
| 247 |
+
process_btn = gr.Button("Process Data", variant="primary")
|
| 248 |
+
output_msg = gr.Textbox(label="Processing Result")
|
| 249 |
+
csv_location = gr.Textbox(label="Output Information")
|
| 250 |
+
gr.Markdown("After processing, switch to the 'Data Insights' tab to view results and download files.")
|
| 251 |
+
|
| 252 |
+
with gr.TabItem("2. Data Insights Dashboard"):
|
| 253 |
+
gr.Markdown("## Step 2: Review insights and download results")
|
| 254 |
+
summary_stats = gr.Markdown("Upload and process a file to see summary statistics.")
|
| 255 |
+
|
| 256 |
+
with gr.Row():
|
| 257 |
+
users_activity_chart = gr.Plot()
|
| 258 |
+
users_courses_chart = gr.Plot()
|
| 259 |
+
|
| 260 |
+
scatter_plot = gr.Plot()
|
| 261 |
+
user_table = gr.DataFrame()
|
| 262 |
+
download_button = gr.File(visible=False, label="Download Results")
|
| 263 |
+
|
| 264 |
+
clear_btn = gr.Button("Clear All Data", variant="secondary")
|
| 265 |
+
gr.Markdown("Click 'Clear All Data' to reset the application and start over.")
|
| 266 |
+
|
| 267 |
+
process_btn.click(
|
| 268 |
+
process_and_update,
|
| 269 |
+
inputs=[file_input],
|
| 270 |
+
outputs=[output_msg, csv_location, summary_stats, users_activity_chart, users_courses_chart, scatter_plot, user_table, download_button]
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
clear_btn.click(
|
| 274 |
+
clear_outputs,
|
| 275 |
+
inputs=[],
|
| 276 |
+
outputs=[output_msg, csv_location, summary_stats, users_activity_chart, users_courses_chart, scatter_plot, user_table, download_button]
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
iface.launch()
|