Aroy1997 commited on
Commit
904898c
·
verified ·
1 Parent(s): 73dc6cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -164
app.py CHANGED
@@ -1,161 +1,10 @@
1
  import gradio as gr
2
- import numpy as np
3
- import matplotlib.pyplot as plt
4
- import sympy as sp
5
- import requests
6
- import yaml
7
-
8
- x, y = sp.symbols('x y')
9
-
10
- # Load theorem database
11
- def load_theorem_db():
12
- try:
13
- with open("theorems.yaml", "r") as f:
14
- return yaml.safe_load(f)
15
- except:
16
- return []
17
-
18
- def generate_context(task_type):
19
- theorems = load_theorem_db()
20
- relevant = []
21
- if task_type == "polynomial":
22
- relevant = [t for t in theorems if "polynomial" in t["tags"]]
23
- elif task_type == "linear":
24
- relevant = [t for t in theorems if "linear" in t["tags"]]
25
- context = ""
26
- for t in relevant:
27
- context += f"Theorem: {t['name']}\nExplanation: {t['short_explanation']}\n\n"
28
- return context
29
-
30
- def explain_with_llm(problem, task_type, llm_url):
31
- try:
32
- context = generate_context(task_type)
33
- payload = {
34
- "prompt": f"Using the theorems below, explain this math solution in depth:\n\n{context}\n\nProblem: {problem}"
35
- }
36
- if llm_url.strip() == "":
37
- raise ValueError("No LLM URL provided.")
38
- response = requests.post(f"{llm_url}/explain", json=payload)
39
- if response.status_code == 200:
40
- return response.json().get("explanation", "✅ Processed but no explanation returned.")
41
- return f"❌ LLM request failed: {response.status_code}"
42
- except Exception as e:
43
- return f"❌ LLM request failed: {e}"
44
-
45
- # Polynomial Solver
46
-
47
- def generate_polynomial_template(degree):
48
- terms = [f"a{i}*x^{degree - i}" for i in range(degree)] + [f"a{degree}"]
49
- return " + ".join(terms) + " = 0"
50
-
51
- def solve_polynomial(degree, coeff_string):
52
- try:
53
- coeffs = [sp.sympify(s) for s in coeff_string.strip().split()]
54
- if len(coeffs) != degree + 1:
55
- return f"⚠️ Please enter exactly {degree + 1} coefficients.", None, None, ""
56
-
57
- poly = sum([coeffs[i] * x**(degree - i) for i in range(degree + 1)])
58
- simplified = sp.simplify(poly)
59
-
60
- factored_steps = []
61
- current_expr = simplified
62
- while True:
63
- factored = sp.factor(current_expr)
64
- if factored == current_expr:
65
- break
66
- factored_steps.append(factored)
67
- current_expr = factored
68
-
69
- roots = sp.solve(sp.Eq(simplified, 0), x)
70
- root_display = []
71
- for i, r in enumerate(roots):
72
- r_simplified = sp.nsimplify(r, rational=True)
73
- root_display.append(f"r_{{{i+1}}} = {sp.latex(r_simplified)}")
74
-
75
- steps_output = f"### 🧐 Polynomial Expression\n\n$$ {sp.latex(poly)} = 0 $$\n\n"
76
- steps_output += f"### ✏️ Simplified\n\n$$ {sp.latex(simplified)} = 0 $$\n\n"
77
-
78
- if factored_steps:
79
- steps_output += f"### 🪜 Step-by-Step Factorization\n\n"
80
- for i, step in enumerate(factored_steps, 1):
81
- steps_output += f"**Step {i}:** $$ {sp.latex(step)} = 0 $$\n\n"
82
- else:
83
- steps_output += f"### 🤷 No further factorization possible\n\n"
84
-
85
- steps_output += "### 🥮 Roots\n\n$$ " + " \\quad ".join(root_display) + " $$"
86
-
87
- f_lambdified = sp.lambdify(x, simplified, modules=["numpy"])
88
- x_vals = np.linspace(-10, 10, 400)
89
- y_vals = f_lambdified(x_vals)
90
-
91
- fig, ax = plt.subplots(figsize=(6, 4))
92
- ax.plot(x_vals, y_vals, label="Polynomial")
93
- ax.axhline(0, color='black', linewidth=0.5)
94
- ax.axvline(0, color='black', linewidth=0.5)
95
- ax.grid(True)
96
- ax.set_title("📈 Graph of the Polynomial")
97
- ax.set_xlabel("x")
98
- ax.set_ylabel("f(x)")
99
-
100
- real_roots = [sp.N(r.evalf()) for r in roots if sp.im(r) == 0]
101
- for r in real_roots:
102
- ax.plot([float(r)], [0], 'ro', label="Real Root")
103
-
104
- ax.legend()
105
-
106
- return steps_output, fig, "", steps_output
107
-
108
- except Exception as e:
109
- return f"❌ Error: {e}", None, "", ""
110
-
111
- # Linear Solver
112
-
113
- def solve_linear_system(eq1_str, eq2_str):
114
- try:
115
- eq1 = sp.sympify(eq1_str)
116
- eq2 = sp.sympify(eq2_str)
117
-
118
- sol = sp.solve((eq1, eq2), (x, y), dict=True)
119
-
120
- steps = "### 🔍 Solving System\n\n"
121
- steps += f"**Equation 1:** $$ {sp.latex(eq1)} $$\n\n"
122
- steps += f"**Equation 2:** $$ {sp.latex(eq2)} $$\n\n"
123
-
124
- if sol:
125
- sol = sol[0]
126
- steps += f"**Solution:** $$ x = {sp.latex(sol[x])}, \\ y = {sp.latex(sol[y])} $$\n\n"
127
- else:
128
- steps += "**No unique solution or inconsistent system**\n"
129
-
130
- x_vals = np.linspace(-10, 10, 400)
131
- f1 = sp.solve(eq1, y)
132
- f2 = sp.solve(eq2, y)
133
-
134
- fig, ax = plt.subplots(figsize=(6, 4))
135
- if f1 and f2:
136
- y1 = sp.lambdify(x, f1[0], modules=['numpy'])(x_vals)
137
- y2 = sp.lambdify(x, f2[0], modules=['numpy'])(x_vals)
138
- ax.plot(x_vals, y1, label='Equation 1')
139
- ax.plot(x_vals, y2, label='Equation 2')
140
-
141
- if sol:
142
- px = float(sp.N(sol[x]))
143
- py = float(sp.N(sol[y]))
144
- ax.plot(px, py, 'ro')
145
- ax.annotate(f"({px:.2f}, {py:.2f})", (px, py), textcoords="offset points", xytext=(10, 5), ha='center', color='red')
146
-
147
- ax.axhline(0, color='black', linewidth=0.5)
148
- ax.axvline(0, color='black', linewidth=0.5)
149
- ax.set_title("📉 Graph of the Linear System")
150
- ax.set_xlabel("x")
151
- ax.set_ylabel("y")
152
- ax.grid(True)
153
- ax.legend()
154
-
155
- return steps, fig, steps
156
-
157
- except Exception as e:
158
- return f"❌ Error: {e}", None, ""
159
 
160
  with gr.Blocks() as demo:
161
  gr.Markdown("## 🔢 Polynomial Solver with Step-by-Step Factorization and Graph")
@@ -164,7 +13,10 @@ with gr.Blocks() as demo:
164
  degree_slider = gr.Slider(1, 8, value=3, step=1, label="Degree of Polynomial")
165
  template_display = gr.Textbox(label="Polynomial Template (Fill in Coefficients)", interactive=False)
166
 
167
- coeff_input = gr.Textbox(label="Enter Coefficients (space-separated, supports pi, e, sqrt(2), I)", placeholder="e.g. 1 -3 sqrt(2) -pi")
 
 
 
168
  llm_url = gr.Textbox(label="LLM Microservice URL (optional)", placeholder="https://your-llm.ngrok.app")
169
 
170
  steps_md = gr.Markdown()
@@ -176,9 +28,21 @@ with gr.Blocks() as demo:
176
  solve_button = gr.Button("Plot Polynomial", variant="primary")
177
  explain_poly = gr.Button("Explain Polynomial with LLM")
178
 
179
- degree_slider.change(fn=generate_polynomial_template, inputs=degree_slider, outputs=template_display)
180
- solve_button.click(fn=solve_polynomial, inputs=[degree_slider, coeff_input], outputs=[steps_md, plot_output, error_box, poly_full_solution])
181
- explain_poly.click(fn=lambda sol, url: explain_with_llm(sol, "polynomial", url), inputs=[poly_full_solution, llm_url], outputs=steps_md)
 
 
 
 
 
 
 
 
 
 
 
 
182
 
183
  gr.Markdown("## 📐 Solve Linear System (2 Equations, 2 Variables)")
184
 
@@ -192,8 +56,15 @@ with gr.Blocks() as demo:
192
  solve_sys_button = gr.Button("Solve Linear System", variant="primary")
193
  explain_linear = gr.Button("Explain Linear System with LLM")
194
 
195
- solve_sys_button.click(fn=solve_linear_system, inputs=[eq1_input, eq2_input], outputs=[sys_steps, sys_plot, linear_full_solution])
196
- explain_linear.click(fn=lambda sol, url: explain_with_llm(sol, "linear", url), inputs=[linear_full_solution, llm_url], outputs=sys_steps)
 
 
 
 
 
 
 
 
197
 
198
  demo.launch()
199
-
 
1
  import gradio as gr
2
+ from solver import (
3
+ generate_polynomial_template,
4
+ solve_polynomial,
5
+ solve_linear_system
6
+ )
7
+ from llm_utils import explain_with_llm
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  with gr.Blocks() as demo:
10
  gr.Markdown("## 🔢 Polynomial Solver with Step-by-Step Factorization and Graph")
 
13
  degree_slider = gr.Slider(1, 8, value=3, step=1, label="Degree of Polynomial")
14
  template_display = gr.Textbox(label="Polynomial Template (Fill in Coefficients)", interactive=False)
15
 
16
+ coeff_input = gr.Textbox(
17
+ label="Enter Coefficients (space-separated, supports pi, e, sqrt(2), I)",
18
+ placeholder="e.g. 1 -3 sqrt(2) -pi"
19
+ )
20
  llm_url = gr.Textbox(label="LLM Microservice URL (optional)", placeholder="https://your-llm.ngrok.app")
21
 
22
  steps_md = gr.Markdown()
 
28
  solve_button = gr.Button("Plot Polynomial", variant="primary")
29
  explain_poly = gr.Button("Explain Polynomial with LLM")
30
 
31
+ degree_slider.change(
32
+ fn=generate_polynomial_template,
33
+ inputs=degree_slider,
34
+ outputs=template_display
35
+ )
36
+ solve_button.click(
37
+ fn=solve_polynomial,
38
+ inputs=[degree_slider, coeff_input],
39
+ outputs=[steps_md, plot_output, error_box, poly_full_solution]
40
+ )
41
+ explain_poly.click(
42
+ fn=lambda sol, url: explain_with_llm(sol, "polynomial", url),
43
+ inputs=[poly_full_solution, llm_url],
44
+ outputs=steps_md
45
+ )
46
 
47
  gr.Markdown("## 📐 Solve Linear System (2 Equations, 2 Variables)")
48
 
 
56
  solve_sys_button = gr.Button("Solve Linear System", variant="primary")
57
  explain_linear = gr.Button("Explain Linear System with LLM")
58
 
59
+ solve_sys_button.click(
60
+ fn=solve_linear_system,
61
+ inputs=[eq1_input, eq2_input],
62
+ outputs=[sys_steps, sys_plot, linear_full_solution]
63
+ )
64
+ explain_linear.click(
65
+ fn=lambda sol, url: explain_with_llm(sol, "linear", url),
66
+ inputs=[linear_full_solution, llm_url],
67
+ outputs=sys_steps
68
+ )
69
 
70
  demo.launch()