File size: 1,768 Bytes
00277e2
b905bd6
00277e2
 
 
 
 
 
b905bd6
 
 
00277e2
 
 
 
 
 
 
 
 
 
b905bd6
00277e2
 
 
 
 
 
 
 
 
 
 
 
 
 
b905bd6
00277e2
 
 
b905bd6
00277e2
 
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
42
43
44
from typing import Annotated
from fastapi import APIRouter, UploadFile, Depends
from app.categorization.file_processing import process_file, save_results
from app.schema.index import FileUploadCreate
import asyncio
import os
import csv

from app.engine.postgresdb import get_db_session
from sqlalchemy.ext.asyncio import AsyncSession

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, db: AsyncSession = Depends(get_db_session)):
    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)
        await save_results(db, result)

    except Exception:
        return {"message": "There was an error uploading this file. Ensure you have a .csv file with the following columns:"
        "\n transaction_date, type, category, name_description, amount"}

    return {"message": f"Successfully uploaded {input_file.filename}"}