import streamlit as st import joblib import pandas as pd import numpy as np from huggingface_hub import upload_file, list_repo_files, HfApi, hf_hub_download import os from io import StringIO # --- 1. CONFIGURATION, MODELS, AND DATA LOADING --- # Streamlit Resource Caching for models (loading only once) @st.cache_resource def load_models(): """Loads the pre-trained ML model and encoders.""" try: pipeline = joblib.load("recommendation_model.pkl") le_subtopic = joblib.load("subtopic_encoder.pkl") le_course = joblib.load("course_encoder.pkl") return pipeline, le_subtopic, le_course except FileNotFoundError: st.error("Error: Required model files (pkl) not found. Please ensure they are uploaded or exist in the execution directory.") st.stop() # Load models and encoders knn_pipeline, le_subtopic, le_course = load_models() # Data from gui.py TOTAL_NUM_QUESTIONS = { "Algebra": 4, "Calculus": 4, "Coordinate geometry": 2, "Networking": 4, "Cybersecurity": 4, "Other_tech": 2, "Physics": 4, "Chemistry": 4, "Biology": 2, "Computer science": 10 } # Advanced/Harder 12th Grade MCQ Questions (Ensures question count matches TOTAL_NUM_QUESTIONS) MCQ_QUESTIONS = { "Algebra": [ ["If a non-singular matrix A is idempotent (Aยฒ = A), what is the inverse of A?", ["A", "I - A", "I", "Aยฒ"], 2], ["For a sequence to be convergent, which condition must it satisfy?", ["Monotonic and unbounded", "Cauchy but not bounded", "Bounded and monotonic", "Unbounded and non-monotonic"], 2], ["If roots of the equation xยฒ - bx + c = 0 are two consecutive integers, then bยฒ - 4c is equal to:", ["4", "3", "2", "1"], 3], ["The greatest integer function f(x) = [x] is continuous at:", ["Integers only", "Non-integers only", "All real numbers", "Nowhere"], 1], ], "Calculus": [ ["What is the value of the definite integral $\int_{0}^{\pi} \cos^2(x) dx$?", ["$\pi$", "$\pi/2$", "0", "$2\pi$"], 1], ["If $y = e^{\sin(x)}$, what is $dy/dx$?", ["$e^{\cos(x)}$", "$\cos(x) e^{\sin(x)}$", "$e^{\sin(x)} / \cos(x)$", "$\sin(x) e^{\sin(x)}$"], 1], ["For which function does the Mean Value Theorem not apply on the interval [0, 4]?", ["$f(x) = |x-2|$", "$f(x) = x^2$", "$f(x) = \sin(x)$", "$f(x) = e^x$"], 0], ["Which test determines local extrema for a single-variable function?", ["Integral Test", "Ratio Test", "First Derivative Test", "Comparison Test"], 2], ], "Coordinate geometry": [ ["The general equation of a sphere with center (h, k, l) and radius r is given by:", ["$(x-h)^2 + (y-k)^2 = r^2$", "$(x-h)^2 + (y-k)^2 + (z-l)^2 = r$", "$x^2 + y^2 + z^2 + 2gx + 2fy + 2hz + c = 0$", "$x^2 + y^2 + 2gx + 2fy + c = 0$"], 2], ["What is the eccentricity of a rectangular hyperbola?", ["$1$", "$\sqrt{2}$", "$1/\sqrt{2}$", "$\infty$"], 1], ], "Networking": [ ["Which TCP/IP model layer combines the OSI's Presentation and Session layers?", ["Application Layer", "Transport Layer", "Network Layer", "Internet Layer"], 0], ["What is the primary function of the ARP protocol?", ["Mapping IP to TCP port numbers", "Mapping MAC to UDP port numbers", "Mapping IP to MAC addresses", "Mapping hostnames to IP addresses"], 2], ["The term 'three-way handshake' is associated with:", ["UDP connection establishment", "TCP connection termination", "ARP request/reply", "TCP connection establishment"], 3], ["In CIDR notation, what does the suffix /24 represent in an IPv4 address?", ["A Class C network", "The first 24 bits are the network ID", "The last 24 bits are the host ID", "24 subnets"], 1], ], "Cybersecurity": [ ["A zero-day exploit targets:", ["A patchable vulnerability known for years", "A newly discovered vulnerability with no patch available", "Software running with elevated privileges", "Misconfigured database access"], 1], ["What mathematical function underpins public-key cryptography like RSA?", ["Matrix Inversion", "One-way Hash Function", "Prime Factorization Difficulty", "Discrete Fourier Transform"], 2], ["A 'Man-in-the-Middle' (MITM) attack relies primarily on:", ["DDoS to overload the server", "Eavesdropping on a secure channel", "Impersonating one party to both communicating parties", "Exploiting a buffer overflow"], 2], ["What is the term for a logical grouping of users or resources that share security policies within an Active Directory environment?", ["Domain", "Workgroup", "Forest", "Realm"], 0], ], "Other_tech": [ ["Which technology uses a decentralized, distributed ledger that is immutable?", ["Cloud Computing", "NoSQL Database", "Blockchain", "Virtualization"], 2], ["What is the fundamental difference between a virtual machine (VM) and a container (e.g., Docker)?", ["VMs use kernel-level isolation; containers use hardware emulation", "VMs emulate hardware; containers share the host OS kernel", "VMs are platform-independent; containers are not", "VMs are significantly faster than containers"], 1], ], "Physics": [ ["In an ideal transformer, the voltage ratio is proportional to the:", ["Current ratio", "Power ratio", "Number of turns ratio", "Frequency ratio"], 2], ["According to de Broglie, the wavelength $\lambda$ associated with a particle of momentum $p$ is:", ["$\lambda = p/h$", "$\lambda = h/p$", "$\lambda = h \cdot p$", "$\lambda = h^2/p$"], 1], ["What does the term 'critical angle' relate to in optics?", ["Reflection", "Dispersion", "Total Internal Reflection", "Polarization"], 2], ["The property of a semiconductor that determines its conductivity at absolute zero (0 K) is its:", ["Doping concentration", "Band gap energy", "Hole mobility", "Effective mass"], 1], ], "Chemistry": [ ["What is the oxidation state of sulfur in sulfuric acid ($H_2SO_4$)?", ["+2", "+4", "+6", "+7"], 2], ["The process of converting vegetable oil into solid fat is an example of which type of chemical reaction?", ["Hydrolysis", "Saponification", "Hydrogenation", "Esterification"], 2], ["Which factor increases the rate of reaction by lowering the activation energy without being consumed?", ["Inhibitor", "Catalyst", "Reagent", "Solvent"], 1], ["According to VSEPR theory, a molecule with four bonding pairs and zero lone pairs around the central atom has what geometry?", ["Trigonal planar", "Tetrahedral", "Bent", "Trigonal bipyramidal"], 1], ], "Biology": [ ["Which enzyme is responsible for synthesizing a new strand of DNA during replication in the 5' to 3' direction?", ["DNA Ligase", "Helicase", "DNA Polymerase III", "Primase"], 2], ["In eukaryotic cells, where does the Krebs cycle (Citric Acid Cycle) occur?", ["Cytosol", "Mitochondrial matrix", "Ribosome", "Nucleus"], 1], ], "Computer science": [ ["The complexity $O(n^2)$ algorithm is generally preferred over $O(n \log n)$ for large datasets. (True/False)", ["True", "False", "Only if $n > 1000$", "Depends on constant factors"], 1], ["In SQL, which keyword is used to sort the result-set of a query?", ["SORT BY", "ARRANGE", "ORDER BY", "GROUP BY"], 2], ["What is the purpose of normalization in database design?", ["To speed up query execution", "To reduce data redundancy and dependency issues", "To encrypt sensitive data", "To manage user permissions"], 1], ["Which search algorithm requires the graph edges to have non-negative weights?", ["Breadth-First Search (BFS)", "Depth-First Search (DFS)", "Dijkstra's Algorithm", "A* Search"], 2], ["A 'race condition' is characteristic of which programming paradigm?", ["Functional programming", "Concurrent programming", "Procedural programming", "Object-Oriented programming"], 1], ["What is the primary role of a Hypervisor (VMM)?", ["Managing network traffic flow", "Creating and running virtual machines", "Providing secure browser environment", "Compiling high-level code"], 1], ["Which of the following is a non-volatile memory type?", ["SRAM", "DRAM", "Cache memory", "Flash memory"], 3], ["What data structure is used to implement a recursive function call stack?", ["Queue", "Hash Table", "Binary Tree", "Stack"], 3], ["Which of the following protocols operates at the Transport Layer of the OSI model, guaranteeing reliable, ordered data delivery?", ["IP", "HTTP", "TCP", "UDP"], 2], ["The technique used to handle multiple interrupts by assigning priority levels is called:", ["Polling", "Vectored interrupt", "Interrupt chaining", "Daisy chaining"], 3], ] } # --- 2. RECOMMENDATION LOGIC --- def recommend_courses_batch(subtopics, num_questions, correct_answers): """ Predicts and returns course recommendations based on user performance. Matches the original logic from gui.py. """ # Use correct_answers as the 'Score out of 10' feature, matching the original script. scores = correct_answers data = pd.DataFrame({ 'Sub topics': subtopics, 'Num of questions': num_questions, 'Correct answers': correct_answers, 'Score out of 10': scores, }) # Feature Engineering: Calculate Accuracy data['Accuracy'] = data['Correct answers'] / data['Num of questions'] # Encoding: Transform categorical feature 'Sub topics' # Check if a subtopic wasn't in the original training data (which shouldn't happen here) for topic in data['Sub topics'].unique(): if topic not in le_subtopic.classes_: st.warning(f"Subtopic '{topic}' not recognized by the model encoder. Skipping recommendation.") return ["Error: Subtopic not found in model vocabulary."] data['Sub topics'] = le_subtopic.transform(data['Sub topics']) # [cite_start]Ensure feature order matches the model training data [cite: 5] X_predict = data[['Sub topics', 'Num of questions', 'Correct answers', 'Score out of 10', 'Accuracy']] # Predict courses try: preds = knn_pipeline.predict(X_predict) courses = le_course.inverse_transform(preds) # Return unique courses return list(set(courses)) except Exception as e: st.error(f"Error during model prediction: {e}. Check model integrity.") return ["Error: Model failed to generate recommendation."] # --- 3. STREAMLIT APP STATE MANAGEMENT --- # Initialize session state for navigation and data storage if 'page' not in st.session_state: st.session_state['page'] = 'start' if 'selected_topics' not in st.session_state: st.session_state['selected_topics'] = [] if 'mcq_results' not in st.session_state: st.session_state['mcq_results'] = {} def set_page(page_name): """Function to change the page/state.""" st.session_state['page'] = page_name # --- 4. STREAMLIT PAGE FUNCTIONS --- def start_screen(): """Step 1: Welcome Screen""" st.markdown("