import streamlit as st from PIL import Image import pytesseract import openai import io # App title and description st.set_page_config(page_title="Math Solver from Image", layout="centered") st.title("🧮 ChatGPT Math Solver from Image") st.markdown(""" Upload an image containing a math problem (handwritten or printed), and this app will: 1. Extract the text using OCR. 2. Send it to ChatGPT to solve the problem. 3. Display the solution below. --- 👉 **Steps to use:** - Click **Browse files** below to upload an image. - Wait a moment for processing. - View the OCR result and ChatGPT's solution. *Note: Make sure your OpenAI API key is valid.* """) # Input for API Key api_key = st.text_input("🔑 Enter your OpenAI API Key", type="password") # Image uploader uploaded_file = st.file_uploader("📷 Upload an image with a math problem", type=["png", "jpg", "jpeg"]) # When an image is uploaded if uploaded_file and api_key: image = Image.open(uploaded_file) st.image(image, caption="Uploaded Image", use_column_width=True) with st.spinner("🔍 Extracting text from image..."): extracted_text = pytesseract.image_to_string(image) st.markdown("### 📝 Extracted Text") st.code(extracted_text) if extracted_text.strip(): openai.api_key = api_key with st.spinner("🧠 Solving with ChatGPT..."): try: response = openai.ChatCompletion.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a math expert."}, {"role": "user", "content": f"Solve this math problem step by step: {extracted_text}"} ] ) solution = response["choices"][0]["message"]["content"] st.markdown("### ✅ Solution") st.success(solution) except Exception as e: st.error(f"Error from OpenAI API: {str(e)}") else: st.warning("No text was extracted. Please try a clearer image.") elif uploaded_file and not api_key: st.warning("Please enter your OpenAI API key to proceed.")