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("OCR Output:", text) # Print raw OCR output # Filter out potential math expressions math_problems = re.findall(r'[\d+\-*/().÷]+', text) print("Recognized Problems:", math_problems) # Print recognized 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("÷", "/") print("Processing Problem:", problem) # Print each problem being processed # Convert the string expression to a symbolic expression expression = sympify(problem) # Evaluate the expression result = expression.evalf() print("Result:", result) # Print result return result except Exception as e: print(f"Error solving problem '{problem}':", e) # Print specific error 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] 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()