MasteredUltraInstinct commited on
Commit
f992f37
Β·
verified Β·
1 Parent(s): e2deeef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -60
app.py CHANGED
@@ -1,71 +1,84 @@
 
1
  import gradio as gr
2
- from PIL import Image
3
- from pix2tex.cli import LatexOCR
4
- import sympy as sp
5
- from sympy.parsing.latex import parse_latex
6
- import re
7
 
8
- def preprocess_handwritten_image(pil_img):
9
- return pil_img.convert('RGB')
 
 
 
 
10
 
11
- model = LatexOCR(weights='trained_model')
 
12
 
13
- def clean_latex(latex):
14
- latex = re.sub(r'\\(cal|mathcal)\s*X', 'x', latex)
15
- latex = latex.replace('{', '').replace('}', '')
16
- latex = latex.strip().rstrip(',.')
17
- latex = re.sub(r'(\d+)\s*\\pi', r'(\1*3.1416)', latex)
18
- latex = latex.replace(r'\pi', '3.1416')
19
- latex = re.sub(r'(\d+)\s*e', r'(\1*2.7183)', latex)
20
- latex = re.sub(r'(?<![a-zA-Z0-9])e(?![a-zA-Z0-9])', '2.7183', latex)
21
- latex = re.sub(r'(\d)([a-zA-Z])', r'\1*\2', latex)
22
- latex = re.sub(r'(\d+)\s*i', r'\1*I', latex)
23
- latex = re.sub(r'(?<![a-zA-Z0-9])i(?![a-zA-Z0-9])', 'I', latex)
24
- latex = re.sub(r'\(([^()]+?)\)\s*([xX](\^\d+)?)', r'(\1)*\2', latex)
25
- if '=' not in latex:
26
- latex += '=0'
27
- return latex
28
 
29
- def solve_polynomial(image):
30
- try:
31
- img = preprocess_handwritten_image(image)
32
- latex_result = model(img)
33
- cleaned_latex = clean_latex(latex_result)
34
- expr = parse_latex(cleaned_latex)
 
 
 
 
 
 
 
 
 
35
 
36
- output = f"## πŸ“„ Extracted LaTeX\n```\n{latex_result}\n```\n---\n"
37
- output += f"## 🧹 Cleaned LaTeX Used\n```\n{cleaned_latex}\n```\n---\n"
38
- output += f"## 🧠 Parsed Expression\n\n$$ {sp.latex(expr)} $$\n---\n"
 
 
 
39
 
40
- if isinstance(expr, sp.Equality):
41
- lhs = expr.lhs - expr.rhs
42
- output += "## ✏️ Step 1: Standard Form\n"
43
- output += f"$$ {sp.latex(lhs)} = 0 $$\n---\n"
44
- output += "## 🧩 Step 2: Factorized\n"
45
- output += f"$$ {sp.latex(sp.factor(lhs))} = 0 $$\n---\n"
46
- output += "## βœ… Step 3: Roots\n"
47
- roots = sp.solve(sp.Eq(lhs, 0), dict=True)
48
- if roots:
49
- output += "$$\n\\begin{aligned}\n"
50
- for i, sol in enumerate(roots, 1):
51
- for var, val in sol.items():
52
- output += f"\\text{{Root {i}}}: {var} &= {sp.latex(val)}\\\\\n"
53
- output += "\\end{aligned}\n$$"
54
- else:
55
- output += "## βž• Simplified\n"
56
- output += f"$$ {sp.latex(sp.simplify(expr))} $$"
57
 
58
- return output
59
- except Exception as e:
60
- return f"❌ **Error**: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- demo = gr.Interface(
63
- fn=solve_polynomial,
64
- inputs=gr.Image(type="pil", label="πŸ“· Upload Image"),
65
- outputs=gr.Markdown(label="πŸ“‹ Solution"),
66
- title="🧠 Handwritten Polynomial Solver",
67
- description="Extract handwritten polynomials and solve step-by-step.",
68
- allow_flagging="never"
69
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  demo.launch()
 
1
+ import os
2
  import gradio as gr
 
 
 
 
 
3
 
4
+ if os.path.exists("trained_model"):
5
+ from PIL import Image
6
+ from pix2tex.cli import LatexOCR
7
+ import sympy as sp
8
+ from sympy.parsing.latex import parse_latex
9
+ import re
10
 
11
+ def preprocess_handwritten_image(pil_img):
12
+ return pil_img.convert('RGB')
13
 
14
+ model = LatexOCR(weights='trained_model')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ def clean_latex(latex):
17
+ latex = re.sub(r'\\(cal|mathcal)\s*X', 'x', latex)
18
+ latex = latex.replace('{', '').replace('}', '')
19
+ latex = latex.strip().rstrip(',.')
20
+ latex = re.sub(r'(\d+)\s*\\pi', r'(\1*3.1416)', latex)
21
+ latex = latex.replace(r'\pi', '3.1416')
22
+ latex = re.sub(r'(\d+)\s*e', r'(\1*2.7183)', latex)
23
+ latex = re.sub(r'(?<![a-zA-Z0-9])e(?![a-zA-Z0-9])', '2.7183', latex)
24
+ latex = re.sub(r'(\d)([a-zA-Z])', r'\1*\2', latex)
25
+ latex = re.sub(r'(\d+)\s*i', r'\1*I', latex)
26
+ latex = re.sub(r'(?<![a-zA-Z0-9])i(?![a-zA-Z0-9])', 'I', latex)
27
+ latex = re.sub(r'\(([^()]+?)\)\s*([xX](\^\d+)?)', r'(\1)*\2', latex)
28
+ if '=' not in latex:
29
+ latex += '=0'
30
+ return latex
31
 
32
+ def solve_polynomial(image):
33
+ try:
34
+ img = preprocess_handwritten_image(image)
35
+ latex_result = model(img)
36
+ cleaned_latex = clean_latex(latex_result)
37
+ expr = parse_latex(cleaned_latex)
38
 
39
+ output = f"## πŸ“„ Extracted LaTeX\n```\n{latex_result}\n```\n---\n"
40
+ output += f"## 🧹 Cleaned LaTeX Used\n```\n{cleaned_latex}\n```\n---\n"
41
+ output += f"## 🧠 Parsed Expression\n\n$$ {sp.latex(expr)} $$\n---\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ if isinstance(expr, sp.Equality):
44
+ lhs = expr.lhs - expr.rhs
45
+ output += "## ✏️ Step 1: Standard Form\n"
46
+ output += f"$$ {sp.latex(lhs)} = 0 $$\n---\n"
47
+ output += "## 🧩 Step 2: Factorized\n"
48
+ output += f"$$ {sp.latex(sp.factor(lhs))} = 0 $$\n---\n"
49
+ output += "## βœ… Step 3: Roots\n"
50
+ roots = sp.solve(sp.Eq(lhs, 0), dict=True)
51
+ if roots:
52
+ output += "$$\n\\begin{aligned}\n"
53
+ for i, sol in enumerate(roots, 1):
54
+ for var, val in sol.items():
55
+ output += f"\\text{{Root {i}}}: {var} &= {sp.latex(val)}\\\\\n"
56
+ output += "\\end{aligned}\n$$"
57
+ else:
58
+ output += "## βž• Simplified\n"
59
+ output += f"$$ {sp.latex(sp.simplify(expr))} $$"
60
 
61
+ return output
62
+ except Exception as e:
63
+ return f"❌ **Error**: {str(e)}"
64
+
65
+ demo = gr.Interface(
66
+ fn=solve_polynomial,
67
+ inputs=gr.Image(type="pil", label="πŸ“· Upload Image"),
68
+ outputs=gr.Markdown(label="πŸ“‹ Solution"),
69
+ title="🧠 Handwritten Polynomial Solver",
70
+ description="Upload a handwritten polynomial to extract, solve, and view steps.",
71
+ allow_flagging="never"
72
+ )
73
+
74
+ else:
75
+ # Dummy interface before training is done
76
+ demo = gr.Interface(
77
+ fn=lambda: "Training not completed yet. Please run `train.py` to generate `trained_model/`.",
78
+ inputs=[],
79
+ outputs="text",
80
+ title="⚠️ Model Not Ready",
81
+ description="Run training first to enable polynomial solving."
82
+ )
83
 
84
  demo.launch()