Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,6 +10,48 @@ model = LatexOCR()
|
|
| 10 |
def preprocess_handwritten_image(pil_img):
|
| 11 |
return pil_img.convert('RGB')
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
def clean_latex2(latex):
|
| 14 |
latex = latex.replace('\\ ', '')
|
| 15 |
latex = latex.replace('\\\\', '\\')
|
|
@@ -34,59 +76,96 @@ def clean_latex2(latex):
|
|
| 34 |
latex = re.sub(wrong, right, latex)
|
| 35 |
return latex.strip()
|
| 36 |
|
| 37 |
-
|
|
|
|
| 38 |
try:
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
img = preprocess_handwritten_image(img)
|
| 47 |
latex = model(img)
|
| 48 |
-
|
| 49 |
cleaned = clean_latex2(latex)
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
except:
|
| 56 |
-
continue
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
except Exception as e:
|
| 79 |
-
return f"β Error: {str(e)}"
|
| 80 |
|
|
|
|
| 81 |
with gr.Blocks() as demo:
|
| 82 |
-
gr.
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
img1 = gr.Image(type="pil", label="π· Equation 1")
|
| 85 |
img2 = gr.Image(type="pil", label="π· Equation 2")
|
| 86 |
-
img3 = gr.Image(type="pil", label="π· (Optional)
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
|
| 91 |
if __name__ == "__main__":
|
| 92 |
demo.launch()
|
|
|
|
| 10 |
def preprocess_handwritten_image(pil_img):
|
| 11 |
return pil_img.convert('RGB')
|
| 12 |
|
| 13 |
+
# --- Tab 1 cleaner (UNCHANGED) ---
|
| 14 |
+
def clean_latex(latex):
|
| 15 |
+
latex = latex.replace('\\ ', '')
|
| 16 |
+
latex = latex.replace('\\\\', '\\')
|
| 17 |
+
latex = re.sub(r'\\[ \t\n\r\f\v]*', '', latex)
|
| 18 |
+
latex = re.sub(r'\\([+\-=])', r'\1', latex)
|
| 19 |
+
replacements = {
|
| 20 |
+
r'\\chi': 'x', r'chi': 'x',
|
| 21 |
+
r'\\xi': 'x', r'xi': 'x',
|
| 22 |
+
r'\\alpha': 'x', r'alpha': 'x',
|
| 23 |
+
r'\\beta': 'b', r'beta': 'b',
|
| 24 |
+
r'\\gamma': 'y', r'gamma': 'y',
|
| 25 |
+
r'\\vartheta': '3', r'vartheta': '3',
|
| 26 |
+
r'\\mathcalW': 'x', r'mathcalW': 'x',
|
| 27 |
+
r'\\pi': 'pi', r'pi': 'pi',
|
| 28 |
+
r'\\mathrm': '', r'mathrm': '',
|
| 29 |
+
}
|
| 30 |
+
for wrong, correct in replacements.items():
|
| 31 |
+
latex = re.sub(wrong, correct, latex)
|
| 32 |
+
latex = re.sub(r'\\(cal|mathcal)\s*\{?\s*[Xx]\s*\}?', 'x', latex)
|
| 33 |
+
latex = re.sub(r'\\(cal|mathcal)\s*\{?\s*[Yy]\s*\}?', 'y', latex)
|
| 34 |
+
latex = re.sub(r'\\(cal|mathcal)\s*\{?\s*[Zz]\s*\}?', 'z', latex)
|
| 35 |
+
latex = latex.replace('cal x', 'x').replace('cal X', 'x')
|
| 36 |
+
latex = latex.replace('mathcal x', 'x').replace('mathcal X', 'x')
|
| 37 |
+
latex = latex.replace('{', '').replace('}', '')
|
| 38 |
+
latex = latex.strip().rstrip(',.')
|
| 39 |
+
latex = re.sub(r'(?<![a-zA-Z0-9])e(?![a-zA-Z0-9])', 'E', latex)
|
| 40 |
+
latex = re.sub(r'(\d)([a-zA-Z])', r'\1*\2', latex)
|
| 41 |
+
latex = re.sub(r'(\d+)\s*i', r'\1*I', latex)
|
| 42 |
+
latex = re.sub(r'(?<![a-zA-Z0-9])i(?![a-zA-Z0-9])', 'I', latex)
|
| 43 |
+
latex = re.sub(r'\(([^()]+?)\)\s*([a-zA-Z](\^\d+)?)', r'(\1)*\2', latex)
|
| 44 |
+
latex = latex.replace(r'\cdot', '*')
|
| 45 |
+
latex = latex.replace('β', '-')
|
| 46 |
+
latex = re.sub(r'[^\w\s^=+*\-().]', '', latex)
|
| 47 |
+
if '=' not in latex:
|
| 48 |
+
latex += '=0'
|
| 49 |
+
latex = latex.replace('pi', '3.1416')
|
| 50 |
+
latex = latex.replace('e', '2.7183')
|
| 51 |
+
latex = latex.replace('E', '2.7183')
|
| 52 |
+
return latex
|
| 53 |
+
|
| 54 |
+
# --- Tab 2 cleaner ---
|
| 55 |
def clean_latex2(latex):
|
| 56 |
latex = latex.replace('\\ ', '')
|
| 57 |
latex = latex.replace('\\\\', '\\')
|
|
|
|
| 76 |
latex = re.sub(wrong, right, latex)
|
| 77 |
return latex.strip()
|
| 78 |
|
| 79 |
+
# --- Polynomial Solver (unchanged) ---
|
| 80 |
+
def solve_polynomial(image):
|
| 81 |
try:
|
| 82 |
+
img = preprocess_handwritten_image(image)
|
| 83 |
+
latex_result = model(img)
|
| 84 |
+
if not latex_result or len(latex_result.strip()) < 2:
|
| 85 |
+
return "β Could not extract valid LaTeX from image.", "", ""
|
| 86 |
+
cleaned_latex = clean_latex(latex_result)
|
| 87 |
+
expr = parse_latex(cleaned_latex)
|
| 88 |
+
expr = expr.subs(sp.pi, sp.Float(3.1416)).subs(sp.E, sp.Float(2.7183))
|
| 89 |
+
if not isinstance(expr, sp.Equality):
|
| 90 |
+
raise ValueError("Expression is not an equation.")
|
| 91 |
+
lhs = expr.lhs - expr.rhs
|
| 92 |
+
if not lhs.is_polynomial():
|
| 93 |
+
raise ValueError("Not a polynomial")
|
| 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"
|
| 96 |
+
output += f"---\n## π§ Parsed Expression\n$$ {sp.latex(expr)} $$\n"
|
| 97 |
+
factor = sp.factor(lhs)
|
| 98 |
+
output += f"---\n## βοΈ Standard Form\n$$ {sp.latex(lhs)} = 0 $$\n"
|
| 99 |
+
output += f"---\n## π§© Factorized\n$$ {sp.latex(factor)} = 0 $$\n"
|
| 100 |
+
x = next(iter(lhs.free_symbols))
|
| 101 |
+
roots = sp.solve(lhs, x)
|
| 102 |
+
output += "## β
Roots\n"
|
| 103 |
+
output += "$$\n\\begin{aligned}\n"
|
| 104 |
+
for i, r in enumerate(roots, 1):
|
| 105 |
+
root_val = sp.N(r, 6)
|
| 106 |
+
output += f"\\text{{Root {i}}}:\\quad x &\\approx {sp.latex(root_val)} \\\\\n"
|
| 107 |
+
output += "\\end{aligned}\n$$\n"
|
| 108 |
+
return output, cleaned_latex, ""
|
| 109 |
+
except Exception as e:
|
| 110 |
+
return f"β Error: {str(e)}", "", ""
|
| 111 |
|
| 112 |
+
# --- NEW Multi-image System Solver ---
|
| 113 |
+
def solve_system_multi(img1, img2, img3):
|
| 114 |
+
images = [img1, img2, img3]
|
| 115 |
+
cleaned_equations = []
|
| 116 |
+
raw_outputs = []
|
| 117 |
+
for img in images:
|
| 118 |
+
if img is None:
|
| 119 |
+
continue
|
| 120 |
+
try:
|
| 121 |
img = preprocess_handwritten_image(img)
|
| 122 |
latex = model(img)
|
| 123 |
+
raw_outputs.append(latex)
|
| 124 |
cleaned = clean_latex2(latex)
|
| 125 |
+
parsed = parse_latex(cleaned)
|
| 126 |
+
if isinstance(parsed, sp.Equality):
|
| 127 |
+
cleaned_equations.append(parsed)
|
| 128 |
+
except:
|
| 129 |
+
continue
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
if len(cleaned_equations) < 2:
|
| 132 |
+
return f"β Could not parse enough valid equations."
|
| 133 |
|
| 134 |
+
symbols = set()
|
| 135 |
+
for eq in cleaned_equations:
|
| 136 |
+
symbols.update(eq.free_symbols)
|
| 137 |
|
| 138 |
+
sol = sp.solve(cleaned_equations, list(symbols), dict=True)
|
| 139 |
+
output = "## π Raw LaTeX:\n"
|
| 140 |
+
for latex in raw_outputs:
|
| 141 |
+
output += f"- ```latex\n{latex}\n```\n"
|
| 142 |
+
output += "---\n## βοΈ Parsed Equations:\n"
|
| 143 |
+
for eq in cleaned_equations:
|
| 144 |
+
output += f"$$ {sp.latex(eq)} $$\n"
|
| 145 |
+
output += "---\n## β
Solution:\n"
|
| 146 |
+
if sol:
|
| 147 |
+
output += "$$" + sp.latex(sol[0]) + "$$"
|
| 148 |
+
else:
|
| 149 |
+
output += "β No solution found or system may be inconsistent."
|
| 150 |
+
return output
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
# === UI ===
|
| 153 |
with gr.Blocks() as demo:
|
| 154 |
+
with gr.Tab("πΌοΈ Parse from Image"):
|
| 155 |
+
image_input = gr.Image(type="pil", label="π· Upload Image of Polynomial")
|
| 156 |
+
hidden_latex = gr.Textbox(visible=False)
|
| 157 |
+
explanation_prompt = gr.Textbox(visible=False)
|
| 158 |
+
output_box = gr.Markdown(label="π Step-by-step Solution")
|
| 159 |
+
submit_btn = gr.Button("π Solve")
|
| 160 |
+
submit_btn.click(fn=solve_polynomial, inputs=[image_input], outputs=[output_box, hidden_latex, explanation_prompt])
|
| 161 |
+
|
| 162 |
+
with gr.Tab("π Solve System (Multi-Image)"):
|
| 163 |
img1 = gr.Image(type="pil", label="π· Equation 1")
|
| 164 |
img2 = gr.Image(type="pil", label="π· Equation 2")
|
| 165 |
+
img3 = gr.Image(type="pil", label="π· Equation 3 (Optional)")
|
| 166 |
+
sys_output = gr.Markdown(label="π Solved System Output")
|
| 167 |
+
sys_btn = gr.Button("π Solve System")
|
| 168 |
+
sys_btn.click(fn=solve_system_multi, inputs=[img1, img2, img3], outputs=[sys_output])
|
| 169 |
|
| 170 |
if __name__ == "__main__":
|
| 171 |
demo.launch()
|