testtrial / app.py
Hidayatmahar's picture
Update app.py
e89aa82 verified
import streamlit as st
import fpdf
import time
from datetime import datetime, timedelta
# Set test duration (120 minutes)
TEST_DURATION = 120
# Initialize session state for the timer
if "start_time" not in st.session_state:
st.session_state.start_time = datetime.now()
# Calculate end time
end_time = st.session_state.start_time + timedelta(minutes=TEST_DURATION)
# Timer display
timer_placeholder = st.sidebar.empty() # Place the timer in the sidebar
def update_timer():
"""Updates the countdown timer in real-time."""
while True:
remaining_time = end_time - datetime.now()
if remaining_time.total_seconds() <= 0:
timer_placeholder.warning("Time's up! Submitting the test now...")
st.session_state.test_completed = True
st.rerun()
break
minutes, seconds = divmod(int(remaining_time.total_seconds()), 60)
timer_placeholder.info(f"🕒 Time Remaining: {minutes:02d}:{seconds:02d}")
time.sleep(1) # Refresh every second
st.rerun()
# Run the timer in the sidebar
update_timer()
#import streamlit as st
#from fpdf import FPDF
#import datetime
# Function to Generate PDF
def generate_pdf(name, roll_no, nic_number, father_name, form_number, scores):
pdf = FPDF()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.add_page()
# Title
pdf.set_font("Arial", style='B', size=16)
pdf.cell(200, 10, "NFC Institute of Engineering & Technology, Multan (Admission Test)", ln=True, align='C')
pdf.ln(10)
# Student Details
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, f"Name: {name}", ln=True)
pdf.cell(200, 10, f"Roll Number: {roll_no}", ln=True)
pdf.cell(200, 10, f"NIC Number: {nic_number}", ln=True)
pdf.cell(200, 10, f"Father's Name: {father_name}", ln=True)
pdf.cell(200, 10, f"Form Number: {form_number}", ln=True)
pdf.cell(200, 10, f"Test Date: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True)
pdf.ln(10)
# Test Scores
pdf.set_font("Arial", style='B', size=14)
for subject, score in scores.items():
pdf.cell(200, 10, f"{subject} Section Score: {score} out of 100", ln=True)
total_score = sum(scores.values())
pdf.cell(200, 10, f"Total Score: {total_score} out of 400", ln=True)
# Save PDF
pdf_path = "test_result.pdf"
pdf.output(pdf_path)
return pdf_path
# Streamlit UI
st.title("NFC Institute of Engineering & Technology (Admission Test)")
st.subheader("Student Information")
name = st.text_input("Full Name")
roll_no = st.text_input("Roll Number")
nic_number = st.text_input("NIC Number")
father_name = st.text_input("Father's Name")
form_number = st.text_input("Form Number")
# Function to Display Questions
def display_questions(section_name, questions):
st.subheader(f"{section_name} Section (25 Questions)")
answers = {}
for q_no, (question, options, correct_answer) in enumerate(questions, start=1):
answers[q_no] = st.radio(question, options, index=None, key=f"{section_name}_{q_no}")
return answers
# Sample Questions (Only 5 per section shown, add more)
english_questions = [
("1. Choose the correct synonym of 'Benevolent':", ["Kind", "Cruel", "Harsh", "Weak"], "Kind"),
("2. Identify the correct antonym of 'Fragile':", ["Weak", "Strong", "Delicate", "Feeble"], "Strong"),
("3. Choose the correct article: 'I saw ___ elephant at the zoo.'", ["a", "an", "the", "no article"], "an"),
("4. Select the correct spelling:", ["Recieve", "Receive", "Recive", "Receve"], "Receive"),
("5. Fill in the blank: 'She is interested ____ learning new languages.'", ["on", "in", "at", "with"], "in"),
("6. Which word is a noun?", ["Run", "Beautiful", "Happiness", "Quickly"], "Happiness"),
("7. Identify the verb: 'She sings beautifully.'", ["She", "Sings", "Beautifully", "The"], "Sings"),
("8. What is the plural of 'Child'?", ["Childs", "Children", "Childes", "Childer"], "Children"),
("9. Choose the correct sentence:", ["He go to school.", "He goes to school.", "He gone to school.", "He going to school."], "He goes to school."),
("10. What is the past tense of 'Eat'?", ["Eated", "Ate", "Eating", "Eats"], "Ate"),
("11. Choose the correct synonym of 'Meticulous':", ["Careless", "Precise", "Lazy", "Hasty"], "Precise"),
("12. Identify the correct synonym of 'Adversity':", ["Comfort", "Hardship", "Happiness", "Success"], "Hardship"),
("13. Choose the antonym of 'Arrogant':", ["Humble", "Proud", "Confident", "Bold"], "Humble"),
("14. Identify the correct verb: 'He ____ his homework every evening.'", ["do", "does", "doing", "done"], "does"),
("15. Choose the correct preposition: 'The book is lying ____ the table.'", ["on", "in", "at", "by"], "on"),
("16. What is the superlative form of 'Good'?", ["Goodest", "Better", "Best", "More good"], "Best"),
("17. Choose the correct conjunction: 'I was tired, ____ I kept working.'", ["and", "but", "so", "or"], "but"),
("18. What is the correct order of adjectives: 'She bought a ____ car.'", ["red big", "big red", "red and big", "big and red"], "big red"),
("19. Choose the correct passive form: 'They are painting the house.'", ["The house is painted.", "The house is being painted.", "The house was painted.", "The house has been painted."], "The house is being painted."),
("20. What is the plural of 'Mouse'?", ["Mouses", "Mices", "Mice", "Mouse"], "Mice"),
("21. Choose the correct relative pronoun: 'This is the book ____ I borrowed.'", ["who", "whom", "which", "that"], "that"),
("22. What is the meaning of the idiom 'Break the ice'?", ["To start a conversation", "To break something", "To go skating", "To feel cold"], "To start a conversation"),
("23. Identify the indirect speech: She said, 'I am happy.'", ["She said that she was happy.", "She said she is happy.", "She said that I was happy.", "She said that I am happy."], "She said that she was happy."),
("24. Fill in the blank: 'He is the ____ of all the students in the class.'", ["smarter", "smart", "smartest", "more smart"], "smartest"),
("25. Choose the correct modal verb: 'You ____ wear a seatbelt while driving.'", ["can", "may", "should", "must"], "must"),
]
chemistry_questions = [
("1. What is the chemical formula of water?", ["H2O", "O2", "CO2", "H2"], "H2O"),
("2. What is the pH value of pure water?", ["7", "5", "9", "11"], "7"),
("3. Which gas is released when acids react with metals?", ["Oxygen", "Hydrogen", "Nitrogen", "Carbon dioxide"], "Hydrogen"),
("4. What is the common name for sodium chloride?", ["Baking Soda", "Table Salt", "Lime", "Vinegar"], "Table Salt"),
("5. What is the atomic number of carbon?", ["6", "8", "12", "14"], "6"),
("6. What is the most abundant gas in Earth’s atmosphere?", ["Oxygen", "Nitrogen", "Carbon Dioxide", "Argon"], "Nitrogen"),
("7. What is the chemical symbol for gold?", ["Ag", "Au", "Pb", "Fe"], "Au"),
("8. What type of bond is formed between two non-metal atoms?", ["Ionic", "Covalent", "Metallic", "Hydrogen"], "Covalent"),
("9. What is the SI unit of atomic mass?", ["Gram", "Kilogram", "Atomic Mass Unit (AMU)", "Mole"], "Atomic Mass Unit (AMU)"),
("10. What is the chemical formula of methane?", ["CH4", "C2H6", "CO2", "H2O"], "CH4"),
("11. What is the charge on a proton?", ["+1", "-1", "0", "+2"], "+1"),
("12. Which element is liquid at room temperature?", ["Oxygen", "Mercury", "Sodium", "Sulfur"], "Mercury"),
("13. What is the primary component of natural gas?", ["Propane", "Methane", "Butane", "Ethane"], "Methane"),
("14. What type of reaction occurs when an acid and a base react together?", ["Decomposition", "Neutralization", "Combustion", "Oxidation"], "Neutralization"),
("15. Which element is known as the building block of life?", ["Oxygen", "Carbon", "Hydrogen", "Nitrogen"], "Carbon"),
("16. What is the chemical formula of sulfuric acid?", ["H2SO3", "H2SO4", "HCl", "HNO3"], "H2SO4"),
("17. What is the process of converting a solid directly into a gas?", ["Condensation", "Evaporation", "Sublimation", "Freezing"], "Sublimation"),
("18. What is the chemical formula for table sugar (sucrose)?", ["C6H12O6", "C12H22O11", "C2H5OH", "CH3OH"], "C12H22O11"),
("19. What is the name of the reaction where oxygen is gained or hydrogen is lost?", ["Reduction", "Oxidation", "Hydrolysis", "Neutralization"], "Oxidation"),
("20. What is Avogadro’s number?", ["6.022 × 10²²", "6.022 × 10²³", "3.14 × 10²³", "1.67 × 10²⁴"], "6.022 × 10²³"),
("21. Which gas is commonly used in balloons because it is lighter than air?", ["Oxygen", "Carbon Dioxide", "Helium", "Nitrogen"], "Helium"),
("22. What is the function of a catalyst in a chemical reaction?", ["Speeds up the reaction", "Slows down the reaction", "Stops the reaction", "Changes the reactants"], "Speeds up the reaction"),
("23. Which of the following is an alkaline earth metal?", ["Sodium", "Magnesium", "Iron", "Gold"], "Magnesium"),
("24. What is the term for a substance that speeds up a reaction without being consumed?", ["Reactant", "Catalyst", "Inhibitor", "Solvent"], "Catalyst"),
("25. What type of organic compounds are enzymes?", ["Lipids", "Proteins", "Carbohydrates", "Nucleic Acids"], "Proteins"),
]
math_questions = [
("1. What is 7 + 8?", ["15", "16", "14", "17"], "15"),
("2. What is the square root of 64?", ["6", "8", "10", "12"], "8"),
("3. Solve: 5 × 6", ["25", "30", "35", "40"], "30"),
("4. What is 12 ÷ 4?", ["2", "3", "4", "6"], "3"),
("5. If x = 5, what is x²?", ["10", "15", "25", "30"], "25"),
("6. What is the value of sin(30°)?", ["1", "1/2", "√3/2", "0"], "1/2"),
("7. Solve for x: 2x + 3 = 11", ["3", "4", "5", "6"], "4"),
("8. What is the derivative of x²?", ["x", "2x", "x^2", "1"], "2x"),
("9. Solve: log10(1000)", ["1", "2", "3", "4"], "3"),
("10. What is the sum of interior angles of a pentagon?", ["360°", "540°", "720°", "900°"], "540°"),
("11. What is the area of a circle with radius 7?", ["49π", "14π", "7π", "21π"], "49π"),
("12. Solve: 2³ + 3²", ["8", "9", "17", "14"], "17"),
("13. If f(x) = 3x + 2, find f(4).", ["10", "12", "14", "8"], "14"),
("14. Find the determinant of the matrix [[1,2],[3,4]].", ["-2", "2", "0", "4"], "-2"),
("15. What is the value of cos(90°)?", ["1", "0", "-1", "√2/2"], "0"),
("16. Solve for x: 3x - 4 = 11", ["3", "5", "6", "7"], "5"),
("17. What is the sum of the first 10 natural numbers?", ["55", "50", "45", "60"], "55"),
("18. Find the equation of a line with slope 2 and passing through (3,4).", ["y = 2x + 4", "y = 2x - 2", "y = 2x + 1", "y = 2x - 3"], "y = 2x - 2"),
("19. If a triangle has sides 3, 4, and 5, what type of triangle is it?", ["Scalene", "Isosceles", "Right-angled", "Equilateral"], "Right-angled"),
("20. Solve: ∫(2x)dx", ["x²", "2x²", "x² + C", "2x² + C"], "x² + C"),
("21. Convert 60° to radians.", ["π/2", "π/3", "π/6", "π/4"], "π/3"),
("22. Solve for x: x² - 4x + 4 = 0", ["0, 4", "2, 2", "1, 3", "None"], "2, 2"),
("23. What is the probability of getting a head in a single toss of a fair coin?", ["1", "0.5", "0.25", "2"], "0.5"),
("24. If A = {1,2,3,4} and B = {3,4,5,6}, find A ∩ B.", ["{1,2}", "{3,4}", "{5,6}", "{}"], "{3,4}"),
("25. Find the slope of the line passing through (2,3) and (6,7).", ["1", "2", "3", "4"], "1"),
]
physics_questions = [
("1. What is the speed of light?", ["300,000 km/s", "150,000 km/s", "500,000 km/s", "100,000 km/s"], "300,000 km/s"),
("2. Newton’s first law is also called?", ["Law of Gravity", "Law of Inertia", "Law of Motion", "Law of Force"], "Law of Inertia"),
("3. Which of these is not a unit of energy?", ["Joule", "Watt", "Calorie", "Electronvolt"], "Watt"),
("4. What is the SI unit of force?", ["Newton", "Joule", "Watt", "Pascal"], "Newton"),
("5. What is the acceleration due to gravity on Earth?", ["9.8 m/s²", "10 m/s²", "8.5 m/s²", "12 m/s²"], "9.8 m/s²"),
("6. Which force keeps planets in orbit around the Sun?", ["Magnetic Force", "Electrostatic Force", "Gravitational Force", "Nuclear Force"], "Gravitational Force"),
("7. What is the SI unit of work?", ["Joule", "Newton", "Watt", "Pascal"], "Joule"),
("8. What type of lens is used in a magnifying glass?", ["Concave", "Convex", "Plano-concave", "Biconcave"], "Convex"),
("9. The resistance of a wire depends on?", ["Length & cross-sectional area", "Only length", "Only cross-sectional area", "Neither length nor area"], "Length & cross-sectional area"),
("10. What is the function of a fuse in an electric circuit?", ["Increase voltage", "Prevent overcurrent", "Store charge", "Convert AC to DC"], "Prevent overcurrent"),
("11. What is the unit of electric current?", ["Volt", "Ohm", "Ampere", "Watt"], "Ampere"),
("12. What happens to the pressure when the volume of a gas decreases (at constant temperature)?", ["Increases", "Decreases", "Remains the same", "Becomes zero"], "Increases"),
("13. Which wave type does not require a medium to travel?", ["Sound waves", "Water waves", "Seismic waves", "Electromagnetic waves"], "Electromagnetic waves"),
("14. What is the primary energy source for the Earth?", ["Wind", "Sun", "Nuclear", "Geothermal"], "Sun"),
("15. Which law states that the current in a circuit is directly proportional to voltage?", ["Ohm’s Law", "Newton’s Law", "Boyle’s Law", "Faraday’s Law"], "Ohm’s Law"),
("16. What is the charge of a neutron?", ["Positive", "Negative", "Neutral", "Depends on the element"], "Neutral"),
("17. The energy stored in an object due to its position is called?", ["Kinetic energy", "Potential energy", "Thermal energy", "Chemical energy"], "Potential energy"),
("18. What device is used to measure electric current?", ["Voltmeter", "Ammeter", "Ohmmeter", "Galvanometer"], "Ammeter"),
("19. What is the frequency of a wave if its time period is 0.02 seconds?", ["20 Hz", "50 Hz", "100 Hz", "200 Hz"], "50 Hz"),
("20. What type of mirror is used in car rear-view mirrors?", ["Convex", "Concave", "Plane", "Cylindrical"], "Convex"),
("21. Which phenomenon causes a pencil to appear bent in water?", ["Diffraction", "Interference", "Refraction", "Reflection"], "Refraction"),
("22. What is the minimum number of resistors needed to form a circuit?", ["1", "2", "3", "4"], "1"),
("23. Which subatomic particle is responsible for electricity?", ["Proton", "Neutron", "Electron", "Nucleus"], "Electron"),
("24. What is the main function of a transformer?", ["Increase/decrease voltage", "Store energy", "Measure resistance", "Convert AC to DC"], "Increase/decrease voltage"),
("25. What is the standard unit of power?", ["Joule", "Newton", "Watt", "Ampere"], "Watt"),
]
# Collect Answers
english_answers = display_questions("English", english_questions)
chemistry_answers = display_questions("Chemistry", chemistry_questions)
math_answers = display_questions("Math", math_questions)
physics_answers = display_questions("Physics", physics_questions)
# Submit Button
if st.button("Submit Test"):
scores = {"English": 0, "Chemistry": 0, "Math": 0, "Physics": 0}
# Calculate Scores
for section, answers, questions in [
("English", english_answers, english_questions),
("Chemistry", chemistry_answers, chemistry_questions),
("Math", math_answers, math_questions),
("Physics", physics_answers, physics_questions),
]:
for q_no, (question, options, correct_answer) in enumerate(questions, start=1):
if q_no > 25: # Ensure only 25 questions are counted
break
if answers.get(q_no) == correct_answer:
scores[section] += 4 # Correct answer
elif answers.get(q_no) is not None:
scores[section] -= 1 # Incorrect answer
pdf_path = generate_pdf(name, roll_no, nic_number, father_name, form_number, scores)
with open(pdf_path, "rb") as pdf_file:
st.download_button(label="Download Result PDF", data=pdf_file, file_name="test_result.pdf", mime="application/pdf")