qtAnswering / main.py
ikraamkb's picture
Update main.py
c649b34 verified
raw
history blame
1.41 kB
from fastapi import FastAPI, UploadFile, Form
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
import shutil, os
app = FastAPI()
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], allow_credentials=True,
allow_methods=["*"], allow_headers=["*"]
)
# βœ… Basic root redirection (optional)
@app.get("/")
def home():
return RedirectResponse(url="/docs") # Or to a frontend URL
# βœ… File prediction endpoint
@app.post("/predict")
async def predict(question: str = Form(...), file: UploadFile = Form(...)):
try:
temp_path = f"temp_{file.filename}"
with open(temp_path, "wb") as f:
shutil.copyfileobj(file.file, f)
if file.content_type.startswith("image/"):
from appImage import answer_question_from_image
from PIL import Image
image = Image.open(temp_path)
answer = answer_question_from_image(image, question)
else:
from app import answer_question_from_doc
class NamedFile:
def __init__(self, name): self.name = name
answer = answer_question_from_doc(NamedFile(temp_path), question)
os.remove(temp_path)
return JSONResponse(content={"answer": answer})
except Exception as e:
return JSONResponse(content={"error": str(e)}, status_code=500)