Alpha108's picture
Update app.py
81ac99d verified
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
import os
# Configuration
quiz_labels = ["Quiz 1", "Quiz 2", "Quiz 3", "Quiz 4", "Quiz 5", "Grand Quiz"]
weightages = [5, 5, 10, 15, 15, 50]
total_marks_list = [60, 60, 60, 60, 60, 80]
# Streamlit UI
st.set_page_config(page_title="Quiz Result Calculator", layout="centered")
st.title("🎯 Hacking Page – Quiz Marks Weighted Percentage Calculator")
# Input for name
student_name = st.text_input("Enter your name:", max_chars=50)
st.markdown("**Enter only the marks obtained below.**<br>Total marks are fixed: 60 for quizzes and 80 for the Grand Quiz.", unsafe_allow_html=True)
marks_obtained = []
for i in range(6):
obtained = st.number_input(
f"{quiz_labels[i]} - Marks Obtained (out of {total_marks_list[i]})",
min_value=0,
max_value=total_marks_list[i],
step=1,
key=f"obtained_{i}"
)
marks_obtained.append(obtained)
# Function to create PDF
def generate_result_card_pdf(data, final_percentage, student_name):
pdf_path = "result_card.pdf"
doc = SimpleDocTemplate(pdf_path, pagesize=A4)
elements = []
styles = getSampleStyleSheet()
elements.append(Paragraph("πŸŽ“ Quiz Result Card", styles['Title']))
elements.append(Spacer(1, 8))
elements.append(Paragraph(f"<b>Name:</b> {student_name}", styles['Heading3']))
elements.append(Spacer(1, 12))
table_data = [["Quiz", "Marks Obtained", "Total Marks", "Weightage (%)", "Section %", "Contribution (%)"]]
for row in data:
table_data.append([
row["Quiz"],
row["Marks Obtained"],
row["Total Marks"],
row["Weightage (%)"],
f"{row['Section %']}%",
f"{row['Contribution (%)']}%"
])
table = Table(table_data)
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('BACKGROUND', (0, 1), (-1, -1), colors.beige),
('GRID', (0, 0), (-1, -1), 1, colors.black),
]))
elements.append(table)
elements.append(Spacer(1, 24))
elements.append(Paragraph(f"βœ… Final Weighted Percentage: <b>{final_percentage:.2f}%</b>", styles['Heading2']))
doc.build(elements)
return pdf_path
# On button click
if st.button("πŸ” Calculate Result"):
if not student_name.strip():
st.error("Please enter your name to generate the result card.")
else:
data = []
total_weighted_percentage = 0
section_percentages = []
for i in range(6):
total = total_marks_list[i]
percent = (marks_obtained[i] / total) * 100
contribution = percent * (weightages[i] / 100)
total_weighted_percentage += contribution
section_percentages.append(percent)
data.append({
"Quiz": quiz_labels[i],
"Marks Obtained": marks_obtained[i],
"Total Marks": total,
"Weightage (%)": weightages[i],
"Section %": round(percent, 2),
"Contribution (%)": round(contribution, 2)
})
df = pd.DataFrame(data)
df.set_index("Quiz", inplace=True)
st.markdown("### πŸ“Š Results Table")
st.dataframe(df)
st.success(f"βœ… Final Weighted Percentage: **{total_weighted_percentage:.2f}%**")
# Plotting
fig, ax = plt.subplots()
ax.barh(quiz_labels, section_percentages, color='skyblue')
ax.set_xlabel("Percentage %")
ax.set_title("Marks Percentage per Quiz")
st.pyplot(fig)
# Generate PDF with student name
pdf_path = generate_result_card_pdf(data, total_weighted_percentage, student_name)
with open(pdf_path, "rb") as f:
st.download_button(
label="πŸ“„ Download Result Card (PDF)",
data=f,
file_name=f"{student_name.replace(' ', '_')}_result_card.pdf",
mime="application/pdf"
)