ikraamkb commited on
Commit
2d75ddd
Β·
verified Β·
1 Parent(s): 064b85f

Update qtAnswering/main.py

Browse files
Files changed (1) hide show
  1. qtAnswering/main.py +67 -72
qtAnswering/main.py CHANGED
@@ -1,72 +1,67 @@
1
- from fastapi import FastAPI, UploadFile, Form, Request
2
- from fastapi.middleware.cors import CORSMiddleware
3
- from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
4
- from fastapi.staticfiles import StaticFiles
5
- from fastapi.templating import Jinja2Templates
6
- import shutil, os
7
- from tempfile import gettempdir
8
-
9
- app = FastAPI()
10
-
11
- # βœ… CORS to allow frontend access
12
- app.add_middleware(
13
- CORSMiddleware,
14
- allow_origins=["*"],
15
- allow_credentials=True,
16
- allow_methods=["*"],
17
- allow_headers=["*"],
18
- )
19
-
20
- # βœ… Static assets
21
- app.mount("/resources", StaticFiles(directory="resources"), name="resources")
22
- app.mount("/static", StaticFiles(directory="static"), name="static")
23
-
24
- # βœ… Jinja2 Templates
25
- templates = Jinja2Templates(directory="templates")
26
-
27
- # βœ… Serve Homepage
28
- @app.get("/", response_class=HTMLResponse)
29
- async def serve_home(request: Request):
30
- return templates.TemplateResponse("home.html", {"request": request})
31
-
32
- # βœ… Predict endpoint (handles image + document)
33
- @app.post("/predict")
34
- async def predict(question: str = Form(...), file: UploadFile = Form(...)):
35
- try:
36
- temp_path = f"temp_{file.filename}"
37
- with open(temp_path, "wb") as f:
38
- shutil.copyfileobj(file.file, f)
39
-
40
- is_image = file.content_type.startswith("image/")
41
-
42
- if is_image:
43
- from appImage import answer_question_from_image
44
- from PIL import Image
45
- image = Image.open(temp_path).convert("RGB")
46
- answer, audio_path = answer_question_from_image(image, question)
47
-
48
- else:
49
- from app import answer_question_from_doc
50
- class NamedFile:
51
- def __init__(self, name): self.filename = name
52
- def read(self): return open(self.filename, "rb").read()
53
- answer, audio_path = answer_question_from_doc(NamedFile(temp_path), question)
54
-
55
- os.remove(temp_path)
56
-
57
- if audio_path and os.path.exists(audio_path):
58
- return JSONResponse({
59
- "answer": answer,
60
- "audio": f"/audio/{os.path.basename(audio_path)}"
61
- })
62
- else:
63
- return JSONResponse({"answer": answer})
64
-
65
- except Exception as e:
66
- return JSONResponse({"error": str(e)}, status_code=500)
67
-
68
- # βœ… Serve audio
69
- @app.get("/audio/{filename}")
70
- async def get_audio(filename: str):
71
- filepath = os.path.join(gettempdir(), filename)
72
- return FileResponse(filepath, media_type="audio/mpeg")
 
1
+ from fastapi import FastAPI, UploadFile, Form, Request
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
4
+ from fastapi.templating import Jinja2Templates
5
+ import shutil, os
6
+ from tempfile import gettempdir
7
+
8
+ # βœ… Create app
9
+ app = FastAPI()
10
+
11
+ # βœ… CORS middleware
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"],
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
+ # βœ… Templates
21
+ templates = Jinja2Templates(directory="templates")
22
+
23
+ # βœ… Serve Homepage
24
+ @app.get("/", response_class=HTMLResponse)
25
+ async def serve_home(request: Request):
26
+ return templates.TemplateResponse("home.html", {"request": request})
27
+
28
+ # βœ… Predict endpoint (handles image + document)
29
+ @app.post("/predict")
30
+ async def predict(question: str = Form(...), file: UploadFile = Form(...)):
31
+ try:
32
+ temp_path = f"temp_{file.filename}"
33
+ with open(temp_path, "wb") as f:
34
+ shutil.copyfileobj(file.file, f)
35
+
36
+ is_image = file.content_type.startswith("image/")
37
+
38
+ if is_image:
39
+ from .appImage import answer_question_from_image
40
+ from PIL import Image
41
+ image = Image.open(temp_path).convert("RGB")
42
+ answer, audio_path = answer_question_from_image(image, question)
43
+ else:
44
+ from .app import answer_question_from_doc
45
+ class NamedFile:
46
+ def __init__(self, name): self.filename = name
47
+ def read(self): return open(self.filename, "rb").read()
48
+ answer, audio_path = answer_question_from_doc(NamedFile(temp_path), question)
49
+
50
+ os.remove(temp_path)
51
+
52
+ if audio_path and os.path.exists(audio_path):
53
+ return JSONResponse({
54
+ "answer": answer,
55
+ "audio": f"/qtAnswering/audio/{os.path.basename(audio_path)}"
56
+ })
57
+ else:
58
+ return JSONResponse({"answer": answer})
59
+
60
+ except Exception as e:
61
+ return JSONResponse({"error": str(e)}, status_code=500)
62
+
63
+ # βœ… Serve audio files
64
+ @app.get("/audio/{filename}")
65
+ async def get_audio(filename: str):
66
+ filepath = os.path.join(gettempdir(), filename)
67
+ return FileResponse(filepath, media_type="audio/mpeg")