Spaces:
Sleeping
Sleeping
amaye15
commited on
Commit
·
fdc226e
1
Parent(s):
0fd1b97
Feat - embed endpoint created
Browse files- src/api/services/embedding_service.py +132 -3
- src/main.py +226 -2
src/api/services/embedding_service.py
CHANGED
|
@@ -61,9 +61,89 @@
|
|
| 61 |
# df_batch[output_column] = embeddings
|
| 62 |
# return df_batch
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
from openai import AsyncOpenAI
|
| 65 |
import logging
|
| 66 |
-
from typing import List, Dict
|
| 67 |
import pandas as pd
|
| 68 |
import asyncio
|
| 69 |
from src.api.exceptions import OpenAIError
|
|
@@ -106,10 +186,41 @@ class EmbeddingService:
|
|
| 106 |
raise OpenAIError(f"OpenAI API error: {e}")
|
| 107 |
|
| 108 |
async def create_embeddings(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
self, df: pd.DataFrame, target_column: str, output_column: str
|
| 110 |
) -> pd.DataFrame:
|
| 111 |
-
"""Create embeddings for the target column in the
|
| 112 |
-
logger.info("Generating embeddings...")
|
| 113 |
self.total_requests = len(df) # Set total number of requests
|
| 114 |
self.completed_requests = 0 # Reset completed requests counter
|
| 115 |
|
|
@@ -124,6 +235,24 @@ class EmbeddingService:
|
|
| 124 |
)
|
| 125 |
return pd.concat(processed_batches)
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
async def _process_batch(
|
| 128 |
self, df_batch: pd.DataFrame, target_column: str, output_column: str
|
| 129 |
) -> pd.DataFrame:
|
|
|
|
| 61 |
# df_batch[output_column] = embeddings
|
| 62 |
# return df_batch
|
| 63 |
|
| 64 |
+
# from openai import AsyncOpenAI
|
| 65 |
+
# import logging
|
| 66 |
+
# from typing import List, Dict
|
| 67 |
+
# import pandas as pd
|
| 68 |
+
# import asyncio
|
| 69 |
+
# from src.api.exceptions import OpenAIError
|
| 70 |
+
|
| 71 |
+
# # Set up structured logging
|
| 72 |
+
# logging.basicConfig(
|
| 73 |
+
# level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
| 74 |
+
# )
|
| 75 |
+
# logger = logging.getLogger(__name__)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# class EmbeddingService:
|
| 79 |
+
# def __init__(
|
| 80 |
+
# self,
|
| 81 |
+
# openai_api_key: str,
|
| 82 |
+
# model: str = "text-embedding-3-small",
|
| 83 |
+
# batch_size: int = 10,
|
| 84 |
+
# max_concurrent_requests: int = 10, # Limit to 10 concurrent requests
|
| 85 |
+
# ):
|
| 86 |
+
# self.client = AsyncOpenAI(api_key=openai_api_key)
|
| 87 |
+
# self.model = model
|
| 88 |
+
# self.batch_size = batch_size
|
| 89 |
+
# self.semaphore = asyncio.Semaphore(max_concurrent_requests) # Rate limiter
|
| 90 |
+
# self.total_requests = 0 # Total number of requests to process
|
| 91 |
+
# self.completed_requests = 0 # Number of completed requests
|
| 92 |
+
|
| 93 |
+
# async def get_embedding(self, text: str) -> List[float]:
|
| 94 |
+
# """Generate embeddings for the given text using OpenAI."""
|
| 95 |
+
# text = text.replace("\n", " ")
|
| 96 |
+
# try:
|
| 97 |
+
# async with self.semaphore: # Acquire a semaphore slot
|
| 98 |
+
# response = await self.client.embeddings.create(
|
| 99 |
+
# input=[text], model=self.model
|
| 100 |
+
# )
|
| 101 |
+
# self.completed_requests += 1 # Increment completed requests
|
| 102 |
+
# self._log_progress() # Log progress
|
| 103 |
+
# return response.data[0].embedding
|
| 104 |
+
# except Exception as e:
|
| 105 |
+
# logger.error(f"Failed to generate embedding: {e}")
|
| 106 |
+
# raise OpenAIError(f"OpenAI API error: {e}")
|
| 107 |
+
|
| 108 |
+
# async def create_embeddings(
|
| 109 |
+
# self, df: pd.DataFrame, target_column: str, output_column: str
|
| 110 |
+
# ) -> pd.DataFrame:
|
| 111 |
+
# """Create embeddings for the target column in the dataset."""
|
| 112 |
+
# logger.info("Generating embeddings...")
|
| 113 |
+
# self.total_requests = len(df) # Set total number of requests
|
| 114 |
+
# self.completed_requests = 0 # Reset completed requests counter
|
| 115 |
+
|
| 116 |
+
# batches = [
|
| 117 |
+
# df[i : i + self.batch_size] for i in range(0, len(df), self.batch_size)
|
| 118 |
+
# ]
|
| 119 |
+
# processed_batches = await asyncio.gather(
|
| 120 |
+
# *[
|
| 121 |
+
# self._process_batch(batch, target_column, output_column)
|
| 122 |
+
# for batch in batches
|
| 123 |
+
# ]
|
| 124 |
+
# )
|
| 125 |
+
# return pd.concat(processed_batches)
|
| 126 |
+
|
| 127 |
+
# async def _process_batch(
|
| 128 |
+
# self, df_batch: pd.DataFrame, target_column: str, output_column: str
|
| 129 |
+
# ) -> pd.DataFrame:
|
| 130 |
+
# """Process a batch of rows to generate embeddings."""
|
| 131 |
+
# embeddings = await asyncio.gather(
|
| 132 |
+
# *[self.get_embedding(row[target_column]) for _, row in df_batch.iterrows()]
|
| 133 |
+
# )
|
| 134 |
+
# df_batch[output_column] = embeddings
|
| 135 |
+
# return df_batch
|
| 136 |
+
|
| 137 |
+
# def _log_progress(self):
|
| 138 |
+
# """Log the progress of embedding generation."""
|
| 139 |
+
# progress = (self.completed_requests / self.total_requests) * 100
|
| 140 |
+
# logger.info(
|
| 141 |
+
# f"Progress: {self.completed_requests}/{self.total_requests} ({progress:.2f}%)"
|
| 142 |
+
# )
|
| 143 |
+
|
| 144 |
from openai import AsyncOpenAI
|
| 145 |
import logging
|
| 146 |
+
from typing import List, Dict, Union
|
| 147 |
import pandas as pd
|
| 148 |
import asyncio
|
| 149 |
from src.api.exceptions import OpenAIError
|
|
|
|
| 186 |
raise OpenAIError(f"OpenAI API error: {e}")
|
| 187 |
|
| 188 |
async def create_embeddings(
|
| 189 |
+
self,
|
| 190 |
+
data: Union[pd.DataFrame, List[str]],
|
| 191 |
+
target_column: str = None,
|
| 192 |
+
output_column: str = "embeddings",
|
| 193 |
+
) -> Union[pd.DataFrame, List[List[float]]]:
|
| 194 |
+
"""
|
| 195 |
+
Create embeddings for either a DataFrame or a list of strings.
|
| 196 |
+
|
| 197 |
+
Args:
|
| 198 |
+
data: Either a DataFrame or a list of strings.
|
| 199 |
+
target_column: The column in the DataFrame to generate embeddings for (required if data is a DataFrame).
|
| 200 |
+
output_column: The column to store embeddings in the DataFrame (default: "embeddings").
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
If data is a DataFrame, returns the DataFrame with the embeddings column.
|
| 204 |
+
If data is a list of strings, returns a list of embeddings.
|
| 205 |
+
"""
|
| 206 |
+
if isinstance(data, pd.DataFrame):
|
| 207 |
+
if not target_column:
|
| 208 |
+
raise ValueError("target_column is required when data is a DataFrame.")
|
| 209 |
+
return await self._create_embeddings_for_dataframe(
|
| 210 |
+
data, target_column, output_column
|
| 211 |
+
)
|
| 212 |
+
elif isinstance(data, list):
|
| 213 |
+
return await self._create_embeddings_for_texts(data)
|
| 214 |
+
else:
|
| 215 |
+
raise TypeError(
|
| 216 |
+
"data must be either a pandas DataFrame or a list of strings."
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
async def _create_embeddings_for_dataframe(
|
| 220 |
self, df: pd.DataFrame, target_column: str, output_column: str
|
| 221 |
) -> pd.DataFrame:
|
| 222 |
+
"""Create embeddings for the target column in the DataFrame."""
|
| 223 |
+
logger.info("Generating embeddings for DataFrame...")
|
| 224 |
self.total_requests = len(df) # Set total number of requests
|
| 225 |
self.completed_requests = 0 # Reset completed requests counter
|
| 226 |
|
|
|
|
| 235 |
)
|
| 236 |
return pd.concat(processed_batches)
|
| 237 |
|
| 238 |
+
async def _create_embeddings_for_texts(self, texts: List[str]) -> List[List[float]]:
|
| 239 |
+
"""Create embeddings for a list of strings."""
|
| 240 |
+
logger.info("Generating embeddings for list of texts...")
|
| 241 |
+
self.total_requests = len(texts) # Set total number of requests
|
| 242 |
+
self.completed_requests = 0 # Reset completed requests counter
|
| 243 |
+
|
| 244 |
+
batches = [
|
| 245 |
+
texts[i : i + self.batch_size]
|
| 246 |
+
for i in range(0, len(texts), self.batch_size)
|
| 247 |
+
]
|
| 248 |
+
embeddings = []
|
| 249 |
+
for batch in batches:
|
| 250 |
+
batch_embeddings = await asyncio.gather(
|
| 251 |
+
*[self.get_embedding(text) for text in batch]
|
| 252 |
+
)
|
| 253 |
+
embeddings.extend(batch_embeddings)
|
| 254 |
+
return embeddings
|
| 255 |
+
|
| 256 |
async def _process_batch(
|
| 257 |
self, df_batch: pd.DataFrame, target_column: str, output_column: str
|
| 258 |
) -> pd.DataFrame:
|
src/main.py
CHANGED
|
@@ -1,3 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
from fastapi import FastAPI, Depends, HTTPException
|
| 3 |
from fastapi.responses import JSONResponse, RedirectResponse
|
|
@@ -71,7 +259,44 @@ def get_huggingface_service() -> HuggingFaceService:
|
|
| 71 |
return HuggingFaceService()
|
| 72 |
|
| 73 |
|
| 74 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
@app.post("/create_embedding")
|
| 76 |
async def create_embedding(
|
| 77 |
request: CreateEmbeddingRequest,
|
|
@@ -118,7 +343,6 @@ async def create_embedding(
|
|
| 118 |
|
| 119 |
|
| 120 |
# Endpoint to read embeddings
|
| 121 |
-
# @app.get("/read_embeddings/{dataset_name}")
|
| 122 |
@app.post("/read_embeddings")
|
| 123 |
async def read_embeddings(
|
| 124 |
request: ReadEmbeddingRequest,
|
|
|
|
| 1 |
+
# import os
|
| 2 |
+
# from fastapi import FastAPI, Depends, HTTPException
|
| 3 |
+
# from fastapi.responses import JSONResponse, RedirectResponse
|
| 4 |
+
# from fastapi.middleware.gzip import GZipMiddleware
|
| 5 |
+
# from pydantic import BaseModel
|
| 6 |
+
# from typing import List, Dict
|
| 7 |
+
# from src.api.models.embedding_models import (
|
| 8 |
+
# CreateEmbeddingRequest,
|
| 9 |
+
# ReadEmbeddingRequest,
|
| 10 |
+
# UpdateEmbeddingRequest,
|
| 11 |
+
# DeleteEmbeddingRequest,
|
| 12 |
+
# )
|
| 13 |
+
# from src.api.database import get_db, Database, QueryExecutionError, HealthCheckError
|
| 14 |
+
# from src.api.services.embedding_service import EmbeddingService
|
| 15 |
+
# from src.api.services.huggingface_service import HuggingFaceService
|
| 16 |
+
# from src.api.exceptions import DatasetNotFoundError, DatasetPushError, OpenAIError
|
| 17 |
+
# import pandas as pd
|
| 18 |
+
# import logging
|
| 19 |
+
# from dotenv import load_dotenv
|
| 20 |
+
|
| 21 |
+
# # Load environment variables
|
| 22 |
+
# load_dotenv()
|
| 23 |
+
|
| 24 |
+
# # Set up structured logging
|
| 25 |
+
# logging.basicConfig(
|
| 26 |
+
# level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
| 27 |
+
# )
|
| 28 |
+
# logger = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
# description = """A FastAPI application for similarity search with PostgreSQL and OpenAI embeddings.
|
| 31 |
+
|
| 32 |
+
# Direct/API URL:
|
| 33 |
+
# https://re-mind-similarity-search.hf.space
|
| 34 |
+
# """
|
| 35 |
+
|
| 36 |
+
# # Initialize FastAPI app
|
| 37 |
+
# app = FastAPI(
|
| 38 |
+
# title="Similarity Search API",
|
| 39 |
+
# description=description,
|
| 40 |
+
# version="1.0.0",
|
| 41 |
+
# )
|
| 42 |
+
|
| 43 |
+
# app.add_middleware(GZipMiddleware, minimum_size=1000)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# # Root endpoint redirects to /docs
|
| 47 |
+
# @app.get("/")
|
| 48 |
+
# async def root():
|
| 49 |
+
# return RedirectResponse(url="/docs")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# # Health check endpoint
|
| 53 |
+
# @app.get("/health")
|
| 54 |
+
# async def health_check(db: Database = Depends(get_db)):
|
| 55 |
+
# try:
|
| 56 |
+
# is_healthy = await db.health_check()
|
| 57 |
+
# if not is_healthy:
|
| 58 |
+
# raise HTTPException(status_code=500, detail="Database is unhealthy")
|
| 59 |
+
# return {"status": "healthy"}
|
| 60 |
+
# except HealthCheckError as e:
|
| 61 |
+
# raise HTTPException(status_code=500, detail=str(e))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# # Dependency to get EmbeddingService
|
| 65 |
+
# def get_embedding_service() -> EmbeddingService:
|
| 66 |
+
# return EmbeddingService(openai_api_key=os.getenv("OPENAI_API_KEY"))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# # Dependency to get HuggingFaceService
|
| 70 |
+
# def get_huggingface_service() -> HuggingFaceService:
|
| 71 |
+
# return HuggingFaceService()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# # Endpoint to create embeddings
|
| 75 |
+
# @app.post("/create_embedding")
|
| 76 |
+
# async def create_embedding(
|
| 77 |
+
# request: CreateEmbeddingRequest,
|
| 78 |
+
# db: Database = Depends(get_db),
|
| 79 |
+
# embedding_service: EmbeddingService = Depends(get_embedding_service),
|
| 80 |
+
# huggingface_service: HuggingFaceService = Depends(get_huggingface_service),
|
| 81 |
+
# ):
|
| 82 |
+
# """
|
| 83 |
+
# Create embeddings for the target column in the dataset.
|
| 84 |
+
# """
|
| 85 |
+
# try:
|
| 86 |
+
# # Step 1: Query the database
|
| 87 |
+
# logger.info("Fetching data from the database...")
|
| 88 |
+
# result = await db.fetch(request.query)
|
| 89 |
+
# df = pd.DataFrame(result)
|
| 90 |
+
|
| 91 |
+
# # Step 2: Generate embeddings
|
| 92 |
+
# df = await embedding_service.create_embeddings(
|
| 93 |
+
# df, request.target_column, request.output_column
|
| 94 |
+
# )
|
| 95 |
+
|
| 96 |
+
# # Step 3: Push to Hugging Face Hub
|
| 97 |
+
# await huggingface_service.push_to_hub(df, request.dataset_name)
|
| 98 |
+
|
| 99 |
+
# return JSONResponse(
|
| 100 |
+
# content={
|
| 101 |
+
# "message": "Embeddings created and pushed to Hugging Face Hub.",
|
| 102 |
+
# "dataset_name": request.dataset_name,
|
| 103 |
+
# "num_rows": len(df),
|
| 104 |
+
# }
|
| 105 |
+
# )
|
| 106 |
+
# except QueryExecutionError as e:
|
| 107 |
+
# logger.error(f"Database query failed: {e}")
|
| 108 |
+
# raise HTTPException(status_code=500, detail=f"Database query failed: {e}")
|
| 109 |
+
# except OpenAIError as e:
|
| 110 |
+
# logger.error(f"OpenAI API error: {e}")
|
| 111 |
+
# raise HTTPException(status_code=500, detail=f"OpenAI API error: {e}")
|
| 112 |
+
# except DatasetPushError as e:
|
| 113 |
+
# logger.error(f"Failed to push dataset: {e}")
|
| 114 |
+
# raise HTTPException(status_code=500, detail=f"Failed to push dataset: {e}")
|
| 115 |
+
# except Exception as e:
|
| 116 |
+
# logger.error(f"An error occurred: {e}")
|
| 117 |
+
# raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# # Endpoint to read embeddings
|
| 121 |
+
# # @app.get("/read_embeddings/{dataset_name}")
|
| 122 |
+
# @app.post("/read_embeddings")
|
| 123 |
+
# async def read_embeddings(
|
| 124 |
+
# request: ReadEmbeddingRequest,
|
| 125 |
+
# huggingface_service: HuggingFaceService = Depends(get_huggingface_service),
|
| 126 |
+
# ):
|
| 127 |
+
# """
|
| 128 |
+
# Read embeddings from a Hugging Face dataset.
|
| 129 |
+
# """
|
| 130 |
+
# try:
|
| 131 |
+
# df = await huggingface_service.read_dataset(request.dataset_name)
|
| 132 |
+
# return df
|
| 133 |
+
# except DatasetNotFoundError as e:
|
| 134 |
+
# logger.error(f"Dataset not found: {e}")
|
| 135 |
+
# raise HTTPException(status_code=404, detail=f"Dataset not found: {e}")
|
| 136 |
+
# except Exception as e:
|
| 137 |
+
# logger.error(f"An error occurred: {e}")
|
| 138 |
+
# raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# # Endpoint to update embeddings
|
| 142 |
+
# @app.post("/update_embeddings")
|
| 143 |
+
# async def update_embeddings(
|
| 144 |
+
# request: UpdateEmbeddingRequest,
|
| 145 |
+
# huggingface_service: HuggingFaceService = Depends(get_huggingface_service),
|
| 146 |
+
# ):
|
| 147 |
+
# """
|
| 148 |
+
# Update embeddings in a Hugging Face dataset.
|
| 149 |
+
# """
|
| 150 |
+
# try:
|
| 151 |
+
# df = await huggingface_service.update_dataset(
|
| 152 |
+
# request.dataset_name, request.updates
|
| 153 |
+
# )
|
| 154 |
+
# return {
|
| 155 |
+
# "message": "Embeddings updated successfully.",
|
| 156 |
+
# "dataset_name": request.dataset_name,
|
| 157 |
+
# }
|
| 158 |
+
# except DatasetPushError as e:
|
| 159 |
+
# logger.error(f"Failed to update dataset: {e}")
|
| 160 |
+
# raise HTTPException(status_code=500, detail=f"Failed to update dataset: {e}")
|
| 161 |
+
# except Exception as e:
|
| 162 |
+
# logger.error(f"An error occurred: {e}")
|
| 163 |
+
# raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# # Endpoint to delete embeddings
|
| 167 |
+
# @app.post("/delete_embeddings")
|
| 168 |
+
# async def delete_embeddings(
|
| 169 |
+
# request: DeleteEmbeddingRequest,
|
| 170 |
+
# huggingface_service: HuggingFaceService = Depends(get_huggingface_service),
|
| 171 |
+
# ):
|
| 172 |
+
# """
|
| 173 |
+
# Delete embeddings from a Hugging Face dataset.
|
| 174 |
+
# """
|
| 175 |
+
# try:
|
| 176 |
+
# await huggingface_service.delete_dataset(request.dataset_name)
|
| 177 |
+
# return {
|
| 178 |
+
# "message": "Embeddings deleted successfully.",
|
| 179 |
+
# "dataset_name": request.dataset_name,
|
| 180 |
+
# }
|
| 181 |
+
# except DatasetPushError as e:
|
| 182 |
+
# logger.error(f"Failed to delete columns: {e}")
|
| 183 |
+
# raise HTTPException(status_code=500, detail=f"Failed to delete columns: {e}")
|
| 184 |
+
# except Exception as e:
|
| 185 |
+
# logger.error(f"An error occurred: {e}")
|
| 186 |
+
# raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
|
| 187 |
+
|
| 188 |
+
|
| 189 |
import os
|
| 190 |
from fastapi import FastAPI, Depends, HTTPException
|
| 191 |
from fastapi.responses import JSONResponse, RedirectResponse
|
|
|
|
| 259 |
return HuggingFaceService()
|
| 260 |
|
| 261 |
|
| 262 |
+
# Request model for the /embed endpoint
|
| 263 |
+
class EmbedRequest(BaseModel):
|
| 264 |
+
texts: List[str] # List of strings to generate embeddings for
|
| 265 |
+
output_column: str = (
|
| 266 |
+
"embeddings" # Column to store embeddings (default: "embeddings")
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
# Endpoint to generate embeddings for a list of strings
|
| 271 |
+
@app.post("/embed")
|
| 272 |
+
async def embed(
|
| 273 |
+
request: EmbedRequest,
|
| 274 |
+
embedding_service: EmbeddingService = Depends(get_embedding_service),
|
| 275 |
+
):
|
| 276 |
+
"""
|
| 277 |
+
Generate embeddings for a list of strings and return them in the response.
|
| 278 |
+
"""
|
| 279 |
+
try:
|
| 280 |
+
# Step 1: Generate embeddings
|
| 281 |
+
logger.info("Generating embeddings for list of texts...")
|
| 282 |
+
embeddings = await embedding_service.create_embeddings(request.texts)
|
| 283 |
+
|
| 284 |
+
return JSONResponse(
|
| 285 |
+
content={
|
| 286 |
+
"message": "Embeddings generated successfully.",
|
| 287 |
+
"embeddings": embeddings,
|
| 288 |
+
"num_texts": len(request.texts),
|
| 289 |
+
}
|
| 290 |
+
)
|
| 291 |
+
except OpenAIError as e:
|
| 292 |
+
logger.error(f"OpenAI API error: {e}")
|
| 293 |
+
raise HTTPException(status_code=500, detail=f"OpenAI API error: {e}")
|
| 294 |
+
except Exception as e:
|
| 295 |
+
logger.error(f"An error occurred: {e}")
|
| 296 |
+
raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# Endpoint to create embeddings from a database query
|
| 300 |
@app.post("/create_embedding")
|
| 301 |
async def create_embedding(
|
| 302 |
request: CreateEmbeddingRequest,
|
|
|
|
| 343 |
|
| 344 |
|
| 345 |
# Endpoint to read embeddings
|
|
|
|
| 346 |
@app.post("/read_embeddings")
|
| 347 |
async def read_embeddings(
|
| 348 |
request: ReadEmbeddingRequest,
|