Spaces:
Sleeping
Sleeping
File size: 1,552 Bytes
831a016 10399f1 831a016 acdfb5c 10399f1 acdfb5c bfa9638 831a016 10399f1 831a016 10399f1 831a016 bfa9638 10399f1 44296f1 10399f1 831a016 10399f1 831a016 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
from typing import Any
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException
import os
from dependencies import get_current_user
# Assuming a utility for processing PDFs and generating embeddings
from utils.doc_ingest import ingest_document
from utils.chat_rag import sanitize_collection_name
router = APIRouter()
@router.post("/user/upload")
async def upload_file(file: UploadFile = File(...), current_user: Any = Depends(get_current_user)):
if file.content_type != "application/pdf":
raise HTTPException(status_code=400, detail="Unsupported file type. Please upload a PDF.")
upload_dir = "/home/user/data/uploads"
os.makedirs(upload_dir, exist_ok=True)
file_location = f"{upload_dir}/{file.filename}"
with open(file_location, "wb") as buffer:
contents = await file.read()
buffer.write(contents)
try:
# Process PDF and store embeddings
ingest_document(file_location, sanitize_collection_name(current_user["user_id"]))
except Exception as e:
# If processing fails, attempt to clean up the file before re-raising the error
os.remove(file_location)
raise HTTPException(status_code=500, detail=f"Failed to process file: {e}")
# Clean up file in uploads directory after successful processing
os.remove(file_location)
return {
"status": "File uploaded and processed successfully.",
"user_id": current_user["user_id"],
"name": current_user["name"],
"role": current_user["role"]
}
|