ProblemSolver / app.py
JHigg's picture
Update app.py
03f3bfb verified
raw
history blame
2.05 kB
import gradio as gr
import pytesseract
import cv2
import re
from sympy import sympify
# Function to extract math problems from an image
def extract_text_from_image(image):
# Convert image to grayscale for better OCR performance
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Perform OCR on the grayscale image
text = pytesseract.image_to_string(gray)
# Print the raw OCR output for debugging purposes
print("OCR Output:", text)
# Filter out potential math expressions (numbers, operators, and parentheses)
math_problems = re.findall(r'[\d+\-*/().÷]+', text)
# Print recognized math problems for debugging
print("Recognized Problems:", math_problems)
return math_problems
# Function to solve the extracted math problems
def solve_math_problem(problem):
try:
# Replace any OCR misinterpretations if needed
problem = problem.replace("÷", "/") # Replace division symbol with "/"
# Convert the string expression to a symbolic expression
expression = sympify(problem)
# Evaluate the expression
result = expression.evalf()
return result
except Exception as e:
# Return a clear error message for debugging
print(f"Error solving problem '{problem}':", e)
return f"Error: {e}"
# Main function to recognize and solve math problems from an image
def recognize_and_solve(image):
problems = extract_text_from_image(image)
solutions = [f"{p} = {solve_math_problem(p)}" for p in problems]
# Format the output or return a message if no math problems were detected
return "\n".join(solutions) if solutions else "No math problems detected."
# Gradio interface
interface = gr.Interface(
fn=recognize_and_solve,
inputs="image",
outputs="text",
title="Math Problem Recognizer and Solver",
description="Upload an image containing math problems, and this app will recognize and solve them."
)
# Launch the Gradio app
interface.launch()