Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: multiple file uploading, CORS #28

Merged
merged 1 commit into from
Jul 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -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:
"""
45 changes: 25 additions & 20 deletions app/routers/upload.py
Original file line number Diff line number Diff line change
@@ -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."}