backend / app /api /routers /file_upload.py
palexis3's picture
File Upload API (#10)
00277e2 verified
Raw
History Blame
1.6 kB
from typing import Annotated
from fastapi import APIRouter, UploadFile
from app.categorization.file_processing import process_file, save_results
from app.schema.index import FileUploadCreate
import asyncio
import os
import csv
file_upload_router = r = APIRouter(prefix="/api/v1/file_upload", tags=["file_upload"])
@r.post(
"/",
responses={
200: {"description": "File successfully uploaded"},
400: {"description": "Bad request"},
500: {"description": "Internal server error"},
},
)
async def create_file(input_file: UploadFile):
try:
# Create directory to store all uploaded .csv files
file_upload_directory_path = "data/tx_data/input"
if not os.path.exists(file_upload_directory_path):
os.makedirs(file_upload_directory_path)
# Write items of .csv filte to directory
with open(os.path.join(file_upload_directory_path, input_file.filename)) as output_file:
[output_file.write(" ".join(row)+'\n') for row in csv.reader(input_file)]
output_file.close()
# With the newly created file and it's path, process and save it for embedding
processed_file = process_file(os.path.realpath(input_file.filename))
result = await asyncio.gather(processed_file)
save_results(result)
except Exception:
return {"message": "There was an error uploading this file. Ensure you have a .csv file with the following columns:"
"\n source, date, type, category, description, amount"}
return {"message": f"Successfully uploaded {input_file.filename}"}