MasteredUltraInstinct commited on
Commit
0e67dc9
ยท
verified ยท
1 Parent(s): f31eb73

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -40
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import gradio as gr
2
  from PIL import Image
3
  from pix2tex.cli import LatexOCR
4
  import sympy as sp
@@ -7,17 +7,20 @@ import re
7
  import cv2
8
  import numpy as np
9
 
10
- # Preprocessing for handwritten image
11
  def preprocess_handwritten_image(pil_img):
12
- img = np.array(pil_img.convert('L')) # Grayscale
13
  _, binary = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
14
  denoised = cv2.medianBlur(binary, 3)
15
- return Image.fromarray(255 - denoised) # Text black on white
16
 
17
- # Load Pix2Tex model (once)
18
- model = LatexOCR()
 
 
19
 
20
- # Clean LaTeX output
 
 
21
  def clean_latex(latex):
22
  latex = re.sub(r'\\(cal|mathcal)\s*X', 'x', latex)
23
  latex = latex.replace('{', '').replace('}', '')
@@ -26,51 +29,56 @@ def clean_latex(latex):
26
  latex += '=0'
27
  return latex
28
 
29
- # Main function
30
- def solve_polynomial(image):
31
- try:
32
- img = preprocess_handwritten_image(image)
 
 
 
 
 
 
 
 
 
33
  latex_result = model(img)
34
  cleaned_latex = clean_latex(latex_result)
35
 
 
 
 
 
 
 
 
 
36
  expr = parse_latex(cleaned_latex)
37
- output = f"### ๐Ÿ“„ Extracted LaTeX\n`{latex_result}`\n\n"
38
- output += f"### ๐Ÿงน Cleaned LaTeX Used\n`{cleaned_latex}`\n\n"
39
- output += f"### ๐Ÿง  Parsed Expression\n${sp.latex(expr)}$\n\n"
40
 
41
  if isinstance(expr, sp.Equality):
42
- lhs = expr.lhs - expr.rhs
43
- output += "### โœ๏ธ Step 1: Convert to Polynomial Equation\n"
44
- output += f"${sp.latex(lhs)} = 0$\n\n"
 
 
45
 
46
- output += "### ๐Ÿงฉ Step 2: Factor the Polynomial\n"
47
  factored = sp.factor(lhs)
48
- output += f"${sp.latex(factored)} = 0$\n\n"
49
 
50
- output += "### โœ… Step 3: Solve for Roots\n"
51
  roots = sp.solve(sp.Eq(lhs, 0), dict=True)
52
- for i, sol in enumerate(roots, 1):
 
53
  for var, val in sol.items():
54
- output += f"**Root {i}:** ${var} = {sp.latex(val)}$\n\n"
 
55
  else:
56
  simplified = sp.simplify(expr)
57
- output += "### โž• Simplified Expression\n"
58
- output += f"${sp.latex(simplified)}$"
59
-
60
- return output
61
 
62
  except Exception as e:
63
- return f"โŒ Error: {str(e)}"
64
-
65
- # Gradio UI
66
- demo = gr.Interface(
67
- fn=solve_polynomial,
68
- inputs=gr.Image(type="pil", label="๐Ÿ“ท Upload Image of Polynomial"),
69
- outputs=gr.Markdown(label="๐Ÿ“‹ Step-by-step Solution"),
70
- title="๐Ÿง  Polynomial Solver from Image",
71
- description="Upload an image of a polynomial (typed or handwritten). The app will extract, solve, and explain it step-by-step.",
72
- allow_flagging="never"
73
- )
74
-
75
- if __name__ == "__main__":
76
- demo.launch()
 
1
+ import streamlit as st
2
  from PIL import Image
3
  from pix2tex.cli import LatexOCR
4
  import sympy as sp
 
7
  import cv2
8
  import numpy as np
9
 
 
10
  def preprocess_handwritten_image(pil_img):
11
+ img = np.array(pil_img.convert('L')) # Convert to grayscale
12
  _, binary = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
13
  denoised = cv2.medianBlur(binary, 3)
14
+ return Image.fromarray(255 - denoised) # Make text black on white background
15
 
16
+ # Load the model once using Streamlit's caching
17
+ @st.cache_resource
18
+ def load_model():
19
+ return LatexOCR()
20
 
21
+ model = load_model()
22
+
23
+ # Function to clean the LaTeX output
24
  def clean_latex(latex):
25
  latex = re.sub(r'\\(cal|mathcal)\s*X', 'x', latex)
26
  latex = latex.replace('{', '').replace('}', '')
 
29
  latex += '=0'
30
  return latex
31
 
32
+ # Streamlit UI
33
+ st.title("๐Ÿง  Polynomial Solver from Image")
34
+ st.write("Upload an image with a polynomial (e.g., $x^3 + 4x^2 + x - 6$).")
35
+
36
+ uploaded_file = st.file_uploader("Upload Image", type=["png", "jpg", "jpeg"])
37
+
38
+ if uploaded_file:
39
+ # Display the uploaded image
40
+ raw_img = Image.open(uploaded_file)
41
+ img = preprocess_handwritten_image(raw_img)
42
+ st.image(img, caption="Preprocessed Image", use_column_width=True)
43
+
44
+ with st.spinner("๐Ÿ” Extracting LaTeX from image..."):
45
  latex_result = model(img)
46
  cleaned_latex = clean_latex(latex_result)
47
 
48
+ st.subheader("๐Ÿ“„ Extracted LaTeX")
49
+ st.code(latex_result, language="latex")
50
+
51
+ st.subheader("๐Ÿงน Cleaned LaTeX Used")
52
+ st.code(cleaned_latex, language="latex")
53
+
54
+ # Try to parse and solve
55
+ try:
56
  expr = parse_latex(cleaned_latex)
57
+ st.subheader("๐Ÿง  Parsed Expression")
58
+ st.latex(sp.latex(expr))
 
59
 
60
  if isinstance(expr, sp.Equality):
61
+ lhs = expr.lhs - expr.rhs # Convert equation to f(x) = 0
62
+
63
+ st.markdown("---")
64
+ st.markdown("### โœ๏ธ Step 1: Convert to Polynomial Equation")
65
+ st.latex(f"{sp.latex(lhs)} = 0")
66
 
67
+ st.markdown("### ๐Ÿงฉ Step 2: Factor the Polynomial")
68
  factored = sp.factor(lhs)
69
+ st.latex(f"{sp.latex(factored)} = 0")
70
 
71
+ st.markdown("### โœ… Step 3: Solve for Roots")
72
  roots = sp.solve(sp.Eq(lhs, 0), dict=True)
73
+ clean_roots = [{str(k): v} for r in roots for k, v in r.items()]
74
+ for i, sol in enumerate(clean_roots, 1):
75
  for var, val in sol.items():
76
+ st.latex(f"{var} = {sp.latex(val)}")
77
+
78
  else:
79
  simplified = sp.simplify(expr)
80
+ st.subheader("๐Ÿงฎ Simplified Expression")
81
+ st.latex(sp.latex(simplified))
 
 
82
 
83
  except Exception as e:
84
+ st.error(f"โŒ Error: {e}")