pratham0011
commited on
Update main.py
Browse files
main.py
CHANGED
@@ -1,46 +1,47 @@
|
|
1 |
-
import os
|
2 |
-
import shutil
|
3 |
-
import uvicorn
|
4 |
-
|
5 |
-
from pydantic import BaseModel
|
6 |
-
from fastapi import FastAPI, File, UploadFile, HTTPException
|
7 |
-
from fastapi.middleware.cors import CORSMiddleware
|
8 |
-
|
9 |
-
from app.app import data_ingestion, handle_query, DATA_DIR
|
10 |
-
|
11 |
-
class Query(BaseModel):
|
12 |
-
question: str
|
13 |
-
|
14 |
-
app = FastAPI()
|
15 |
-
|
16 |
-
app.add_middleware(
|
17 |
-
CORSMiddleware,
|
18 |
-
allow_origins=["*"], # Adjust this to your needs
|
19 |
-
allow_credentials=True,
|
20 |
-
allow_methods=["*"],
|
21 |
-
allow_headers=["*"],
|
22 |
-
)
|
23 |
-
|
24 |
-
@app.post("/upload")
|
25 |
-
async def upload_file(file: UploadFile = File(...)):
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
|
|
46 |
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
import uvicorn
|
4 |
+
|
5 |
+
from pydantic import BaseModel
|
6 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
7 |
+
from fastapi.middleware.cors import CORSMiddleware
|
8 |
+
|
9 |
+
from app.app import data_ingestion, handle_query, DATA_DIR
|
10 |
+
|
11 |
+
class Query(BaseModel):
|
12 |
+
question: str
|
13 |
+
|
14 |
+
app = FastAPI()
|
15 |
+
|
16 |
+
app.add_middleware(
|
17 |
+
CORSMiddleware,
|
18 |
+
allow_origins=["*"], # Adjust this to your needs
|
19 |
+
allow_credentials=True,
|
20 |
+
allow_methods=["*"],
|
21 |
+
allow_headers=["*"],
|
22 |
+
)
|
23 |
+
|
24 |
+
@app.post("/upload")
|
25 |
+
async def upload_file(file: UploadFile = File(...)):
|
26 |
+
print(f"Received file: {file.filename}")
|
27 |
+
file_extension = os.path.splitext(file.filename)[1].lower()
|
28 |
+
if file_extension not in [".pdf", ".docx", ".txt"]:
|
29 |
+
raise HTTPException(status_code=400, detail="Invalid file type. Only PDF, DOCX, and TXT are allowed.")
|
30 |
+
|
31 |
+
file_path = os.path.join(DATA_DIR, file.filename)
|
32 |
+
with open(file_path, "wb") as buffer:
|
33 |
+
shutil.copyfileobj(file.file, buffer)
|
34 |
+
|
35 |
+
data_ingestion()
|
36 |
+
return {"message": "File uploaded and processed successfully"}
|
37 |
+
|
38 |
+
@app.post("/query")
|
39 |
+
async def query_document(query: Query):
|
40 |
+
if not os.listdir(DATA_DIR):
|
41 |
+
raise HTTPException(status_code=400, detail="No document has been uploaded yet.")
|
42 |
+
|
43 |
+
response = handle_query(query.question)
|
44 |
+
return {"response": response}
|
45 |
+
|
46 |
+
if __name__ == "__main__":
|
47 |
uvicorn.run(app, host="0.0.0.0", port=8000)
|