Taiken_chatbot_API / app /routes /embedding_routes.py
vumichien's picture
Add application file
11aa943
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 containing question-answer pairs.
- **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.",
)
# Ensure temp directory exists
temp_dir = "/app/temp"
if not os.path.exists(temp_dir):
os.makedirs(temp_dir, exist_ok=True)
# Create a temporary file to store the uploaded file
safe_filename = os.path.basename(file.filename).replace(" ", "_")
temp_file_path = os.path.join(temp_dir, f"temp_{safe_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):
try:
os.remove(temp_file_path)
except Exception as e:
print(
f"Warning: Could not remove temporary file {temp_file_path}: {str(e)}"
)