NSamson1 commited on
Commit
ea0ce7e
·
verified ·
1 Parent(s): 750cbc8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -0
app.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import os
4
+ import zipfile
5
+ from PIL import Image
6
+ import sympy as sp
7
+ import time
8
+ from sentence_transformers import SentenceTransformer
9
+ from sklearn.metrics.pairwise import cosine_similarity
10
+
11
+ # Page config
12
+ st.set_page_config(page_title="🎓 Smart Math Teacher", layout="centered")
13
+
14
+ # Custom CSS
15
+ st.markdown("""
16
+ <style>
17
+ .fun-title { font-size: 40px; color: #ff3399; text-align: center; font-family: 'Comic Sans MS', cursive; }
18
+ .question-box { border: 4px dotted #ffcc00; padding: 20px; border-radius: 20px; background-color: #fff7e6; font-size: 20px; }
19
+ .stButton > button { font-size: 18px; background-color: #00cc99; color: white; border-radius: 10px; padding: 10px; }
20
+ .stTextInput > div > input { font-size: 18px; }
21
+ </style>
22
+ """, unsafe_allow_html=True)
23
+
24
+ # Welcome title
25
+ st.markdown("<div class='fun-title'>🧠✨ Welcome to the Smart Math Teacher! ✨🧠</div>", unsafe_allow_html=True)
26
+
27
+ # Age group setup
28
+ age_groups = {
29
+ "4-6 Age Group": {"dataset": "Dataset for 4-6 Age Group.xlsx", "zip_file": "Image_for_group_4-6.zip", "image_folder": "Image_for_group_4-6"},
30
+ "7-9 Age Group": {"dataset": "Dataset for 7-9 Age Group.xlsx", "zip_file": "Image_for_group_7-9.zip", "image_folder": "Image_for_group_7-9"},
31
+ "13-15 Age Group": {"dataset": "Dataset for 13-15 Age Group.xlsx", "zip_file": "Image_for_group_13-15.zip", "image_folder": "Image_for_group_13-15"},
32
+ }
33
+
34
+ selected_age_group = st.selectbox("🧒 Select your Age Group:", list(age_groups.keys()))
35
+
36
+ # Initialize session
37
+ if "session_initialized" not in st.session_state or st.session_state.age_group != selected_age_group:
38
+ st.session_state.age_group = selected_age_group
39
+ st.session_state.category = None
40
+ st.session_state.question_index = 0
41
+ st.session_state.show_answer = False
42
+ st.session_state.show_steps = False
43
+ st.session_state.session_initialized = True
44
+
45
+ # Load dataset
46
+ group_info = age_groups[selected_age_group]
47
+ dataset_path = group_info["dataset"]
48
+ zip_path = group_info["zip_file"]
49
+ image_folder = group_info["image_folder"]
50
+
51
+ os.makedirs(image_folder, exist_ok=True)
52
+ if not any(f.lower().endswith(('.png', '.jpg', '.jpeg')) for f in os.listdir(image_folder)):
53
+ if os.path.exists(zip_path):
54
+ with zipfile.ZipFile(zip_path, "r") as zip_ref:
55
+ zip_ref.extractall(image_folder)
56
+
57
+ if not os.path.exists(dataset_path):
58
+ st.error(f"Dataset not found: {dataset_path}")
59
+ st.stop()
60
+
61
+ df = pd.read_excel(dataset_path)
62
+ df['category'] = df['category'].astype(str).str.strip()
63
+
64
+ # Category selection
65
+ categories = sorted(df['category'].dropna().unique())
66
+ selected_category = st.selectbox("📚 Choose a Math Category:", options=categories)
67
+
68
+ # Update session if category changes
69
+ if st.session_state.category != selected_category:
70
+ st.session_state.category = selected_category
71
+ st.session_state.question_index = 0
72
+ st.session_state.show_answer = False
73
+ st.session_state.show_steps = False
74
+ st.rerun()
75
+
76
+ # Filter questions by selected category only
77
+ subset_df = df[df['category'] == selected_category].reset_index(drop=True)
78
+
79
+ if not subset_df.empty and st.session_state.question_index < len(subset_df):
80
+ question = subset_df.iloc[st.session_state.question_index]
81
+ progress = int((st.session_state.question_index / len(subset_df)) * 100)
82
+ st.progress(progress)
83
+
84
+ st.markdown(f"<div class='question-box'>📘 <b>Question {st.session_state.question_index + 1}:</b><br><br>{question['problem']}</div>", unsafe_allow_html=True)
85
+
86
+ # Display image
87
+ if pd.notna(question.get('image')):
88
+ image_name = str(question['image']).strip()
89
+ for root, _, files in os.walk(image_folder):
90
+ for file in files:
91
+ if file.lower().startswith(image_name.lower()) or os.path.splitext(file)[0].lower() == image_name.lower():
92
+ try:
93
+ st.image(Image.open(os.path.join(root, file)), use_column_width=True)
94
+ except:
95
+ st.warning("❌ Image couldn't be loaded.")
96
+ break
97
+
98
+ user_ans = st.text_input("📝 Your Answer:", key=f"ans_{st.session_state.question_index}")
99
+
100
+ if st.button("✅ Submit Answer"):
101
+ if str(user_ans).strip().lower() == str(question['answer']).strip().lower():
102
+ st.success("🎉 Correct! Well done!")
103
+ st.balloons()
104
+ time.sleep(2)
105
+ st.session_state.question_index += 1
106
+ st.session_state.show_answer = False
107
+ st.session_state.show_steps = False
108
+ st.rerun()
109
+ else:
110
+ st.error("❌ Try again or view the correct answer below.")
111
+ st.session_state.show_answer = True
112
+ st.session_state.show_steps = False
113
+
114
+ if st.session_state.show_answer:
115
+ st.info(f"✅ Correct Answer: **{question['answer']}**")
116
+ if selected_age_group in ["7-9 Age Group", "13-15 Age Group"]:
117
+ if st.button("🔍 Show Steps"):
118
+ st.session_state.show_steps = True
119
+ if st.session_state.show_steps and pd.notna(question.get("steps", None)):
120
+ st.success(f"### 🪄 Steps:\n{question['steps']}")
121
+
122
+ if st.button("⏭️ Skip"):
123
+ st.session_state.question_index += 1
124
+ st.session_state.show_answer = False
125
+ st.session_state.show_steps = False
126
+ st.rerun()
127
+ elif subset_df.empty:
128
+ st.warning("⚠️ No questions available in this category. Try another one.")
129
+ else:
130
+ st.success("🏁 You've completed all questions in this category!")
131
+
132
+ # -------------------------------------------------------------
133
+ # ✅ Enhanced "Ask Any Math Question" Section Using MiniLM Model
134
+ # -------------------------------------------------------------
135
+
136
+ @st.cache_resource
137
+ def load_model():
138
+ return SentenceTransformer("all-MiniLM-L6-v2")
139
+
140
+ model = load_model()
141
+
142
+ qa_pairs = {
143
+ "what is the area of a triangle": "Area = (1/2) × base × height",
144
+ "what is the area of a square": "Area = side²",
145
+ "what is the area of a circle": "Area = π × radius²",
146
+ "perimeter of square": "Perimeter = 4 × side",
147
+ "perimeter of rectangle": "Perimeter = 2 × (length + width)",
148
+ "volume of cube": "Volume = side³",
149
+ "volume of sphere": "Volume = (4/3) × π × radius³",
150
+ "what is pi": "π ≈ 3.14159",
151
+ "how to calculate speed": "Speed = Distance ÷ Time",
152
+ "what is the derivative of x squared": "The derivative of x² is 2x."
153
+ }
154
+
155
+ qa_questions = list(qa_pairs.keys())
156
+ qa_embeddings = model.encode(qa_questions)
157
+
158
+ st.markdown("## 💡 Ask Any Math Question")
159
+ question_input = st.text_input("Ask a question like 'What is the area of a circle?' or 'Derivative of x^2'")
160
+
161
+ if question_input:
162
+ user_embedding = model.encode([question_input])
163
+ scores = cosine_similarity(user_embedding, qa_embeddings)[0]
164
+ best_idx = scores.argmax()
165
+ best_score = scores[best_idx]
166
+
167
+ if best_score > 0.6:
168
+ st.success(f"🤖 Answer:\n\n**{qa_pairs[qa_questions[best_idx]]}**")
169
+ else:
170
+ try:
171
+ if "derivative" in question_input.lower():
172
+ expr = question_input.lower().split("of")[-1].strip()
173
+ var = sp.symbols('x')
174
+ derivative = sp.diff(sp.sympify(expr.replace("^", "**")), var)
175
+ st.success(f"🧮 Derivative of {expr} is:\n\n**{derivative}**")
176
+ else:
177
+ result = sp.sympify(question_input.replace("^", "**"))
178
+ simplified = sp.simplify(result)
179
+ st.success(f"✅ Answer: {simplified}")
180
+ except Exception as e:
181
+ st.warning(f"⚠️ Couldn't understand the question. Error: {e}")