Update app.py
Browse files
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 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
def request_llm_explanation(prompt, llm_url):
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def solve_polynomial(image
|
| 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 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 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 |
-
|
| 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
|
| 164 |
-
result, cleaned, prompt = solve_polynomial(img
|
| 165 |
return result, cleaned, prompt
|
| 166 |
|
| 167 |
-
def solve_from_coeffs(degree, coeff_str):
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 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
|
| 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 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 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()
|