from fastapi import FastAPI, File, UploadFile, Form
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
import cv2
import pytesseract
import os
# Initialize FastAPI app
app = FastAPI()
# Define upload folder
UPLOAD_FOLDER = "static/uploads/"
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
# Inform pytesseract where Tesseract is installed
pytesseract.pytesseract.tesseract_cmd = "/usr/local/bin/tesseract"
# Serve static files (images, etc.)
app.mount("/static", StaticFiles(directory="static"), name="static")
# Home route
@app.get("/", response_class=HTMLResponse)
async def home():
html_content = """
Image to Text Converter
Image to Text Converter
Quickly extract text from your uploaded images!
"""
return HTMLResponse(content=html_content)
# Upload image route
@app.post("/upload_image/")
async def upload_image(image: UploadFile = File(...)):
file_location = f"{UPLOAD_FOLDER}/{image.filename}"
with open(file_location, "wb") as file:
file.write(await image.read())
return {"image_url": f"/static/uploads/{image.filename}"}
# Process image and extract text
@app.post("/process_image/")
async def process_image(image_path: str = Form(...)):
img = cv2.imread(image_path)
if img is None:
return {"error": "Unable to read the uploaded image. Please upload a valid image."}
# Extract text from the image
extracted_text = pytesseract.image_to_string(img)
return {"extracted_text": extracted_text}