Spaces:
Sleeping
Sleeping
File size: 1,430 Bytes
785fe24 705ae48 785fe24 705ae48 785fe24 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
from fastapi import FastAPI, File, UploadFile
import fitz # PyMuPDF
import pytesseract
from PIL import Image
import io
app = FastAPI()
@app.post("/extract-text")
async def extract_text(file: UploadFile = File(...)):
try:
contents = await file.read()
doc = fitz.open(stream=contents, filetype="pdf")
extracted_text = ""
for i, page in enumerate(doc):
extracted_text += f"\n\n--- Page {i + 1} ---\n\n" + page.get_text()
return {"filename": file.filename, "text": extracted_text}
except Exception as e:
return {"error": str(e)}
@app.post("/extract-text-ocr")
async def extract_text_ocr(file: UploadFile = File(...)):
try:
contents = await file.read()
doc = fitz.open(stream=contents, filetype="pdf")
full_text = ""
for i in range(len(doc)):
page = doc.load_page(i)
# Normal text
text = page.get_text()
# Render page to an image
pix = page.get_pixmap()
img = Image.open(io.BytesIO(pix.tobytes()))
# OCR text
ocr_text = pytesseract.image_to_string(img)
full_text += f"\n\n--- Page {i + 1} ---\n\n"
full_text += text + "\n"
full_text += "[OCR Text]\n" + ocr_text
return {"filename": file.filename, "text": full_text}
except Exception as e:
return {"error": str(e)}
|