document / app.py
Mube
Create app.py
f04cd76 verified
Raw History Blame Contribute Delete
1.03 kB
from fastapi import FastAPI, UploadFile, File
from PIL import Image
import pytesseract
import fitz # PyMuPDF
import io
import uuid
app = FastAPI()
@app.get("/")
def home():
return {
"status": "running",
"usage": "POST /extract (image or pdf file)"
}
# -------------------------
# MAIN DOCUMENT PROCESSOR
# -------------------------
@app.post("/extract")
async def extract(file: UploadFile = File(...)):
content = await file.read()
filename = file.filename.lower()
text = ""
# -------------------------
# PDF HANDLING
# -------------------------
if filename.endswith(".pdf"):
doc = fitz.open(stream=content, filetype="pdf")
for page in doc:
text += page.get_text()
# -------------------------
# IMAGE OCR HANDLING
# -------------------------
else:
image = Image.open(io.BytesIO(content))
text = pytesseract.image_to_string(image)
return {
"filename": file.filename,
"text": text.strip()
}