Aroy1997 commited on
Commit
73dc6cd
Β·
verified Β·
1 Parent(s): f231c81

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -61
app.py CHANGED
@@ -1,53 +1,62 @@
1
- # app.py
2
  import gradio as gr
3
  import numpy as np
4
  import matplotlib.pyplot as plt
5
  import sympy as sp
6
- import yaml
7
  import requests
 
8
 
9
  x, y = sp.symbols('x y')
10
 
11
- # Load theorems database
12
- def load_theorems(file="theorems.yaml"):
13
- with open(file, 'r') as f:
14
- return yaml.safe_load(f)
15
-
16
- theorems_db = load_theorems()
17
-
18
- # Helper to construct LLM explanation prompt
19
- def build_llm_prompt(context, eq_type="polynomial"):
20
- selected = [t for t in theorems_db if ("polynomial" in t["tags"] if eq_type == "polynomial" else "linear" in t["tags"])]
21
- theory_context = "\n".join([f"{t['name']}: {t['short_explanation']}" for t in selected])
22
- return f"Context:\n{theory_context}\n\nQuestion:\nExplain how the following was solved:\n{context}"
23
-
24
- # Call LLM microservice
25
- def get_llm_explanation(context, url, eq_type):
 
 
 
 
 
 
26
  try:
27
- prompt = build_llm_prompt(context, eq_type)
28
- resp = requests.post(f"{url}/explain", json={"prompt": prompt})
29
- if resp.status_code == 200:
30
- return resp.json().get("explanation", "❌ No explanation returned.")
31
- return f"❌ LLM returned status {resp.status_code}"
 
 
 
 
 
32
  except Exception as e:
33
  return f"❌ LLM request failed: {e}"
34
 
35
- # Generate polynomial template
 
36
  def generate_polynomial_template(degree):
37
  terms = [f"a{i}*x^{degree - i}" for i in range(degree)] + [f"a{degree}"]
38
  return " + ".join(terms) + " = 0"
39
 
40
- # Solve and plot polynomial
41
  def solve_polynomial(degree, coeff_string):
42
  try:
43
  coeffs = [sp.sympify(s) for s in coeff_string.strip().split()]
44
  if len(coeffs) != degree + 1:
45
- return f"⚠️ Please enter exactly {degree + 1} coefficients.", None, None
46
 
47
  poly = sum([coeffs[i] * x**(degree - i) for i in range(degree + 1)])
48
  simplified = sp.simplify(poly)
49
 
50
- # Factor step-by-step
51
  factored_steps = []
52
  current_expr = simplified
53
  while True:
@@ -94,12 +103,13 @@ def solve_polynomial(degree, coeff_string):
94
 
95
  ax.legend()
96
 
97
- return steps_output, fig, steps_output
98
 
99
  except Exception as e:
100
- return f"❌ Error: {e}", None, ""
 
 
101
 
102
- # Solve linear system
103
  def solve_linear_system(eq1_str, eq2_str):
104
  try:
105
  eq1 = sp.sympify(eq1_str)
@@ -147,44 +157,43 @@ def solve_linear_system(eq1_str, eq2_str):
147
  except Exception as e:
148
  return f"❌ Error: {e}", None, ""
149
 
150
- # UI
151
- def build_ui():
152
- with gr.Blocks() as demo:
153
- gr.Markdown("## πŸ”’ Polynomial & Linear System Solver with Step-by-Step Explanation")
 
 
 
 
 
154
 
155
- with gr.Tab("Polynomial"):
156
- with gr.Row():
157
- degree_slider = gr.Slider(1, 8, value=3, step=1, label="Degree")
158
- template_display = gr.Textbox(label="Template", interactive=False)
159
 
160
- coeff_input = gr.Textbox(label="Coefficients", placeholder="e.g. 1 -3 sqrt(2) -pi")
161
- steps_md = gr.Markdown()
162
- plot_output = gr.Plot()
163
- error_box = gr.Textbox(visible=False)
164
- explanation_md = gr.Markdown()
165
- llm_url = gr.Textbox(label="LLM URL", placeholder="https://your-llm.ngrok-free.app")
166
 
167
- degree_slider.change(generate_polynomial_template, degree_slider, template_display)
168
- solve_btn = gr.Button("Solve Polynomial", variant="primary")
169
- solve_btn.click(solve_polynomial, [degree_slider, coeff_input], [steps_md, plot_output, error_box])
170
 
171
- explain_btn = gr.Button("Explain Polynomial Solution", variant="primary")
172
- explain_btn.click(lambda context, url: get_llm_explanation(context, url, "polynomial"), [steps_md, llm_url], explanation_md)
173
 
174
- with gr.Tab("Linear System"):
175
- eq1_input = gr.Textbox(label="Equation 1", placeholder="2*x + 3*y - 6")
176
- eq2_input = gr.Textbox(label="Equation 2", placeholder="-x + y - 2")
177
- sys_steps = gr.Markdown()
178
- sys_plot = gr.Plot()
179
- sys_explain = gr.Markdown()
180
 
181
- solve_sys_btn = gr.Button("Solve Linear System", variant="primary")
182
- solve_sys_btn.click(solve_linear_system, [eq1_input, eq2_input], [sys_steps, sys_plot])
 
183
 
184
- explain_sys_btn = gr.Button("Explain Linear Solution", variant="primary")
185
- explain_sys_btn.click(lambda context, url: get_llm_explanation(context, url, "linear"), [sys_steps, llm_url], sys_explain)
186
 
187
- return demo
188
 
189
- if __name__ == "__main__":
190
- build_ui().launch()
 
 
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:
 
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)
 
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")
162
+
163
+ with gr.Row():
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()
171
+ plot_output = gr.Plot()
172
+ error_box = gr.Textbox(visible=False)
173
+ poly_full_solution = gr.Textbox(visible=False)
174
 
175
+ with gr.Row():
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
 
185
+ eq1_input = gr.Textbox(label="Equation 1 (in x and y)", placeholder="e.g. 2*x + 3*y - 6")
186
+ eq2_input = gr.Textbox(label="Equation 2 (in x and y)", placeholder="e.g. -x + y - 2")
187
+ sys_steps = gr.Markdown()
188
+ sys_plot = gr.Plot()
189
+ linear_full_solution = gr.Textbox(visible=False)
 
190
 
191
+ with gr.Row():
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