ikraamkb commited on
Commit
2918218
·
verified ·
1 Parent(s): 4915e32

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +40 -38
main.py CHANGED
@@ -1,38 +1,40 @@
1
- from fastapi import FastAPI
2
- from fastapi.responses import RedirectResponse
3
- import gradio as gr
4
-
5
- from app import answer_question_from_doc
6
- from appImage import answer_question_from_image
7
-
8
- app = FastAPI()
9
-
10
- # === Document QA Tab ===
11
- with gr.Blocks() as doc_interface:
12
- gr.Markdown("## 📄 Document QA")
13
- doc_file = gr.File(label="Upload File (PDF, DOCX, PPTX, XLSX)")
14
- doc_question = gr.Textbox(label="Ask a question")
15
- doc_answer = gr.Textbox(label="Answer")
16
- doc_submit = gr.Button("Get Answer")
17
- doc_submit.click(fn=answer_question_from_doc, inputs=[doc_file, doc_question], outputs=doc_answer)
18
-
19
- # === Image QA Tab ===
20
- with gr.Blocks() as img_interface:
21
- gr.Markdown("## 🖼️ Image QA")
22
- img_input = gr.Image(label="Upload an Image")
23
- img_question = gr.Textbox(label="Ask a question")
24
- img_answer = gr.Textbox(label="Answer")
25
- img_submit = gr.Button("Get Answer")
26
- img_submit.click(fn=answer_question_from_image, inputs=[img_input, img_question], outputs=img_answer)
27
-
28
- # === Combine Tabs ===
29
- demo = gr.TabbedInterface([doc_interface, img_interface], tab_names=["Document QA", "Image QA"])
30
-
31
- # Mount Gradio App
32
- app = gr.mount_gradio_app(app, demo, path="/")
33
-
34
- @app.get("/")
35
- def root():
36
- return RedirectResponse(url="/")
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)