saad-sust commited on
Commit
84f42b2
ยท
verified ยท
1 Parent(s): b14e24b

Upload app2.py

Browse files
Files changed (1) hide show
  1. app2.py +511 -0
app2.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # โ”€โ”€ Imports โ”€โ”€ (ORDER MATTERS: re must come after sympy wildcard)
2
+ import streamlit as st
3
+ import sympy as sp
4
+ import anthropic
5
+ from sympy import (
6
+ symbols, diff, integrate, limit, solve, simplify, expand, factor,
7
+ latex, sympify, oo, sin, cos, tan, exp, log, sqrt, pi, E,
8
+ Matrix, Symbol, Function, dsolve, Eq,
9
+ series, Sum, Product, Rational, Integer, Float, Abs
10
+ )
11
+ from sympy.parsing.sympy_parser import (
12
+ parse_expr,
13
+ standard_transformations,
14
+ implicit_multiplication_application
15
+ )
16
+ import re # MUST be last โ€” sympy wildcard would overwrite it otherwise
17
+
18
+ # โ”€โ”€โ”€ Page Config โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
19
+ st.set_page_config(
20
+ page_title="SAAD AI ACADEMY",
21
+ page_icon="๐Ÿ“",
22
+ layout="wide",
23
+ initial_sidebar_state="expanded"
24
+ )
25
+
26
+ # โ”€โ”€โ”€ CSS Styling โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
27
+ st.markdown("""
28
+ <style>
29
+ @import url('https://fonts.googleapis.com/css2?family=Rajdhani:wght@400;600;700&family=JetBrains+Mono:wght@400;500&family=Nunito:wght@300;400;600&display=swap');
30
+
31
+ :root {
32
+ --bg: #060b14;
33
+ --surface: #0d1526;
34
+ --card: #111d35;
35
+ --border: #1e3058;
36
+ --accent: #38bdf8;
37
+ --accent2: #818cf8;
38
+ --gold: #f59e0b;
39
+ --green: #34d399;
40
+ --text: #e2e8f0;
41
+ --muted: #64748b;
42
+ }
43
+
44
+ html, body, [class*="css"] {
45
+ background-color: var(--bg);
46
+ color: var(--text);
47
+ font-family: 'Nunito', sans-serif;
48
+ }
49
+
50
+ #MainMenu, footer, header { visibility: hidden; }
51
+ .block-container { padding: 1.5rem 2rem 2rem 2rem; max-width: 1100px; }
52
+
53
+ .hero {
54
+ background: linear-gradient(135deg, #0d1526 0%, #0f1f40 50%, #091428 100%);
55
+ border: 1px solid var(--border);
56
+ border-radius: 16px;
57
+ padding: 2rem 2.5rem;
58
+ margin-bottom: 1.5rem;
59
+ position: relative;
60
+ overflow: hidden;
61
+ }
62
+ .hero::before {
63
+ content: "";
64
+ position: absolute;
65
+ top: -60px; right: -60px;
66
+ width: 220px; height: 220px;
67
+ background: radial-gradient(circle, rgba(56,189,248,0.12) 0%, transparent 70%);
68
+ border-radius: 50%;
69
+ }
70
+ .hero-title {
71
+ font-family: 'Rajdhani', sans-serif;
72
+ font-size: 2.4rem;
73
+ font-weight: 700;
74
+ background: linear-gradient(90deg, var(--accent), var(--accent2));
75
+ -webkit-background-clip: text;
76
+ -webkit-text-fill-color: transparent;
77
+ margin: 0 0 0.3rem 0;
78
+ letter-spacing: 2px;
79
+ }
80
+ .hero-sub {
81
+ color: var(--muted);
82
+ font-size: 0.95rem;
83
+ letter-spacing: 1px;
84
+ text-transform: uppercase;
85
+ }
86
+ .badge-row { display: flex; gap: 0.5rem; flex-wrap: wrap; margin-top: 1rem; }
87
+ .badge {
88
+ background: rgba(56,189,248,0.08);
89
+ border: 1px solid rgba(56,189,248,0.25);
90
+ color: var(--accent);
91
+ padding: 3px 10px;
92
+ border-radius: 20px;
93
+ font-size: 0.72rem;
94
+ font-family: 'JetBrains Mono', monospace;
95
+ letter-spacing: 0.5px;
96
+ }
97
+
98
+ .chat-area {
99
+ background: var(--surface);
100
+ border: 1px solid var(--border);
101
+ border-radius: 14px;
102
+ padding: 1.2rem 1.5rem;
103
+ min-height: 420px;
104
+ max-height: 560px;
105
+ overflow-y: auto;
106
+ margin-bottom: 1rem;
107
+ }
108
+
109
+ .msg-user {
110
+ display: flex;
111
+ justify-content: flex-end;
112
+ margin: 0.8rem 0;
113
+ }
114
+ .msg-user .bubble {
115
+ background: linear-gradient(135deg, #1e3a5f, #1a2f50);
116
+ border: 1px solid rgba(56,189,248,0.3);
117
+ color: var(--text);
118
+ padding: 0.75rem 1.1rem;
119
+ border-radius: 14px 4px 14px 14px;
120
+ max-width: 75%;
121
+ font-size: 0.92rem;
122
+ line-height: 1.6;
123
+ }
124
+ .msg-ai {
125
+ display: flex;
126
+ justify-content: flex-start;
127
+ margin: 0.8rem 0;
128
+ gap: 0.6rem;
129
+ align-items: flex-start;
130
+ }
131
+ .ai-avatar {
132
+ width: 34px; height: 34px;
133
+ background: linear-gradient(135deg, var(--accent), var(--accent2));
134
+ border-radius: 50%;
135
+ display: flex; align-items: center; justify-content: center;
136
+ font-size: 0.9rem;
137
+ flex-shrink: 0;
138
+ color: #fff;
139
+ }
140
+ .msg-ai .bubble {
141
+ background: var(--card);
142
+ border: 1px solid var(--border);
143
+ color: var(--text);
144
+ padding: 0.85rem 1.2rem;
145
+ border-radius: 4px 14px 14px 14px;
146
+ max-width: 82%;
147
+ font-size: 0.92rem;
148
+ line-height: 1.7;
149
+ }
150
+
151
+ .stTextInput > div > div > input {
152
+ background: var(--card) !important;
153
+ border: 1px solid var(--border) !important;
154
+ border-radius: 10px !important;
155
+ color: var(--text) !important;
156
+ font-family: 'Nunito', sans-serif !important;
157
+ font-size: 0.95rem !important;
158
+ padding: 0.75rem 1rem !important;
159
+ }
160
+ .stTextInput > div > div > input:focus {
161
+ border-color: var(--accent) !important;
162
+ box-shadow: 0 0 0 2px rgba(56,189,248,0.15) !important;
163
+ }
164
+
165
+ .stButton > button {
166
+ background: linear-gradient(135deg, #1e4080, #1a3060) !important;
167
+ border: 1px solid var(--accent) !important;
168
+ color: var(--accent) !important;
169
+ border-radius: 10px !important;
170
+ font-family: 'Rajdhani', sans-serif !important;
171
+ font-weight: 600 !important;
172
+ letter-spacing: 1px !important;
173
+ padding: 0.5rem 1.5rem !important;
174
+ transition: all 0.2s !important;
175
+ }
176
+ .stButton > button:hover {
177
+ background: linear-gradient(135deg, #2a50a0, #2040a0) !important;
178
+ transform: translateY(-1px) !important;
179
+ box-shadow: 0 4px 15px rgba(56,189,248,0.2) !important;
180
+ }
181
+
182
+ [data-testid="stSidebar"] {
183
+ background: var(--surface) !important;
184
+ border-right: 1px solid var(--border) !important;
185
+ }
186
+ [data-testid="stSidebar"] .stMarkdown h3 {
187
+ font-family: 'Rajdhani', sans-serif;
188
+ color: var(--accent);
189
+ letter-spacing: 1px;
190
+ }
191
+
192
+ .topic-pill {
193
+ background: rgba(129,140,248,0.08);
194
+ border: 1px solid rgba(129,140,248,0.2);
195
+ color: var(--accent2);
196
+ padding: 4px 12px;
197
+ border-radius: 20px;
198
+ font-size: 0.78rem;
199
+ margin: 3px 2px;
200
+ display: inline-block;
201
+ font-family: 'JetBrains Mono', monospace;
202
+ }
203
+
204
+ ::-webkit-scrollbar { width: 6px; }
205
+ ::-webkit-scrollbar-track { background: var(--surface); }
206
+ ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
207
+ ::-webkit-scrollbar-thumb:hover { background: var(--muted); }
208
+
209
+ .stSelectbox > div > div {
210
+ background: var(--card) !important;
211
+ border-color: var(--border) !important;
212
+ color: var(--text) !important;
213
+ border-radius: 10px !important;
214
+ }
215
+ </style>
216
+ """, unsafe_allow_html=True)
217
+
218
+ # โ”€โ”€โ”€ Session State โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
219
+ if "messages" not in st.session_state:
220
+ st.session_state.messages = []
221
+ if "last_submitted" not in st.session_state:
222
+ st.session_state.last_submitted = "" # prevents infinite rerun loop
223
+
224
+ # โ”€โ”€โ”€ SymPy Engine โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
225
+ def run_sympy(problem: str) -> dict:
226
+ """
227
+ Safely attempt symbolic computation.
228
+ Uses sp.* explicitly โ€” no wildcard collisions possible here.
229
+ """
230
+ p = problem.lower().strip()
231
+ x = sp.Symbol('x')
232
+ default = {"type": "general", "result": None, "latex": ""}
233
+
234
+ try:
235
+ tfms = standard_transformations + (implicit_multiplication_application,)
236
+
237
+ def clean(s):
238
+ """Normalise expression string for sympy parsing."""
239
+ s = re.sub(r"\s+", "", s)
240
+ s = re.sub(r"\^", "**", s)
241
+ return s
242
+
243
+ # โ”€โ”€ Derivative โ”€โ”€
244
+ if any(k in p for k in ["derivative", "differentiate", "d/dx", "diff"]):
245
+ raw = p
246
+ for kw in ["derivative of", "differentiate", "diff of", "d/dx of", "d/dx"]:
247
+ if kw in p:
248
+ raw = p.split(kw, 1)[-1].strip()
249
+ break
250
+ raw = re.sub(r"\s*(dx|with\s*respect\s*to\s*x).*$", "", raw).strip()
251
+ expr = parse_expr(clean(raw), transformations=tfms, local_dict={"x": x, "e": sp.E, "E": sp.E, "pi": sp.pi, "ln": sp.log, "inf": sp.oo})
252
+ result = sp.diff(expr, x)
253
+ return {"type": "Derivative", "result": str(result), "latex": sp.latex(result)}
254
+
255
+ # โ”€โ”€ Integral โ”€โ”€
256
+ elif any(k in p for k in ["integral", "integrate", "antiderivative"]):
257
+ raw = p
258
+ for kw in ["integral of", "integrate", "antiderivative of"]:
259
+ if kw in p:
260
+ raw = p.split(kw, 1)[-1].strip()
261
+ break
262
+ raw = re.sub(r"\s*dx.*$", "", raw).strip()
263
+ expr = parse_expr(clean(raw), transformations=tfms, local_dict={"x": x, "e": sp.E, "E": sp.E, "pi": sp.pi, "ln": sp.log, "inf": sp.oo})
264
+ result = sp.integrate(expr, x)
265
+ return {"type": "Integral", "result": str(result), "latex": sp.latex(result)}
266
+
267
+ # โ”€โ”€ Limit โ”€โ”€
268
+ elif "limit" in p:
269
+ match = re.search(
270
+ r"limit\s+of\s+([\w\s\(\)\+\-\*/\^\.\,]+?)\s+as\s+x\s*(?:->|โ†’|approaches)\s*([\w\.\+\-]+)",
271
+ p
272
+ )
273
+ if match:
274
+ raw_expr = clean(match.group(1))
275
+ point_str = match.group(2).strip()
276
+ point = sp.oo if point_str in ("inf", "infinity", "oo") else sp.sympify(point_str)
277
+ expr = parse_expr(raw_expr, transformations=tfms, local_dict={"x": x, "e": sp.E, "E": sp.E, "pi": sp.pi, "ln": sp.log, "inf": sp.oo})
278
+ result = sp.limit(expr, x, point)
279
+ return {"type": "Limit", "result": str(result), "latex": sp.latex(result)}
280
+
281
+ # โ”€โ”€ Solve equation โ”€โ”€
282
+ elif any(k in p for k in ["solve", "roots", "find x"]):
283
+ raw = re.sub(r"(solve|find x|roots of|roots|the equation)", "", p).strip().strip(": ")
284
+ if "=" in raw:
285
+ lhs_s, rhs_s = raw.split("=", 1)
286
+ lhs_e = parse_expr(clean(lhs_s), transformations=tfms, local_dict={"x": x, "e": sp.E, "E": sp.E, "pi": sp.pi, "ln": sp.log, "inf": sp.oo})
287
+ rhs_e = parse_expr(clean(rhs_s), transformations=tfms, local_dict={"x": x, "e": sp.E, "E": sp.E, "pi": sp.pi, "ln": sp.log, "inf": sp.oo})
288
+ expr = lhs_e - rhs_e
289
+ else:
290
+ expr = parse_expr(clean(raw), transformations=tfms, local_dict={"x": x, "e": sp.E, "E": sp.E, "pi": sp.pi, "ln": sp.log, "inf": sp.oo})
291
+ if x in expr.free_symbols:
292
+ sol = sp.solve(expr, x)
293
+ sol_latex = ", ".join([sp.latex(s) for s in sol])
294
+ return {"type": "Equation", "result": str(sol), "latex": f"x \\in \\{{{sol_latex}\\}}"}
295
+
296
+ # โ”€โ”€ Matrix / eigenvalues โ€” delegate to Claude โ”€โ”€
297
+ elif any(k in p for k in ["matrix", "determinant", "eigenvalue", "eigenvector", "det("]):
298
+ return {"type": "Matrix", "result": "matrix_detected", "latex": ""}
299
+
300
+ # โ”€โ”€ Modular arithmetic โ€” delegate to Claude โ”€โ”€
301
+ elif "mod" in p or "congruence" in p:
302
+ return {"type": "NumberTheory", "result": "mod_detected", "latex": ""}
303
+
304
+ except Exception:
305
+ pass # fall back gracefully; Claude handles it without sympy hint
306
+
307
+ return default
308
+
309
+
310
+ # โ”€โ”€โ”€ Claude API Call โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
311
+ def ask_claude(problem: str, sympy_info: dict, history: list) -> str:
312
+ sympy_context = ""
313
+ if (sympy_info.get("result")
314
+ and sympy_info["result"] not in (None, "matrix_detected", "mod_detected")):
315
+ sympy_context = f"""
316
+ SYMPY VERIFIED RESULT (mathematically exact โ€” your final answer MUST match this):
317
+ - Operation : {sympy_info.get('type', 'N/A')}
318
+ - Result : {sympy_info.get('result', 'N/A')}
319
+ - LaTeX : {sympy_info.get('latex', 'N/A')}
320
+ """
321
+
322
+ system_prompt = f"""You are SAAD AI โ€” an elite BSc Mathematics tutor.
323
+ {sympy_context}
324
+ RULES:
325
+ 1. Label every step: "Step 1:", "Step 2:", etc. โ€” no steps skipped.
326
+ 2. Use $...$ for inline math and $$...$$ for display equations.
327
+ 3. State the method/theorem at the start.
328
+ 4. Show ALL intermediate algebra.
329
+ 5. End with: **Final Answer:** $$...$$
330
+ 6. If a SymPy verified result is shown above, your final answer MUST match it exactly.
331
+ 7. NEVER make arithmetic errors.
332
+
333
+ TOPICS: Calculus | Linear Algebra | Number Theory | ODEs | Numerical Methods |
334
+ Differential Geometry | Hydro Mechanics | Theory of Numbers | Real Analysis II | General Math
335
+ """
336
+
337
+ messages = []
338
+ for msg in history[-8:]:
339
+ messages.append({"role": msg["role"], "content": msg["content"]})
340
+ messages.append({"role": "user", "content": problem})
341
+
342
+ client = anthropic.Anthropic()
343
+ response = client.messages.create(
344
+ model="claude-sonnet-4-5",
345
+ max_tokens=3000,
346
+ system=system_prompt,
347
+ messages=messages
348
+ )
349
+ return response.content[0].text
350
+
351
+
352
+ # โ”€โ”€โ”€ Sidebar โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
353
+ with st.sidebar:
354
+ st.markdown("### ๐Ÿ“š SAAD AI ACADEMY")
355
+ st.markdown("---")
356
+
357
+ st.markdown("**๐ŸŽฏ Topics Covered**")
358
+ topics = [
359
+ "Calculus", "Linear Algebra", "Number Theory",
360
+ "Differential Equations", "Numerical Methods",
361
+ "Differential Geometry", "Hydro Mechanics",
362
+ "Theory of Numbers", "Real Analysis II", "General Math"
363
+ ]
364
+ pills_html = "".join([f'<span class="topic-pill">{t}</span>' for t in topics])
365
+ st.markdown(pills_html, unsafe_allow_html=True)
366
+
367
+ st.markdown("---")
368
+ st.markdown("**โšก Quick Examples**")
369
+
370
+ examples = {
371
+ "-- Choose --": "",
372
+ "๐Ÿ”ข Derivative": "Find the derivative of x^3 + 5x^2 - 3x + 7",
373
+ "โˆซ Integral": "Integrate sin(x) * e^x dx",
374
+ "๐Ÿ“Š Eigenvalue": "Find eigenvalues of matrix [[3,1],[1,3]]",
375
+ "๐Ÿ” Congruence": "Solve 14x โ‰ก 30 (mod 44)",
376
+ "๐ŸŒŠ ODE": "Solve dy/dx + 2y = e^x",
377
+ "๐Ÿ“ Limit": "Find limit of sin(x)/x as x -> 0",
378
+ "๐Ÿ” Series": "Test convergence of sum 1/n^2 from n=1 to infinity",
379
+ "๐Ÿ“ Newton-Raphson": "Apply Newton-Raphson to find root of x^3 - 2x - 5 = 0",
380
+ }
381
+
382
+ selected_example = st.selectbox(
383
+ "Load an example:",
384
+ list(examples.keys()),
385
+ key="example_select"
386
+ )
387
+
388
+ st.markdown("---")
389
+ st.markdown("**๐Ÿ”ง Engine**")
390
+ st.markdown("""
391
+ <div style="font-size:0.8rem; color:#64748b; line-height:1.8;">
392
+ ๐Ÿค– <b style="color:#38bdf8">Claude AI</b> โ€” reasoning & steps<br>
393
+ ๐Ÿงฎ <b style="color:#34d399">SymPy</b> โ€” verified computation<br>
394
+ โœ… Zero arithmetic errors
395
+ </div>
396
+ """, unsafe_allow_html=True)
397
+
398
+ st.markdown("---")
399
+ if st.button("๐Ÿ—‘๏ธ Clear Chat"):
400
+ st.session_state.messages = []
401
+ st.session_state.last_submitted = ""
402
+ st.rerun()
403
+
404
+
405
+ # โ”€โ”€โ”€ Hero Banner โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
406
+ st.markdown("""
407
+ <div class="hero">
408
+ <div class="hero-title">๐Ÿ“ SAAD AI ACADEMY</div>
409
+ <div class="hero-sub">BSc Mathematics โ€” Computational Engine</div>
410
+ <div class="badge-row">
411
+ <span class="badge">Claude AI</span>
412
+ <span class="badge">SymPy Verified</span>
413
+ <span class="badge">Step-by-Step</span>
414
+ <span class="badge">Zero Errors</span>
415
+ <span class="badge">LaTeX Output</span>
416
+ </div>
417
+ </div>
418
+ """, unsafe_allow_html=True)
419
+
420
+
421
+ # โ”€โ”€โ”€ Chat Display โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
422
+ chat_html = '<div class="chat-area" id="chatArea">'
423
+
424
+ if not st.session_state.messages:
425
+ chat_html += """
426
+ <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;
427
+ height:300px;color:#334155;text-align:center;">
428
+ <div style="font-size:3rem;margin-bottom:1rem;">๐Ÿ“</div>
429
+ <div style="font-family:'Rajdhani',sans-serif;font-size:1.2rem;color:#475569;letter-spacing:1px;">
430
+ Ask any BSc Mathematics problem
431
+ </div>
432
+ <div style="font-size:0.82rem;color:#334155;margin-top:0.5rem;">
433
+ Calculus ยท Linear Algebra ยท Number Theory ยท ODEs ยท Real Analysis ยท and more
434
+ </div>
435
+ </div>
436
+ """
437
+ else:
438
+ for msg in st.session_state.messages:
439
+ if msg["role"] == "user":
440
+ # Escape HTML to prevent rendering issues with math symbols
441
+ safe = (msg['content']
442
+ .replace("&", "&amp;")
443
+ .replace("<", "&lt;")
444
+ .replace(">", "&gt;"))
445
+ chat_html += f'<div class="msg-user"><div class="bubble">๐Ÿง‘โ€๐ŸŽ“ {safe}</div></div>'
446
+ else:
447
+ content = msg['content']
448
+ # Escape first, then apply safe bold conversion
449
+ content = (content
450
+ .replace("&", "&amp;")
451
+ .replace("<", "&lt;")
452
+ .replace(">", "&gt;"))
453
+ content = re.sub(r'\*\*(.*?)\*\*', r'<b>\1</b>', content)
454
+ content = content.replace('\n', '<br>')
455
+ chat_html += (
456
+ f'<div class="msg-ai">'
457
+ f'<div class="ai-avatar">โˆ‘</div>'
458
+ f'<div class="bubble">{content}</div>'
459
+ f'</div>'
460
+ )
461
+
462
+ chat_html += '</div>'
463
+ st.markdown(chat_html, unsafe_allow_html=True)
464
+
465
+ st.markdown("""
466
+ <script>
467
+ const c = document.getElementById('chatArea');
468
+ if (c) c.scrollTop = c.scrollHeight;
469
+ </script>
470
+ """, unsafe_allow_html=True)
471
+
472
+
473
+ # โ”€โ”€โ”€ Input Row โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
474
+ col1, col2 = st.columns([5, 1])
475
+
476
+ with col1:
477
+ prefill = examples.get(selected_example, "") if selected_example != "-- Choose --" else ""
478
+ user_input = st.text_input(
479
+ label="problem_input",
480
+ value=prefill,
481
+ placeholder="Type a BSc math problem... e.g. 'Solve dยฒy/dxยฒ + 4y = cos(2x)'",
482
+ label_visibility="collapsed",
483
+ key="user_input_field"
484
+ )
485
+
486
+ with col2:
487
+ send_btn = st.button("SOLVE โ†’", use_container_width=True)
488
+
489
+
490
+ # โ”€โ”€โ”€ Process Input โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
491
+ # Only fires when SOLVE is clicked, input is non-empty, AND it's a new problem
492
+ # This prevents the infinite rerun loop caused by value="" pre-fill on every cycle
493
+ problem = user_input.strip() if user_input else ""
494
+
495
+ if send_btn and problem and problem != st.session_state.last_submitted:
496
+ st.session_state.last_submitted = problem
497
+
498
+ with st.spinner("๐Ÿงฎ Running SymPy verification + Claude reasoning..."):
499
+ sympy_result = run_sympy(problem)
500
+ try:
501
+ answer = ask_claude(problem, sympy_result, st.session_state.messages)
502
+ except Exception as e:
503
+ answer = (
504
+ f"โš ๏ธ **API Error:** {str(e)}\n\n"
505
+ "Please ensure **ANTHROPIC_API_KEY** is added in your Hugging Face Space โ†’ "
506
+ "Settings โ†’ Variables and Secrets."
507
+ )
508
+
509
+ st.session_state.messages.append({"role": "user", "content": problem})
510
+ st.session_state.messages.append({"role": "assistant", "content": answer})
511
+ st.rerun()