balafromtn commited on
Commit
64c5917
ยท
verified ยท
1 Parent(s): 3eae81a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -165
app.py CHANGED
@@ -1,166 +1,153 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import io
4
-
5
- def calculate_attendance(total_days, absent_hours):
6
- total_hours = total_days * 5 # Each day has 5 hours
7
- present_hours = total_hours - absent_hours
8
- present_percentage = (present_hours / total_hours) * 100
9
-
10
- if present_percentage >= 74:
11
- exam_status = "Eligible to write the exam"
12
- elif 65 <= present_percentage <= 75:
13
- exam_status = "Should pay fine to write the exam"
14
- elif 50 <= present_percentage < 65:
15
- exam_status = "Not eligible to write the exam"
16
- else:
17
- exam_status = "Redo"
18
-
19
- # Round to two decimal places
20
- present_percentage = round(present_percentage, 2)
21
-
22
- return present_percentage, present_hours, exam_status
23
-
24
- # Initialize session state for calculator mode
25
- if "calculator_mode" not in st.session_state:
26
- st.session_state.calculator_mode = "normal"
27
-
28
- st.set_page_config(
29
- page_icon="๐Ÿงฎ",
30
- page_title="Student Attendance Calculator",
31
- layout="centered"
32
- )
33
-
34
- # Custom CSS for styling
35
- st.markdown("""
36
- <style>
37
- .css-1d391kg {text-align: center;}
38
- .stButton>button {background-color: #87CEFA; color: black; padding: 10px; border-radius: 10px; font-weight: bold;}
39
- .stFileUploader {text-align: center;}
40
- .uploadedFile {color: green;}
41
- .stDownloadButton>button {background-color: #4682B4; color: white; padding: 10px; border-radius: 10px; font-weight: bold;}
42
- .stNumberInput>div>div>input {border-radius: 5px;}
43
- </style>
44
- """, unsafe_allow_html=True)
45
-
46
- st.title("๐Ÿ“˜ Student Attendance Calculator")
47
- st.markdown("______")
48
-
49
- with st.container():
50
- col1, col2 = st.columns(2)
51
- with col1:
52
- if st.button("Normal Calculator"):
53
- st.session_state.calculator_mode = "normal"
54
- with col2:
55
- if st.button("Excel Calculator"):
56
- st.session_state.calculator_mode = "excel"
57
-
58
- # Display the appropriate calculator based on session state
59
- if st.session_state.calculator_mode == "normal":
60
- with st.container():
61
- st.subheader("Enter Details Below")
62
- col1, col2 = st.columns(2)
63
- with col1:
64
- total_days = st.number_input("Total Working Days", min_value=1, max_value=365, value=5)
65
- with col2:
66
- absent_hours = st.number_input("Absent Hours of the Student", min_value=0, step=1)
67
-
68
- if st.button("Calculate Attendance"):
69
- present_percentage, present_hours, exam_status = calculate_attendance(total_days, absent_hours)
70
-
71
- st.write(f"โœ… **Present Percentage**: {present_percentage:.2f}%")
72
- st.write(f"โœ… **Present Hours**: {present_hours}")
73
- st.write(f"๐Ÿ“ข **Exam Status**: {exam_status}")
74
-
75
- elif st.session_state.calculator_mode == "excel":
76
- st.subheader("Upload an Excel or CSV File")
77
- st.write("""Your file should contain "Student Name" and their "Absent Hours" as columns.""")
78
-
79
- with st.container():
80
- uploaded_file = st.file_uploader("Upload File", type=["csv", "xlsx"])
81
-
82
- if uploaded_file:
83
- try:
84
- # Read the file correctly
85
- if uploaded_file.name.endswith(".csv"):
86
- df = pd.read_csv(uploaded_file)
87
- else:
88
- df = pd.read_excel(uploaded_file, engine='openpyxl')
89
-
90
- # Ensure required columns exist
91
- required_columns = {"Student Name", "Absent Hours"}
92
- if not required_columns.issubset(df.columns):
93
- st.error(f"Error: The uploaded file must contain the following columns: {required_columns}")
94
- else:
95
- with st.container():
96
- total_days = st.number_input("Enter Total Days", min_value=1, step=1)
97
-
98
- if st.button("Process File"):
99
- # Calculate attendance details
100
- df["Total Hours"] = total_days * 5
101
- df["Present Hours"] = df["Total Hours"] - df["Absent Hours"]
102
- df["Present Percentage"] = (df["Present Hours"] / df["Total Hours"]) * 100
103
- df["Exam Status"] = df["Present Percentage"].apply(
104
- lambda x: "Eligible" if x >= 74 else "Fine Required" if x >= 65 else "Arrear" if x >= 50 else "Redo"
105
- )
106
-
107
- # Round to two decimal places
108
- df["Present Percentage"] = df["Present Percentage"].round(2)
109
-
110
- # Calculate class present percentage
111
- class_present_percentage = df["Present Percentage"].mean()
112
-
113
- # Display results in Streamlit
114
- st.write("โœ… **File Processed Successfully!**")
115
- st.write(f"๐Ÿ“Š **Class Present Percentage:** {class_present_percentage:.2f}%")
116
- st.dataframe(df)
117
-
118
- # Convert DataFrame to Excel for download
119
- output = io.BytesIO()
120
- with pd.ExcelWriter(output, engine='openpyxl') as writer:
121
- df.to_excel(writer, index=False, sheet_name="Attendance")
122
-
123
- # Access workbook and worksheet
124
- workbook = writer.book
125
- worksheet = writer.sheets["Attendance"]
126
-
127
- # Add summary row at the bottom
128
- row_num = len(df) + 2
129
- worksheet.cell(row=row_num, column=1, value="Class Present Percentage")
130
- worksheet.cell(row=row_num, column=2, value=class_present_percentage)
131
-
132
- # Save and close writer
133
- writer.close()
134
- processed_data = output.getvalue()
135
-
136
- # Download button for processed Excel file
137
- st.download_button(
138
- "Download Processed File",
139
- data=processed_data,
140
- file_name="processed_attendance.xlsx",
141
- mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
142
- )
143
- except Exception as e:
144
- st.error(f"โš ๏ธ Error processing file: {e}")
145
-
146
- # Footer
147
- footer_html = """
148
- <style>
149
- .footer {
150
- position: fixed;
151
- bottom: 0;
152
- left: 0;
153
- width: 100%;
154
- background-color: #f1f1f1;
155
- text-align: center;
156
- padding: 10px;
157
- font-size: 14px;
158
- color: #333;
159
- }
160
- </style>
161
- <div class="footer">
162
- Made By balafromtn ๐Ÿ˜‰
163
- </div>
164
- """
165
-
166
  st.markdown(footer_html, unsafe_allow_html=True)
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import io
4
+
5
+ def calculate_attendance(total_days, absent_hours):
6
+ total_hours = total_days * 5 # Each day has 5 hours
7
+ present_hours = total_hours - absent_hours
8
+ present_percentage = (present_hours / total_hours) * 100
9
+
10
+ if present_percentage >= 74:
11
+ exam_status = "Eligible to write the exam"
12
+ elif 65 <= present_percentage <= 75:
13
+ exam_status = "Should pay fine to write the exam"
14
+ elif 50 <= present_percentage < 65:
15
+ exam_status = "Not eligible to write the exam"
16
+ else:
17
+ exam_status = "Redo"
18
+
19
+ # Round to two decimal places
20
+ present_percentage = round(present_percentage, 2)
21
+
22
+ return present_percentage, present_hours, exam_status
23
+
24
+ # Initialize session state for calculator mode
25
+ if "calculator_mode" not in st.session_state:
26
+ st.session_state.calculator_mode = "normal"
27
+
28
+ st.set_page_config(
29
+ page_icon="๐Ÿงฎ",
30
+ page_title="Student Attendance Calculator",
31
+ layout="centered"
32
+ )
33
+
34
+ # Custom CSS for styling
35
+ st.markdown("""
36
+ <style>
37
+ .css-1d391kg {text-align: center;}
38
+ .stButton>button {background-color: #87CEFA; color: black; padding: 10px; border-radius: 10px; font-weight: bold;}
39
+ .stFileUploader {text-align: center;}
40
+ .uploadedFile {color: green;}
41
+ .stDownloadButton>button {background-color: #4682B4; color: white; padding: 10px; border-radius: 10px; font-weight: bold;}
42
+ .stNumberInput>div>div>input {border-radius: 5px;}
43
+ </style>
44
+ """, unsafe_allow_html=True)
45
+
46
+ st.title("๐Ÿ“˜ Student Attendance Calculator")
47
+ st.markdown("______")
48
+
49
+ with st.container():
50
+ col1, col2 = st.columns(2)
51
+ with col1:
52
+ if st.button("Normal Calculator"):
53
+ st.session_state.calculator_mode = "normal"
54
+ with col2:
55
+ if st.button("Excel Calculator"):
56
+ st.session_state.calculator_mode = "excel"
57
+
58
+ # Display the appropriate calculator based on session state
59
+ if st.session_state.calculator_mode == "normal":
60
+ with st.container():
61
+ st.subheader("Enter Details Below")
62
+ col1, col2 = st.columns(2)
63
+ with col1:
64
+ total_days = st.number_input("Total Working Days", min_value=1, max_value=365, value=5)
65
+ with col2:
66
+ absent_hours = st.number_input("Absent Hours of the Student", min_value=0, step=1)
67
+
68
+ if st.button("Calculate Attendance"):
69
+ present_percentage, present_hours, exam_status = calculate_attendance(total_days, absent_hours)
70
+
71
+ st.write(f"โœ… **Present Percentage**: {present_percentage:.2f}%")
72
+ st.write(f"โœ… **Present Hours**: {present_hours}")
73
+ st.write(f"๐Ÿ“ข **Exam Status**: {exam_status}")
74
+
75
+ elif st.session_state.calculator_mode == "excel":
76
+ st.subheader("Upload an Excel or CSV File")
77
+ st.write("""Your file should contain "Student Name" and their "Absent Hours" as columns.""")
78
+
79
+ with st.container():
80
+ uploaded_file = st.file_uploader("Upload File", type=["csv", "xlsx"])
81
+
82
+ if uploaded_file:
83
+ try:
84
+ # Read the file correctly
85
+ if uploaded_file.name.endswith(".csv"):
86
+ df = pd.read_csv(uploaded_file)
87
+ else:
88
+ df = pd.read_excel(uploaded_file, engine='openpyxl')
89
+
90
+ # Ensure required columns exist
91
+ required_columns = {"Student Name", "Absent Hours"}
92
+ if not required_columns.issubset(df.columns):
93
+ st.error(f"Error: The uploaded file must contain the following columns: {required_columns}")
94
+ else:
95
+ with st.container():
96
+ total_days = st.number_input("Enter Total Days", min_value=1, step=1)
97
+
98
+ if st.button("Process File"):
99
+ # Calculate attendance details
100
+ df["Total Hours"] = total_days * 5
101
+ df["Present Hours"] = df["Total Hours"] - df["Absent Hours"]
102
+ df["Present Percentage"] = (df["Present Hours"] / df["Total Hours"]) * 100
103
+ df["Exam Status"] = df["Present Percentage"].apply(
104
+ lambda x: "Eligible" if x >= 74 else "Fine Required" if x >= 65 else "Arrear" if x >= 50 else "Redo"
105
+ )
106
+
107
+ # Round to two decimal places
108
+ df["Present Percentage"] = df["Present Percentage"].round(2)
109
+
110
+ # Calculate class present percentage
111
+ class_present_percentage = df["Present Percentage"].mean()
112
+
113
+ # Display results in Streamlit
114
+ st.write("โœ… **File Processed Successfully!**")
115
+ st.write(f"๐Ÿ“Š **Class Present Percentage:** {class_present_percentage:.2f}%")
116
+ st.dataframe(df)
117
+
118
+ # Convert DataFrame to Excel for download
119
+ output = io.BytesIO()
120
+ with pd.ExcelWriter(output, engine='openpyxl') as writer:
121
+ df.to_excel(writer, index=False, sheet_name="Attendance")
122
+
123
+ # Access workbook and worksheet
124
+ workbook = writer.book
125
+ worksheet = writer.sheets["Attendance"]
126
+
127
+ # Add summary row at the bottom
128
+ row_num = len(df) + 2
129
+ worksheet.cell(row=row_num, column=1, value="Class Present Percentage")
130
+ worksheet.cell(row=row_num, column=2, value=class_present_percentage)
131
+
132
+ # Save and close writer
133
+ writer.close()
134
+ processed_data = output.getvalue()
135
+
136
+ # Download button for processed Excel file
137
+ st.download_button(
138
+ "Download Processed File",
139
+ data=processed_data,
140
+ file_name="processed_attendance.xlsx",
141
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
142
+ )
143
+ except Exception as e:
144
+ st.error(f"โš ๏ธ Error processing file: {e}")
145
+
146
+ # Footer
147
+ footer_html = """
148
+ <div class="footer">
149
+ Made By balafromtn ๐Ÿ˜‰
150
+ </div>
151
+ """
152
+
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  st.markdown(footer_html, unsafe_allow_html=True)