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

Update app.py

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