Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
@@ -1,31 +1,30 @@
|
|
1 |
from fastapi import FastAPI, UploadFile, Form
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
-
from fastapi.responses import JSONResponse
|
4 |
-
import shutil
|
5 |
-
import os
|
6 |
|
7 |
-
# β
Create FastAPI app
|
8 |
app = FastAPI()
|
9 |
|
10 |
-
#
|
11 |
app.add_middleware(
|
12 |
CORSMiddleware,
|
13 |
-
allow_origins=["*"],
|
14 |
-
|
15 |
-
allow_methods=["*"],
|
16 |
-
allow_headers=["*"],
|
17 |
)
|
18 |
|
19 |
-
# β
|
20 |
@app.get("/")
|
|
|
|
|
|
|
|
|
|
|
21 |
async def predict(question: str = Form(...), file: UploadFile = Form(...)):
|
22 |
try:
|
23 |
-
# Save uploaded file temporarily
|
24 |
temp_path = f"temp_{file.filename}"
|
25 |
with open(temp_path, "wb") as f:
|
26 |
shutil.copyfileobj(file.file, f)
|
27 |
|
28 |
-
# β
Decide handler based on file type
|
29 |
if file.content_type.startswith("image/"):
|
30 |
from appImage import answer_question_from_image
|
31 |
from PIL import Image
|
@@ -34,8 +33,7 @@ async def predict(question: str = Form(...), file: UploadFile = Form(...)):
|
|
34 |
else:
|
35 |
from app import answer_question_from_doc
|
36 |
class NamedFile:
|
37 |
-
def __init__(self, name):
|
38 |
-
self.name = name
|
39 |
answer = answer_question_from_doc(NamedFile(temp_path), question)
|
40 |
|
41 |
os.remove(temp_path)
|
|
|
1 |
from fastapi import FastAPI, UploadFile, Form
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
+
from fastapi.responses import JSONResponse, RedirectResponse
|
4 |
+
import shutil, os
|
|
|
5 |
|
|
|
6 |
app = FastAPI()
|
7 |
|
8 |
+
# CORS
|
9 |
app.add_middleware(
|
10 |
CORSMiddleware,
|
11 |
+
allow_origins=["*"], allow_credentials=True,
|
12 |
+
allow_methods=["*"], allow_headers=["*"]
|
|
|
|
|
13 |
)
|
14 |
|
15 |
+
# β
Basic root redirection (optional)
|
16 |
@app.get("/")
|
17 |
+
def home():
|
18 |
+
return RedirectResponse(url="/docs") # Or to a frontend URL
|
19 |
+
|
20 |
+
# β
File prediction endpoint
|
21 |
+
@app.post("/predict")
|
22 |
async def predict(question: str = Form(...), file: UploadFile = Form(...)):
|
23 |
try:
|
|
|
24 |
temp_path = f"temp_{file.filename}"
|
25 |
with open(temp_path, "wb") as f:
|
26 |
shutil.copyfileobj(file.file, f)
|
27 |
|
|
|
28 |
if file.content_type.startswith("image/"):
|
29 |
from appImage import answer_question_from_image
|
30 |
from PIL import Image
|
|
|
33 |
else:
|
34 |
from app import answer_question_from_doc
|
35 |
class NamedFile:
|
36 |
+
def __init__(self, name): self.name = name
|
|
|
37 |
answer = answer_question_from_doc(NamedFile(temp_path), question)
|
38 |
|
39 |
os.remove(temp_path)
|