Team Ai
Apppublic

JHigg/ProblemSolver

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py59 linesDownload Raw Back to root
1import gradio as gr2import pytesseract3import cv24import re5from sympy import sympify6 7# Function to extract math problems from an image8def extract_text_from_image(image):9    # Convert image to grayscale for better OCR performance10    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)11    12    # Perform OCR on the grayscale image13    text = pytesseract.image_to_string(gray)14    print("OCR Output:", text)  # Print raw OCR output15    16    # Filter out potential math expressions17    math_problems = re.findall(r'[\d+\-*/().÷]+', text)18    print("Recognized Problems:", math_problems)  # Print recognized problems19    20    return math_problems21 22# Function to solve the extracted math problems23def solve_math_problem(problem):24    try:25        # Replace any OCR misinterpretations if needed26        problem = problem.replace("÷", "/")27        print("Processing Problem:", problem)  # Print each problem being processed28        29        # Convert the string expression to a symbolic expression30        expression = sympify(problem)31        32        # Evaluate the expression33        result = expression.evalf()34        print("Result:", result)  # Print result35        36        return result37    except Exception as e:38        print(f"Error solving problem '{problem}':", e)  # Print specific error39        return f"Error: {e}"40 41# Main function to recognize and solve math problems from an image42def recognize_and_solve(image):43    problems = extract_text_from_image(image)44    solutions = [f"{p} = {solve_math_problem(p)}" for p in problems]45    46    return "\n".join(solutions) if solutions else "No math problems detected."47 48# Gradio interface49interface = gr.Interface(50    fn=recognize_and_solve,51    inputs="image",52    outputs="text",53    title="Math Problem Recognizer and Solver",54    description="Upload an image containing math problems, and this app will recognize and solve them."55)56 57# Launch the Gradio app58interface.launch()59