File size: 1,815 Bytes
84ef14b
2918218
84ef14b
 
 
c649b34
2918218
d92713e
 
84ef14b
2918218
 
84ef14b
 
 
 
2918218
 
84ef14b
 
c649b34
84ef14b
 
 
 
 
 
 
 
 
c649b34
2918218
 
 
 
 
 
 
 
 
 
 
 
 
 
c649b34
2918218
 
 
 
 
 
 
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
54
from fastapi import FastAPI, UploadFile, Form, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import shutil, os

app = FastAPI()

# βœ… CORS to allow frontend to access backend
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# βœ… Mount static folder (optional JS/CSS support)
app.mount("/static", StaticFiles(directory="static"), name="static")

# βœ… Set templates folder
templates = Jinja2Templates(directory="templates")

# βœ… Serve home.html
@app.get("/", response_class=HTMLResponse)
async def serve_home(request: Request):
    return templates.TemplateResponse("home.html", {"request": request})

# βœ… Backend prediction API
@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)