Update app.py
Browse files
app.py
CHANGED
|
@@ -130,40 +130,48 @@ with gr.Blocks() as demo:
|
|
| 130 |
sim_button = gr.Button("π Solve System")
|
| 131 |
|
| 132 |
def solve_system_of_equations(image):
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
sim_button.click(fn=solve_system_of_equations, inputs=[sim_image_input], outputs=[sim_output])
|
| 169 |
|
|
|
|
| 130 |
sim_button = gr.Button("π Solve System")
|
| 131 |
|
| 132 |
def solve_system_of_equations(image):
|
| 133 |
+
try:
|
| 134 |
+
img = preprocess_handwritten_image(image)
|
| 135 |
+
raw_latex = model(img)
|
| 136 |
+
if not raw_latex or len(raw_latex.strip()) < 3:
|
| 137 |
+
return "β Could not extract valid LaTeX."
|
| 138 |
+
|
| 139 |
+
# Clean up array environments if present
|
| 140 |
+
if r"\begin{array" in raw_latex:
|
| 141 |
+
lines = re.findall(r'\\begin{array}{[^}]+}(.+?)\\end{array}', raw_latex, re.DOTALL)
|
| 142 |
+
if lines:
|
| 143 |
+
raw_latex = lines[0]
|
| 144 |
+
raw_latex = raw_latex.replace(r'\\', '\n') # line separator
|
| 145 |
+
raw_latex = re.sub(r'&', '', raw_latex) # remove LaTeX column markers
|
| 146 |
+
|
| 147 |
+
raw_latex = raw_latex.replace("\n", " ")
|
| 148 |
+
equations = re.split(r'[;,]', raw_latex)
|
| 149 |
+
cleaned_equations = [clean_latex2(eq) for eq in equations if '=' in eq]
|
| 150 |
+
|
| 151 |
+
sympy_eqs = []
|
| 152 |
+
symbols = set()
|
| 153 |
+
for eq in cleaned_equations:
|
| 154 |
+
parsed = parse_latex(eq)
|
| 155 |
+
if isinstance(parsed, sp.Equality):
|
| 156 |
+
sympy_eqs.append(parsed)
|
| 157 |
+
symbols.update(parsed.free_symbols)
|
| 158 |
+
|
| 159 |
+
if len(sympy_eqs) < 2:
|
| 160 |
+
return f"β Not enough valid equations detected.\n\n```latex\n{raw_latex}\n```"
|
| 161 |
+
|
| 162 |
+
sol = sp.solve(sympy_eqs, list(symbols), dict=True)
|
| 163 |
+
output = f"## π§Ύ Detected Equations:\n```latex\n{raw_latex}\n```\n"
|
| 164 |
+
output += "---\n## βοΈ Parsed & Cleaned:\n"
|
| 165 |
+
for eq in sympy_eqs:
|
| 166 |
+
output += f"$$ {sp.latex(eq)} $$\n"
|
| 167 |
+
output += "---\n## β
Solution:\n"
|
| 168 |
+
if sol:
|
| 169 |
+
output += "$$" + sp.latex(sol[0]) + "$$"
|
| 170 |
+
else:
|
| 171 |
+
output += "β No solution found or system may be inconsistent."
|
| 172 |
+
return output
|
| 173 |
+
except Exception as e:
|
| 174 |
+
return f"β Error: {str(e)}"
|
| 175 |
|
| 176 |
sim_button.click(fn=solve_system_of_equations, inputs=[sim_image_input], outputs=[sim_output])
|
| 177 |
|