Spaces:
Sleeping
Sleeping
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() | |
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) | |