MasteredUltraInstinct commited on
Commit
fd8a8f4
Β·
verified Β·
1 Parent(s): f7b7723

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -12
app.py CHANGED
@@ -9,38 +9,42 @@ import re
9
  def preprocess_handwritten_image(pil_img):
10
  return pil_img.convert('RGB') # Minimal processing, just convert to RGB
11
 
12
-
13
  # Load Pix2Tex model (once)
14
  model = LatexOCR()
15
 
16
  # Clean LaTeX output
17
  def clean_latex(latex):
18
  # Replace \mathcal{X} or \cal X with 'x'
19
- latex = re.sub(r'\\(cal|mathcal)\s*X', 'x', latex)
20
 
21
  # Remove curly braces
22
  latex = latex.replace('{', '').replace('}', '')
23
  latex = latex.strip().rstrip(',.')
24
-
25
  # Replace coefficients like 5\pi with (5*3.1416)
26
- latex = re.sub(r'(\d+)\s*\\pi', r'(\1*3.1416)', latex)
27
  latex = latex.replace(r'\pi', '3.1416')
28
 
29
  # Replace coefficients like 5e with (5*2.7183)
30
- latex = re.sub(r'(\d+)\s*e', r'(\1*2.7183)', latex)
31
  latex = re.sub(r'(?<![a-zA-Z0-9])e(?![a-zA-Z0-9])', '2.7183', latex)
32
 
33
  # Insert * between number and variable (e.g., 45x β†’ 45*x)
34
  latex = re.sub(r'(\d)([a-zA-Z])', r'\1*\2', latex)
35
 
36
  # Replace number followed by i with number*I
37
- latex = re.sub(r'(\d+)\s*i', r'\1*I', latex)
38
 
39
  # Replace standalone i with I
40
  latex = re.sub(r'(?<![a-zA-Z0-9])i(?![a-zA-Z0-9])', 'I', latex)
41
 
42
  # Wrap complex coefficients with variables: (a+bI)x^n β†’ (a+b*I)*x^n
43
- latex = re.sub(r'\(([^()]+?)\)\s*([xX](\^\d+)?)', r'(\1)*\2', latex)
 
 
 
 
 
44
 
45
  # Append '=0' if not already present
46
  if '=' not in latex:
@@ -48,6 +52,17 @@ def clean_latex(latex):
48
 
49
  return latex
50
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  # Main function
53
  def solve_polynomial(image):
@@ -56,10 +71,23 @@ def solve_polynomial(image):
56
  latex_result = model(img)
57
  cleaned_latex = clean_latex(latex_result)
58
 
59
- expr = parse_latex(cleaned_latex)
60
- output = f"## πŸ“„ Extracted LaTeX\n```\n{latex_result}\n```\n"
 
 
 
 
 
 
 
 
 
 
 
 
61
  output += "---\n"
62
- output += f"## 🧹 Cleaned LaTeX Used\n```\n{cleaned_latex}\n```\n"
 
63
  output += "---\n"
64
  output += f"## 🧠 Parsed Expression\n\n$$ {sp.latex(expr)} $$\n"
65
  output += "---\n"
@@ -83,7 +111,7 @@ def solve_polynomial(image):
83
  output += "$$\n\\begin{aligned}\n"
84
  for i, sol in enumerate(roots, 1):
85
  for var, val in sol.items():
86
- output += f"\\text{{Root {i}}}:\\quad {var} &= {sp.latex(val)} \\\\\n"
87
  output += "\\end{aligned}\n$$\n"
88
 
89
  else:
@@ -96,7 +124,6 @@ def solve_polynomial(image):
96
  except Exception as e:
97
  return f"❌ **Error**: {str(e)}"
98
 
99
-
100
  # Gradio UI
101
  demo = gr.Interface(
102
  fn=solve_polynomial,
 
9
  def preprocess_handwritten_image(pil_img):
10
  return pil_img.convert('RGB') # Minimal processing, just convert to RGB
11
 
 
12
  # Load Pix2Tex model (once)
13
  model = LatexOCR()
14
 
15
  # Clean LaTeX output
16
  def clean_latex(latex):
17
  # Replace \mathcal{X} or \cal X with 'x'
18
+ latex = re.sub(r'\\(cal|mathcal)\\s*X', 'x', latex)
19
 
20
  # Remove curly braces
21
  latex = latex.replace('{', '').replace('}', '')
22
  latex = latex.strip().rstrip(',.')
23
+
24
  # Replace coefficients like 5\pi with (5*3.1416)
25
+ latex = re.sub(r'(\d+)\\s*\\pi', r'(\1*3.1416)', latex)
26
  latex = latex.replace(r'\pi', '3.1416')
27
 
28
  # Replace coefficients like 5e with (5*2.7183)
29
+ latex = re.sub(r'(\d+)\\s*e', r'(\1*2.7183)', latex)
30
  latex = re.sub(r'(?<![a-zA-Z0-9])e(?![a-zA-Z0-9])', '2.7183', latex)
31
 
32
  # Insert * between number and variable (e.g., 45x β†’ 45*x)
33
  latex = re.sub(r'(\d)([a-zA-Z])', r'\1*\2', latex)
34
 
35
  # Replace number followed by i with number*I
36
+ latex = re.sub(r'(\d+)\\s*i', r'\1*I', latex)
37
 
38
  # Replace standalone i with I
39
  latex = re.sub(r'(?<![a-zA-Z0-9])i(?![a-zA-Z0-9])', 'I', latex)
40
 
41
  # Wrap complex coefficients with variables: (a+bI)x^n β†’ (a+b*I)*x^n
42
+ latex = re.sub(r'\\(([^()]+?)\\)\\s*([xX](\\^\d+)?)', r'(\1)*\2', latex)
43
+
44
+ # Fix common OCR mistakes
45
+ latex = re.sub(r'\bL(\d)', r'1\1', latex)
46
+ latex = latex.replace('\\pm', '').replace('!', '')
47
+ latex = re.sub(r'[^\w\s\^\+\-\*/=xX\(\)\.\*]', '', latex)
48
 
49
  # Append '=0' if not already present
50
  if '=' not in latex:
 
52
 
53
  return latex
54
 
55
+ # Fallback parser if LaTeX parsing fails
56
+ def fallback_parse(cleaned_latex):
57
+ try:
58
+ if '=' in cleaned_latex:
59
+ cleaned_latex = cleaned_latex.split('=')[0]
60
+ cleaned_latex = cleaned_latex.replace('^', '**')
61
+ x = sp.symbols('x')
62
+ expr = eval(cleaned_latex, {"x": x, "I": sp.I, "pi": sp.pi})
63
+ return sp.Eq(expr, 0)
64
+ except Exception:
65
+ return None
66
 
67
  # Main function
68
  def solve_polynomial(image):
 
71
  latex_result = model(img)
72
  cleaned_latex = clean_latex(latex_result)
73
 
74
+ try:
75
+ expr = parse_latex(cleaned_latex)
76
+ except Exception:
77
+ expr = None
78
+
79
+ if not expr:
80
+ expr = fallback_parse(cleaned_latex)
81
+
82
+ if not expr:
83
+ return f"❌ Could not parse expression from cleaned LaTeX:\n```
84
+ {cleaned_latex}\n```"
85
+
86
+ output = f"## πŸ“„ Extracted LaTeX\n```
87
+ {latex_result}\n```\n"
88
  output += "---\n"
89
+ output += f"## 🧹 Cleaned LaTeX Used\n```
90
+ {cleaned_latex}\n```\n"
91
  output += "---\n"
92
  output += f"## 🧠 Parsed Expression\n\n$$ {sp.latex(expr)} $$\n"
93
  output += "---\n"
 
111
  output += "$$\n\\begin{aligned}\n"
112
  for i, sol in enumerate(roots, 1):
113
  for var, val in sol.items():
114
+ output += f"\\text{{Root {i}}}:\\quad {var} &= {sp.latex(val)} \\\\n"
115
  output += "\\end{aligned}\n$$\n"
116
 
117
  else:
 
124
  except Exception as e:
125
  return f"❌ **Error**: {str(e)}"
126
 
 
127
  # Gradio UI
128
  demo = gr.Interface(
129
  fn=solve_polynomial,