saad-sust commited on
Commit
784ecc3
·
verified ·
1 Parent(s): a71cc51

Upload 8 files

Browse files

Deploy portfolio refactor and preserve verified answers when AI providers fail

Files changed (8) hide show
  1. .env.example +14 -0
  2. .gitignore +10 -0
  3. README.md +104 -55
  4. ai.py +791 -0
  5. app.py +0 -0
  6. config.py +63 -0
  7. requirements.txt +15 -7
  8. sympy_engine.py +1230 -0
.env.example ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI provider credentials. At least one text provider key is needed for explanations.
2
+ GROQ_API_KEY_1=
3
+ GROQ_API_KEY_2=
4
+ GROQ_API_KEY_3=
5
+ GEMINI_API_KEY_1=
6
+ GEMINI_API_KEY_2=
7
+ GEMINI_API_KEY_3=
8
+ GEMINI_API_KEY_4=
9
+ OPENROUTER_API_KEY=
10
+
11
+ # Operational limits. Values are clamped by src/config.py.
12
+ PROVIDER_TIMEOUT_SECONDS=60
13
+ MAX_UPLOAD_BYTES=5242880
14
+ MAX_PDF_PAGES=6
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ .env
6
+ .env.*
7
+ !.env.example
8
+ .streamlit/secrets.toml
9
+ .pytest_cache/
10
+ .DS_Store
README.md CHANGED
@@ -1,55 +1,104 @@
1
- ---
2
- title: Saad.AI
3
- emoji: 🧠
4
- colorFrom: blue
5
- colorTo: indigo
6
- sdk: streamlit
7
- sdk_version: 1.32.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- # 🧠 Saad.AI BSc Mathematics Engine
14
-
15
- A powerful AI math solver combining **Groq Llama 3.3 70B** (step-by-step reasoning) with **SymPy** (verified symbolic computation) — designed for BSc-level mathematics.
16
-
17
- ## Features
18
- - **Zero arithmetic errors** SymPy verifies every calculation
19
- - 📝 **Step-by-step solutions** every step shown clearly
20
- - 📐 **LaTeX math rendering** beautiful equations
21
- - 🧠 **Groq Llama 3.3 70B** understands complex problems in plain English
22
-
23
- ## 📚 Topics Covered
24
- | Subject | Examples |
25
- |---|---|
26
- | Calculus | Derivatives, Integrals, Limits, Series |
27
- | Linear Algebra | Matrices, Eigenvalues, Vector Spaces |
28
- | Number Theory | Congruences, Primes, Euler's Theorem |
29
- | Differential Equations | ODEs, PDEs, Laplace Transforms |
30
- | Numerical Methods | Newton-Raphson, Euler's Method |
31
- | Differential Geometry | Curves, Curvature, Surfaces |
32
- | Hydro Mechanics | Fluid Dynamics, Bernoulli, Continuity |
33
- | Theory of Numbers | GCD, LCM, Fermat's Little Theorem |
34
- | Real Analysis II | Convergence, Continuity, Riemann Integral |
35
-
36
- ## 🚀 Setup on Hugging Face
37
- 1. Create a new **Space** on [huggingface.co/spaces](https://huggingface.co/spaces)
38
- 2. Choose **Streamlit** as the SDK
39
- 3. Upload all 3 files: `app.py`, `requirements.txt`, `README.md`
40
- 4. Go to **Settings → Variables and Secrets**
41
- 5. Add secret: `GROQ_API_KEY` = your key from [console.groq.com](https://console.groq.com)
42
- 6. The app will automatically build and run!
43
-
44
- ## 💡 Example Problems to Try
45
- - `Find the derivative of x^3 * sin(x)`
46
- - `Integrate e^x * cos(x) dx`
47
- - `Solve 14x ≡ 30 (mod 44)`
48
- - `Find eigenvalues of matrix [[4,1],[2,3]]`
49
- - `Solve the ODE dy/dx + 2y = e^(-x)`
50
- - `Find limit of (1 + 1/n)^n as n → ∞`
51
- - `Apply Newton-Raphson to x^3 - 2x - 5 = 0`
52
-
53
- ## 👨‍💻 Built By
54
- Created by **Saad** — a passionate developer who built this from scratch
55
- to help BSc Mathematics students solve problems with 100% accuracy.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Saad.AI — B.Sc. Mathematics Engine
2
+
3
+ Saad.AI is an academic mathematics assistant for university students. It combines a deterministic **SymPy computation engine** with configurable AI providers for explanations, proofs, theory questions, graph descriptions, and image/PDF-based problem solving. See [PORTFOLIO.md](PORTFOLIO.md) for the project story and demo flow.
4
+
5
+ > **Important:** SymPy verification applies only when a request matches one of the implemented deterministic adapters. General proofs, theory questions, unsupported matrix formats, and unsupported subjects are treated as AI-generated unless a deterministic adapter returns a verified result.
6
+
7
+ ## Current capabilities
8
+
9
+ | Area | Examples | Verification mode |
10
+ |---|---|---|
11
+ | Calculus | Derivatives, integrals, limits | SymPy when parsed successfully |
12
+ | Equations | Polynomial equations and roots | SymPy when parsed successfully |
13
+ | Differential equations | Selected first- and second-order ODE forms | SymPy for supported forms |
14
+ | Numerical methods | Newton–Raphson, bisection, secant, Simpson, trapezoidal, Euler, RK4 | Deterministic numeric adapter |
15
+ | Number theory | GCD, LCM, factorization, totient, congruences, CRT, selected theorems, modulo | SymPy / deterministic adapter |
16
+ | Linear algebra | Determinants, eigenvalues/eigenvectors, inverses, ranks, transposes | Deterministic SymPy adapter |
17
+ | Real analysis | Selected sequence, series, Taylor, and integral computations | SymPy for supported computations; AI for theory/proofs |
18
+ | Differential geometry | Curvature, arc length, Frenet–Serret, fundamental forms | SymPy for supported parametric forms |
19
+ | Hydro mechanics | Continuity, Bernoulli, Reynolds, flow rate, pressure, Torricelli | Deterministic formula adapter for supported prompts |
20
+ | Graphing | Explicit requests to plot or graph a function | Matplotlib rendering |
21
+ | Attachments | JPG, PNG, WEBP, and PDF questions | Vision provider; deterministic verification when extractable |
22
+
23
+ The engine is intentionally not presented as a universal proof checker. For questions that cannot be deterministically parsed, the application sends the prompt to the configured AI provider and labels the result as AI-generated where appropriate.
24
+
25
+ ## Architecture
26
+
27
+ The current stabilization refactor keeps Streamlit as the user interface while separating the main responsibilities:
28
+
29
+ ```text
30
+ math-engine/
31
+ ├── app.py # Streamlit UI, session flow, and graph rendering
32
+ ├── src/
33
+ │ ├── engine/
34
+ │ │ └── sympy_engine.py # Deterministic symbolic and numeric adapters
35
+ │ └── services/
36
+ │ └── ai.py # Provider rotation, vision, uploads, verification
37
+ ├── tests/
38
+ │ └── test_engine.py # Deterministic engine regression tests
39
+ ├── requirements.txt # Runtime dependencies actually used by the app
40
+ └── README.md
41
+ ```
42
+
43
+ The next recommended phase is to split the remaining UI, persistence, and plotting concerns into their own modules and add provider mocks and upload fixtures.
44
+
45
+ ## Run locally
46
+
47
+ ```bash
48
+ git clone https://github.com/almuyed-saad/math-engine.git
49
+ cd math-engine
50
+ python -m venv .venv
51
+ source .venv/bin/activate
52
+ pip install -r requirements.txt
53
+ streamlit run app.py
54
+ ```
55
+
56
+ Open `http://localhost:8501` in a browser.
57
+
58
+ Run the deterministic regression tests with:
59
+
60
+ ```bash
61
+ python -m unittest discover -s tests -v
62
+ ```
63
+
64
+ ## Configuration
65
+
66
+ AI providers are optional for deterministic SymPy requests but required for explanations and unsupported subjects. Configure provider credentials through environment variables or Hugging Face Space secrets:
67
+
68
+ ```text
69
+ GROQ_API_KEY_1
70
+ GROQ_API_KEY_2
71
+ GROQ_API_KEY_3
72
+ GEMINI_API_KEY_1
73
+ GEMINI_API_KEY_2
74
+ GEMINI_API_KEY_3
75
+ GEMINI_API_KEY_4
76
+ OPENROUTER_API_KEY
77
+ ```
78
+
79
+ Chat history is intentionally **session-local** in the portfolio edition. This keeps the application easy to understand and deploy while still allowing users to create, switch, and delete conversations during a demo session. A database is not required.
80
+
81
+ ## Example prompts
82
+
83
+ ```text
84
+ Find the derivative of x^3 + 5x^2 - 3x + 7
85
+ Integrate sin(x) * e^x dx
86
+ Find limit of sin(x)/x as x -> 0
87
+ Apply Newton-Raphson to x^3 - 2x - 5 = 0, x0=2, 3 iterations
88
+ Apply bisection of x^3 - x on [0, 2], 4 iterations
89
+ Find gcd of 84 and 30
90
+ Solve 14x ≡ 30 (mod 44) using Euclidean algorithm
91
+ Plot y = x^2 - 4 from -3 to 3
92
+ ```
93
+
94
+ ## Deployment notes
95
+
96
+ The active source uses hosted API providers rather than loading a local Hugging Face model at runtime. The dependency list therefore excludes the previously declared `transformers` and `torch` packages, which were not used by the current application and added unnecessary deployment weight.
97
+
98
+ Runtime configuration is centralized in `src/config.py`. Copy `.env.example` to `.env` for local development, or add the same variables as Hugging Face Space secrets. Provider timeouts, upload size, and PDF page limits are validated and clamped at startup so malformed deployment values cannot create unbounded resource usage.
99
+
100
+ For a portfolio deployment, add the provider secrets to Hugging Face Spaces or another Streamlit host, then launch the app with `streamlit run app.py`. No database or authentication setup is required. Every push and pull request runs the deterministic test suite and Python compilation checks through [`.github/workflows/ci.yml`](.github/workflows/ci.yml).
101
+
102
+ ## Credits
103
+
104
+ The project was created by Saad for B.Sc. Mathematics students at Shahjalal University of Science and Technology. It uses [Streamlit](https://streamlit.io), [SymPy](https://www.sympy.org), [Matplotlib](https://matplotlib.org), and hosted AI provider APIs.
ai.py ADDED
@@ -0,0 +1,791 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AI provider integrations and file/vision processing for Saad.AI."""
2
+
3
+ import re
4
+ import time
5
+ import requests
6
+
7
+ from config import settings
8
+ from sympy_engine import run_sympy
9
+
10
+
11
+ def _post_with_retry(url: str, *, headers: dict, json: dict, timeout: float | None = None, attempts: int = 2):
12
+ """POST with a small bounded retry budget for transient provider failures."""
13
+ timeout = timeout or settings.provider_timeout_seconds
14
+ attempts = max(1, min(attempts, 3))
15
+
16
+ for attempt in range(attempts):
17
+ try:
18
+ response = requests.post(url, headers=headers, json=json, timeout=timeout)
19
+ except requests.exceptions.Timeout:
20
+ if attempt == attempts - 1:
21
+ raise
22
+ time.sleep(min(0.5 * (2**attempt), 2.0))
23
+ continue
24
+
25
+ retryable = response.status_code == 429 or response.status_code >= 500
26
+ if retryable and attempt < attempts - 1:
27
+ retry_after = response.headers.get("Retry-After", "")
28
+ try:
29
+ delay = min(max(float(retry_after), 0.0), 2.0)
30
+ except ValueError:
31
+ delay = min(0.5 * (2**attempt), 2.0)
32
+ time.sleep(delay)
33
+ continue
34
+ return response
35
+
36
+ raise RuntimeError("Provider request exhausted retry budget")
37
+
38
+ def _deterministic_fallback(sympy_info: dict, reason: str = "") -> str:
39
+ """Return a useful verified answer when external explanation APIs fail."""
40
+ result = sympy_info.get("result")
41
+ latex = sympy_info.get("latex") or ""
42
+ method = sympy_info.get("type") or "Deterministic computation"
43
+ if not result:
44
+ return ""
45
+
46
+ reason_line = ""
47
+ if reason:
48
+ reason_line = f"\n\n_AI explanation unavailable: {reason}. The computation above is still deterministic._"
49
+ latex_block = f"\n\n**Mathematical form:**\n\n$${latex}$$" if latex else ""
50
+ return (
51
+ "✅ **SymPy Verified**\n\n"
52
+ f"**Method:** {method}\n\n"
53
+ f"**Computed result:**\n\n`{result}`"
54
+ f"{latex_block}"
55
+ f"{reason_line}"
56
+ )
57
+
58
+
59
+ def ask_ai(problem: str, sympy_info: dict, history: list) -> str:
60
+
61
+ # ── Multi-provider auto-rotation ────────────────────────────────
62
+ # Try each provider in order — skip if key missing or 429
63
+ def try_groq(key, messages):
64
+ resp = _post_with_retry(
65
+ "https://api.groq.com/openai/v1/chat/completions",
66
+ headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
67
+ json={"model": "llama-3.3-70b-versatile", "messages": messages,
68
+ "max_tokens": 2048, "temperature": 0.15, "top_p": 0.9},
69
+ timeout=settings.provider_timeout_seconds
70
+ )
71
+ resp.raise_for_status()
72
+ return resp.json()["choices"][0]["message"]["content"]
73
+
74
+ def try_gemini(key, messages):
75
+ # Convert messages to Gemini format
76
+ system_msg = next((m["content"] for m in messages if m["role"]=="system"), "")
77
+ user_msgs = [m for m in messages if m["role"] != "system"]
78
+ contents = []
79
+ for m in user_msgs:
80
+ role = "user" if m["role"]=="user" else "model"
81
+ contents.append({"role": role, "parts": [{"text": m["content"]}]})
82
+ payload = {
83
+ "system_instruction": {"parts": [{"text": system_msg}]},
84
+ "contents": contents,
85
+ "generationConfig": {"maxOutputTokens": 2048, "temperature": 0.15}
86
+ }
87
+ # Try 2.0-flash first, fall back to 1.5-flash if model not available
88
+ for model in ["gemini-2.0-flash", "gemini-1.5-flash"]:
89
+ resp = _post_with_retry(
90
+ f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={key}",
91
+ headers={"Content-Type": "application/json"},
92
+ json=payload,
93
+ timeout=settings.provider_timeout_seconds
94
+ )
95
+ if resp.status_code == 404:
96
+ continue # model not found — try next model
97
+ if not resp.ok:
98
+ # Attach real error body to the exception so the caller can log it
99
+ try:
100
+ err_msg = resp.json().get("error", {}).get("message", resp.text[:100])
101
+ except Exception:
102
+ err_msg = resp.text[:100]
103
+ resp._content = f"{resp.status_code}: {err_msg}".encode()
104
+ resp.raise_for_status()
105
+ return resp.json()["candidates"][0]["content"]["parts"][0]["text"]
106
+ # Both models failed with 404
107
+ raise requests.exceptions.HTTPError("Both gemini-2.0-flash and gemini-1.5-flash returned 404")
108
+
109
+ def try_openrouter(key, messages):
110
+ resp = _post_with_retry(
111
+ "https://openrouter.ai/api/v1/chat/completions",
112
+ headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
113
+ json={"model": "deepseek/deepseek-r1:free",
114
+ "messages": messages, "max_tokens": 2048, "temperature": 0.15},
115
+ timeout=settings.provider_timeout_seconds
116
+ )
117
+ resp.raise_for_status()
118
+ return resp.json()["choices"][0]["message"]["content"]
119
+
120
+ # All providers in rotation order
121
+ providers = [
122
+ ("Groq-1", settings.groq_api_keys[0], try_groq),
123
+ ("Groq-2", settings.groq_api_keys[1], try_groq),
124
+ ("Groq-3", settings.groq_api_keys[2], try_groq),
125
+ ("Gemini-1", settings.gemini_api_keys[0], try_gemini),
126
+ ("Gemini-2", settings.gemini_api_keys[1], try_gemini),
127
+ ("Gemini-3", settings.gemini_api_keys[2], try_gemini),
128
+ ("Gemini-4", settings.gemini_api_keys[3], try_gemini),
129
+ ("OpenRouter", settings.openrouter_api_key, try_openrouter),
130
+ ]
131
+
132
+ # Check at least one key exists
133
+ if not any(key for _, key, _ in providers):
134
+ fallback = _deterministic_fallback(sympy_info, "no AI provider keys are configured")
135
+ if fallback:
136
+ return fallback
137
+ return (
138
+ "⚠️ **No AI provider keys are configured.**\n\n"
139
+ "Add a provider secret in the Hugging Face Space settings to enable explanations."
140
+ )
141
+
142
+ # Build sympy context if we have a verified result
143
+ sympy_context = ""
144
+ if (sympy_info.get("result")
145
+ and sympy_info["result"] not in (None, "matrix_detected", "mod_detected")):
146
+ sympy_context = (
147
+ "\n\n=== PRE-COMPUTED VERIFIED RESULT ===\n"
148
+ "IMPORTANT: The answer has already been computed below with 100% accuracy.\n"
149
+ "Your ONLY job is to EXPLAIN the steps — DO NOT recompute anything.\n"
150
+ "USE these exact numbers in your explanation. DO NOT recalculate.\n"
151
+ "If you compute different numbers, you are WRONG. Trust only these values.\n"
152
+ f" Method : {sympy_info.get('type', '')}\n"
153
+ f" Answer : {sympy_info.get('result', '')}\n"
154
+ f" LaTeX : {sympy_info.get('latex', '')}\n"
155
+ "FINAL ANSWER must be exactly as shown in Answer above.\n"
156
+ "=== END PRE-COMPUTED RESULT ==="
157
+ )
158
+
159
+ system_prompt = (
160
+ "You are Saad.AI, a BSc Mathematics assistant built by Saad. "
161
+ "You are friendly, helpful, and professional — like ChatGPT or Claude. "
162
+ "If anyone asks who made you, who built you, who created you, or who invented you, "
163
+ "always say: I was built by Saad, a passionate developer who created me from scratch "
164
+ "to help BSc Mathematics students. Never mention Groq, Meta, Gemini, or any AI company as your creator.\n\n"
165
+
166
+ "=== CONVERSATION MODE ===\n"
167
+ "You have TWO modes:\n\n"
168
+ "MODE A — CASUAL (when sympy type is 'casual' or message is a greeting/small talk):\n"
169
+ " → Respond naturally like ChatGPT or Claude — warm, friendly, conversational.\n"
170
+ " → NO math structure. NO steps. NO boxed answers. NO LaTeX.\n"
171
+ " → Just reply naturally in 1-3 sentences.\n"
172
+ " → Examples: 'Hi!' → 'Hey! How can I help you today?'\n"
173
+ " 'How are you?' → 'Doing great! Ready to tackle some math. What would you like to solve?'\n"
174
+ " 'What can you do?' → Briefly explain you solve BSc Math problems step by step.\n\n"
175
+ "MODE B — MATH (when sympy type is anything else — actual math problem):\n"
176
+ " → Use full math structure below.\n\n"
177
+
178
+ "═══════════════════════════════════════════════════════\n"
179
+ "CORE FORMATTING RULES — follow every rule without exception\n"
180
+ "═══════════════════════════════════════════════════════\n\n"
181
+
182
+ "RULE 1 — SOLUTION STRUCTURE (mandatory for every answer):\n"
183
+ " 🔍 **Given:** state what is given clearly\n"
184
+ " 📌 **Method:** state the method name (e.g. Integration by Parts, Newton-Raphson, Bisection)\n"
185
+ " 🧮 **Step 1:** [one single action only + one sentence explanation]\n"
186
+ " 🧮 **Step 2:** [one single action only + one sentence explanation]\n"
187
+ " 🧮 **Step 3:** [continue as needed — never merge two actions into one step]\n"
188
+ " ✅ **Final Answer:** $$\\boxed{answer}$$\n"
189
+ " → Never skip this structure. Never merge steps. Never jump to answer without showing work.\n"
190
+ " → If user says plot/draw/graph/sketch/visualize: a real graph renders automatically.\n"
191
+ " Do NOT draw ASCII art. Do NOT say you cannot draw.\n"
192
+ " Give this SHORT response only — then graph renders below automatically:\n"
193
+ " 📌 **Function:** state f(x) clearly in LaTeX\n"
194
+ " 🔍 **Key Features:**\n"
195
+ " - Domain and range\n"
196
+ " - x-intercepts: solve f(x)=0\n"
197
+ " - y-intercept: f(0)\n"
198
+ " - Turning points / vertex if any\n"
199
+ " - Behavior as $x \\to \\pm\\infty$\n"
200
+ " 📊 **Graph** is shown below.\n"
201
+ " Keep it SHORT — max 8 lines. No long paragraphs. No step-by-step for graph requests.\n\n"
202
+
203
+ "RULE 2 — LATEX (zero exceptions):\n"
204
+ " - Inline math (inside a sentence): $expression$\n"
205
+ " - Display math (standalone line, centered): $$expression$$\n"
206
+ " - Fractions: ALWAYS use \\frac{a}{b} — NEVER write a/b in display math\n"
207
+ " - Multi-character exponents: use x^{n+1} not x^n+1\n"
208
+ " - Final answer: ALWAYS wrap in \\boxed{} — e.g. $$\\boxed{x = 2}$$\n"
209
+ " - NEVER write math in plain text — e.g. NEVER write 'x = 3x^2 + 2' without $ signs\n"
210
+ " - NEVER repeat the same expression in both plain text AND LaTeX\n"
211
+ " - FOR GRAPH RESPONSES ESPECIALLY: every value must be in LaTeX — no exceptions.\n"
212
+ " WRONG: 'Domain and range: (-∞,∞) and [-1,1]'\n"
213
+ " RIGHT: 'Domain: $(-\\infty, \\infty)$, Range: $[-1, 1]$'\n"
214
+ " WRONG: 'x-intercepts: x = kπ'\n"
215
+ " RIGHT: 'x-intercepts: $x = k\\pi$ where $k \\in \\mathbb{Z}$'\n"
216
+ " - NEVER use \\begin{} or \\end{} LaTeX environments — Streamlit cannot render them\n"
217
+ " - NEVER use \\begin{vmatrix}, \\begin{matrix}, \\begin{pmatrix}\n"
218
+ " Instead write cross products inline: $i(a_2b_3-a_3b_2) - j(a_1b_3-a_3b_1) + k(a_1b_2-a_2b_1)$\n\n"
219
+
220
+ "RULE 3 — EXPLANATION TYPE:\n"
221
+ " A. If question starts with Explain / What is / Why / How does / Describe / Define:\n"
222
+ " → Explain like talking to a smart student seeing it for the first time.\n"
223
+ " → ALWAYS add: 💡 **Intuition:** with a real-life analogy.\n"
224
+ " → Use simple language first, then give the formal definition.\n"
225
+ " → Example analogies to use:\n"
226
+ " Continuity = water flowing without any breaks or jumps\n"
227
+ " Convergence = walking toward a wall, each step gets you closer\n"
228
+ " Bernoulli = airplane wing — faster air above = lower pressure = lift\n"
229
+ " Curvature = how sharply a road bends at a corner\n"
230
+ " Eigenvalue = natural vibration frequency of a guitar string\n"
231
+ " Reynolds number = whether a river flows smoothly or chaotically\n"
232
+ " Geodesic = shortest flight path between two cities on a globe\n"
233
+ " Fourier series = any sound = sum of pure sine waves\n"
234
+ " Complex number = a point on a 2D plane, not just a number line\n"
235
+ " Group = a set of moves where doing two moves is still a valid move\n"
236
+ " B. If question starts with Find / Calculate / Compute / Solve / Prove:\n"
237
+ " → Skip the analogy. Go straight to 🔍 Given → 📌 Method → Steps.\n"
238
+ " → Show every calculation. Never skip intermediate results.\n\n"
239
+
240
+ "RULE 4 — STEP QUALITY:\n"
241
+ " - Each step = ONE action + ONE short explanation sentence\n"
242
+ " - Show intermediate results at every step — never jump directly to answer\n"
243
+ " - Never say 'simplifying...' without actually showing the simplification\n"
244
+ " - Never say 'it can be shown that' — show it fully\n"
245
+ " - Never say 'similarly' and skip — write it out\n\n"
246
+
247
+ "RULE 5 — NUMERICAL METHODS (table format required):\n"
248
+ " For Newton-Raphson, Bisection, Secant, False Position, Euler, RK4:\n"
249
+ " ALWAYS present iterations in a markdown table. Example for Newton-Raphson:\n"
250
+ " | n | $x_n$ | $f(x_n)$ | $f'(x_n)$ | $x_{n+1}$ |\n"
251
+ " |---|--------|-----------|------------|------------|\n"
252
+ " Columns vary by method but table format is mandatory every time.\n"
253
+ " ALWAYS use SymPy verified values — NEVER recalculate anything yourself.\n"
254
+ " Final answer must EXACTLY match the verified result — no exceptions.\n\n"
255
+
256
+ "═══════════════════════════════════════════════════════\n"
257
+ "SUBJECT-SPECIFIC RULES\n"
258
+ "═══════════════════════════════════════════════════════\n\n"
259
+
260
+ "=== ODE RULES ===\n"
261
+ "A. Always find CF first by solving the auxiliary/characteristic equation.\n"
262
+ "B. For PI: if forcing term matches CF, multiply by x (reduction of order).\n"
263
+ " Example: if $e^x$ in CF and RHS=$e^x$, try PI=$Cxe^x$ NOT $Ce^x$.\n"
264
+ "C. ALWAYS verify PI by substituting back into the full ODE before final answer.\n"
265
+ "D. Handle all types: separable, linear 1st order, 2nd order constant coefficients,\n"
266
+ " Cauchy-Euler, exact, Bernoulli ODE, variation of parameters, Laplace.\n"
267
+ "E. For IVP: apply initial conditions clearly in a separate step after general solution.\n\n"
268
+
269
+ "=== NEWTON-RAPHSON RULES — STRICT FORMAT ===\n"
270
+ "For Newton-Raphson ALWAYS follow this EXACT format:\n\n"
271
+ "1. Show formula first: $$x_{n+1} = x_n - \\frac{f(x_n)}{f'(x_n)}$$\n"
272
+ "2. Show Given: write f(x) and f'(x) and x0 in LaTeX\n"
273
+ "3. For EACH iteration write it like this:\n"
274
+ " 🧮 **Iteration n:**\n"
275
+ " Substitute $x_n = value$:\n"
276
+ " $$f(x_n) = (...) = (...) = result$$\n"
277
+ " $$f'(x_n) = (...) = (...) = result$$\n"
278
+ " $$x_{n+1} = x_n - \\frac{f(x_n)}{f'(x_n)} = result$$\n"
279
+ "4. After ALL iterations show summary table:\n"
280
+ " | n | $x_n$ | $f(x_n)$ | $f'(x_n)$ | $x_{n+1}$ |\n"
281
+ " |---|--------|-----------|------------|------------|\n"
282
+ "5. End with ✅ **Final Answer:** $$\\boxed{answer}$$\n\n"
283
+ "STRICT RULES:\n"
284
+ "A. NEVER write as paragraphs — each iteration is its own block\n"
285
+ "B. NEVER mix plain text math with LaTeX — LaTeX only\n"
286
+ "C. NEVER write f(x)=...f(x)=... doubled — one LaTeX expression only\n"
287
+ "D. Show full substitution at every step — students must see HOW\n"
288
+ "E. Use ONLY SymPy verified values — never recalculate\n\n"
289
+
290
+ "=== NUMERICAL METHODS RULES ===\n"
291
+ "A. Simpson's rule formula: $\\frac{h}{3}[f(x_0) + 4f(x_1) + 2f(x_2) + \\cdots + f(x_n)]$\n"
292
+ "B. Trapezoidal formula: $\\frac{h}{2}[f(x_0) + 2f(x_1) + \\cdots + f(x_n)]$\n"
293
+ "C. State exact trig values directly: $\\sin(\\pi)=0$, $\\cos(\\pi)=-1$ — never recompute.\n"
294
+ "D. For Lagrange/Newton interpolation: DO NOT re-derive the polynomial.\n"
295
+ " Show basis polynomials then state final polynomial from the verified result.\n"
296
+ "E. For Euler/RK4: show k-values at each step then give $y_{n+1}$.\n\n"
297
+
298
+ "=== THEORY OF NUMBERS RULES ===\n"
299
+ "A. For congruences $ax \\equiv b \\pmod{n}$: always show full Euclidean algorithm steps.\n"
300
+ "B. For GCD/LCM: show both prime factorization AND Euclidean algorithm.\n"
301
+ "C. For CRT: state theorem conditions (moduli must be pairwise coprime) before solving.\n"
302
+ "D. For Fermat/Euler/Wilson: state theorem → prove it → give numerical example.\n"
303
+ "E. For Legendre symbol: state definition → compute using Euler's criterion.\n\n"
304
+
305
+ "=== REAL ANALYSIS II RULES ===\n"
306
+ "A. Always start with FORMAL DEFINITION using proper symbols.\n"
307
+ "B. State theorem COMPLETELY before proving.\n"
308
+ "C. Give a concrete numerical example after every definition or theorem.\n"
309
+ "D. For $\\varepsilon$-$\\delta$: write formal definition first, then explain in plain words.\n"
310
+ "E. For convergence tests: state test → conditions → apply to the specific example.\n"
311
+ "F. Use proper symbols: $\\forall$, $\\exists$, $\\varepsilon$, $\\delta$, $\\sup$, $\\inf$, $\\lim$.\n\n"
312
+
313
+ "=== DIFFERENTIAL GEOMETRY RULES ===\n"
314
+ "A. State the definition or theorem FIRST before any computation.\n"
315
+ "B. Plane curvature: $\\kappa = \\frac{|y''|}{(1+y'^2)^{3/2}}$\n"
316
+ "C. Space curve: $\\kappa = \\frac{|r' \\times r''|}{|r'|^3}$, "
317
+ "$\\tau = \\frac{(r' \\times r'') \\cdot r'''}{|r' \\times r''|^2}$\n"
318
+ "D. Frenet-Serret: $\\frac{dT}{ds}=\\kappa N$, $\\frac{dN}{ds}=-\\kappa T+\\tau B$, "
319
+ "$\\frac{dB}{ds}=-\\tau N$\n"
320
+ "E. Unit vectors: $T=r'/|r'|$, $N=T'/|T'|$, $B=T\\times N$\n"
321
+ "F. First Fundamental Form: $ds^2=E\\,du^2+2F\\,du\\,dv+G\\,dv^2$\n"
322
+ "G. Gaussian curvature: $K=\\frac{LN-M^2}{EG-F^2}$, Mean: $H=\\frac{EN-2FM+GL}{2(EG-F^2)}$\n"
323
+ "H. For proofs: Given → To Prove → Proof steps.\n"
324
+ "I. Christoffel symbols: $\\Gamma^k_{ij} = \\frac{1}{2}g^{kl}(\\partial_i g_{jl}+\\partial_j g_{il}-\\partial_l g_{ij})$\n\n"
325
+
326
+ "=== HYDRO MECHANICS RULES ===\n"
327
+ "A. State fluid type (ideal/viscous, compressible/incompressible) first.\n"
328
+ "B. Continuity: $A_1v_1 = A_2v_2$ (incompressible), $\\frac{\\partial\\rho}{\\partial t}+\\nabla\\cdot(\\rho\\mathbf{v})=0$ (general)\n"
329
+ "C. Bernoulli: $P + \\frac{1}{2}\\rho v^2 + \\rho gh = \\text{const}$ (along streamline, ideal fluid)\n"
330
+ "D. Reynolds: $Re = \\frac{\\rho v D}{\\mu}$ — $Re<2300$ laminar, $Re>4000$ turbulent\n"
331
+ "E. Navier-Stokes: $\\rho\\frac{D\\mathbf{v}}{Dt} = -\\nabla P + \\mu\\nabla^2\\mathbf{v} + \\rho\\mathbf{g}$\n"
332
+ "F. Torricelli: $v=\\sqrt{2gh}$ — derived from Bernoulli\n"
333
+ "G. Always give physical interpretation of the result.\n\n"
334
+
335
+ "=== MATLAB RULES ===\n"
336
+ "A. Always start every script with: clc; clear; close all;\n"
337
+ "B. Add % comments explaining every section.\n"
338
+ "C. Use semicolons (;) to suppress unwanted output.\n"
339
+ "D. For numerical methods: display iteration table using fprintf.\n"
340
+ "E. For plots: use plot(), xlabel(), ylabel(), title(), grid on.\n"
341
+ "F. Test logic mentally — code must be correct and directly runnable.\n\n"
342
+
343
+ "=== NEW / UNKNOWN SUBJECT RULES ===\n"
344
+ "When the question is from a subject not listed above "
345
+ "(e.g. Complex Analysis, Abstract Algebra, Probability, Statistics, "
346
+ "Fourier Series, Laplace Transform, Vector Calculus, Topology, etc.):\n"
347
+ "A. NEVER refuse. ALWAYS attempt the problem fully.\n"
348
+ "B. Follow the SAME structure: 🔍 Given → 📌 Method → 🧮 Steps → ✅ Final Answer.\n"
349
+ "C. Start with the relevant definition or theorem for that topic.\n"
350
+ "D. Solve step by step exactly like the known subjects above.\n"
351
+ "E. Use correct subject-specific notation and formulas:\n"
352
+ " - Complex Analysis: $z=a+bi$, modulus $|z|=\\sqrt{a^2+b^2}$, argument $\\arg(z)$,\n"
353
+ " Cauchy-Riemann: $\\frac{\\partial u}{\\partial x}=\\frac{\\partial v}{\\partial y}$, "
354
+ "$\\frac{\\partial u}{\\partial y}=-\\frac{\\partial v}{\\partial x}$\n"
355
+ " - Abstract Algebra: group $(G,*)$, order $|G|$, Lagrange theorem, cosets, homomorphism\n"
356
+ " - Probability: $P(A\\cup B)=P(A)+P(B)-P(A\\cap B)$, Bayes: $P(A|B)=\\frac{P(B|A)P(A)}{P(B)}$\n"
357
+ " - Statistics: mean $\\bar{x}=\\frac{\\sum x_i}{n}$, variance $s^2=\\frac{\\sum(x_i-\\bar{x})^2}{n-1}$\n"
358
+ " - Fourier Series: $f(x)=\\frac{a_0}{2}+\\sum_{n=1}^{\\infty}(a_n\\cos\\frac{n\\pi x}{L}+b_n\\sin\\frac{n\\pi x}{L})$\n"
359
+ " - Laplace Transform: $\\mathcal{L}\\{f(t)\\}=\\int_0^{\\infty}e^{-st}f(t)\\,dt$\n"
360
+ " - Vector Calculus: $\\nabla f$, $\\nabla\\cdot\\mathbf{F}$, $\\nabla\\times\\mathbf{F}$, "
361
+ "Green's/Stokes/Divergence theorems\n"
362
+ "F. Add 💡 **Intuition:** analogy for explanation-type questions.\n"
363
+ "G. ALWAYS end with ✅ **Final Answer:** $$\\boxed{answer}$$\n\n"
364
+
365
+ "Topics covered: Calculus, Linear Algebra, Number Theory, ODEs, "
366
+ "Numerical Methods, Differential Geometry, Hydro Mechanics, "
367
+ "Theory of Numbers, Real Analysis II, MATLAB, Complex Analysis, "
368
+ "Abstract Algebra, Probability, Statistics, Fourier Series, "
369
+ "Laplace Transform, Vector Calculus, and all other BSc Mathematics topics."
370
+ + sympy_context
371
+ )
372
+
373
+ # Build messages — last 6 exchanges for context
374
+ messages = [{"role": "system", "content": system_prompt}]
375
+ for msg in history[-12:]:
376
+ messages.append({"role": msg["role"], "content": msg["content"]})
377
+ # Inject verified result directly into user message — AI cannot ignore this
378
+ p_lower = problem.lower()
379
+ is_graph_req = any(k in p_lower for k in ["plot","graph","draw","sketch","visualize"])
380
+
381
+ if (sympy_info.get("result")
382
+ and sympy_info["result"] not in (None, "matrix_detected", "mod_detected")):
383
+ final_latex = sympy_info.get("latex", "")
384
+ user_msg = (
385
+ f"PROBLEM: {problem}\n\n"
386
+ f"⚠️ IMPORTANT: This problem is already solved. Use ONLY these verified values:\n"
387
+ f"{sympy_info.get('result', '')}\n\n"
388
+ f"✅ FINAL ANSWER IS: $${final_latex}$$\n\n"
389
+ f"Your task: explain the method steps clearly, and end with the EXACT final answer shown above."
390
+ )
391
+ elif is_graph_req:
392
+ user_msg = (
393
+ f"PROBLEM: {problem}\n\n"
394
+ f"⚠️ CRITICAL: A real graph is ALREADY rendering below this response automatically.\n"
395
+ f"You MUST NOT say you cannot draw or display images — the graph IS showing.\n"
396
+ f"You MUST NOT suggest Desmos, graphing calculators, or any external tools.\n"
397
+ f"Your ONLY job:\n"
398
+ f"1. State the function clearly in LaTeX — e.g. $f(x) = \\sin(x)$\n"
399
+ f"2. List key features — ALL values must be in LaTeX, NO plain text math\n"
400
+ f"3. Give step-by-step drawing instructions with exact coordinates\n"
401
+ f"4. End with exactly: '📊 Graph is shown below.'\n"
402
+ f"EVERY mathematical expression must use $ signs. NEVER write math in plain text."
403
+ )
404
+ else:
405
+ user_msg = problem
406
+ messages.append({"role": "user", "content": user_msg})
407
+
408
+ # ── Permanent fix: force correct final answer from SymPy ────────
409
+ def enforce_verified_answer(ai_response: str) -> str:
410
+ """Remove AI final answer, replace with SymPy verified one."""
411
+ result = sympy_info.get("result", "")
412
+ latex = sympy_info.get("latex", "")
413
+ # Only enforce if SymPy has a real computed result
414
+ if (not result or
415
+ result in (None, "matrix_detected", "mod_detected") or
416
+ not latex):
417
+ return ai_response # theory question — leave AI response untouched
418
+ # Remove everything after last "✅" or "Final Answer"
419
+ cleaned = re.sub(
420
+ r'(✅\s*\*{0,2}Final\s*Answer\*{0,2}.*|✅[^\n]*$)',
421
+ "", ai_response,
422
+ flags=re.DOTALL | re.IGNORECASE
423
+ ).rstrip()
424
+ # Append our verified final answer
425
+ verified_line = f"\n\n✅ **Final Answer:** $$\\boxed{{{latex}}}$$"
426
+ return cleaned + verified_line
427
+
428
+ # Try each provider in order — auto-rotate on 429 or error
429
+ last_error = ""
430
+ for provider_name, key, call_fn in providers:
431
+ if not key:
432
+ continue # skip if key not set
433
+ try:
434
+ response = call_fn(key, messages)
435
+ return enforce_verified_answer(response)
436
+ except requests.exceptions.Timeout:
437
+ last_error = f"⏳ {provider_name} timed out"
438
+ continue
439
+ except requests.exceptions.HTTPError as e:
440
+ code = e.response.status_code if e.response else 0
441
+ # Include the real error body if available (set by try_gemini)
442
+ try:
443
+ body = e.response.text[:120] if e.response else str(e)
444
+ except Exception:
445
+ body = str(e)[:120]
446
+ last_error = f"⚠️ {provider_name} HTTP {code}: {body}"
447
+ continue # always try next provider
448
+ except Exception as e:
449
+ last_error = f"⚠️ {provider_name} error: {str(e)}"
450
+ continue
451
+
452
+ # All providers exhausted. Preserve deterministic value if one exists.
453
+ fallback = _deterministic_fallback(sympy_info, last_error or "all providers failed")
454
+ if fallback:
455
+ return fallback
456
+ return (
457
+ "⚠️ **AI explanation unavailable.**\n\n"
458
+ f"Last provider error: `{last_error or 'unknown provider error'}`\n\n"
459
+ "Check the provider secret and quota in the Hugging Face Space settings."
460
+ )
461
+
462
+
463
+
464
+ # ════════════════════════════════════════════════════════════════════
465
+ # FILE UPLOAD — image/PDF sent to Gemini Vision, then SymPy verified
466
+ # ════════════════════════════════════════════════════════════════════
467
+ def ask_gemini_vision(image_b64: str, mime_type: str, user_note: str) -> str:
468
+ """
469
+ Multi-provider vision: tries Groq → Gemini → OpenRouter in order.
470
+ Groq vision is primary (much more generous free limits, user already has keys).
471
+ Gemini is fallback (needed for PDFs; Groq/OpenRouter are image-only).
472
+ OpenRouter free vision models are the last resort.
473
+ """
474
+ import base64 as _b64
475
+ is_pdf = (mime_type == "application/pdf")
476
+
477
+ # ── Convert PDF → PNG image so Groq/OpenRouter can read it ───────
478
+ # PyMuPDF (fitz) converts PDF pages to images.
479
+ # Add "PyMuPDF" to your HF Space requirements.txt to enable this.
480
+ if is_pdf:
481
+ try:
482
+ import fitz # PyMuPDF
483
+ import io
484
+ pdf_bytes = _b64.b64decode(image_b64)
485
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
486
+ # Render all pages (up to 4) as one tall PNG
487
+ imgs = []
488
+ for page_num in range(min(len(doc), settings.max_pdf_pages)):
489
+ pix = doc[page_num].get_pixmap(matrix=fitz.Matrix(3, 3)) # 3x zoom for crisp text
490
+ imgs.append(pix.tobytes("png"))
491
+ doc.close()
492
+ # Stack page images vertically using PIL if available, else just use first page
493
+ try:
494
+ from PIL import Image
495
+ pages_pil = [Image.open(io.BytesIO(b)) for b in imgs]
496
+ total_h = sum(p.height for p in pages_pil)
497
+ max_w = max(p.width for p in pages_pil)
498
+ combined = Image.new("RGB", (max_w, total_h), (255, 255, 255))
499
+ y_offset = 0
500
+ for p in pages_pil:
501
+ combined.paste(p, (0, y_offset))
502
+ y_offset += p.height
503
+ buf = io.BytesIO()
504
+ combined.save(buf, format="PNG")
505
+ image_b64 = _b64.b64encode(buf.getvalue()).decode("utf-8")
506
+ except Exception:
507
+ # PIL not available — just use first page
508
+ image_b64 = _b64.b64encode(imgs[0]).decode("utf-8")
509
+ mime_type = "image/png"
510
+ is_pdf = False # now it's an image — Groq/OpenRouter can handle it
511
+ except ImportError:
512
+ pass # PyMuPDF not installed — will fall through to Gemini (which reads PDFs natively)
513
+ except Exception as e:
514
+ pass # Conversion failed — fall through to Gemini
515
+
516
+ prompt = (
517
+ "You are Saad.AI, a helpful AI assistant built by Saad.\n"
518
+ "You can read and understand ALL types of images and documents.\n\n"
519
+
520
+ "STEP 1 — Look at the image carefully from top to bottom.\n"
521
+ "STEP 2 — Identify what type of content is in the image:\n\n"
522
+
523
+ "━━━ CASE A: IMAGE CONTAINS MATH PROBLEMS ━━━\n"
524
+ "(Equations, exam paper, homework sheet, math diagrams, numbered questions)\n"
525
+ "→ Read the ENTIRE document. Extract EVERY question — do NOT skip any.\n"
526
+ "→ Do NOT invent questions. ONLY solve what is actually written.\n"
527
+ "→ For EACH problem use this structure:\n"
528
+ " ---\n"
529
+ " ### Question [N]: [restate exact question from file]\n"
530
+ " 🔍 **Given:** ...\n"
531
+ " 📌 **Method:** ...\n"
532
+ " 🧮 **Step 1:** ...\n"
533
+ " ✅ **Final Answer:** $$\\boxed{answer}$$\n"
534
+ " ---\n"
535
+ "→ ALL math must be in LaTeX — never plain text math.\n\n"
536
+
537
+ "━━━ CASE B: IMAGE IS NOT A MATH PROBLEM ━━━\n"
538
+ "(Photo, screenshot, diagram, chart, meme, nature, objects, people, text, etc.)\n"
539
+ "→ Describe the image in detail — what you see, what it shows.\n"
540
+ "→ Be conversational and helpful like ChatGPT or Claude.\n"
541
+ "→ Answer the student's specific question about the image.\n"
542
+ "→ No forced math structure. Just natural, helpful conversation.\n"
543
+ "→ Point out interesting details, context, or meaning.\n\n"
544
+
545
+ f"Student's instruction: {user_note if user_note else 'Look at this image and describe or analyze it.'}\n\n"
546
+ "Always be helpful, friendly, and clear."
547
+ )
548
+
549
+ errors = []
550
+
551
+ # ── PROVIDER 1: Groq vision (images only — not PDFs) ─────────────
552
+ # Groq free tier: ~100 req/min, much more generous than Gemini's 15/min
553
+ if not is_pdf:
554
+ groq_keys = settings.groq_api_keys
555
+ groq_vision_models = [
556
+ "meta-llama/llama-4-scout-17b-16e-instruct",
557
+ "llama-3.2-11b-vision-preview",
558
+ ]
559
+ for i, key in enumerate(groq_keys):
560
+ if not key.strip():
561
+ continue
562
+ for model in groq_vision_models:
563
+ try:
564
+ resp = _post_with_retry(
565
+ "https://api.groq.com/openai/v1/chat/completions",
566
+ headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
567
+ json={
568
+ "model": model,
569
+ "messages": [{
570
+ "role": "user",
571
+ "content": [
572
+ {"type": "image_url",
573
+ "image_url": {"url": f"data:{mime_type};base64,{image_b64}"}},
574
+ {"type": "text", "text": prompt}
575
+ ]
576
+ }],
577
+ "max_tokens": 2048,
578
+ "temperature": 0.15
579
+ },
580
+ timeout=settings.provider_timeout_seconds
581
+ )
582
+ if resp.status_code == 200:
583
+ return resp.json()["choices"][0]["message"]["content"]
584
+ elif resp.status_code == 429:
585
+ errors.append(f"Groq-{i+1}/{model}: rate limited")
586
+ break # try next key
587
+ elif resp.status_code == 400:
588
+ # Model may not support vision — try next model
589
+ try:
590
+ msg = resp.json().get("error", {}).get("message", "")[:80]
591
+ except Exception:
592
+ msg = ""
593
+ errors.append(f"Groq-{i+1}/{model}: {msg}")
594
+ continue
595
+ else:
596
+ errors.append(f"Groq-{i+1}/{model}: HTTP {resp.status_code}")
597
+ break
598
+ except requests.exceptions.Timeout:
599
+ errors.append(f"Groq-{i+1}/{model}: timeout")
600
+ break
601
+ except Exception as e:
602
+ errors.append(f"Groq-{i+1}/{model}: {str(e)[:60]}")
603
+ break
604
+
605
+ # ── PROVIDER 2: Gemini (images + PDFs) ───────────────────────────
606
+ # 15 req/min, 1500 req/day per key — use as fallback
607
+ gemini_keys = settings.gemini_api_keys
608
+ gemini_models = ["gemini-2.0-flash", "gemini-1.5-flash"]
609
+ for i, key in enumerate(gemini_keys):
610
+ if not key.strip():
611
+ continue
612
+ for model in gemini_models:
613
+ try:
614
+ resp = _post_with_retry(
615
+ f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={key}",
616
+ headers={"Content-Type": "application/json"},
617
+ json={
618
+ "contents": [{"parts": [
619
+ {"inline_data": {"mime_type": mime_type, "data": image_b64}},
620
+ {"text": prompt}
621
+ ]}],
622
+ "generationConfig": {"maxOutputTokens": 2048, "temperature": 0.15}
623
+ },
624
+ timeout=settings.provider_timeout_seconds
625
+ )
626
+ if resp.status_code == 200:
627
+ candidates = resp.json().get("candidates", [])
628
+ if candidates:
629
+ return candidates[0]["content"]["parts"][0]["text"]
630
+ errors.append(f"Gemini-{i+1}/{model}: safety blocked")
631
+ break
632
+ elif resp.status_code == 429:
633
+ errors.append(f"Gemini-{i+1}/{model}: rate limited (429)")
634
+ break
635
+ elif resp.status_code == 404:
636
+ errors.append(f"Gemini-{i+1}/{model}: model not found")
637
+ continue # try next model
638
+ else:
639
+ try:
640
+ msg = resp.json().get("error", {}).get("message", resp.text[:80])
641
+ except Exception:
642
+ msg = resp.text[:80]
643
+ errors.append(f"Gemini-{i+1}/{model}: HTTP {resp.status_code} — {msg}")
644
+ break
645
+ except requests.exceptions.Timeout:
646
+ errors.append(f"Gemini-{i+1}/{model}: timeout")
647
+ break
648
+ except Exception as e:
649
+ errors.append(f"Gemini-{i+1}/{model}: {str(e)[:60]}")
650
+ break
651
+
652
+ # ── PROVIDER 3: OpenRouter free vision models (images only) ───────
653
+ if not is_pdf:
654
+ or_key = settings.openrouter_api_key
655
+ if or_key.strip():
656
+ or_models = [
657
+ "meta-llama/llama-3.2-11b-vision-instruct:free",
658
+ "qwen/qwen2-vl-7b-instruct:free",
659
+ ]
660
+ for model in or_models:
661
+ try:
662
+ resp = _post_with_retry(
663
+ "https://openrouter.ai/api/v1/chat/completions",
664
+ headers={"Authorization": f"Bearer {or_key}", "Content-Type": "application/json"},
665
+ json={
666
+ "model": model,
667
+ "messages": [{
668
+ "role": "user",
669
+ "content": [
670
+ {"type": "image_url",
671
+ "image_url": {"url": f"data:{mime_type};base64,{image_b64}"}},
672
+ {"type": "text", "text": prompt}
673
+ ]
674
+ }],
675
+ "max_tokens": 2048
676
+ },
677
+ timeout=settings.provider_timeout_seconds
678
+ )
679
+ if resp.status_code == 200:
680
+ return resp.json()["choices"][0]["message"]["content"]
681
+ errors.append(f"OpenRouter/{model}: HTTP {resp.status_code}")
682
+ except Exception as e:
683
+ errors.append(f"OpenRouter/{model}: {str(e)[:60]}")
684
+
685
+ # ── All providers failed ──────────────────────────────────────────
686
+ error_summary = " | ".join(errors[-6:]) # show last 6 errors
687
+ if is_pdf:
688
+ pdf_note = (
689
+ "\n\n**To make PDFs work without Gemini:** add `PyMuPDF` to your HF Space `requirements.txt` — "
690
+ "it converts PDF pages to images so Groq can read them (no Gemini needed)."
691
+ )
692
+ else:
693
+ pdf_note = ""
694
+ return (
695
+ f"⚠️ **All vision providers failed.**\n\n"
696
+ f"Errors: `{error_summary}`\n\n"
697
+ f"**Most likely fix:** make sure `GROQ_API_KEY_1`, `GROQ_API_KEY_2`, `GROQ_API_KEY_3` "
698
+ f"are added in your HF Space → Settings → Secrets. Groq reads images with much higher limits than Gemini.\n\n"
699
+ f"**Gemini 429:** wait 60 sec (per-minute limit) or until midnight Pacific (daily limit)."
700
+ f"{pdf_note}"
701
+ )
702
+
703
+
704
+ class _MemoryUpload:
705
+ """Small upload-compatible wrapper for bytes already held in session state."""
706
+
707
+ def __init__(self, file_bytes: bytes, name: str, mime_type: str):
708
+ self._file_bytes = file_bytes
709
+ self.name = name
710
+ self.type = mime_type
711
+
712
+ def read(self) -> bytes:
713
+ return self._file_bytes
714
+
715
+
716
+ def handle_uploaded_file(uploaded_file, user_note: str) -> str:
717
+ """
718
+ Process uploaded image or PDF:
719
+ 1. Convert to base64
720
+ 2. Send to Gemini Vision
721
+ 3. Try SymPy verification on extracted text
722
+ 4. Return final answer
723
+ """
724
+ import base64
725
+
726
+ # ── Validate size ────────────────────────────────────────────────
727
+ MAX_SIZE = settings.max_upload_bytes
728
+ file_bytes = uploaded_file.read()
729
+ if len(file_bytes) == 0:
730
+ return "⚠️ The uploaded file is empty. Please try again."
731
+ if len(file_bytes) > MAX_SIZE:
732
+ return f"⚠️ File too large ({len(file_bytes)//1024}KB). Please upload under 5MB."
733
+
734
+ # ── Detect MIME type from Streamlit's type field, not filename ────
735
+ # This works even if filename has spaces, brackets, or no extension
736
+ mime_map = {
737
+ "jpg": "image/jpeg", "jpeg": "image/jpeg",
738
+ "png": "image/png", "webp": "image/webp",
739
+ "pdf": "application/pdf"
740
+ }
741
+ # Try Streamlit's type first (most reliable), fall back to extension
742
+ mime_type = uploaded_file.type if uploaded_file.type else None
743
+ if not mime_type:
744
+ ext = uploaded_file.name.rsplit(".", 1)[-1].lower() if "." in uploaded_file.name else ""
745
+ mime_type = mime_map.get(ext)
746
+ if mime_type not in mime_map.values():
747
+ return "⚠️ Unsupported format. Please upload JPG, PNG, WEBP or PDF."
748
+
749
+ # ── Convert to base64 ────────────────────────────────────────────
750
+ image_b64 = base64.b64encode(file_bytes).decode("utf-8")
751
+
752
+ # ── Send to Gemini Vision ────────────────────────────────────────
753
+ gemini_response = ask_gemini_vision(image_b64, mime_type, user_note)
754
+
755
+ # ── Gemini failed → return single clean error only ───────────────
756
+ if gemini_response.startswith("⚠️"):
757
+ return gemini_response
758
+
759
+ # ── SymPy verification — extract problem line first ───────────────
760
+ # Run SymPy on the first user-question line, not Gemini's full markdown
761
+ # This avoids SymPy choking on LaTeX formatting in the solution
762
+ extracted_problem = ""
763
+ for line in gemini_response.splitlines():
764
+ stripped = line.strip()
765
+ # Skip empty lines, headers, and Gemini's own solution steps
766
+ if (stripped and
767
+ not stripped.startswith("#") and
768
+ not stripped.startswith("🔍") and
769
+ not stripped.startswith("📌") and
770
+ not stripped.startswith("🧮") and
771
+ not stripped.startswith("✅") and
772
+ not stripped.startswith("**") and
773
+ len(stripped) > 5):
774
+ extracted_problem = stripped
775
+ break
776
+ sympy_result = run_sympy(extracted_problem) if extracted_problem else {"type": "general", "result": None, "latex": ""}
777
+
778
+ if (sympy_result.get("result") and
779
+ sympy_result["result"] not in (None, "matrix_detected", "mod_detected")):
780
+ latex = sympy_result.get("latex", "")
781
+ cleaned = re.sub(
782
+ r'(✅\s*\*{0,2}Final\s*Answer\*{0,2}.*|✅[^\n]*$)',
783
+ "", gemini_response,
784
+ flags=re.DOTALL | re.IGNORECASE
785
+ ).rstrip()
786
+ return cleaned + "\n\n🔒 **SymPy Verified**" + f"\n\n✅ **Final Answer:** $$\\boxed{{{latex}}}$$"
787
+ else:
788
+ # Gemini answered, SymPy couldn't verify — single clean note
789
+ return gemini_response + "\n\n⚠️ *AI-generated answer — not SymPy verified.*"
790
+
791
+
app.py CHANGED
The diff for this file is too large to render. See raw diff
 
config.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Application configuration loaded from environment variables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import os
7
+
8
+
9
+ def _env(name: str, default: str = "") -> str:
10
+ return os.environ.get(name, default).strip()
11
+
12
+
13
+ def _numbered_keys(prefix: str, count: int) -> tuple[str, ...]:
14
+ return tuple(_env(f"{prefix}_{index}") for index in range(1, count + 1))
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Settings:
19
+ groq_api_keys: tuple[str, ...]
20
+ gemini_api_keys: tuple[str, ...]
21
+ openrouter_api_key: str
22
+ provider_timeout_seconds: float
23
+ max_upload_bytes: int
24
+ max_pdf_pages: int
25
+
26
+ @property
27
+ def any_text_provider_enabled(self) -> bool:
28
+ return any(self.groq_api_keys) or any(self.gemini_api_keys) or bool(self.openrouter_api_key)
29
+
30
+
31
+
32
+ def load_settings() -> Settings:
33
+ """Load and normalize settings once at application startup."""
34
+ timeout_raw = _env("PROVIDER_TIMEOUT_SECONDS", "60")
35
+ upload_raw = _env("MAX_UPLOAD_BYTES", str(5 * 1024 * 1024))
36
+ pages_raw = _env("MAX_PDF_PAGES", "6")
37
+
38
+ try:
39
+ timeout = max(5.0, min(float(timeout_raw), 120.0))
40
+ except ValueError:
41
+ timeout = 60.0
42
+
43
+ try:
44
+ max_upload_bytes = max(1024, min(int(upload_raw), 25 * 1024 * 1024))
45
+ except ValueError:
46
+ max_upload_bytes = 5 * 1024 * 1024
47
+
48
+ try:
49
+ max_pdf_pages = max(1, min(int(pages_raw), 20))
50
+ except ValueError:
51
+ max_pdf_pages = 6
52
+
53
+ return Settings(
54
+ groq_api_keys=_numbered_keys("GROQ_API_KEY", 3),
55
+ gemini_api_keys=_numbered_keys("GEMINI_API_KEY", 4),
56
+ openrouter_api_key=_env("OPENROUTER_API_KEY"),
57
+ provider_timeout_seconds=timeout,
58
+ max_upload_bytes=max_upload_bytes,
59
+ max_pdf_pages=max_pdf_pages,
60
+ )
61
+
62
+
63
+ settings = load_settings()
requirements.txt CHANGED
@@ -1,7 +1,15 @@
1
- streamlit>=1.32.0
2
- sympy>=1.12
3
- requests>=2.31.0
4
- supabase
5
- matplotlib
6
- numpy
7
- PyMuPDF
 
 
 
 
 
 
 
 
 
1
+ # Core application
2
+ streamlit>=1.40,<2
3
+ requests>=2.32,<3
4
+
5
+ # Deterministic mathematics and graphing
6
+ sympy>=1.13,<2
7
+ numpy>=2.0,<3
8
+ matplotlib>=3.9,<4
9
+
10
+ # Image/PDF upload support
11
+ Pillow>=10,<13
12
+ PyMuPDF>=1.24,<2
13
+
14
+ # Optional: keep this file focused on the active API-backed runtime.
15
+ # Transformers and torch were removed because the current app does not load a local Hugging Face model.
sympy_engine.py ADDED
@@ -0,0 +1,1230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic symbolic mathematics engine for Saad.AI.
2
+
3
+ This module intentionally contains no Streamlit or network dependencies so it can be
4
+ unit-tested independently of the UI and provider integrations.
5
+ """
6
+
7
+ import re
8
+ import sympy as sp
9
+ from sympy.parsing.sympy_parser import (
10
+ parse_expr,
11
+ standard_transformations,
12
+ implicit_multiplication_application,
13
+ )
14
+
15
+ def run_sympy(problem: str) -> dict:
16
+ """
17
+ Symbolic computation engine. Returns verified result dict.
18
+ Falls back silently on any error.
19
+ ELIF ORDER (important — must check ODE before Solve):
20
+ Derivative → Integral → Limit → ODE → NR → Solve → Matrix → Mod
21
+ """
22
+ p = problem.lower().strip()
23
+ x = sp.Symbol('x')
24
+ tfms = standard_transformations + (implicit_multiplication_application,)
25
+ ld = {
26
+ "x": x,
27
+ "e": sp.E, "E": sp.E,
28
+ "pi": sp.pi, "PI": sp.pi,
29
+ "sin": sp.sin, "cos": sp.cos, "tan": sp.tan,
30
+ "exp": sp.exp, "log": sp.log, "ln": sp.log,
31
+ "sqrt": sp.sqrt, "inf": sp.oo, "oo": sp.oo
32
+ }
33
+
34
+ def clean(s):
35
+ s = re.sub(r"\s+", "", s)
36
+ s = re.sub(r"\^", "**", s)
37
+ return s
38
+
39
+ def to_coeff(s):
40
+ """Convert string to sympy integer/rational — never float (floats break dsolve)."""
41
+ s = s.replace(" ", "")
42
+ if s in ("", "+"): return sp.Integer(1)
43
+ if s == "-": return sp.Integer(-1)
44
+ try:
45
+ f = float(s)
46
+ return sp.Integer(int(f)) if f == int(f) else sp.Rational(s)
47
+ except Exception:
48
+ return sp.Integer(1)
49
+
50
+ try:
51
+ # ── 1. Derivative ────────────────────────────────────────────
52
+ if any(k in p for k in ["derivative", "differentiate", "d/dx", "diff"]):
53
+ raw = p
54
+ for kw in ["derivative of", "differentiate", "diff of", "d/dx of", "d/dx"]:
55
+ if kw in p:
56
+ raw = p.split(kw, 1)[-1].strip()
57
+ break
58
+ raw = re.sub(r"\s*(dx|with\s*respect\s*to\s*x).*$", "", raw).strip()
59
+ expr = parse_expr(clean(raw), transformations=tfms, local_dict=ld)
60
+ result = sp.diff(expr, x)
61
+ return {"type": "Derivative", "result": str(result), "latex": sp.latex(result)}
62
+
63
+ # ── 2. Integral ──────────────────────────────────────────────
64
+ elif any(k in p for k in ["integral", "integrate", "antiderivative"]):
65
+ raw = p
66
+ for kw in ["integral of", "integrate", "antiderivative of"]:
67
+ if kw in p:
68
+ raw = p.split(kw, 1)[-1].strip()
69
+ break
70
+ raw = re.sub(r"\s*dx.*$", "", raw).strip()
71
+ expr = parse_expr(clean(raw), transformations=tfms, local_dict=ld)
72
+ result = sp.integrate(expr, x)
73
+ return {"type": "Integral", "result": str(result), "latex": sp.latex(result)}
74
+
75
+ # ── 3. Limit ─────────────────────────────────────────────────
76
+ elif "limit" in p:
77
+ match = re.search(
78
+ r"limit\s+of\s+([\w\s\(\)\+\-\*/\^\.\,]+?)"
79
+ r"\s+as\s+x\s*(?:->|→|approaches)\s*([\w\.\+\-]+)", p
80
+ )
81
+ if match:
82
+ raw_expr = clean(match.group(1))
83
+ pt = match.group(2).strip()
84
+ point = sp.oo if pt in ("inf", "infinity", "oo") else sp.sympify(pt)
85
+ expr = parse_expr(raw_expr, transformations=tfms, local_dict=ld)
86
+ result = sp.limit(expr, x, point)
87
+ return {"type": "Limit", "result": str(result), "latex": sp.latex(result)}
88
+
89
+ # ── 4. ODE — MUST be before Solve (many ODE problems start with "solve") ──
90
+ elif any(k in p for k in ["d²y", "d^2y", "d2y", "dy/dx",
91
+ "differential equation", "second order", "first order"]):
92
+ y_fn = sp.Function('y')
93
+ ode_sol = None
94
+ try:
95
+ # Extract RHS — everything after = and before "with"
96
+ rhs_m = re.search(r"=\s*(.+?)(?:\s+with|\s*$)", p)
97
+ rhs_str = clean(rhs_m.group(1).strip()) if rhs_m else "0"
98
+ rhs_expr = parse_expr(rhs_str, transformations=tfms, local_dict=ld)
99
+ lhs = p.split("=")[0]
100
+
101
+ # Second order: d²y/dx² + a*dy/dx + b*y = rhs
102
+ if any(k in p for k in ["d²y", "d^2y", "d2y", "second order"]):
103
+ # Match coefficient of dy/dx (must be dy/dx not just dy to avoid d²y match)
104
+ c1_m = re.search(r"([+\-]\s*\d*\.?\d*)\s*dy/dx", lhs)
105
+ # Match coefficient of standalone y (word boundary)
106
+ c0_m = re.search(r"([+\-]\s*\d+\.?\d*)\s*y\b", lhs)
107
+ a1 = to_coeff(c1_m.group(1)) if c1_m else sp.Integer(0)
108
+ a0 = to_coeff(c0_m.group(1)) if c0_m else sp.Integer(0)
109
+ ode_eq = sp.Eq(
110
+ y_fn(x).diff(x, 2) + a1*y_fn(x).diff(x) + a0*y_fn(x),
111
+ rhs_expr
112
+ )
113
+ ode_sol = sp.dsolve(ode_eq, y_fn(x))
114
+
115
+ # First order: dy/dx + a*y = rhs
116
+ elif "dy/dx" in p:
117
+ c0_m = re.search(r"([+\-]\s*\d+\.?\d*)\s*y\b", lhs)
118
+ a0 = to_coeff(c0_m.group(1)) if c0_m else sp.Integer(0)
119
+ ode_eq = sp.Eq(y_fn(x).diff(x) + a0*y_fn(x), rhs_expr)
120
+ ode_sol = sp.dsolve(ode_eq, y_fn(x))
121
+
122
+ except Exception:
123
+ ode_sol = None # safe fallback to AI
124
+
125
+ if ode_sol is not None:
126
+ return {
127
+ "type": "ODE",
128
+ "result": f"General solution: y = {str(ode_sol.rhs)}",
129
+ "latex": f"y = {sp.latex(ode_sol.rhs)}"
130
+ }
131
+
132
+ # ── 5. Newton-Raphson ────────────────────────────────────────
133
+ elif any(k in p for k in ["newton", "newton-raphson", "newton raphson"]):
134
+ # Extract: equation (between of/to/for and "= 0"), x0, iterations
135
+ eq_m = re.search(r"(?:of|to|for)\s+(.+?)\s*=\s*0", p)
136
+ x0_m = re.search(r"x\s*0\s*[=:]\s*([\d\.]+)", p)
137
+ iter_m = re.search(r"(\d+)\s*iter", p)
138
+
139
+ if eq_m and x0_m:
140
+ raw_eq = clean(eq_m.group(1).strip())
141
+ x0_val = float(x0_m.group(1))
142
+ n_iter = int(iter_m.group(1)) if iter_m else 3
143
+
144
+ expr_nr = parse_expr(raw_eq, transformations=tfms, local_dict=ld)
145
+ f_sym = sp.lambdify(x, expr_nr, modules="math")
146
+ df_sym = sp.lambdify(x, sp.diff(expr_nr, x), modules="math")
147
+
148
+ # Run all iterations with full precision — never round intermediate values
149
+ iterations = []
150
+ xn = x0_val
151
+ for i in range(n_iter):
152
+ fxn = f_sym(xn)
153
+ dfxn = df_sym(xn)
154
+ if abs(dfxn) < 1e-15:
155
+ break # avoid division by zero
156
+ xn1 = xn - fxn / dfxn
157
+ iterations.append({
158
+ "n": i, "xn": round(xn, 8),
159
+ "fxn": round(fxn, 8), "dfxn": round(dfxn, 8),
160
+ "xn1": round(xn1, 8)
161
+ })
162
+ xn = xn1 # use FULL precision for next iteration
163
+
164
+ final_x = iterations[-1]["xn1"] if iterations else x0_val
165
+ final_fx = round(f_sym(final_x), 10)
166
+ iter_str = "\n".join([
167
+ f" x{it['n']+1} = {it['xn']} - ({it['fxn']}) / ({it['dfxn']}) = {it['xn1']}"
168
+ for it in iterations
169
+ ])
170
+ result_str = (
171
+ f"f(x) = {str(expr_nr)}, f'(x) = {str(sp.diff(expr_nr, x))}\n"
172
+ f"x0 = {x0_val}, iterations = {n_iter}\n"
173
+ f"VERIFIED ITERATIONS (AI MUST use these exact values):\n"
174
+ f"{iter_str}\n"
175
+ f"Final answer: x{n_iter} = {final_x}\n"
176
+ f"Verification: f({final_x}) = {final_fx} ≈ 0"
177
+ )
178
+ return {
179
+ "type": "Newton-Raphson",
180
+ "result": result_str,
181
+ "latex": f"x_{{{n_iter}}} = {final_x}"
182
+ }
183
+
184
+ # ── 6. Numerical Analysis Methods ───────────────────────────
185
+ elif any(k in p for k in ["bisection", "secant method", "false position",
186
+ "regula falsi", "gauss elimination", "gauss elim",
187
+ "lu decomposition", "lu decomp",
188
+ "lagrange interpolation", "lagrange interp",
189
+ "newton divided", "divided difference",
190
+ "trapezoidal", "trapezoid rule",
191
+ "simpson", "euler method", "euler's method",
192
+ "runge-kutta", "runge kutta", "rk4"]):
193
+ import math as _math
194
+
195
+ # ── Helper: extract f(x) expression ──────────────────────
196
+ def get_expr():
197
+ # Stop before common natural-language delimiters so prompts such as
198
+ # "bisection of x^3 - x on [1,2]" do not parse the interval as math.
199
+ eq_m = re.search(
200
+ r"(?:of|to|for|function)\s+(.+?)(?=\s*(?:=\s*0|,|\bon\b|\bfrom\b|\bbetween\b|\[|$))",
201
+ p,
202
+ )
203
+ if eq_m:
204
+ raw = clean(eq_m.group(1).strip())
205
+ return parse_expr(raw, transformations=tfms, local_dict=ld)
206
+ return None
207
+
208
+ # ── Helper: extract bounds a, b ───────────────────────────
209
+ def get_bounds():
210
+ nums = re.findall(r"[-]?\d+\.?\d*", p)
211
+ floats = [float(n) for n in nums]
212
+ # x0 value
213
+ x0_m = re.search(r"x\s*0\s*[=:]\s*([-]?\d+\.?\d*)", p)
214
+ x1_m = re.search(r"x\s*1\s*[=:]\s*([-]?\d+\.?\d*)", p)
215
+ # interval [a,b]
216
+ ab_m = re.search(r"\[\s*([-]?\d+\.?\d*)\s*,\s*([-]?\d+\.?\d*)\s*\]", p)
217
+ return floats, x0_m, x1_m, ab_m
218
+
219
+ # ── Helper: extract iterations ────────────────────────────
220
+ def get_iters(default=5):
221
+ m = re.search(r"(\d+)\s*iter", p)
222
+ return int(m.group(1)) if m else default
223
+
224
+ # ── Helper: extract step size h ───────────────────────────
225
+ def get_h():
226
+ m = re.search(r"h\s*[=:]\s*([\d\.]+)", p)
227
+ return float(m.group(1)) if m else 0.1
228
+
229
+ # ── Helper: extract ODE rhs f(x,y) ───────────────────────
230
+ def get_ode_rhs():
231
+ # dy/dx = f(x,y) → extract rhs
232
+ m = re.search(r"dy/dx\s*=\s*(.+?)(?:\s*,|\s*with|\s*y\s*\(|$)", p)
233
+ return m.group(1).strip() if m else None
234
+
235
+ floats, x0_m, x1_m, ab_m = get_bounds()
236
+ n_iter = max(1, get_iters())
237
+
238
+ # ════════════════════════════════════════════════════════
239
+ # BISECTION METHOD
240
+ # ════════════════════════════════════════════════════════
241
+ if "bisection" in p:
242
+ expr_b = get_expr()
243
+ if expr_b is not None and ab_m:
244
+ a_val = float(ab_m.group(1))
245
+ b_val = float(ab_m.group(2))
246
+ f_b = sp.lambdify(x, expr_b, modules="math")
247
+ fa, fb = f_b(a_val), f_b(b_val)
248
+ if fa == 0:
249
+ return {"type": "Bisection", "result": f"Root = {a_val}", "latex": f"x = {a_val}"}
250
+ if fb == 0:
251
+ return {"type": "Bisection", "result": f"Root = {b_val}", "latex": f"x = {b_val}"}
252
+ if fa * fb > 0:
253
+ return {
254
+ "type": "Bisection",
255
+ "result": f"Cannot apply bisection: f({a_val}) and f({b_val}) have the same sign.",
256
+ "latex": "\\text{Invalid bracket}",
257
+ }
258
+ steps = []
259
+ a_n, b_n = a_val, b_val
260
+ for i in range(n_iter):
261
+ c = (a_n + b_n) / 2
262
+ fc = f_b(c)
263
+ steps.append({"iter": i+1, "a": round(a_n,8),
264
+ "b": round(b_n,8), "c": round(c,8),
265
+ "fc": round(fc,8)})
266
+ if f_b(a_n) * fc < 0: b_n = c
267
+ else: a_n = c
268
+ step_str = "\n".join([
269
+ f" Iter {s['iter']}: a={s['a']}, b={s['b']}, c={s['c']}, f(c)={s['fc']}"
270
+ for s in steps])
271
+ final_c = steps[-1]["c"]
272
+ return {
273
+ "type": "Bisection",
274
+ "result": (f"f(x) = {str(expr_b)}\n"
275
+ f"Interval [{a_val},{b_val}], {n_iter} iterations\n"
276
+ f"VERIFIED ITERATIONS:\n{step_str}\n"
277
+ f"Root ≈ {final_c}"),
278
+ "latex": f"x \\approx {final_c}"
279
+ }
280
+
281
+ # ════════════════════════════════════════════════════════
282
+ # SECANT METHOD
283
+ # ════════════════════════════════════════════════════════
284
+ elif "secant" in p:
285
+ expr_s = get_expr()
286
+ if expr_s is not None and x0_m and x1_m:
287
+ x0_v = float(x0_m.group(1))
288
+ x1_v = float(x1_m.group(1))
289
+ f_s = sp.lambdify(x, expr_s, modules="math")
290
+ steps = []
291
+ xp, xc = x0_v, x1_v
292
+ for i in range(n_iter):
293
+ fxp, fxc = f_s(xp), f_s(xc)
294
+ if abs(fxc - fxp) < 1e-15: break
295
+ xn_val = xc - fxc*(xc-xp)/(fxc-fxp)
296
+ steps.append({"iter": i+1, "x": round(xn_val, 8),
297
+ "fx": round(f_s(xn_val), 8)})
298
+ xp, xc = xc, xn_val
299
+ step_str = "\n".join([
300
+ f" Iter {s['iter']}: x={s['x']}, f(x)={s['fx']}"
301
+ for s in steps])
302
+ return {
303
+ "type": "Secant",
304
+ "result": (f"f(x) = {str(expr_s)}\n"
305
+ f"x0={x0_v}, x1={x1_v}, {n_iter} iterations\n"
306
+ f"VERIFIED ITERATIONS:\n{step_str}\n"
307
+ f"Root ≈ {steps[-1]['x']}"),
308
+ "latex": f"x \\approx {steps[-1]['x']}"
309
+ }
310
+
311
+ # ════════════════════════════════════════════════════════
312
+ # FALSE POSITION (Regula Falsi)
313
+ # ════════════════════════════════════════════════════════
314
+ elif any(k in p for k in ["false position", "regula falsi"]):
315
+ expr_fp = get_expr()
316
+ if expr_fp is not None and ab_m:
317
+ a_val = float(ab_m.group(1))
318
+ b_val = float(ab_m.group(2))
319
+ f_fp = sp.lambdify(x, expr_fp, modules="math")
320
+ steps = []
321
+ a_n, b_n = a_val, b_val
322
+ for i in range(n_iter):
323
+ fa, fb = f_fp(a_n), f_fp(b_n)
324
+ c = (a_n*fb - b_n*fa) / (fb - fa)
325
+ fc = f_fp(c)
326
+ steps.append({"iter": i+1, "a": round(a_n,8),
327
+ "b": round(b_n,8), "c": round(c,8),
328
+ "fc": round(fc,8)})
329
+ if fa * fc < 0: b_n = c
330
+ else: a_n = c
331
+ step_str = "\n".join([
332
+ f" Iter {s['iter']}: a={s['a']}, b={s['b']}, c={s['c']}, f(c)={s['fc']}"
333
+ for s in steps])
334
+ return {
335
+ "type": "FalsePosition",
336
+ "result": (f"f(x) = {str(expr_fp)}\n"
337
+ f"Interval [{a_val},{b_val}], {n_iter} iterations\n"
338
+ f"VERIFIED ITERATIONS:\n{step_str}\n"
339
+ f"Root ≈ {steps[-1]['c']}"),
340
+ "latex": f"x \\approx {steps[-1]['c']}"
341
+ }
342
+
343
+ # ════════════════════════════════════════════════════════
344
+ # GAUSS ELIMINATION
345
+ # ════════════════════════════════════════════════════════
346
+ elif any(k in p for k in ["gauss elimination", "gauss elim"]):
347
+ # Extract matrix from problem — look for [[...]] pattern
348
+ mat_m = re.search(r"\[\s*\[(.+?)\]\s*\]", p)
349
+ rhs_m = re.search(r"(?:rhs|=|b)\s*[=:]?\s*\[([^\]]+)\]", p)
350
+ if mat_m and rhs_m:
351
+ rows = re.findall(r"\[([^\]]+)\]", p)
352
+ mat_data = [[sp.Rational(v) for v in re.split(r"[,\s]+", r.strip()) if v]
353
+ for r in rows[:-1]]
354
+ rhs_data = [sp.Rational(v) for v in re.split(r"[,\s]+", rows[-1].strip()) if v]
355
+ A = sp.Matrix(mat_data)
356
+ b_vec = sp.Matrix(rhs_data)
357
+ sol = A.solve(b_vec)
358
+ sol_str = ", ".join([f"x{i+1}={sol[i]}" for i in range(len(sol))])
359
+ return {
360
+ "type": "GaussElimination",
361
+ "result": f"VERIFIED SOLUTION: {sol_str}",
362
+ "latex": sol_str
363
+ }
364
+
365
+ # ════════════════════════════════════════════════════════
366
+ # LU DECOMPOSITION
367
+ # ════════════════════════════════════════════════════════
368
+ elif any(k in p for k in ["lu decomposition", "lu decomp"]):
369
+ rows = re.findall(r"\[([^\]]+)\]", p)
370
+ if rows:
371
+ mat_data = [[sp.Rational(v) for v in re.split(r"[,\s]+", r.strip()) if v]
372
+ for r in rows]
373
+ M = sp.Matrix(mat_data)
374
+ L, U, _ = M.LUdecomposition()
375
+ return {
376
+ "type": "LUDecomposition",
377
+ "result": (f"VERIFIED:\nL = {str(L)}\nU = {str(U)}"),
378
+ "latex": f"L={sp.latex(L)}, U={sp.latex(U)}"
379
+ }
380
+
381
+ # ════════════════════════════════════════════════════════
382
+ # LAGRANGE INTERPOLATION
383
+ # ════════════════════════════════════════════════════════
384
+ elif any(k in p for k in ["lagrange interpolation", "lagrange interp"]):
385
+ # Extract data points (x0,y0),(x1,y1),...
386
+ pts = re.findall(r"\(\s*([-\d\.]+)\s*,\s*([-\d\.]+)\s*\)", p)
387
+ if pts:
388
+ data = [(sp.Rational(px), sp.Rational(py)) for px, py in pts]
389
+ poly = sp.interpolate(data, x)
390
+ poly_exp = sp.expand(poly)
391
+ return {
392
+ "type": "LagrangeInterpolation",
393
+ "result": f"VERIFIED polynomial: {str(poly_exp)}",
394
+ "latex": sp.latex(poly_exp)
395
+ }
396
+
397
+ # ════════════════════════════════════════════════════════
398
+ # NEWTON DIVIDED DIFFERENCE
399
+ # ════════════════════════════════════════════════════════
400
+ elif any(k in p for k in ["newton divided", "divided difference"]):
401
+ pts = re.findall(r"\(\s*([-\d\.]+)\s*,\s*([-\d\.]+)\s*\)", p)
402
+ if pts:
403
+ xs_v = [float(px) for px, py in pts]
404
+ ys_v = [float(py) for px, py in pts]
405
+ n_p = len(xs_v)
406
+ dd = [[0.0]*n_p for _ in range(n_p)]
407
+ for i in range(n_p): dd[i][0] = ys_v[i]
408
+ for j in range(1, n_p):
409
+ for i in range(n_p - j):
410
+ dd[i][j] = (dd[i+1][j-1]-dd[i][j-1])/(xs_v[i+j]-xs_v[i])
411
+ coeffs = [round(dd[0][j], 8) for j in range(n_p)]
412
+ # Build polynomial
413
+ poly_s = sp.interpolate(list(zip(xs_v, ys_v)), x)
414
+ return {
415
+ "type": "NewtonDividedDiff",
416
+ "result": (f"VERIFIED divided differences: {coeffs}\n"
417
+ f"Polynomial: {str(sp.expand(poly_s))}"),
418
+ "latex": sp.latex(sp.expand(poly_s))
419
+ }
420
+
421
+ # ════════════════════════════════════════════════════════
422
+ # TRAPEZOIDAL RULE
423
+ # ════════════════════════════════════════════════════════
424
+ elif any(k in p for k in ["trapezoidal", "trapezoid rule"]):
425
+ expr_t = get_expr()
426
+ ab_m2 = re.search(r"\[\s*([-\d\.]+)\s*,\s*([-\d\.]+)\s*\]", p)
427
+ n_m = re.search(r"n\s*[=:]\s*(\d+)", p)
428
+ if expr_t is not None and ab_m2 and n_m:
429
+ a_v = float(ab_m2.group(1))
430
+ b_v = float(ab_m2.group(2))
431
+ n_v = int(n_m.group(1))
432
+ f_t = sp.lambdify(x, expr_t, modules="math")
433
+ h = (b_v - a_v) / n_v
434
+ s = f_t(a_v) + f_t(b_v)
435
+ pts_str = [f"f({round(a_v,4)})={round(f_t(a_v),6)}", ]
436
+ for i in range(1, n_v):
437
+ xi = a_v + i*h
438
+ pts_str.append(f"f({round(xi,4)})={round(f_t(xi),6)}")
439
+ pts_str.append(f"f({round(b_v,4)})={round(f_t(b_v),6)}")
440
+ result_val = round(h/2 * (f_t(a_v)+f_t(b_v) + 2*sum(f_t(a_v+i*h) for i in range(1,n_v))), 8)
441
+ return {
442
+ "type": "Trapezoidal",
443
+ "result": (f"f(x)={str(expr_t)}, [{a_v},{b_v}], n={n_v}, h={round(h,6)}\n"
444
+ f"Function values: {', '.join(pts_str)}\n"
445
+ f"VERIFIED result: {result_val}"),
446
+ "latex": f"\\int_{{{a_v}}}^{{{b_v}}} \\approx {result_val}"
447
+ }
448
+
449
+ # ════════════════════════════════════════════════════════
450
+ # SIMPSON'S 1/3 RULE
451
+ # ════════════════════════════════════════════════════════
452
+ elif any(k in p for k in ["simpson"]):
453
+ expr_si = get_expr()
454
+ ab_m3 = re.search(r"\[\s*([-\d\.]+)\s*,\s*([-\d\.]+)\s*\]", p)
455
+ n_m2 = re.search(r"n\s*[=:]\s*(\d+)", p)
456
+ if expr_si is not None and ab_m3 and n_m2:
457
+ a_v = float(ab_m3.group(1))
458
+ b_v = float(ab_m3.group(2))
459
+ n_v = int(n_m2.group(1))
460
+ if n_v % 2 != 0: n_v += 1 # must be even
461
+ f_si = sp.lambdify(x, expr_si, modules="math")
462
+ h = (b_v - a_v) / n_v
463
+ s = f_si(a_v) + f_si(b_v)
464
+ for i in range(1, n_v):
465
+ s += (4 if i % 2 != 0 else 2) * f_si(a_v + i*h)
466
+ result_val = round(h/3 * s, 8)
467
+ return {
468
+ "type": "Simpsons",
469
+ "result": (f"f(x)={str(expr_si)}, [{a_v},{b_v}], n={n_v}, h={round(h,6)}\n"
470
+ f"VERIFIED result: {result_val}"),
471
+ "latex": f"\\int_{{{a_v}}}^{{{b_v}}} \\approx {result_val}"
472
+ }
473
+
474
+ # ════════════════════════════════════════════════════════
475
+ # EULER'S METHOD
476
+ # ════════════════════════════════════════════════════════
477
+ elif any(k in p for k in ["euler method", "euler's method"]):
478
+ rhs_str = get_ode_rhs()
479
+ x0_em = re.search(r"x\s*0?\s*[=:]\s*([-\d\.]+)", p)
480
+ y0_em = re.search(r"y\s*[=\(]\s*0?\s*\)?\s*[=:]\s*([-\d\.]+)", p)
481
+ h_val = get_h()
482
+ n_steps = get_iters(default=5)
483
+ if rhs_str and x0_em and y0_em:
484
+ x_s, y_s = sp.symbols('x y')
485
+ rhs_expr_ode = parse_expr(clean(rhs_str), transformations=tfms,
486
+ local_dict={**ld, "y": y_s})
487
+ f_ode = sp.lambdify((x_s, y_s), rhs_expr_ode, modules="math")
488
+ xn_e, yn_e = float(x0_em.group(1)), float(y0_em.group(1))
489
+ steps = []
490
+ for i in range(n_steps):
491
+ yn1 = yn_e + h_val * f_ode(xn_e, yn_e)
492
+ xn_e += h_val
493
+ steps.append({"n": i+1, "x": round(xn_e,6), "y": round(yn1,8)})
494
+ yn_e = yn1
495
+ step_str = "\n".join([f" Step {s['n']}: x={s['x']}, y={s['y']}" for s in steps])
496
+ final_y_e = steps[-1]['y']
497
+ return {
498
+ "type": "EulersMethod",
499
+ "result": (f"dy/dx = {rhs_str}, h={h_val}, {n_steps} steps\n"
500
+ f"VERIFIED ITERATIONS (USE THESE EXACT VALUES):\n{step_str}\n"
501
+ f"FINAL ANSWER: y({steps[-1]['x']}) = {final_y_e} — USE THIS EXACTLY"),
502
+ "latex": f"y_{{{n_steps}}} = {final_y_e}"
503
+ }
504
+
505
+ # ════════════════════════════════════════════════════════
506
+ # RUNGE-KUTTA RK4
507
+ # ════════════════════════════════════════════════════════
508
+ elif any(k in p for k in ["runge-kutta", "runge kutta", "rk4"]):
509
+ rhs_str = get_ode_rhs()
510
+ x0_rk = re.search(r"x\s*0?\s*[=:]\s*([-\d\.]+)", p)
511
+ y0_rk = re.search(r"y\s*[=\(]\s*0?\s*\)?\s*[=:]\s*([-\d\.]+)", p)
512
+ h_val = get_h()
513
+ n_steps = get_iters(default=3)
514
+ if rhs_str and x0_rk and y0_rk:
515
+ x_s, y_s = sp.symbols('x y')
516
+ rhs_expr_rk = parse_expr(clean(rhs_str), transformations=tfms,
517
+ local_dict={**ld, "y": y_s})
518
+ f_rk = sp.lambdify((x_s, y_s), rhs_expr_rk, modules="math")
519
+ xn_r, yn_r = float(x0_rk.group(1)), float(y0_rk.group(1))
520
+ steps = []
521
+ for i in range(n_steps):
522
+ k1 = h_val * f_rk(xn_r, yn_r)
523
+ k2 = h_val * f_rk(xn_r+h_val/2, yn_r+k1/2)
524
+ k3 = h_val * f_rk(xn_r+h_val/2, yn_r+k2/2)
525
+ k4 = h_val * f_rk(xn_r+h_val, yn_r+k3)
526
+ yn1 = yn_r + (k1+2*k2+2*k3+k4)/6
527
+ xn_r += h_val
528
+ steps.append({"n": i+1, "x": round(xn_r,6),
529
+ "k1": round(k1,8), "k2": round(k2,8),
530
+ "k3": round(k3,8), "k4": round(k4,8),
531
+ "y": round(yn1,8)})
532
+ yn_r = yn1
533
+ step_str = "\n".join([
534
+ f" Step {s['n']}: x={s['x']}, k1={s['k1']}, k2={s['k2']}, k3={s['k3']}, k4={s['k4']}, y={s['y']}"
535
+ for s in steps])
536
+ final_y = steps[-1]['y']
537
+ return {
538
+ "type": "RungeKutta4",
539
+ "result": (f"dy/dx={rhs_str}, h={h_val}, {n_steps} steps\n"
540
+ f"VERIFIED ITERATIONS (USE THESE EXACT k VALUES):\n{step_str}\n"
541
+ f"FINAL ANSWER: y({round(xn_r,4)}) = {final_y} — USE THIS EXACTLY"),
542
+ "latex": f"y_{{{n_steps}}} = {final_y}"
543
+ }
544
+
545
+ # ── 7. Theory of Numbers — SymPy computes exactly ───────────────
546
+ elif any(k in p for k in [
547
+ "gcd", "greatest common divisor", "hcf",
548
+ "lcm", "least common multiple",
549
+ "prime factor", "factoriz", "factori",
550
+ "is prime", "isprime", "prime or not", "check prime",
551
+ "totient", "euler's totient",
552
+ "number of divisor", "sum of divisor", "divisors of",
553
+ "mobius", "möbius",
554
+ "diophantine",
555
+ "chinese remainder", "crt",
556
+ "fermat", "wilson",
557
+ "quadratic residu", "legendre",
558
+ "primitive root",
559
+ "linear congruence", "congruence", "≡",
560
+ "euler's theorem", "euler theorem",
561
+ ]) or re.search(r'\bis\s+\d+\s+prime\b', p):
562
+ import math as _math
563
+
564
+ def _nums(text):
565
+ return [int(n) for n in re.findall(r'\b\d+\b', text)]
566
+
567
+ x_d, y_d = sp.symbols('x y')
568
+
569
+ try:
570
+ # ── GCD (Extended Euclidean) ──────────────────────────────
571
+ if any(k in p for k in ["gcd","greatest common divisor","hcf"]):
572
+ nums = _nums(p)
573
+ if len(nums) >= 2:
574
+ a,b = nums[0],nums[1]
575
+ g = int(sp.gcd(a,b))
576
+ # Extended Euclidean
577
+ old_r,r = a,b; old_s,s = 1,0; old_t,t2 = 0,1
578
+ while r:
579
+ q=old_r//r; old_r,r=r,old_r-q*r
580
+ old_s,s=s,old_s-q*s; old_t,t2=t2,old_t-q*t2
581
+ result_str = (f"gcd({a},{b}) = {old_r}\n"
582
+ f"Extended Euclidean: {a}×({old_s}) + {b}×({old_t}) = {old_r}\n"
583
+ f"Verify: {a*old_s + b*old_t} = {old_r} ✅")
584
+ return {"type":"GCD","result":result_str,
585
+ "latex":f"\\gcd({a},{b})={old_r}"}
586
+
587
+ # ── LCM ───────────────────────────────────────────────────
588
+ elif any(k in p for k in ["lcm","least common multiple"]):
589
+ nums = _nums(p)
590
+ if len(nums) >= 2:
591
+ l = int(sp.lcm(nums[0],nums[1]))
592
+ g = int(sp.gcd(nums[0],nums[1]))
593
+ return {"type":"LCM",
594
+ "result":f"lcm({nums[0]},{nums[1]}) = {l}, gcd = {g}",
595
+ "latex":f"\\text{{lcm}}({nums[0]},{nums[1]})={l}"}
596
+
597
+ # ── PRIME FACTORIZATION ───────────────────────────────────
598
+ elif any(k in p for k in ["prime factor","factoriz","factori"]):
599
+ nums = _nums(p)
600
+ if nums:
601
+ f_dict = sp.factorint(nums[0])
602
+ f_str = " × ".join([f"{pp}^{e}" if e>1 else str(pp) for pp,e in f_dict.items()])
603
+ return {"type":"PrimeFactorization",
604
+ "result":f"{nums[0]} = {f_str}",
605
+ "latex":f"{nums[0]} = {f_str}"}
606
+
607
+ # ── IS PRIME ──────────────────────────────────────────────
608
+ elif any(k in p for k in ["is prime","isprime","prime or not","check prime"]) or re.search(r'\bis\s+\d+\s+prime\b',p):
609
+ nums = _nums(p)
610
+ if nums:
611
+ n_val = nums[0]
612
+ is_p = sp.isprime(n_val)
613
+ ans = "PRIME" if is_p else "COMPOSITE (NOT PRIME)"
614
+ return {"type":"PrimeCheck",
615
+ "result":f"{n_val} is {ans}",
616
+ "latex":f"{n_val}\\text{{ is }}{ans}"}
617
+
618
+ # ── EULER TOTIENT ─────────────────────────────────────────
619
+ elif any(k in p for k in ["totient","euler's totient"]):
620
+ nums = _nums(p)
621
+ if nums:
622
+ phi = int(sp.totient(nums[0]))
623
+ f_dict = sp.factorint(nums[0])
624
+ return {"type":"EulerTotient",
625
+ "result":f"φ({nums[0]}) = {phi}, factorization = {f_dict}",
626
+ "latex":f"\\phi({nums[0]})={phi}"}
627
+
628
+ # ── DIVISOR FUNCTIONS τ, σ ────────────────────────────────
629
+ elif any(k in p for k in ["number of divisor","sum of divisor","divisors of","tau","sigma"]):
630
+ nums = _nums(p)
631
+ if nums:
632
+ divs = sp.divisors(nums[0])
633
+ return {"type":"DivisorFunctions",
634
+ "result":f"divisors({nums[0]}) = {divs}, τ = {len(divs)}, σ = {sum(divs)}",
635
+ "latex":f"\\tau({nums[0]})={len(divs)}, \\sigma({nums[0]})={sum(divs)}"}
636
+
637
+ # ── MOBIUS FUNCTION ───────────────────────────────────────
638
+ elif any(k in p for k in ["mobius","möbius"]):
639
+ nums = _nums(p)
640
+ if nums:
641
+ mu = sp.mobius(nums[0])
642
+ return {"type":"Mobius",
643
+ "result":f"μ({nums[0]}) = {mu}",
644
+ "latex":f"\\mu({nums[0]})={mu}"}
645
+
646
+ # ── DIOPHANTINE EQUATION ──────────────────────────────────
647
+ elif "diophantine" in p:
648
+ m = re.search(r"(\d+)\s*x\s*[+\-]\s*(\d+)\s*y\s*=\s*(\d+)",p)
649
+ if m:
650
+ a_d,b_d,c_d = int(m.group(1)),int(m.group(2)),int(m.group(3))
651
+ g = int(sp.gcd(a_d,b_d))
652
+ if c_d%g == 0:
653
+ sol = sp.diophantine(sp.Eq(a_d*x_d+b_d*y_d, c_d))
654
+ return {"type":"Diophantine",
655
+ "result":f"{a_d}x+{b_d}y={c_d}: general solution={sol}, gcd={g}",
656
+ "latex":str(sol)}
657
+ else:
658
+ return {"type":"Diophantine",
659
+ "result":f"No integer solution: gcd({a_d},{b_d})={g} does not divide {c_d}",
660
+ "latex":"\\text{No solution}"}
661
+
662
+ # ── CRT — MUST be before congruence ───────────────────────
663
+ elif any(k in p for k in ["chinese remainder","crt"]):
664
+ pairs = re.findall(r'x\s*[≡=]\s*(\d+)\s*(?:mod|modulo|\(mod)\s*(\d+)',p)
665
+ if len(pairs) >= 2:
666
+ remainders = [int(r) for r,m in pairs]
667
+ moduli = [int(m) for r,m in pairs]
668
+ sol = sp.ntheory.modular.crt(moduli, remainders)
669
+ verify = [f"{sol[0]}%{m}={sol[0]%m}" for m in moduli]
670
+ return {"type":"CRT",
671
+ "result":f"x ≡ {sol[0]} (mod {sol[1]}), verify: {verify}",
672
+ "latex":f"x\\equiv {sol[0]}\\pmod{{{sol[1]}}}"}
673
+
674
+ # ── FERMAT'S LITTLE THEOREM ───────────────────────────────
675
+ elif "fermat" in p:
676
+ nums = _nums(p)
677
+ if len(nums) >= 2:
678
+ a_f,p_f = nums[0],nums[1]
679
+ if sp.isprime(p_f):
680
+ r = pow(a_f,p_f-1,p_f)
681
+ return {"type":"FermatTheorem",
682
+ "result":f"{a_f}^({p_f}-1) mod {p_f} = {r} ≡ 1 (mod {p_f})",
683
+ "latex":f"{a_f}^{{{p_f-1}}}\\equiv 1\\pmod{{{p_f}}}"}
684
+
685
+ # ── EULER'S THEOREM ───────────────────────────────────────
686
+ elif "euler" in p and ("theorem" in p or "theorem" in p):
687
+ nums = _nums(p)
688
+ if len(nums) >= 2:
689
+ a_e,n_e = nums[0],nums[1]
690
+ phi = int(sp.totient(n_e))
691
+ r = pow(a_e,phi,n_e)
692
+ return {"type":"EulerTheorem",
693
+ "result":f"φ({n_e})={phi}, {a_e}^{phi} mod {n_e} = {r} ≡ 1 (mod {n_e})",
694
+ "latex":f"{a_e}^{{\\phi({n_e})}}\\equiv 1\\pmod{{{n_e}}}"}
695
+
696
+ # ── WILSON'S THEOREM ──────────────────────────────────────
697
+ elif "wilson" in p:
698
+ nums = _nums(p)
699
+ if nums:
700
+ p_w = nums[0]
701
+ val = _math.factorial(p_w-1)%p_w
702
+ return {"type":"WilsonTheorem",
703
+ "result":f"({p_w}-1)! mod {p_w} = {val} ≡ -1 (mod {p_w})",
704
+ "latex":f"({p_w}-1)!\\equiv -1\\pmod{{{p_w}}}"}
705
+
706
+ # ── LINEAR CONGRUENCE ─────────────────────────────────────
707
+ elif any(k in p for k in ["congruence","linear congruence"]) or re.search(r'\d+\s*x\s*[≡=]',p):
708
+ m = re.search(r"(\d+)\s*x\s*[≡=]\s*(\d+)\s*(?:\(mod|mod|modulo)\s*(\d+)",p)
709
+ if m:
710
+ a_c,b_c,n_c = int(m.group(1)),int(m.group(2)),int(m.group(3))
711
+ g = int(sp.gcd(a_c,n_c))
712
+ if b_c%g != 0:
713
+ return {"type":"LinearCongruence",
714
+ "result":f"No solution: gcd({a_c},{n_c})={g} ∤ {b_c}",
715
+ "latex":"\\text{No solution}"}
716
+ sols = [i for i in range(n_c) if (a_c*i)%n_c==b_c%n_c]
717
+ return {"type":"LinearCongruence",
718
+ "result":f"{a_c}x ≡ {b_c} (mod {n_c}): x ≡ {sols} (mod {n_c}), {g} solution(s)",
719
+ "latex":f"x\\equiv {sols[0]}\\pmod{{{n_c//g}}}"}
720
+
721
+ # ── QUADRATIC RESIDUES ────────────────────────────────────
722
+ elif any(k in p for k in ["quadratic residu","quadratic non"]):
723
+ nums = _nums(p)
724
+ if nums:
725
+ p_q = nums[0]
726
+ qr = sorted(set([pow(i,2,p_q) for i in range(1,p_q)]))
727
+ qnr = [i for i in range(1,p_q) if i not in qr]
728
+ return {"type":"QuadraticResidues",
729
+ "result":f"QR mod {p_q} = {qr}, QNR mod {p_q} = {qnr}",
730
+ "latex":f"QR\\pmod{{{p_q}}}={qr}"}
731
+
732
+ # ── LEGENDRE SYMBOL ───────────────────────────────────────
733
+ elif "legendre" in p:
734
+ m = re.search(r"\(\s*(\d+)\s*/\s*(\d+)\s*\)",p)
735
+ if m:
736
+ a_l,p_l = int(m.group(1)),int(m.group(2))
737
+ val = 1 if pow(a_l,(p_l-1)//2,p_l)==1 else (-1 if a_l%p_l!=0 else 0)
738
+ meaning = "QR (quadratic residue)" if val==1 else ("QNR (non-residue)" if val==-1 else "0 (divisible)")
739
+ return {"type":"LegendreSymbol",
740
+ "result":f"({a_l}/{p_l}) = {val} → {a_l} is {meaning} mod {p_l}",
741
+ "latex":f"\\left(\\frac{{{a_l}}}{{{p_l}}}\\right)={val}"}
742
+
743
+ # ── PRIMITIVE ROOT ────────────────────────────────────────
744
+ elif "primitive root" in p:
745
+ nums = _nums(p)
746
+ if nums:
747
+ pr = sp.ntheory.primitive_root(nums[0])
748
+ return {"type":"PrimitiveRoot",
749
+ "result":f"primitive_root({nums[0]}) = {pr}",
750
+ "latex":f"g={pr}"}
751
+
752
+ except Exception:
753
+ pass # safe fallback to AI
754
+
755
+ # ── 7. Solve equation ────────────────────────────────────────
756
+ elif any(k in p for k in ["solve", "roots", "find x"]):
757
+ raw = re.sub(r"(solve|find x|roots of|roots|the equation)", "", p)
758
+ raw = raw.strip().strip(":").strip()
759
+ if "=" in raw:
760
+ lhs_s, rhs_s = raw.split("=", 1)
761
+ lhs_e = parse_expr(clean(lhs_s), transformations=tfms, local_dict=ld)
762
+ rhs_e = parse_expr(clean(rhs_s), transformations=tfms, local_dict=ld)
763
+ expr = lhs_e - rhs_e
764
+ else:
765
+ expr = parse_expr(clean(raw), transformations=tfms, local_dict=ld)
766
+ if x in expr.free_symbols:
767
+ sol = sp.solve(expr, x)
768
+ sol_latex = ", ".join([sp.latex(s) for s in sol])
769
+ return {
770
+ "type": "Equation",
771
+ "result": str(sol),
772
+ "latex": r"x \in \{" + sol_latex + r"\}"
773
+ }
774
+
775
+ # ── 8. Real Analysis II — SymPy for computations, AI for theory ──
776
+ elif any(k in p for k in [
777
+ # Sets & Real Numbers
778
+ "supremum", "infimum", "least upper bound", "greatest lower bound",
779
+ "lub", "glb", "archimedean", "bounded set", "completeness",
780
+ "cartesian product", "density of rational", "real number system",
781
+ "field propert", "order propert",
782
+ # Sequences
783
+ "sequence", "cauchy sequence", "bounded sequence",
784
+ "monotone sequence", "subsequence", "bolzano", "weierstrass",
785
+ # Series
786
+ "ratio test", "root test", "integral test", "comparison test",
787
+ "alternating series", "leibniz test", "absolute convergence",
788
+ "conditional convergence", "cauchy criterion",
789
+ "pointwise convergence", "uniform convergence",
790
+ "weierstrass m-test", "m-test",
791
+ # Limits & Continuity
792
+ "epsilon delta", "epsilon-delta", "uniform continuity",
793
+ "intermediate value", "extreme value theorem",
794
+ # Differentiation theorems
795
+ "mean value theorem", "rolle", "taylor's theorem",
796
+ "lhopital", "l'hopital",
797
+ # Riemann Integration
798
+ "riemann sum", "riemann integral", "upper sum", "lower sum",
799
+ "darboux", "integrability", "fundamental theorem of calculus",
800
+ ]):
801
+ try:
802
+ n_s = sp.Symbol('n', positive=True)
803
+
804
+ # ── Sequence limit ────────────────────────────────────────
805
+ if any(k in p for k in ["sequence","limit of sequence"]):
806
+ # Extract expression after "of" or "for"
807
+ m = re.search(r"(?:of|for|lim)\s+(.+?)\s*(?:as|when|$)", p)
808
+ if m:
809
+ raw = clean(m.group(1))
810
+ try:
811
+ expr_s = parse_expr(raw, transformations=tfms,
812
+ local_dict={**ld, "n": n_s})
813
+ lim_val = sp.limit(expr_s, n_s, sp.oo)
814
+ return {
815
+ "type": "SequenceLimit",
816
+ "result": f"lim({m.group(1)}) as n→∞ = {lim_val}",
817
+ "latex": f"\\lim_{{n\\to\\infty}} = {sp.latex(lim_val)}"
818
+ }
819
+ except Exception:
820
+ pass
821
+
822
+ # ── Series sum ────────────────────────────────────────────
823
+ elif any(k in p for k in ["series","sum of"]):
824
+ m = re.search(r"(?:sum\s+of|series\s+(?:of\s+)?|convergence\s+of)\s*(.+?)(?:\s+from|\s+using|\s+by|$)", p)
825
+ if m:
826
+ raw = m.group(1).strip()
827
+ raw = re.sub(r"^series\s+sum\s+of\s+", "", raw)
828
+ raw = re.sub(r"^series\s+of\s+", "", raw)
829
+ raw = re.sub(r"^sum\s+of\s+", "", raw)
830
+ raw = re.sub(r"^of\s+", "", raw)
831
+ raw = clean(raw)
832
+ try:
833
+ expr_ser = parse_expr(raw, transformations=tfms,
834
+ local_dict={**ld, "n": n_s})
835
+ s_val = sp.summation(expr_ser, (n_s, 1, sp.oo))
836
+ converges = s_val.is_finite
837
+ return {
838
+ "type": "SeriesConvergence",
839
+ "result": (f"Series sum = {s_val}, "
840
+ f"Converges: {converges}"),
841
+ "latex": f"\\sum_{{n=1}}^{{\\infty}} = {sp.latex(s_val)}"
842
+ }
843
+ except Exception:
844
+ pass
845
+
846
+ # ── Taylor Series ─────────────────────────────────────────
847
+ elif any(k in p for k in ["taylor", "maclaurin"]):
848
+ funcs = {
849
+ "sin": sp.sin(x), "cos": sp.cos(x),
850
+ "exp": sp.exp(x), "e^x": sp.exp(x),
851
+ "ln": sp.log(1+x), "log": sp.log(1+x),
852
+ "tan": sp.tan(x)
853
+ }
854
+ for fname, fexpr in funcs.items():
855
+ if fname in p:
856
+ n_terms = 6
857
+ ts = sp.series(fexpr, x, 0, n_terms)
858
+ return {
859
+ "type": "TaylorSeries",
860
+ "result": f"Taylor series of {fname}: {ts}",
861
+ "latex": sp.latex(ts)
862
+ }
863
+
864
+ # ── L'Hopital ──────────────────────────────────��──────────
865
+ elif any(k in p for k in ["lhopital","l'hopital"]):
866
+ m = re.search(r"(?:of|for)\s+(.+?)\s*(?:as|at|when)\s*x\s*[→→=]\s*([\d\.]+|inf)", p)
867
+ if m:
868
+ raw = clean(m.group(1))
869
+ pt_str = m.group(2)
870
+ pt = sp.oo if pt_str in ("inf","infinity") else sp.sympify(pt_str)
871
+ try:
872
+ expr_lh = parse_expr(raw, transformations=tfms, local_dict=ld)
873
+ lim_val = sp.limit(expr_lh, x, pt)
874
+ return {
875
+ "type": "LHopital",
876
+ "result": f"lim({m.group(1)}) as x→{pt_str} = {lim_val}",
877
+ "latex": f"\\lim_{{x\\to {pt_str}}} = {sp.latex(lim_val)}"
878
+ }
879
+ except Exception:
880
+ pass
881
+
882
+ # ── Riemann Integral ──────────────────────────────────────
883
+ elif any(k in p for k in ["riemann","riemann integral","riemann sum"]):
884
+ # Try to extract definite integral
885
+ m = re.search(r"(?:of|for)\s+(.+?)\s+(?:from|on)\s+([\d\.]+)\s+to\s+([\d\.]+)", p)
886
+ if m:
887
+ raw = clean(m.group(1))
888
+ a_v = sp.sympify(m.group(2))
889
+ b_v = sp.sympify(m.group(3))
890
+ try:
891
+ expr_r = parse_expr(raw, transformations=tfms, local_dict=ld)
892
+ result_r = sp.integrate(expr_r, (x, a_v, b_v))
893
+ return {
894
+ "type": "RiemannIntegral",
895
+ "result": f"∫({m.group(1)}) from {a_v} to {b_v} = {result_r}",
896
+ "latex": f"\\int_{{{a_v}}}^{{{b_v}}} = {sp.latex(result_r)}"
897
+ }
898
+ except Exception:
899
+ pass
900
+
901
+ except Exception:
902
+ pass # safe fallback to AI for all theory/proof questions
903
+
904
+ # ── 9. Differential Geometry — SymPy for computations ──────────
905
+ elif any(k in p for k in [
906
+ "curvature", "torsion", "tangent vector", "normal vector",
907
+ "binormal", "serret-frenet", "frenet", "osculating",
908
+ "arc length", "space curve", "plane curve", "helix", "helices",
909
+ "evolute", "involute", "rectifying plane",
910
+ "first fundamental form", "second fundamental form",
911
+ "fundamental form", "gaussian curvature", "mean curvature",
912
+ "principal curvature", "geodesic",
913
+ "parametric surface", "christoffel", "covariant derivative",
914
+ "contravariant", "metric tensor",
915
+ ]):
916
+ t_s = sp.Symbol('t')
917
+ u_s, v_s = sp.symbols('u v')
918
+ try:
919
+
920
+ # ── Curvature of plane curve y=f(x) ──────────────────────
921
+ if "curvature" in p and not any(k in p for k in ["gaussian","mean","space","torsion"]):
922
+ # Extract function and point
923
+ m = re.search(r"(?:of|for)\s+y\s*=\s*(.+?)(?:\s+at|\s*$)", p)
924
+ pt_m = re.search(r"at\s+x\s*[=:]\s*([-\d\.]+)", p)
925
+ if m:
926
+ raw = clean(m.group(1).strip())
927
+ expr_c = parse_expr(raw, transformations=tfms, local_dict=ld)
928
+ dy = sp.diff(expr_c, x)
929
+ d2y = sp.diff(expr_c, x, 2)
930
+ kappa_expr = sp.Abs(d2y) / (1 + dy**2)**sp.Rational(3,2)
931
+ if pt_m:
932
+ pt_val = float(pt_m.group(1))
933
+ kappa_val = sp.simplify(kappa_expr.subs(x, pt_val))
934
+ return {
935
+ "type": "Curvature",
936
+ "result": f"κ at x={pt_val}: y'={dy.subs(x,pt_val)}, y''={d2y.subs(x,pt_val)}, κ={kappa_val}",
937
+ "latex": f"\\kappa = {sp.latex(kappa_val)}"
938
+ }
939
+ else:
940
+ return {
941
+ "type": "Curvature",
942
+ "result": f"κ(x) = {sp.simplify(kappa_expr)}",
943
+ "latex": f"\\kappa = {sp.latex(sp.simplify(kappa_expr))}"
944
+ }
945
+
946
+ # ── Arc Length ────────────────────────────────────────────
947
+ elif "arc length" in p:
948
+ m = re.search(r"(?:of|for)\s+y\s*=\s*(.+?)\s+from\s+([-\d\.]+)\s+to\s+([-\d\.]+)", p)
949
+ if m:
950
+ raw = clean(m.group(1).strip())
951
+ a_v = sp.sympify(m.group(2))
952
+ b_v = sp.sympify(m.group(3))
953
+ expr_al = parse_expr(raw, transformations=tfms, local_dict=ld)
954
+ dy = sp.diff(expr_al, x)
955
+ integrand = sp.sqrt(1 + dy**2)
956
+ L = sp.integrate(integrand, (x, a_v, b_v))
957
+ L_simplified = sp.simplify(L)
958
+ return {
959
+ "type": "ArcLength",
960
+ "result": f"L = ∫√(1+y'²)dx from {a_v} to {b_v} = {L_simplified}",
961
+ "latex": f"L = {sp.latex(L_simplified)}"
962
+ }
963
+
964
+ # ── Space Curve: Curvature + Torsion ─────────────────────
965
+ elif any(k in p for k in ["space curve","torsion","frenet","serret"]):
966
+ # Extract parametric curve r(t) = (x(t), y(t), z(t))
967
+ pts = re.findall(r"\(\s*(.+?)\s*,\s*(.+?)\s*,\s*(.+?)\s*\)", p)
968
+ pt_m = re.search(r"at\s+t\s*[=:]\s*([-\d\.]+)", p)
969
+ if pts:
970
+ rx = parse_expr(clean(pts[0][0]), transformations=tfms, local_dict={**ld, "t": t_s})
971
+ ry = parse_expr(clean(pts[0][1]), transformations=tfms, local_dict={**ld, "t": t_s})
972
+ rz = parse_expr(clean(pts[0][2]), transformations=tfms, local_dict={**ld, "t": t_s})
973
+ r_vec = sp.Matrix([rx, ry, rz])
974
+ dr = r_vec.diff(t_s)
975
+ d2r = dr.diff(t_s)
976
+ d3r = d2r.diff(t_s)
977
+ speed = sp.sqrt(dr.dot(dr))
978
+ cross = dr.cross(d2r)
979
+ kappa = sp.simplify(sp.sqrt(cross.dot(cross)) / speed**3)
980
+ torsion_val = sp.simplify(cross.dot(d3r) / cross.dot(cross))
981
+ t_val = float(pt_m.group(1)) if pt_m else 0
982
+ k_at = sp.simplify(kappa.subs(t_s, t_val))
983
+ tau_at = sp.simplify(torsion_val.subs(t_s, t_val))
984
+ T_vec = sp.simplify(dr / speed)
985
+ return {
986
+ "type": "FrenetSerret",
987
+ "result": (f"r(t)={pts[0]}, at t={t_val}:\n"
988
+ f"κ = {k_at}, τ = {tau_at}\n"
989
+ f"T = {T_vec.subs(t_s,t_val).T}"),
990
+ "latex": f"\\kappa={sp.latex(k_at)}, \\tau={sp.latex(tau_at)}"
991
+ }
992
+
993
+ # ── First Fundamental Form ────────────────────────────────
994
+ elif "first fundamental form" in p:
995
+ pts = re.findall(r"\(\s*(.+?)\s*,\s*(.+?)\s*,\s*(.+?)\s*\)", p)
996
+ if pts:
997
+ rx = parse_expr(clean(pts[0][0]), transformations=tfms, local_dict={**ld, "u": u_s, "v": v_s})
998
+ ry = parse_expr(clean(pts[0][1]), transformations=tfms, local_dict={**ld, "u": u_s, "v": v_s})
999
+ rz = parse_expr(clean(pts[0][2]), transformations=tfms, local_dict={**ld, "u": u_s, "v": v_s})
1000
+ r_vec = sp.Matrix([rx, ry, rz])
1001
+ ru = r_vec.diff(u_s)
1002
+ rv = r_vec.diff(v_s)
1003
+ E = sp.simplify(ru.dot(ru))
1004
+ F = sp.simplify(ru.dot(rv))
1005
+ G = sp.simplify(rv.dot(rv))
1006
+ return {
1007
+ "type": "FirstFundamentalForm",
1008
+ "result": f"E={E}, F={F}, G={G}, ds²={E}du²+{2*F}dudv+{G}dv²",
1009
+ "latex": f"E={sp.latex(E)}, F={sp.latex(F)}, G={sp.latex(G)}"
1010
+ }
1011
+
1012
+ # ── Gaussian + Mean Curvature ─────────────────────────────
1013
+ elif any(k in p for k in ["gaussian curvature","mean curvature"]):
1014
+ pts = re.findall(r"\(\s*(.+?)\s*,\s*(.+?)\s*,\s*(.+?)\s*\)", p)
1015
+ if pts:
1016
+ rx = parse_expr(clean(pts[0][0]), transformations=tfms, local_dict={**ld, "u": u_s, "v": v_s})
1017
+ ry = parse_expr(clean(pts[0][1]), transformations=tfms, local_dict={**ld, "u": u_s, "v": v_s})
1018
+ rz = parse_expr(clean(pts[0][2]), transformations=tfms, local_dict={**ld, "u": u_s, "v": v_s})
1019
+ r_vec = sp.Matrix([rx, ry, rz])
1020
+ ru = r_vec.diff(u_s); rv = r_vec.diff(v_s)
1021
+ E = sp.simplify(ru.dot(ru)); F = sp.simplify(ru.dot(rv)); G = sp.simplify(rv.dot(rv))
1022
+ n = ru.cross(rv); N = sp.simplify(n / sp.sqrt(n.dot(n)))
1023
+ L = sp.simplify(N.dot(ru.diff(u_s)))
1024
+ M = sp.simplify(N.dot(ru.diff(v_s)))
1025
+ Nv = sp.simplify(N.dot(rv.diff(v_s)))
1026
+ K = sp.simplify((L*Nv - M**2)/(E*G - F**2))
1027
+ H = sp.simplify((E*Nv - 2*F*M + G*L)/(2*(E*G - F**2)))
1028
+ return {
1029
+ "type": "GaussianCurvature",
1030
+ "result": f"K (Gaussian) = {K}, H (Mean) = {H}",
1031
+ "latex": f"K={sp.latex(K)}, H={sp.latex(H)}"
1032
+ }
1033
+
1034
+ except Exception:
1035
+ pass # safe fallback to AI
1036
+
1037
+ # ── 10. Hydro Mechanics — SymPy for computations, AI for theory ──
1038
+ elif any(k in p for k in [
1039
+ "continuity equation", "equation of continuity",
1040
+ "streamline", "stream function", "stream line",
1041
+ "velocity potential", "irrotational", "rotational motion",
1042
+ "lagrangian", "eulerian", "vortex", "vorticity",
1043
+ "path line", "streak line",
1044
+ "bernoulli", "euler's equation", "euler equation of motion",
1045
+ "torricelli", "flow rate", "discharge",
1046
+ "reynolds number", "reynolds",
1047
+ "hydrostatic pressure", "pressure at depth",
1048
+ "hydrostatic", "buoyancy", "archimedes",
1049
+ "laminar flow", "turbulent flow", "viscous flow",
1050
+ "incompressible fluid", "steady flow",
1051
+ "navier-stokes", "navier stokes",
1052
+ "stokes stream function", "complex velocity potential",
1053
+ "source", "sink", "doublet",
1054
+ "milne thomson", "blasius theorem",
1055
+ "dimensional analysis", "buckingham pi",
1056
+ ]):
1057
+ try:
1058
+ x_h, y_h = sp.symbols('x y')
1059
+ g_val = sp.Rational(981, 100) # 9.81
1060
+
1061
+ # ── Continuity: find v2 from A1v1=A2v2 ───────────────
1062
+ if any(k in p for k in ["continuity equation","equation of continuity"]):
1063
+ nums = [float(n) for n in re.findall(r"[-]?\d+\.?\d*", p)]
1064
+ if len(nums) >= 3:
1065
+ A1_v,v1_v,A2_v = nums[0],nums[1],nums[2]
1066
+ v2_v = round(A1_v*v1_v/A2_v, 6)
1067
+ Q_v = round(A1_v*v1_v, 6)
1068
+ return {
1069
+ "type": "ContinuityEq",
1070
+ "result": (f"A1={A1_v}, v1={v1_v}, A2={A2_v}\n"
1071
+ f"v2 = A1*v1/A2 = {v2_v} m/s\n"
1072
+ f"Flow rate Q = A1*v1 = {Q_v} m³/s"),
1073
+ "latex": f"v_2 = {v2_v}\\text{{ m/s}}"
1074
+ }
1075
+
1076
+ # ── Reynolds Number ────────────────────────────────────
1077
+ elif any(k in p for k in ["reynolds number","reynolds"]):
1078
+ nums = [float(n) for n in re.findall(r"[-]?\d+\.?\d*", p)]
1079
+ if len(nums) >= 4:
1080
+ rho_v,v_v,D_v,mu_v = nums[0],nums[1],nums[2],nums[3]
1081
+ Re = round(rho_v*v_v*D_v/mu_v, 2)
1082
+ flow = "Turbulent (Re>4000)" if Re>4000 else ("Transitional (2300<Re<4000)" if Re>2300 else "Laminar (Re<2300)")
1083
+ return {
1084
+ "type": "ReynoldsNumber",
1085
+ "result": f"Re = ρvD/μ = {rho_v}×{v_v}×{D_v}/{mu_v} = {Re} → {flow}",
1086
+ "latex": f"Re = {Re}"
1087
+ }
1088
+
1089
+ # ── Bernoulli: find P2 ─────────────────────────────────
1090
+ elif "bernoulli" in p:
1091
+ nums = [float(n) for n in re.findall(r"[-]?\d+\.?\d*", p)]
1092
+ if len(nums) >= 5:
1093
+ P1_v,v1_v,h1_v,v2_v,h2_v = nums[0],nums[1],nums[2],nums[3],nums[4]
1094
+ rho_v = 1000 # default water
1095
+ P2_v = round(P1_v + 0.5*rho_v*(v1_v**2-v2_v**2) + rho_v*9.81*(h1_v-h2_v), 4)
1096
+ return {
1097
+ "type": "Bernoulli",
1098
+ "result": (f"P1+½ρv1²+ρgh1 = P2+½ρv2²+ρgh2\n"
1099
+ f"P2 = {P2_v} Pa"),
1100
+ "latex": f"P_2 = {P2_v}\\text{{ Pa}}"
1101
+ }
1102
+
1103
+ # ── Torricelli: v = √(2gh) ─────────────────────────────
1104
+ elif "torricelli" in p:
1105
+ nums = [float(n) for n in re.findall(r"[-]?\d+\.?\d*", p)]
1106
+ if nums:
1107
+ h_v = nums[0]
1108
+ v_torr = round((2*9.81*h_v)**0.5, 6)
1109
+ return {
1110
+ "type": "Torricelli",
1111
+ "result": f"v = √(2gh) = √(2×9.81×{h_v}) = {v_torr} m/s",
1112
+ "latex": f"v = {v_torr}\\text{{ m/s}}"
1113
+ }
1114
+
1115
+ # ── Hydrostatic Pressure ───────────────────────────────
1116
+ elif any(k in p for k in ["hydrostatic pressure","pressure at depth"]):
1117
+ nums = [float(n) for n in re.findall(r"[-]?\d+\.?\d*", p)]
1118
+ if nums:
1119
+ h_v = nums[0]
1120
+ rho_v = 1000
1121
+ P_gauge = round(rho_v*9.81*h_v, 4)
1122
+ P_abs = round(101325 + P_gauge, 4)
1123
+ return {
1124
+ "type": "HydrostaticPressure",
1125
+ "result": (f"At depth h={h_v}m:\n"
1126
+ f"Gauge pressure = ρgh = {P_gauge} Pa\n"
1127
+ f"Absolute pressure = P0+ρgh = {P_abs} Pa"),
1128
+ "latex": f"P = P_0 + \\rho g h = {P_abs}\\text{{ Pa}}"
1129
+ }
1130
+
1131
+ # ── Flow Rate ──────────────────────────────────────────
1132
+ elif any(k in p for k in ["flow rate","discharge"]):
1133
+ nums = [float(n) for n in re.findall(r"[-]?\d+\.?\d*", p)]
1134
+ if len(nums) >= 2:
1135
+ A_v, v_v = nums[0], nums[1]
1136
+ Q_v = round(A_v*v_v, 8)
1137
+ return {
1138
+ "type": "FlowRate",
1139
+ "result": f"Q = A×v = {A_v}×{v_v} = {Q_v} m³/s",
1140
+ "latex": f"Q = {Q_v}\\text{{ m³/s}}"
1141
+ }
1142
+
1143
+ # ── Velocity Potential ─────────────────────────────────
1144
+ elif "velocity potential" in p:
1145
+ m = re.search(r"(?:phi|φ|potential)\s*=\s*(.+?)(?:\s|$)", p)
1146
+ if m:
1147
+ raw = clean(m.group(1))
1148
+ phi_expr = parse_expr(raw, transformations=tfms, local_dict={**ld,"x":x_h,"y":y_h})
1149
+ u_comp = sp.diff(phi_expr, x_h)
1150
+ v_comp = sp.diff(phi_expr, y_h)
1151
+ lap = sp.diff(phi_expr,x_h,2) + sp.diff(phi_expr,y_h,2)
1152
+ return {
1153
+ "type": "VelocityPotential",
1154
+ "result": (f"φ={str(phi_expr)}, u=∂φ/∂x={u_comp}, v=∂φ/∂y={v_comp}\n"
1155
+ f"∇²φ={sp.simplify(lap)} (irrotational: {sp.simplify(lap)==0})"),
1156
+ "latex": f"\\nabla^2\\phi = {sp.latex(sp.simplify(lap))}"
1157
+ }
1158
+
1159
+ except Exception:
1160
+ pass # safe fallback to AI
1161
+
1162
+ # ── 11. Matrix / Eigenvalues — deterministic SymPy adapter ────────
1163
+ elif any(k in p for k in ["matrix", "determinant", "eigenvalue",
1164
+ "eigenvector", "det(", "inverse matrix", "rank"]):
1165
+ rows = re.findall(r"\[([^\[\]]+)\]", p)
1166
+ if rows:
1167
+ try:
1168
+ matrix_data = [
1169
+ [sp.Rational(value.strip()) for value in row.split(",")]
1170
+ for row in rows
1171
+ ]
1172
+ if len({len(row) for row in matrix_data}) != 1:
1173
+ raise ValueError("Matrix rows have different lengths")
1174
+ matrix = sp.Matrix(matrix_data)
1175
+
1176
+ if "determinant" in p or "det(" in p:
1177
+ value = sp.factor(matrix.det())
1178
+ return {"type": "MatrixDeterminant", "result": f"det(A) = {value}", "latex": f"\\det(A)={sp.latex(value)}"}
1179
+ if "eigenvector" in p:
1180
+ value = matrix.eigenvects()
1181
+ return {"type": "Eigenvectors", "result": f"Eigenvectors: {value}", "latex": sp.latex(value)}
1182
+ if "eigenvalue" in p:
1183
+ value = matrix.eigenvals()
1184
+ return {"type": "Eigenvalues", "result": f"Eigenvalues: {value}", "latex": sp.latex(value)}
1185
+ if "inverse" in p:
1186
+ value = matrix.inv()
1187
+ return {"type": "MatrixInverse", "result": f"A^(-1) = {value}", "latex": sp.latex(value)}
1188
+ if "transpose" in p:
1189
+ value = matrix.T
1190
+ return {"type": "MatrixTranspose", "result": f"A^T = {value}", "latex": sp.latex(value)}
1191
+ if "rank" in p:
1192
+ value = matrix.rank()
1193
+ return {"type": "MatrixRank", "result": f"rank(A) = {value}", "latex": f"\\operatorname{{rank}}(A)={value}"}
1194
+ return {"type": "Matrix", "result": f"A = {matrix}", "latex": sp.latex(matrix)}
1195
+ except Exception:
1196
+ pass
1197
+
1198
+ # ── 12. Modular arithmetic — deterministic adapter ───────────────
1199
+ elif "mod" in p or "congruence" in p:
1200
+ congruence = re.search(
1201
+ r"([+-]?\d+)\s*x\s*(?:≡|=)\s*([+-]?\d+)\s*\(?(?:mod|modulo)\s*([+-]?\d+)\)?",
1202
+ p,
1203
+ )
1204
+ if congruence:
1205
+ a_val, b_val, modulus = (int(value) for value in congruence.groups())
1206
+ gcd_value = math.gcd(a_val, modulus)
1207
+ if b_val % gcd_value != 0:
1208
+ return {
1209
+ "type": "LinearCongruence",
1210
+ "result": f"No solution because gcd({a_val},{modulus})={gcd_value} does not divide {b_val}.",
1211
+ "latex": "\\text{No solution}",
1212
+ }
1213
+ solutions = [x_val for x_val in range(modulus) if (a_val * x_val - b_val) % modulus == 0]
1214
+ return {
1215
+ "type": "LinearCongruence",
1216
+ "result": f"{a_val}x ≡ {b_val} (mod {modulus}); solutions: {solutions}",
1217
+ "latex": "x \\equiv " + ", \\".join(str(x_val) for x_val in solutions) + f" \\pmod{{{modulus}}}",
1218
+ }
1219
+
1220
+ remainder = re.search(r"([+-]?\d+)\s+mod\s+([+-]?\d+)", p)
1221
+ if remainder:
1222
+ left, right = (int(value) for value in remainder.groups())
1223
+ value = left % right
1224
+ return {"type": "Modulo", "result": f"{left} mod {right} = {value}", "latex": f"{left} \\bmod {right} = {value}"}
1225
+
1226
+ except Exception:
1227
+ pass # Silently fall back — AI handles it
1228
+
1229
+ return {"type": "general", "result": None, "latex": ""}
1230
+