Atia110/Advanced-Math-Learning-Platform
0
1import os2import streamlit as st3import sympy as sp4import numpy as np5import pandas as pd6import matplotlib.pyplot as plt7from groq import Groq8 9# ---------------- PAGE CONFIG ---------------- #10st.set_page_config(11 page_title="Advanced Math Learning Platform",12 page_icon="๐",13 layout="wide"14)15 16# ---------------- CUSTOM CSS ---------------- #17st.markdown("""18<style>19.main {20 background-color: #f5f7fa;21}22 23h1 {24 color: #4B0082;25 text-align: center;26}27 28h2, h3 {29 color: #333333;30}31 32.stButton > button {33 background-color: #6C63FF;34 color: white;35 border-radius: 10px;36 padding: 10px 20px;37 border: none;38 font-size: 16px;39}40 41.stButton > button:hover {42 background-color: #574fd6;43 color: white;44}45 46.card {47 background-color: white;48 padding: 20px;49 border-radius: 15px;50 box-shadow: 0px 4px 10px rgba(0,0,0,0.1);51 margin-bottom: 20px;52}53 54.chat-user {55 background-color: #E8F0FE;56 padding: 10px;57 border-radius: 10px;58 margin-bottom: 10px;59}60 61.chat-bot {62 background-color: #F1F3F4;63 padding: 10px;64 border-radius: 10px;65 margin-bottom: 10px;66}67</style>68""", unsafe_allow_html=True)69 70# ---------------- GROQ API ---------------- #71st.sidebar.title("Settings")72api_key = st.sidebar.text_input("API", type="password")73 74client = None75if api_key:76 try:77 client = Groq(api_key=api_key)78 except Exception:79 st.sidebar.error("Invalid API Key")80 81# ---------------- SIDEBAR MENU ---------------- #82st.sidebar.title("Navigation")83 84menu = st.sidebar.radio(85 "Choose a Section",86 [87 "Home",88 "Math Chatbot",89 "Equation Solver",90 "Formula Explainer",91 "Graph Plotter",92 "Quiz Generator",93 "Notes Generator",94 "Theorem Explainer",95 "Numerical Methods",96 "Fractional Calculus Assistant",97 "About"98 ]99)100 101# ---------------- TITLE ---------------- #102st.title("๐ Advanced Math Learning Platform")103st.markdown("### Learn Mathematics with AI, Graphs, Quizzes, and Step-by-Step Solutions")104 105# ---------------- HELPER FUNCTION ---------------- #106def get_groq_response(prompt):107 try:108 response = client.chat.completions.create(109 model="llama3-70b-8192",110 messages=[111 {"role": "system", "content": "You are a helpful mathematics tutor."},112 {"role": "user", "content": prompt}113 ]114 )115 return response.choices[0].message.content116 except Exception as e:117 return f"Error: {e}"118 119# ---------------- HOME ---------------- #120if menu == "Home":121 st.markdown("""122 <div class="card">123 <h3>Welcome to the Advanced Math Learning Platform</h3>124 <p>125 This platform helps students learn mathematics using AI tools,126 equation solving, graph plotting, theorem explanations, quizzes,127 notes generation, and more.128 </p>129 </div>130 """, unsafe_allow_html=True)131 132 col1, col2 = st.columns(2)133 134 with col1:135 st.info("๐ค Math Chatbot")136 st.info("๐งฎ Equation Solver")137 st.info("๐ Graph Plotter")138 st.info("๐ Notes Generator")139 st.info("โ Quiz Generator")140 141 with col2:142 st.info("๐ Formula Explainer")143 st.info("๐ Theorem Explainer")144 st.info("๐ข Numerical Methods")145 st.info("๐ฌ Fractional Calculus Assistant")146 st.info("โน๏ธ About")147 148# ---------------- MATH CHATBOT ---------------- #149elif menu == "Math Chatbot":150 st.header("๐ค Math Chatbot")151 152 question = st.text_area("Ask any mathematics question")153 154 if st.button("Get Answer"):155 if not api_key:156 st.warning("Please enter your Groq API key in the sidebar.")157 elif not question.strip():158 st.warning("Please enter a question.")159 else:160 with st.spinner("Generating response..."):161 answer = get_groq_response(question)162 st.markdown(f"<div class='chat-user'><b>You:</b><br>{question}</div>", unsafe_allow_html=True)163 st.markdown(f"<div class='chat-bot'><b>AI:</b><br>{answer}</div>", unsafe_allow_html=True)164 165# ---------------- EQUATION SOLVER ---------------- #166elif menu == "Equation Solver":167 st.header("๐งฎ Step-by-Step Equation Solver")168 169 equation = st.text_input("Enter equation like: x**2 - 5*x + 6 = 0")170 171 if st.button("Solve Equation"):172 if not equation.strip():173 st.warning("Please enter an equation.")174 else:175 try:176 x = sp.symbols('x')177 178 left_side, right_side = equation.split("=")179 180 left_expr = sp.sympify(left_side.strip())181 right_expr = sp.sympify(right_side.strip())182 183 eq = sp.Eq(left_expr, right_expr)184 solutions = sp.solve(eq, x)185 186 st.subheader("Equation")187 st.latex(sp.latex(eq))188 189 st.subheader("Step 1: Move all terms to one side")190 standard_form = sp.expand(left_expr - right_expr)191 st.latex(sp.latex(standard_form) + " = 0")192 193 st.subheader("Step 2: Solve for x")194 st.write(solutions)195 196 st.subheader("Final Answer")197 st.success(f"Solutions: {solutions}")198 199 except Exception:200 st.error("Please enter a valid equation in the correct format.")201 202# ---------------- FORMULA EXPLAINER ---------------- #203elif menu == "Formula Explainer":204 st.header("๐ Formula Explainer")205 206 formula = st.text_input("Enter a formula")207 208 if st.button("Explain Formula"):209 if not api_key:210 st.warning("Please enter your Groq API key in the sidebar.")211 elif not formula.strip():212 st.warning("Please enter a formula.")213 else:214 prompt = f"""215 Explain the formula: {formula}216 217 Include:218 1. Meaning of each symbol219 2. Where the formula is used220 3. Real-world applications221 4. One simple example222 """223 224 with st.spinner("Generating explanation..."):225 answer = get_groq_response(prompt)226 st.write(answer)227 228# ---------------- GRAPH PLOTTER ---------------- #229elif menu == "Graph Plotter":230 st.header("๐ Graph Plotter")231 232 expression = st.text_input("Enter function like: x**2 or sin(x)")233 start = st.number_input("Start Value of x", value=-10)234 end = st.number_input("End Value of x", value=10)235 236 if st.button("Plot Graph"):237 try:238 x = sp.symbols('x')239 expr = sp.sympify(expression)240 f = sp.lambdify(x, expr, modules=['numpy'])241 242 x_vals = np.linspace(start, end, 400)243 y_vals = f(x_vals)244 245 fig, ax = plt.subplots(figsize=(8, 5))246 ax.plot(x_vals, y_vals)247 ax.set_title("Graph of Function")248 ax.set_xlabel("x")249 ax.set_ylabel("y")250 ax.grid(True)251 252 st.pyplot(fig)253 254 except Exception:255 st.error("Please enter a valid mathematical expression.")256 257# ---------------- QUIZ GENERATOR ---------------- #258elif menu == "Quiz Generator":259 st.header("โ Quiz Generator")260 261 subject = st.selectbox(262 "Choose Subject",263 ["Algebra", "Calculus", "Probability", "Linear Algebra", "Numerical Analysis"]264 )265 266 difficulty = st.selectbox(267 "Choose Difficulty",268 ["Easy", "Medium", "Hard"]269 )270 271 num_questions = st.slider("Number of Questions", 1, 10, 5)272 273 if st.button("Generate Quiz"):274 if not api_key:275 st.warning("Please enter your Groq API key in the sidebar.")276 else:277 prompt = f"""278 Generate {num_questions} multiple choice questions for {subject}.279 Difficulty level: {difficulty}.280 281 Include:282 - Question283 - Four options284 - Correct answer285 """286 287 with st.spinner("Generating quiz..."):288 answer = get_groq_response(prompt)289 st.write(answer)290 291# ---------------- NOTES GENERATOR ---------------- #292elif menu == "Notes Generator":293 st.header("๐ Notes Generator")294 295 topic = st.text_input("Enter Topic")296 297 if st.button("Generate Notes"):298 if not api_key:299 st.warning("Please enter your Groq API key in the sidebar.")300 elif not topic.strip():301 st.warning("Please enter a topic.")302 else:303 prompt = f"""304 Generate study notes on: {topic}305 306 Include:307 - Summary308 - Important formulas309 - Key points310 - Examples311 """312 313 with st.spinner("Generating notes..."):314 answer = get_groq_response(prompt)315 st.write(answer)316 317# ---------------- THEOREM EXPLAINER ---------------- #318elif menu == "Theorem Explainer":319 st.header("๐ Theorem Explainer")320 321 theorem = st.text_input("Enter theorem name")322 323 if st.button("Explain Theorem"):324 if not api_key:325 st.warning("Please enter your Groq API key in the sidebar.")326 elif not theorem.strip():327 st.warning("Please enter a theorem name.")328 else:329 prompt = f"""330 Explain the theorem: {theorem}331 332 Include:333 - Statement334 - Explanation335 - Proof idea336 - Example337 - Applications338 """339 340 with st.spinner("Generating explanation..."):341 answer = get_groq_response(prompt)342 st.write(answer)343 344# ---------------- NUMERICAL METHODS ---------------- #345elif menu == "Numerical Methods":346 st.header("๐ข Numerical Methods Visualizer")347 348 function_input = st.text_input("Enter function", value="x**2 - 2")349 initial_guess = st.number_input("Initial Guess", value=1.0)350 351 if st.button("Apply Newton Method"):352 try:353 x = sp.symbols('x')354 expr = sp.sympify(function_input)355 derivative = sp.diff(expr, x)356 357 f = sp.lambdify(x, expr, modules=['numpy'])358 df = sp.lambdify(x, derivative, modules=['numpy'])359 360 current = initial_guess361 steps = []362 363 for i in range(10):364 current = current - f(current) / df(current)365 steps.append(current)366 367 st.subheader("Iteration Steps")368 369 for idx, value in enumerate(steps):370 st.write(f"Iteration {idx + 1}: {value}")371 372 st.success(f"Approximate Root: {current}")373 374 except Exception:375 st.error("Please enter a valid function.")376 377# ---------------- FRACTIONAL CALCULUS ASSISTANT ---------------- #378elif menu == "Fractional Calculus Assistant":379 st.header("๐ฌ Fractional Calculus Assistant")380 381 topic = st.text_input("Enter a fractional calculus topic")382 383 if st.button("Explain Topic"):384 if not api_key:385 st.warning("Please enter your Groq API key in the sidebar.")386 elif not topic.strip():387 st.warning("Please enter a topic.")388 else:389 prompt = f"""390 Explain the following fractional calculus topic in simple words:391 {topic}392 393 Include:394 - Definition395 - Explanation396 - Applications397 - Example398 """399 400 with st.spinner("Generating explanation..."):401 answer = get_groq_response(prompt)402 st.write(answer)403 404# ---------------- ABOUT ---------------- #405elif menu == "About":406 st.header("โน๏ธ About This Project")407 408 st.write("""409 This is an AI-powered mathematics learning platform built using:410 - Streamlit411 - Groq API412 - SymPy413 - NumPy414 - Matplotlib415 416 It helps students learn mathematics through:417 - Chatbot support418 - Equation solving419 - Formula explanation420 - Graph plotting421 - Quiz generation422 - Theorem explanation423 - Numerical methods424 - Fractional calculus topics425 """)426 427 st.write("Developer: Add your name here")