KZTech commited on
Commit
ace1eba
ยท
verified ยท
1 Parent(s): 0a11a25

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ import pytesseract
4
+ import openai
5
+ import io
6
+
7
+ # App title and description
8
+ st.set_page_config(page_title="Math Solver from Image", layout="centered")
9
+
10
+ st.title("๐Ÿงฎ ChatGPT Math Solver from Image")
11
+ st.markdown("""
12
+ Upload an image containing a math problem (handwritten or printed), and this app will:
13
+ 1. Extract the text using OCR.
14
+ 2. Send it to ChatGPT to solve the problem.
15
+ 3. Display the solution below.
16
+
17
+ ---
18
+
19
+ ๐Ÿ‘‰ **Steps to use:**
20
+ - Click **Browse files** below to upload an image.
21
+ - Wait a moment for processing.
22
+ - View the OCR result and ChatGPT's solution.
23
+
24
+ *Note: Make sure your OpenAI API key is valid.*
25
+ """)
26
+
27
+ # Input for API Key
28
+ api_key = st.text_input("๐Ÿ”‘ Enter your OpenAI API Key", type="password")
29
+
30
+ # Image uploader
31
+ uploaded_file = st.file_uploader("๐Ÿ“ท Upload an image with a math problem", type=["png", "jpg", "jpeg"])
32
+
33
+ # When an image is uploaded
34
+ if uploaded_file and api_key:
35
+ image = Image.open(uploaded_file)
36
+ st.image(image, caption="Uploaded Image", use_column_width=True)
37
+
38
+ with st.spinner("๐Ÿ” Extracting text from image..."):
39
+ extracted_text = pytesseract.image_to_string(image)
40
+
41
+ st.markdown("### ๐Ÿ“ Extracted Text")
42
+ st.code(extracted_text)
43
+
44
+ if extracted_text.strip():
45
+ openai.api_key = api_key
46
+ with st.spinner("๐Ÿง  Solving with ChatGPT..."):
47
+ try:
48
+ response = openai.ChatCompletion.create(
49
+ model="gpt-4",
50
+ messages=[
51
+ {"role": "system", "content": "You are a math expert."},
52
+ {"role": "user", "content": f"Solve this math problem step by step: {extracted_text}"}
53
+ ]
54
+ )
55
+ solution = response["choices"][0]["message"]["content"]
56
+ st.markdown("### โœ… Solution")
57
+ st.success(solution)
58
+ except Exception as e:
59
+ st.error(f"Error from OpenAI API: {str(e)}")
60
+ else:
61
+ st.warning("No text was extracted. Please try a clearer image.")
62
+ elif uploaded_file and not api_key:
63
+ st.warning("Please enter your OpenAI API key to proceed.")