From 37e187bc6727aaa68cf58039d977cc90a3632e0d Mon Sep 17 00:00:00 2001 From: nsavinda Date: Sat, 27 Jul 2024 15:44:52 +0530 Subject: [PATCH] feat: multiple file uploading, CORS --- app/main.py | 19 ++++++++++++++++++ app/routers/upload.py | 45 ++++++++++++++++++++++++------------------- 2 files changed, 44 insertions(+), 20 deletions(-) diff --git a/app/main.py b/app/main.py index 3059483..0d4238a 100644 --- a/app/main.py +++ b/app/main.py @@ -1,8 +1,11 @@ from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware import logging from logstash_async.handler import AsynchronousLogstashHandler + + from .core.log import logger logger.info("Testify AI Application Started") @@ -12,6 +15,22 @@ # Create an instance of the FastAPI application with a custom title app = FastAPI(title="Testify AI") +# Enable CORS (Cross-Origin Resource Sharing) to allow requests from the frontend + +origins = [ + 'http://localhost:4500', +] + + +app.add_middleware( + CORSMiddleware, + allow_origins=origins, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + + @app.get("/api/assistant", response_model=dict) async def read_root() -> dict: """ diff --git a/app/routers/upload.py b/app/routers/upload.py index 378e04d..fe61e75 100644 --- a/app/routers/upload.py +++ b/app/routers/upload.py @@ -5,27 +5,32 @@ from ..core.log import logger +from typing import List + + router = APIRouter() + @router.post("/upload-pdf/", status_code=201) -async def upload_pdf(file: UploadFile = None, examid: str = Query(..., description="The ID of the exam related to the uploaded PDF")) -> dict: - if file is None: - file = File(...) - - """Endpoint to upload a PDF and upsert its contents into a Pinecone vector store.""" - if file.content_type != 'application/pdf': - logger.error("Unsupported file type. Please upload a PDF.") - raise HTTPException(status_code=415, detail="Unsupported file type. Please upload a PDF.") - - # Assuming 'upsert' is an async function; if not, consider wrapping with 'await' - # or adjust the function to be a regular call if it's designed to be synchronous - success = upsert(file, examid) - - if not success: - logger.error("Failed to process the PDF file.") - raise HTTPException(status_code=500, detail="Failed to process the PDF file.") +async def upload_pdf(files: List[UploadFile] = File(...), examid: str = Query(..., description="The ID of the exam related to the uploaded PDF")) -> dict: + if not files: + raise HTTPException(status_code=400, detail="No files uploaded.") + + + # Print the exam ID and the number of files uploaded + logger.info(f"Exam ID: {examid}") + logger.info(f"Number of files uploaded: {len(files)}") + errors = [] + for file in files: + if file.content_type != 'application/pdf': + errors.append(f"Unsupported file type for {file.filename}. Please upload PDF.") + continue # Skip files that are not PDFs + + success = upsert(file, examid) # Assuming upsert is correctly defined to handle async operations + if not success: + errors.append(f"Failed to process {file.filename}.") + + if errors: + raise HTTPException(status_code=500, detail="Errors occurred during processing: " + "; ".join(errors)) - logger.info("PDF uploaded successfully.") - - # Directly return a message if upsert is successful; 'Response(status_code=201)' is redundant with `status_code=201` in the decorator - return {"message": "PDF uploaded successfully."} + return {"message": "All PDFs uploaded successfully."}