MasteredUltraInstinct commited on
Commit
95cb2cd
ยท
verified ยท
1 Parent(s): a0c70e3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -52
app.py CHANGED
@@ -82,14 +82,13 @@ def solve_polynomial(image, llm_url):
82
  expr = expr.subs(sp.pi, sp.Float(3.1416)).subs(sp.E, sp.Float(2.7183))
83
  if not isinstance(expr, sp.Equality):
84
  raise ValueError("Expression is not an equation.")
85
- lhs_minus_rhs = expr.lhs - expr.rhs
86
- if not lhs_minus_rhs.is_polynomial():
87
- raise ValueError("Expression is not a polynomial.")
88
- junk_symbols = {"pm", "cdot", "mathrm", "boldmath", "bar", "L"}
89
- symbols = {str(s) for s in expr.free_symbols}
90
- if symbols & junk_symbols:
91
- raise ValueError("Expression contains junk symbols.")
92
- except Exception:
93
  fixed_latex = request_llm_fallback(cleaned_latex, llm_url)
94
  cleaned_latex = clean_latex(fixed_latex)
95
  try:
@@ -97,51 +96,76 @@ def solve_polynomial(image, llm_url):
97
  expr = expr.subs(sp.pi, sp.Float(3.1416)).subs(sp.E, sp.Float(2.7183))
98
  if not isinstance(expr, sp.Equality):
99
  raise ValueError("Expression is not an equation.")
100
- lhs_minus_rhs = expr.lhs - expr.rhs
101
- if not lhs_minus_rhs.is_polynomial():
102
- raise ValueError("Expression is not a polynomial.")
103
- symbols = {str(s) for s in expr.free_symbols}
104
- if symbols & junk_symbols:
105
- raise ValueError("Expression contains junk symbols.")
106
- except Exception:
107
- expr = None
108
- if expr is None:
109
- return f"โŒ Could not parse expression even after fallback:\n\n```latex\n{cleaned_latex}\n```", cleaned_latex, ""
110
- output = (
111
- f"## ๐Ÿ“„ Extracted LaTeX\n\n```latex\n{latex_result}\n```\n"
112
- f"\n---\n## ๐Ÿงน Cleaned LaTeX Used\n\n```latex\n{cleaned_latex}\n```\n"
113
- f"\n---\n## ๐Ÿง  Parsed Expression\n\n$$ {sp.latex(expr)} $$\n\n---\n"
114
- )
115
- if isinstance(expr, sp.Equality):
116
- lhs = expr.lhs - expr.rhs
117
- output += f"## โœ๏ธ Step 1: Standard Form\n$$ {sp.latex(lhs)} = 0 $$\n---\n"
118
- output += f"## ๐Ÿงฉ Step 2: Factor\n$$ {sp.latex(sp.factor(lhs))} = 0 $$\n---\n"
119
- x_sym = None
120
- for sym in lhs.free_symbols:
121
- if str(sym) == "x":
122
- x_sym = sym
123
- break
124
- if x_sym is None:
125
- raise ValueError("โŒ Could not find variable 'x' in the equation.")
126
- roots = sp.solve(sp.Eq(lhs, 0), x_sym, dict=True)
127
- output += "## โœ… Step 3: Solve Roots\n"
128
- if roots:
129
- output += "$$\n\\begin{aligned}\n"
130
- for i, sol in enumerate(roots, 1):
131
- for var, val in sol.items():
132
- evaluated = val.evalf(6)
133
- output += f"\\text{{Root {i}}}:\\quad {var} &\\approx {sp.latex(evaluated)} \\\\\n"
134
- output += "\\end{aligned}\n$$\n"
135
- else:
136
- simplified = sp.simplify(expr)
137
- output += f"## โž• Simplified Expression\n$$ {sp.latex(simplified)} $$"
138
- return output, cleaned_latex, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  except Exception as e:
140
- return f"โŒ **Error**: {str(e)}", "", ""
141
 
142
  def wrapped_solver(img, url):
143
- result, cleaned, _ = solve_polynomial(img, url)
144
- return result, cleaned
145
 
146
  def solve_from_coeffs(degree, coeff_str):
147
  try:
@@ -189,12 +213,13 @@ with gr.Blocks() as demo:
189
  llm_url = gr.Textbox(label="๐Ÿ”— Enter LLM Microservice URL (from Colab)", placeholder="https://xxxx.ngrok-free.app")
190
  image_input = gr.Image(type="pil", label="๐Ÿ“ท Upload Image of Polynomial")
191
  hidden_latex = gr.Textbox(visible=False)
 
192
  output_box = gr.Markdown(label="๐Ÿ“‹ Step-by-step Solution")
193
  submit_btn = gr.Button("๐Ÿ” Solve")
194
- submit_btn.click(fn=wrapped_solver, inputs=[image_input, llm_url], outputs=[output_box, hidden_latex])
195
  explain_box = gr.Markdown(label="๐Ÿ—ฃ๏ธ Human-style Explanation")
196
  explain_btn = gr.Button("๐Ÿง  Explain Human-Solution")
197
- explain_btn.click(fn=request_llm_explanation, inputs=[hidden_latex, llm_url], outputs=explain_box)
198
 
199
  with gr.Tab("๐Ÿงฎ Solve by Coefficients"):
200
  degree_input = gr.Number(label="Enter Degree of Polynomial (e.g. 3)")
 
82
  expr = expr.subs(sp.pi, sp.Float(3.1416)).subs(sp.E, sp.Float(2.7183))
83
  if not isinstance(expr, sp.Equality):
84
  raise ValueError("Expression is not an equation.")
85
+ lhs = expr.lhs - expr.rhs
86
+ if not lhs.is_polynomial():
87
+ raise ValueError("Not a polynomial")
88
+ junk = {"pm", "cdot", "mathrm", "boldmath", "bar", "L"}
89
+ if {str(s) for s in expr.free_symbols} & junk:
90
+ raise ValueError("Junk in symbols")
91
+ except:
 
92
  fixed_latex = request_llm_fallback(cleaned_latex, llm_url)
93
  cleaned_latex = clean_latex(fixed_latex)
94
  try:
 
96
  expr = expr.subs(sp.pi, sp.Float(3.1416)).subs(sp.E, sp.Float(2.7183))
97
  if not isinstance(expr, sp.Equality):
98
  raise ValueError("Expression is not an equation.")
99
+ lhs = expr.lhs - expr.rhs
100
+ if not lhs.is_polynomial():
101
+ raise ValueError("Not a polynomial")
102
+ except:
103
+ return f"โŒ Could not parse expression after fallback:\n\n```latex\n{cleaned_latex}\n```", cleaned_latex, ""
104
+
105
+ output = f"## ๐Ÿ“„ Extracted LaTeX\n```latex\n{latex_result}\n```\n"
106
+ output += f"---\n## ๐Ÿงน Cleaned LaTeX\n```latex\n{cleaned_latex}\n```\n"
107
+ output += f"---\n## ๐Ÿง  Parsed Expression\n$$ {sp.latex(expr)} $$\n"
108
+
109
+ lhs = expr.lhs - expr.rhs
110
+ factor = sp.factor(lhs)
111
+ output += f"---\n## โœ๏ธ Standard Form\n$$ {sp.latex(lhs)} = 0 $$\n"
112
+ output += f"---\n## ๐Ÿงฉ Factorized\n$$ {sp.latex(factor)} = 0 $$\n"
113
+
114
+ x = next(iter(lhs.free_symbols))
115
+ roots = sp.solve(lhs, x)
116
+ output += "## โœ… Roots\n"
117
+ output += "$$\n\\begin{aligned}\n"
118
+ root_strs = []
119
+ for i, r in enumerate(roots, 1):
120
+ root_val = sp.N(r, 6)
121
+ output += f"\\text{{Root {i}}}:\\quad x &\\approx {sp.latex(root_val)} \\\\\n"
122
+ root_strs.append(str(root_val))
123
+ output += "\\end{aligned}\n$$\n"
124
+
125
+ # ๐Ÿ” Build structured LLM prompt
126
+ prompt = ""
127
+ try:
128
+ coeffs = sp.Poly(lhs, x).all_coeffs()
129
+ if len(coeffs) == 3:
130
+ a, b, c = [float(k) for k in coeffs]
131
+ prod = a * c
132
+ found = False
133
+ for m in range(-100, 101):
134
+ if m == 0 or prod % m != 0:
135
+ continue
136
+ n = prod / m
137
+ if m + n == b:
138
+ found = True
139
+ prompt = (
140
+ f"Equation: {lhs} = 0\n"
141
+ f"Factor: {factor} = 0\n"
142
+ f"Roots: {root_strs}\n\n"
143
+ f"Middle-term factorization is applicable: "
144
+ f"a = {a}, b = {b}, c = {c}, a*c = {prod}. "
145
+ f"{m} and {n} satisfy m*n = ac and m+n = b.\n"
146
+ f"Explain this step-by-step in human style."
147
+ )
148
+ break
149
+ if not found:
150
+ raise Exception("No middle term")
151
+ else:
152
+ raise Exception("Not quadratic")
153
+ except:
154
+ prompt = (
155
+ f"Equation: {lhs} = 0\n"
156
+ f"Factor: {factor} = 0\n"
157
+ f"Roots: {root_strs}\n\n"
158
+ f"Middle-term factorization is not suitable. "
159
+ f"Explain using quadratic formula (Sreedhar Acharya) with step-by-step clarity."
160
+ )
161
+
162
+ return output, cleaned_latex, prompt
163
  except Exception as e:
164
+ return f"โŒ Error: {str(e)}", "", ""
165
 
166
  def wrapped_solver(img, url):
167
+ result, cleaned, prompt = solve_polynomial(img, url)
168
+ return result, cleaned, prompt
169
 
170
  def solve_from_coeffs(degree, coeff_str):
171
  try:
 
213
  llm_url = gr.Textbox(label="๐Ÿ”— Enter LLM Microservice URL (from Colab)", placeholder="https://xxxx.ngrok-free.app")
214
  image_input = gr.Image(type="pil", label="๐Ÿ“ท Upload Image of Polynomial")
215
  hidden_latex = gr.Textbox(visible=False)
216
+ explanation_prompt = gr.Textbox(visible=False)
217
  output_box = gr.Markdown(label="๐Ÿ“‹ Step-by-step Solution")
218
  submit_btn = gr.Button("๐Ÿ” Solve")
219
+ submit_btn.click(fn=wrapped_solver, inputs=[image_input, llm_url], outputs=[output_box, hidden_latex, explanation_prompt])
220
  explain_box = gr.Markdown(label="๐Ÿ—ฃ๏ธ Human-style Explanation")
221
  explain_btn = gr.Button("๐Ÿง  Explain Human-Solution")
222
+ explain_btn.click(fn=request_llm_explanation, inputs=[explanation_prompt, llm_url], outputs=explain_box)
223
 
224
  with gr.Tab("๐Ÿงฎ Solve by Coefficients"):
225
  degree_input = gr.Number(label="Enter Degree of Polynomial (e.g. 3)")