Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,9 @@ from sympy.parsing.latex import parse_latex
|
|
| 6 |
import re
|
| 7 |
import os
|
| 8 |
|
|
|
|
|
|
|
|
|
|
| 9 |
# Trigger data download only once
|
| 10 |
if not os.path.exists("dataset/train"):
|
| 11 |
print("π Running data preparation scripts...")
|
|
@@ -13,58 +16,41 @@ if not os.path.exists("dataset/train"):
|
|
| 13 |
os.system("python generate_csv.py")
|
| 14 |
|
| 15 |
|
| 16 |
-
# Preprocessing
|
| 17 |
def preprocess_handwritten_image(pil_img):
|
| 18 |
-
return pil_img.convert('RGB')
|
| 19 |
|
| 20 |
|
| 21 |
-
# Load Pix2Tex model
|
| 22 |
model = LatexOCR()
|
| 23 |
|
|
|
|
| 24 |
# Clean LaTeX output
|
| 25 |
def clean_latex(latex):
|
| 26 |
-
# Replace \mathcal{X} or \cal X with 'x'
|
| 27 |
latex = re.sub(r'\\(cal|mathcal)\s*X', 'x', latex)
|
| 28 |
-
|
| 29 |
-
# Remove curly braces
|
| 30 |
latex = latex.replace('{', '').replace('}', '')
|
| 31 |
latex = latex.strip().rstrip(',.')
|
| 32 |
-
|
| 33 |
-
# Replace coefficients like 5\pi with (5*3.1416)
|
| 34 |
latex = re.sub(r'(\d+)\s*\\pi', r'(\1*3.1416)', latex)
|
| 35 |
latex = latex.replace(r'\pi', '3.1416')
|
| 36 |
-
|
| 37 |
-
# Replace coefficients like 5e with (5*2.7183)
|
| 38 |
latex = re.sub(r'(\d+)\s*e', r'(\1*2.7183)', latex)
|
| 39 |
latex = re.sub(r'(?<![a-zA-Z0-9])e(?![a-zA-Z0-9])', '2.7183', latex)
|
| 40 |
-
|
| 41 |
-
# Insert * between number and variable (e.g., 45x β 45*x)
|
| 42 |
latex = re.sub(r'(\d)([a-zA-Z])', r'\1*\2', latex)
|
| 43 |
-
|
| 44 |
-
# Replace number followed by i with number*I
|
| 45 |
latex = re.sub(r'(\d+)\s*i', r'\1*I', latex)
|
| 46 |
-
|
| 47 |
-
# Replace standalone i with I
|
| 48 |
latex = re.sub(r'(?<![a-zA-Z0-9])i(?![a-zA-Z0-9])', 'I', latex)
|
| 49 |
-
|
| 50 |
-
# Wrap complex coefficients with variables: (a+bI)x^n β (a+b*I)*x^n
|
| 51 |
latex = re.sub(r'\(([^()]+?)\)\s*([xX](\^\d+)?)', r'(\1)*\2', latex)
|
| 52 |
-
|
| 53 |
-
# Append '=0' if not already present
|
| 54 |
if '=' not in latex:
|
| 55 |
latex += '=0'
|
| 56 |
-
|
| 57 |
return latex
|
| 58 |
|
| 59 |
|
| 60 |
-
#
|
| 61 |
def solve_polynomial(image):
|
| 62 |
try:
|
| 63 |
img = preprocess_handwritten_image(image)
|
| 64 |
latex_result = model(img)
|
| 65 |
cleaned_latex = clean_latex(latex_result)
|
| 66 |
-
|
| 67 |
expr = parse_latex(cleaned_latex)
|
|
|
|
| 68 |
output = f"## π Extracted LaTeX\n```\n{latex_result}\n```\n"
|
| 69 |
output += "---\n"
|
| 70 |
output += f"## π§Ή Cleaned LaTeX Used\n```\n{cleaned_latex}\n```\n"
|
|
@@ -74,7 +60,6 @@ def solve_polynomial(image):
|
|
| 74 |
|
| 75 |
if isinstance(expr, sp.Equality):
|
| 76 |
lhs = expr.lhs - expr.rhs
|
| 77 |
-
|
| 78 |
output += "## βοΈ Step 1: Standard Form of the Polynomial\n"
|
| 79 |
output += f"$$ {sp.latex(lhs)} = 0 $$\n"
|
| 80 |
output += "---\n"
|
|
@@ -86,34 +71,49 @@ def solve_polynomial(image):
|
|
| 86 |
|
| 87 |
output += "## β
Step 3: Solve for Roots\n"
|
| 88 |
roots = sp.solve(sp.Eq(lhs, 0), dict=True)
|
| 89 |
-
|
| 90 |
if roots:
|
| 91 |
output += "$$\n\\begin{aligned}\n"
|
| 92 |
for i, sol in enumerate(roots, 1):
|
| 93 |
for var, val in sol.items():
|
| 94 |
output += f"\\text{{Root {i}}}:\\quad {var} &= {sp.latex(val)} \\\\\n"
|
| 95 |
output += "\\end{aligned}\n$$\n"
|
| 96 |
-
|
| 97 |
else:
|
| 98 |
simplified = sp.simplify(expr)
|
| 99 |
output += "## β Simplified Expression\n"
|
| 100 |
output += f"$$ {sp.latex(simplified)} $$"
|
| 101 |
|
| 102 |
return output
|
| 103 |
-
|
| 104 |
except Exception as e:
|
| 105 |
return f"β **Error**: {str(e)}"
|
| 106 |
|
| 107 |
|
| 108 |
-
#
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
if __name__ == "__main__":
|
| 119 |
-
demo.launch()
|
|
|
|
| 6 |
import re
|
| 7 |
import os
|
| 8 |
|
| 9 |
+
# Optional: import training function
|
| 10 |
+
from train import train_model
|
| 11 |
+
|
| 12 |
# Trigger data download only once
|
| 13 |
if not os.path.exists("dataset/train"):
|
| 14 |
print("π Running data preparation scripts...")
|
|
|
|
| 16 |
os.system("python generate_csv.py")
|
| 17 |
|
| 18 |
|
| 19 |
+
# Preprocessing
|
| 20 |
def preprocess_handwritten_image(pil_img):
|
| 21 |
+
return pil_img.convert('RGB')
|
| 22 |
|
| 23 |
|
| 24 |
+
# Load Pix2Tex model
|
| 25 |
model = LatexOCR()
|
| 26 |
|
| 27 |
+
|
| 28 |
# Clean LaTeX output
|
| 29 |
def clean_latex(latex):
|
|
|
|
| 30 |
latex = re.sub(r'\\(cal|mathcal)\s*X', 'x', latex)
|
|
|
|
|
|
|
| 31 |
latex = latex.replace('{', '').replace('}', '')
|
| 32 |
latex = latex.strip().rstrip(',.')
|
|
|
|
|
|
|
| 33 |
latex = re.sub(r'(\d+)\s*\\pi', r'(\1*3.1416)', latex)
|
| 34 |
latex = latex.replace(r'\pi', '3.1416')
|
|
|
|
|
|
|
| 35 |
latex = re.sub(r'(\d+)\s*e', r'(\1*2.7183)', latex)
|
| 36 |
latex = re.sub(r'(?<![a-zA-Z0-9])e(?![a-zA-Z0-9])', '2.7183', latex)
|
|
|
|
|
|
|
| 37 |
latex = re.sub(r'(\d)([a-zA-Z])', r'\1*\2', latex)
|
|
|
|
|
|
|
| 38 |
latex = re.sub(r'(\d+)\s*i', r'\1*I', latex)
|
|
|
|
|
|
|
| 39 |
latex = re.sub(r'(?<![a-zA-Z0-9])i(?![a-zA-Z0-9])', 'I', latex)
|
|
|
|
|
|
|
| 40 |
latex = re.sub(r'\(([^()]+?)\)\s*([xX](\^\d+)?)', r'(\1)*\2', latex)
|
|
|
|
|
|
|
| 41 |
if '=' not in latex:
|
| 42 |
latex += '=0'
|
|
|
|
| 43 |
return latex
|
| 44 |
|
| 45 |
|
| 46 |
+
# Solver logic
|
| 47 |
def solve_polynomial(image):
|
| 48 |
try:
|
| 49 |
img = preprocess_handwritten_image(image)
|
| 50 |
latex_result = model(img)
|
| 51 |
cleaned_latex = clean_latex(latex_result)
|
|
|
|
| 52 |
expr = parse_latex(cleaned_latex)
|
| 53 |
+
|
| 54 |
output = f"## π Extracted LaTeX\n```\n{latex_result}\n```\n"
|
| 55 |
output += "---\n"
|
| 56 |
output += f"## π§Ή Cleaned LaTeX Used\n```\n{cleaned_latex}\n```\n"
|
|
|
|
| 60 |
|
| 61 |
if isinstance(expr, sp.Equality):
|
| 62 |
lhs = expr.lhs - expr.rhs
|
|
|
|
| 63 |
output += "## βοΈ Step 1: Standard Form of the Polynomial\n"
|
| 64 |
output += f"$$ {sp.latex(lhs)} = 0 $$\n"
|
| 65 |
output += "---\n"
|
|
|
|
| 71 |
|
| 72 |
output += "## β
Step 3: Solve for Roots\n"
|
| 73 |
roots = sp.solve(sp.Eq(lhs, 0), dict=True)
|
|
|
|
| 74 |
if roots:
|
| 75 |
output += "$$\n\\begin{aligned}\n"
|
| 76 |
for i, sol in enumerate(roots, 1):
|
| 77 |
for var, val in sol.items():
|
| 78 |
output += f"\\text{{Root {i}}}:\\quad {var} &= {sp.latex(val)} \\\\\n"
|
| 79 |
output += "\\end{aligned}\n$$\n"
|
|
|
|
| 80 |
else:
|
| 81 |
simplified = sp.simplify(expr)
|
| 82 |
output += "## β Simplified Expression\n"
|
| 83 |
output += f"$$ {sp.latex(simplified)} $$"
|
| 84 |
|
| 85 |
return output
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
return f"β **Error**: {str(e)}"
|
| 88 |
|
| 89 |
|
| 90 |
+
# Trigger training
|
| 91 |
+
def run_training():
|
| 92 |
+
try:
|
| 93 |
+
train_model("train.yaml") # path to your training config
|
| 94 |
+
return "β
Training completed successfully."
|
| 95 |
+
except Exception as e:
|
| 96 |
+
return f"β Training failed: {str(e)}"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# Gradio UI with training button
|
| 100 |
+
with gr.Blocks() as demo:
|
| 101 |
+
gr.Markdown("## π§ Polynomial Solver from Handwritten Image")
|
| 102 |
+
gr.Markdown("Upload a handwritten polynomial image. The app will extract and solve it step-by-step.")
|
| 103 |
+
|
| 104 |
+
with gr.Row():
|
| 105 |
+
image_input = gr.Image(type="pil", label="π· Upload Polynomial Image")
|
| 106 |
+
solution_output = gr.Markdown(label="π Step-by-step Solution")
|
| 107 |
+
|
| 108 |
+
image_input.change(fn=solve_polynomial, inputs=image_input, outputs=solution_output)
|
| 109 |
+
|
| 110 |
+
gr.Markdown("----")
|
| 111 |
+
|
| 112 |
+
gr.Markdown("## π Optional: Fine-tune Pix2Tex (CPU)")
|
| 113 |
+
train_btn = gr.Button("π Start CPU Training")
|
| 114 |
+
train_output = gr.Textbox(label="Training Status")
|
| 115 |
+
|
| 116 |
+
train_btn.click(fn=run_training, outputs=train_output)
|
| 117 |
+
|
| 118 |
+
demo.launch()
|
| 119 |
|
|
|
|
|
|