| from fastapi import FastAPI, UploadFile, File, HTTPException |
| from fastapi.middleware.cors import CORSMiddleware |
| from pix2text import Pix2Text |
| import io |
| from PIL import Image |
| import uvicorn |
| import os |
|
|
| |
| os.environ["TOKENIZERS_PARALLELISM"] = "false" |
|
|
| app = FastAPI() |
|
|
| |
| app.add_middleware( |
| CORSMiddleware, |
| allow_origins=["*"], |
| allow_credentials=True, |
| allow_methods=["*"], |
| allow_headers=["*"], |
| ) |
|
|
| |
| p2t = Pix2Text() |
|
|
| @app.get("/") |
| def read_root(): |
| return {"status": "ok", "message": "Pix2Text API is running"} |
|
|
| @app.get("/status") |
| def get_status(): |
| return {"status": "ready"} |
|
|
| @app.post("/predict") |
| async def predict(file: UploadFile = File(...)): |
| if not file.content_type.startswith("image/"): |
| raise HTTPException(status_code=400, detail="File must be an image") |
| |
| try: |
| contents = await file.read() |
| image = Image.open(io.BytesIO(contents)).convert("RGB") |
| |
| |
| res = p2t.recognize_formula(image) |
| |
| return {"latex": res} |
| except Exception as e: |
| return {"error": str(e)} |
|
|
| if __name__ == "__main__": |
| uvicorn.run(app, host="0.0.0.0", port=7860) |
|
|