Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,38 +1,40 @@
|
|
| 1 |
-
from fastapi import
|
| 2 |
-
from fastapi.
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
app
|
| 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 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import UploadFile, Form
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from fastapi.responses import JSONResponse
|
| 4 |
+
import shutil
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Enable CORS so frontend can talk to backend
|
| 8 |
+
app.add_middleware(
|
| 9 |
+
CORSMiddleware,
|
| 10 |
+
allow_origins=["*"],
|
| 11 |
+
allow_credentials=True,
|
| 12 |
+
allow_methods=["*"],
|
| 13 |
+
allow_headers=["*"],
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
@app.post("/predict")
|
| 17 |
+
async def predict(question: str = Form(...), file: UploadFile = Form(...)):
|
| 18 |
+
try:
|
| 19 |
+
# Save uploaded file
|
| 20 |
+
temp_path = f"temp_{file.filename}"
|
| 21 |
+
with open(temp_path, "wb") as f:
|
| 22 |
+
shutil.copyfileobj(file.file, f)
|
| 23 |
+
|
| 24 |
+
if file.content_type.startswith("image/"):
|
| 25 |
+
from appImage import answer_question_from_image
|
| 26 |
+
from PIL import Image
|
| 27 |
+
image = Image.open(temp_path)
|
| 28 |
+
answer = answer_question_from_image(image, question)
|
| 29 |
+
else:
|
| 30 |
+
from app import answer_question_from_doc
|
| 31 |
+
class NamedFile:
|
| 32 |
+
def __init__(self, name):
|
| 33 |
+
self.name = name
|
| 34 |
+
answer = answer_question_from_doc(NamedFile(temp_path), question)
|
| 35 |
+
|
| 36 |
+
os.remove(temp_path)
|
| 37 |
+
return JSONResponse(content={"answer": answer})
|
| 38 |
+
|
| 39 |
+
except Exception as e:
|
| 40 |
+
return JSONResponse(content={"error": str(e)}, status_code=500)
|