Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
-
from fastapi import FastAPI, File, UploadFile
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
import shutil
|
| 4 |
import os
|
| 5 |
-
|
|
|
|
| 6 |
os.environ["MPLCONFIGDIR"] = "/tmp/matplotlib"
|
| 7 |
os.environ["YOLO_CONFIG_DIR"] = "/tmp/ultralytics"
|
| 8 |
os.environ["XDG_CACHE_HOME"] = "/tmp"
|
|
@@ -18,15 +19,39 @@ app = FastAPI()
|
|
| 18 |
|
| 19 |
UPLOAD_DIR = "/tmp/uploads"
|
| 20 |
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
|
|
|
| 21 |
|
| 22 |
@app.post("/extract-invoice")
|
| 23 |
async def extract_invoice(file: UploadFile = File(...)):
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile,HTTPException
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
import shutil
|
| 4 |
import os
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
import uuid
|
| 7 |
os.environ["MPLCONFIGDIR"] = "/tmp/matplotlib"
|
| 8 |
os.environ["YOLO_CONFIG_DIR"] = "/tmp/ultralytics"
|
| 9 |
os.environ["XDG_CACHE_HOME"] = "/tmp"
|
|
|
|
| 19 |
|
| 20 |
UPLOAD_DIR = "/tmp/uploads"
|
| 21 |
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 22 |
+
ALLOWED_EXTENSIONS = {".png", ".jpg", ".jpeg"}
|
| 23 |
|
| 24 |
@app.post("/extract-invoice")
|
| 25 |
async def extract_invoice(file: UploadFile = File(...)):
|
| 26 |
+
file_ext = os.path.splitext(file.filename)[-1].lower()
|
| 27 |
+
|
| 28 |
+
if file_ext not in ALLOWED_EXTENSIONS:
|
| 29 |
+
raise HTTPException(status_code=400, detail="Please upload Jpeg, Jpg or Png images only.")
|
| 30 |
+
|
| 31 |
+
# Save file to disk
|
| 32 |
+
unique_filename = f"{uuid.uuid4().hex}{file_ext}"
|
| 33 |
+
file_location = os.path.join(UPLOAD_DIR, unique_filename)
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
with open(file_location, "wb") as f:
|
| 37 |
+
shutil.copyfileobj(file.file, f)
|
| 38 |
+
|
| 39 |
+
# Process the file with your model
|
| 40 |
+
extracted_data = extract_invoice_data_from_image(file_location)
|
| 41 |
+
|
| 42 |
+
return JSONResponse(content={
|
| 43 |
+
"success": True,
|
| 44 |
+
"message": "Invoice data extracted successfully.",
|
| 45 |
+
"data": extracted_data
|
| 46 |
+
})
|
| 47 |
+
|
| 48 |
+
except Exception as ex:
|
| 49 |
+
return JSONResponse(
|
| 50 |
+
status_code=500,
|
| 51 |
+
content={"success": False, "error": f"Internal Server Error: {str(ex)}"}
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
finally:
|
| 55 |
+
# Clean up the file if it exists
|
| 56 |
+
if os.path.exists(file_location):
|
| 57 |
+
os.remove(file_location)
|