File size: 1,719 Bytes
44a025a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
45
46
47
48
49
50
51
52
53
54
import os
import shutil
from fastapi import APIRouter, UploadFile, File, HTTPException
from typing import Dict, Any

from app.services.embedding_service import process_and_create_embeddings

router = APIRouter()


@router.post("/create-embeddings")
async def create_embeddings(file: UploadFile = File(...)):
    """
    Create embeddings from an uploaded Excel or CSV file.

    - **file**: The Excel or CSV file containing questions and answers

    Returns a success message if embeddings are created successfully.
    """
    # Get file extension
    file_extension = os.path.splitext(file.filename)[1].lower()

    # Determine file type based on extension
    if file_extension == ".xlsx" or file_extension == ".xls":
        file_type = "excel"
    elif file_extension == ".csv":
        file_type = "csv"
    else:
        raise HTTPException(
            status_code=400,
            detail="Unsupported file type. Please upload an Excel (.xlsx, .xls) or CSV (.csv) file.",
        )

    # Create a temporary file to store the uploaded file
    temp_file_path = f"temp_{file.filename}"
    try:
        # Save the uploaded file
        with open(temp_file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Process the file and create embeddings
        result = process_and_create_embeddings(temp_file_path, file_type)

        if result["status"] == "error":
            raise HTTPException(status_code=400, detail=result["message"])

        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        # Clean up the temporary file
        if os.path.exists(temp_file_path):
            os.remove(temp_file_path)