Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- README.md +57 -12
- app.py +163 -0
- requirements.txt +11 -0
README.md
CHANGED
|
@@ -1,12 +1,57 @@
|
|
| 1 |
-
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Educational Question Solver - Hugging Face Spaces
|
| 2 |
+
|
| 3 |
+
This is a Python backend that processes screenshots of questions using OCR and provides AI-powered answers for educational purposes.
|
| 4 |
+
|
| 5 |
+
## Features
|
| 6 |
+
|
| 7 |
+
- **OCR Processing**: Uses Microsoft's TrOCR model to extract text from images
|
| 8 |
+
- **AI Answers**: Integrates with OpenAI's GPT-4 to provide concise answers
|
| 9 |
+
- **Gradio Interface**: Web interface for testing and manual uploads
|
| 10 |
+
- **API Endpoint**: REST API for integration with the Electron app
|
| 11 |
+
|
| 12 |
+
## Setup on Hugging Face Spaces
|
| 13 |
+
|
| 14 |
+
1. Create a new Space on Hugging Face
|
| 15 |
+
2. Upload these files to your Space
|
| 16 |
+
3. Set the following secrets in your Space settings:
|
| 17 |
+
- `OPENAI_API_KEY`: Your OpenAI API key
|
| 18 |
+
|
| 19 |
+
## Local Development
|
| 20 |
+
|
| 21 |
+
1. Install dependencies:
|
| 22 |
+
```bash
|
| 23 |
+
pip install -r requirements.txt
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
2. Set environment variable:
|
| 27 |
+
```bash
|
| 28 |
+
export OPENAI_API_KEY="your-openai-api-key"
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
3. Run the app:
|
| 32 |
+
```bash
|
| 33 |
+
python app.py
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
## API Usage
|
| 37 |
+
|
| 38 |
+
The Electron app will send POST requests to `/api/process` with the following format:
|
| 39 |
+
|
| 40 |
+
```json
|
| 41 |
+
{
|
| 42 |
+
"image_data": "base64-encoded-image-string"
|
| 43 |
+
}
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
Response format:
|
| 47 |
+
```json
|
| 48 |
+
{
|
| 49 |
+
"extracted_text": "Question text extracted from image",
|
| 50 |
+
"answer": "AI-generated answer",
|
| 51 |
+
"success": true
|
| 52 |
+
}
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
## Educational Use Only
|
| 56 |
+
|
| 57 |
+
This tool is designed for educational purposes to help students understand concepts and learn from examples. Please use responsibly and in accordance with your institution's academic integrity policies.
|
app.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import base64
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import requests
|
| 7 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 8 |
+
import openai
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
# Initialize the OCR model (DeepSeek OCR alternative using TrOCR)
|
| 12 |
+
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed")
|
| 13 |
+
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-printed")
|
| 14 |
+
|
| 15 |
+
# OpenAI API setup - you'll need to set this in Hugging Face Spaces secrets
|
| 16 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 17 |
+
|
| 18 |
+
def process_image_ocr(image_data: str) -> str:
|
| 19 |
+
"""
|
| 20 |
+
Process base64 image data and extract text using OCR
|
| 21 |
+
"""
|
| 22 |
+
try:
|
| 23 |
+
# Decode base64 image
|
| 24 |
+
image_bytes = base64.b64decode(image_data.split(',')[1] if ',' in image_data else image_data)
|
| 25 |
+
image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
|
| 26 |
+
|
| 27 |
+
# Process with TrOCR
|
| 28 |
+
pixel_values = processor(image, return_tensors="pt").pixel_values
|
| 29 |
+
generated_ids = model.generate(pixel_values)
|
| 30 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 31 |
+
|
| 32 |
+
return generated_text.strip()
|
| 33 |
+
except Exception as e:
|
| 34 |
+
return f"OCR Error: {str(e)}"
|
| 35 |
+
|
| 36 |
+
def get_gpt_answer(question: str) -> str:
|
| 37 |
+
"""
|
| 38 |
+
Send the extracted question to GPT and get an answer
|
| 39 |
+
"""
|
| 40 |
+
try:
|
| 41 |
+
if not openai.api_key:
|
| 42 |
+
return "Error: OpenAI API key not configured"
|
| 43 |
+
|
| 44 |
+
response = openai.ChatCompletion.create(
|
| 45 |
+
model="gpt-4",
|
| 46 |
+
messages=[
|
| 47 |
+
{
|
| 48 |
+
"role": "system",
|
| 49 |
+
"content": "You are a helpful assistant that provides concise, accurate answers to academic questions. Keep responses brief but informative."
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"role": "user",
|
| 53 |
+
"content": f"Please answer this question concisely: {question}"
|
| 54 |
+
}
|
| 55 |
+
],
|
| 56 |
+
max_tokens=200,
|
| 57 |
+
temperature=0.3
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
return response.choices[0].message.content.strip()
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return f"GPT Error: {str(e)}"
|
| 63 |
+
|
| 64 |
+
def process_screenshot(image_data: str) -> dict:
|
| 65 |
+
"""
|
| 66 |
+
Main processing function that handles the entire pipeline
|
| 67 |
+
"""
|
| 68 |
+
if not image_data:
|
| 69 |
+
return {"error": "No image data provided"}
|
| 70 |
+
|
| 71 |
+
# Extract text from image
|
| 72 |
+
extracted_text = process_image_ocr(image_data)
|
| 73 |
+
|
| 74 |
+
if extracted_text.startswith("OCR Error"):
|
| 75 |
+
return {"error": extracted_text}
|
| 76 |
+
|
| 77 |
+
# Get GPT answer
|
| 78 |
+
gpt_answer = get_gpt_answer(extracted_text)
|
| 79 |
+
|
| 80 |
+
return {
|
| 81 |
+
"extracted_text": extracted_text,
|
| 82 |
+
"answer": gpt_answer,
|
| 83 |
+
"success": True
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
# Gradio interface for testing
|
| 87 |
+
def gradio_interface(image):
|
| 88 |
+
"""
|
| 89 |
+
Gradio interface for testing the OCR + GPT pipeline
|
| 90 |
+
"""
|
| 91 |
+
if image is None:
|
| 92 |
+
return "No image provided", "No answer available"
|
| 93 |
+
|
| 94 |
+
# Convert PIL image to base64
|
| 95 |
+
buffered = io.BytesIO()
|
| 96 |
+
image.save(buffered, format="PNG")
|
| 97 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 98 |
+
|
| 99 |
+
result = process_screenshot(img_str)
|
| 100 |
+
|
| 101 |
+
if "error" in result:
|
| 102 |
+
return result["error"], "Error occurred"
|
| 103 |
+
|
| 104 |
+
return result["extracted_text"], result["answer"]
|
| 105 |
+
|
| 106 |
+
# Create Gradio app
|
| 107 |
+
demo = gr.Interface(
|
| 108 |
+
fn=gradio_interface,
|
| 109 |
+
inputs=gr.Image(type="pil", label="Upload Screenshot"),
|
| 110 |
+
outputs=[
|
| 111 |
+
gr.Textbox(label="Extracted Text", lines=3),
|
| 112 |
+
gr.Textbox(label="GPT Answer", lines=5)
|
| 113 |
+
],
|
| 114 |
+
title="Educational Question Solver",
|
| 115 |
+
description="Upload a screenshot of a question and get an AI-powered answer for educational purposes.",
|
| 116 |
+
examples=None
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# FastAPI setup for proper API endpoints
|
| 120 |
+
from fastapi import FastAPI, HTTPException
|
| 121 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 122 |
+
from pydantic import BaseModel
|
| 123 |
+
import uvicorn
|
| 124 |
+
|
| 125 |
+
app = FastAPI(title="Educational Question Solver API")
|
| 126 |
+
|
| 127 |
+
# Add CORS middleware
|
| 128 |
+
app.add_middleware(
|
| 129 |
+
CORSMiddleware,
|
| 130 |
+
allow_origins=["*"],
|
| 131 |
+
allow_credentials=True,
|
| 132 |
+
allow_methods=["*"],
|
| 133 |
+
allow_headers=["*"],
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
class ImageRequest(BaseModel):
|
| 137 |
+
image_data: str
|
| 138 |
+
|
| 139 |
+
@app.post("/api/process")
|
| 140 |
+
async def process_image_endpoint(request: ImageRequest):
|
| 141 |
+
"""
|
| 142 |
+
API endpoint that the Electron app will call
|
| 143 |
+
"""
|
| 144 |
+
try:
|
| 145 |
+
result = process_screenshot(request.image_data)
|
| 146 |
+
return result
|
| 147 |
+
except Exception as e:
|
| 148 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 149 |
+
|
| 150 |
+
@app.get("/")
|
| 151 |
+
async def root():
|
| 152 |
+
return {"message": "Educational Question Solver API is running"}
|
| 153 |
+
|
| 154 |
+
@app.get("/health")
|
| 155 |
+
async def health_check():
|
| 156 |
+
return {"status": "healthy"}
|
| 157 |
+
|
| 158 |
+
# Mount Gradio app
|
| 159 |
+
app = gr.mount_gradio_app(app, demo, path="/gradio")
|
| 160 |
+
|
| 161 |
+
if __name__ == "__main__":
|
| 162 |
+
# For local testing
|
| 163 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.44.0
|
| 2 |
+
transformers==4.36.0
|
| 3 |
+
torch==2.1.0
|
| 4 |
+
torchvision==0.16.0
|
| 5 |
+
Pillow==10.1.0
|
| 6 |
+
openai==1.3.0
|
| 7 |
+
requests==2.31.0
|
| 8 |
+
numpy==1.24.3
|
| 9 |
+
fastapi==0.104.1
|
| 10 |
+
uvicorn==0.24.0
|
| 11 |
+
pydantic==2.5.0
|