MasteredUltraInstinct commited on
Commit
fbda286
ยท
verified ยท
1 Parent(s): 68fae68

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -130
app.py CHANGED
@@ -50,27 +50,27 @@ def clean_latex(latex):
50
  latex = latex.replace('e', '2.7183')
51
  return latex
52
 
53
- def request_llm_fallback(bad_latex, llm_url):
54
- pre_cleaned = re.sub(r'(\\!?pm|\\not=?|\\!|\\L|\\perp|\\bar|\\Sigma|\\boldmath|G|L(?=\^))', '', bad_latex)
55
- try:
56
- response = requests.post(f"{llm_url}/clean", json={"prompt": pre_cleaned})
57
- if response.status_code == 200:
58
- return response.json().get("cleaned_latex", pre_cleaned)
59
- except Exception as e:
60
- print(f"LLM fallback failed: {e}")
61
- return pre_cleaned
62
-
63
- def request_llm_explanation(prompt, llm_url):
64
- try:
65
- response = requests.post(f"{llm_url}/explain", json={"prompt": prompt})
66
- if response.status_code == 200:
67
- return response.json().get("explanation", "โŒ No explanation returned.")
68
- else:
69
- return f"โŒ LLM explanation failed: {response.status_code}"
70
- except Exception as e:
71
- return f"โŒ LLM explanation error: {e}"
72
-
73
- def solve_polynomial(image, llm_url):
74
  try:
75
  img = preprocess_handwritten_image(image)
76
  latex_result = model(img)
@@ -86,18 +86,10 @@ def solve_polynomial(image, llm_url):
86
  if not lhs.is_polynomial():
87
  raise ValueError("Not a polynomial")
88
  except:
89
- fixed_latex = request_llm_fallback(cleaned_latex, llm_url)
90
- cleaned_latex = clean_latex(fixed_latex)
91
- try:
92
- expr = parse_latex(cleaned_latex)
93
- expr = expr.subs(sp.pi, sp.Float(3.1416)).subs(sp.E, sp.Float(2.7183))
94
- if not isinstance(expr, sp.Equality):
95
- raise ValueError("Expression is not an equation.")
96
- lhs = expr.lhs - expr.rhs
97
- if not lhs.is_polynomial():
98
- raise ValueError("Not a polynomial")
99
- except:
100
- return f"โŒ Could not parse expression after fallback:\n\n```latex\n{cleaned_latex}\n```", cleaned_latex, ""
101
 
102
  output = f"## ๐Ÿ“„ Extracted LaTeX\n```latex\n{latex_result}\n```\n"
103
  output += f"---\n## ๐Ÿงน Cleaned LaTeX\n```latex\n{cleaned_latex}\n```\n"
@@ -112,121 +104,82 @@ def solve_polynomial(image, llm_url):
112
  roots = sp.solve(lhs, x)
113
  output += "## โœ… Roots\n"
114
  output += "$$\n\\begin{aligned}\n"
115
- root_strs = []
116
  for i, r in enumerate(roots, 1):
117
  root_val = sp.N(r, 6)
118
  output += f"\\text{{Root {i}}}:\\quad x &\\approx {sp.latex(root_val)} \\\\\n"
119
- root_strs.append(str(root_val))
120
  output += "\\end{aligned}\n$$\n"
121
 
122
- # ๐Ÿ‘‡ Build structured prompt
123
- prompt = ""
124
- try:
125
- coeffs = sp.Poly(lhs, x).all_coeffs()
126
- if len(coeffs) == 3:
127
- a, b, c = [float(k) for k in coeffs]
128
- prod = a * c
129
- found = False
130
- for m in range(-100, 101):
131
- if m == 0 or prod % m != 0:
132
- continue
133
- n = prod / m
134
- if m + n == b:
135
- found = True
136
- prompt = (
137
- f"Equation: {lhs} = 0\n"
138
- f"Factor: {factor} = 0\n"
139
- f"Roots: {root_strs}\n\n"
140
- f"This was solved using middle-term factorization:\n"
141
- f"a = {a}, b = {b}, c = {c}, a*c = {prod}. "
142
- f"{m} and {n} satisfy m*n = ac and m+n = b.\n"
143
- f"Explain the process step-by-step in friendly, simple language."
144
- )
145
- break
146
- if not found:
147
- raise Exception("No middle term")
148
- else:
149
- raise Exception("Not quadratic")
150
- except:
151
- prompt = (
152
- f"Equation: {lhs} = 0\n"
153
- f"Factor: {factor} = 0\n"
154
- f"Roots: {root_strs}\n\n"
155
- f"This was solved using the quadratic formula (Sreedhar Acharya method). "
156
- f"Explain the process step-by-step in friendly, simple language."
157
- )
158
-
159
- return output, cleaned_latex, prompt
160
  except Exception as e:
161
  return f"โŒ Error: {str(e)}", "", ""
162
 
163
- def wrapped_solver(img, url):
164
- result, cleaned, prompt = solve_polynomial(img, url)
165
  return result, cleaned, prompt
166
 
167
- def solve_from_coeffs(degree, coeff_str):
168
- try:
169
- coeffs = [float(c.strip()) for c in coeff_str.split(",")]
170
- if len(coeffs) != int(degree) + 1:
171
- return f"โŒ You entered {len(coeffs)} coefficients, but degree {degree} needs {int(degree)+1}.", ""
172
-
173
- x = sp.Symbol("x")
174
- poly_expr = sum(coeffs[i] * x**(int(degree) - i) for i in range(len(coeffs)))
175
- factored = sp.factor(poly_expr)
176
- roots = sp.solve(poly_expr, x)
177
-
178
- result = "## ๐Ÿงฎ Symbolic Roots:\n"
179
- for i, r in enumerate(roots, 1):
180
- result += f"- Root {i}: $${sp.latex(sp.N(r, 6))}$$\n"
181
-
182
- terms = []
183
- for i, c in enumerate(coeffs):
184
- power = int(degree) - i
185
- if power == 0:
186
- terms.append(f"{c}")
187
- elif power == 1:
188
- terms.append(f"{c}x")
189
- else:
190
- terms.append(f"{c}x^{power}")
191
- equation_str = " + ".join(terms).replace("+ -", "- ") + " = 0"
192
- roots_str = f"[{', '.join(str(sp.N(r, 6)) for r in roots)}]"
193
- factored_str = sp.pretty(factored)
194
-
195
- llm_prompt = (
196
- f"Equation: {equation_str}\n"
197
- f"Factor: {factored_str} = 0\n"
198
- f"Roots: {roots_str}\n\n"
199
- "Explain the solution step-by-step in human language. "
200
- "These roots are correct (up to approximation), so base your reasoning on them."
201
- )
202
-
203
- return result, llm_prompt
204
- except Exception as e:
205
- return f"โŒ Error: {str(e)}", ""
206
 
207
  with gr.Blocks() as demo:
208
  with gr.Tab("๐Ÿ–ผ๏ธ Parse from Image"):
209
- llm_url = gr.Textbox(label="๐Ÿ”— Enter LLM Microservice URL (from Colab)", placeholder="https://xxxx.ngrok-free.app")
210
  image_input = gr.Image(type="pil", label="๐Ÿ“ท Upload Image of Polynomial")
211
  hidden_latex = gr.Textbox(visible=False)
212
  explanation_prompt = gr.Textbox(visible=False)
213
  output_box = gr.Markdown(label="๐Ÿ“‹ Step-by-step Solution")
214
  submit_btn = gr.Button("๐Ÿ” Solve")
215
- submit_btn.click(fn=wrapped_solver, inputs=[image_input, llm_url], outputs=[output_box, hidden_latex, explanation_prompt])
216
- explain_box = gr.Markdown(label="๐Ÿ—ฃ๏ธ Human-style Explanation")
217
- explain_btn = gr.Button("๐Ÿง  Explain Human-Solution")
218
- explain_btn.click(fn=request_llm_explanation, inputs=[explanation_prompt, llm_url], outputs=explain_box)
219
-
220
- with gr.Tab("๐Ÿงฎ Solve by Coefficients"):
221
- degree_input = gr.Number(label="Enter Degree of Polynomial (e.g. 3)")
222
- coeffs_input = gr.Textbox(label="Enter Coefficients (comma-separated)", placeholder="e.g. 1, 2, 0, -4")
223
- roots_output = gr.Markdown(label="โœ… Roots")
224
- coeff_hidden_equation = gr.Textbox(visible=False)
225
- coeff_btn = gr.Button("๐Ÿ“Œ Solve")
226
- coeff_btn.click(fn=solve_from_coeffs, inputs=[degree_input, coeffs_input], outputs=[roots_output, coeff_hidden_equation])
227
- coeff_explain_box = gr.Markdown(label="๐Ÿ—ฃ๏ธ Human-style Explanation")
228
- coeff_explain_btn = gr.Button("๐Ÿง  Explain Human-Solution")
229
- coeff_explain_btn.click(fn=request_llm_explanation, inputs=[coeff_hidden_equation, llm_url], outputs=coeff_explain_box)
230
 
231
  if __name__ == "__main__":
232
  demo.launch()
 
50
  latex = latex.replace('e', '2.7183')
51
  return latex
52
 
53
+ # def request_llm_fallback(bad_latex, llm_url):
54
+ # pre_cleaned = re.sub(r'(\\!?pm|\\not=?|\\!|\\L|\\perp|\\bar|\\Sigma|\\boldmath|G|L(?=\^))', '', bad_latex)
55
+ # try:
56
+ # response = requests.post(f"{llm_url}/clean", json={"prompt": pre_cleaned})
57
+ # if response.status_code == 200:
58
+ # return response.json().get("cleaned_latex", pre_cleaned)
59
+ # except Exception as e:
60
+ # print(f"LLM fallback failed: {e}")
61
+ # return pre_cleaned
62
+
63
+ # def request_llm_explanation(prompt, llm_url):
64
+ # try:
65
+ # response = requests.post(f"{llm_url}/explain", json={"prompt": prompt})
66
+ # if response.status_code == 200:
67
+ # return response.json().get("explanation", "โŒ No explanation returned.")
68
+ # else:
69
+ # return f"โŒ LLM explanation failed: {response.status_code}"
70
+ # except Exception as e:
71
+ # return f"โŒ LLM explanation error: {e}"
72
+
73
+ def solve_polynomial(image): # removed llm_url
74
  try:
75
  img = preprocess_handwritten_image(image)
76
  latex_result = model(img)
 
86
  if not lhs.is_polynomial():
87
  raise ValueError("Not a polynomial")
88
  except:
89
+ # Commented out LLM fallback
90
+ # fixed_latex = request_llm_fallback(cleaned_latex, llm_url)
91
+ # cleaned_latex = clean_latex(fixed_latex)
92
+ return f"โŒ Could not parse expression:\n\n```latex\n{cleaned_latex}\n```", cleaned_latex, ""
 
 
 
 
 
 
 
 
93
 
94
  output = f"## ๐Ÿ“„ Extracted LaTeX\n```latex\n{latex_result}\n```\n"
95
  output += f"---\n## ๐Ÿงน Cleaned LaTeX\n```latex\n{cleaned_latex}\n```\n"
 
104
  roots = sp.solve(lhs, x)
105
  output += "## โœ… Roots\n"
106
  output += "$$\n\\begin{aligned}\n"
 
107
  for i, r in enumerate(roots, 1):
108
  root_val = sp.N(r, 6)
109
  output += f"\\text{{Root {i}}}:\\quad x &\\approx {sp.latex(root_val)} \\\\\n"
 
110
  output += "\\end{aligned}\n$$\n"
111
 
112
+ return output, cleaned_latex, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  except Exception as e:
114
  return f"โŒ Error: {str(e)}", "", ""
115
 
116
+ def wrapped_solver(img): # removed url
117
+ result, cleaned, prompt = solve_polynomial(img)
118
  return result, cleaned, prompt
119
 
120
+ # def solve_from_coeffs(degree, coeff_str):
121
+ # try:
122
+ # coeffs = [float(c.strip()) for c in coeff_str.split(",")]
123
+ # if len(coeffs) != int(degree) + 1:
124
+ # return f"โŒ You entered {len(coeffs)} coefficients, but degree {degree} needs {int(degree)+1}.", ""
125
+
126
+ # x = sp.Symbol("x")
127
+ # poly_expr = sum(coeffs[i] * x**(int(degree) - i) for i in range(len(coeffs)))
128
+ # factored = sp.factor(poly_expr)
129
+ # roots = sp.solve(poly_expr, x)
130
+
131
+ # result = "## ๐Ÿงฎ Symbolic Roots:\n"
132
+ # for i, r in enumerate(roots, 1):
133
+ # result += f"- Root {i}: $${sp.latex(sp.N(r, 6))}$$\n"
134
+
135
+ # terms = []
136
+ # for i, c in enumerate(coeffs):
137
+ # power = int(degree) - i
138
+ # if power == 0:
139
+ # terms.append(f"{c}")
140
+ # elif power == 1:
141
+ # terms.append(f"{c}x")
142
+ # else:
143
+ # terms.append(f"{c}x^{power}")
144
+ # equation_str = " + ".join(terms).replace("+ -", "- ") + " = 0"
145
+ # roots_str = f"[{', '.join(str(sp.N(r, 6)) for r in roots)}]"
146
+ # factored_str = sp.pretty(factored)
147
+
148
+ # llm_prompt = (
149
+ # f"Equation: {equation_str}\n"
150
+ # f"Factor: {factored_str} = 0\n"
151
+ # f"Roots: {roots_str}\n\n"
152
+ # "Explain the solution step-by-step in human language. "
153
+ # "These roots are correct (up to approximation), so base your reasoning on them."
154
+ # )
155
+
156
+ # return result, llm_prompt
157
+ # except Exception as e:
158
+ # return f"โŒ Error: {str(e)}", ""
159
 
160
  with gr.Blocks() as demo:
161
  with gr.Tab("๐Ÿ–ผ๏ธ Parse from Image"):
162
+ # llm_url = gr.Textbox(label="๐Ÿ”— Enter LLM Microservice URL (from Colab)", placeholder="https://xxxx.ngrok-free.app")
163
  image_input = gr.Image(type="pil", label="๐Ÿ“ท Upload Image of Polynomial")
164
  hidden_latex = gr.Textbox(visible=False)
165
  explanation_prompt = gr.Textbox(visible=False)
166
  output_box = gr.Markdown(label="๐Ÿ“‹ Step-by-step Solution")
167
  submit_btn = gr.Button("๐Ÿ” Solve")
168
+ submit_btn.click(fn=wrapped_solver, inputs=[image_input], outputs=[output_box, hidden_latex, explanation_prompt])
169
+ # explain_box = gr.Markdown(label="๐Ÿ—ฃ๏ธ Human-style Explanation")
170
+ # explain_btn = gr.Button("๐Ÿง  Explain Human-Solution")
171
+ # explain_btn.click(fn=request_llm_explanation, inputs=[explanation_prompt, llm_url], outputs=explain_box)
172
+
173
+ # with gr.Tab("๐Ÿงฎ Solve by Coefficients"):
174
+ # degree_input = gr.Number(label="Enter Degree of Polynomial (e.g. 3)")
175
+ # coeffs_input = gr.Textbox(label="Enter Coefficients (comma-separated)", placeholder="e.g. 1, 2, 0, -4")
176
+ # roots_output = gr.Markdown(label="โœ… Roots")
177
+ # coeff_hidden_equation = gr.Textbox(visible=False)
178
+ # coeff_btn = gr.Button("๐Ÿ“Œ Solve")
179
+ # coeff_btn.click(fn=solve_from_coeffs, inputs=[degree_input, coeffs_input], outputs=[roots_output, coeff_hidden_equation])
180
+ # coeff_explain_box = gr.Markdown(label="๐Ÿ—ฃ๏ธ Human-style Explanation")
181
+ # coeff_explain_btn = gr.Button("๐Ÿง  Explain Human-Solution")
182
+ # coeff_explain_btn.click(fn=request_llm_explanation, inputs=[coeff_hidden_equation, llm_url], outputs=coeff_explain_box)
183
 
184
  if __name__ == "__main__":
185
  demo.launch()