Spaces:
Sleeping
Sleeping
File size: 1,765 Bytes
07c3ebf 1f7a6ca 07c3ebf ae47781 07c3ebf ae47781 07c3ebf 194d499 07c3ebf 194d499 07c3ebf | 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 55 56 57 58 | """
This module provides functionality to embed texts using the Hugging Face API.
It includes an EmbeddingFunction class for asynchronous embedding and a sync_embed function for synchronous embedding.
"""
from huggingface_hub import InferenceClient
import os
from typing import List, Optional, Union
import os
from huggingface_hub import InferenceClient
from dotenv import load_dotenv
load_dotenv()
TextType = Union[str, List[str]]
class EmbeddingFunction:
"""
A class to handle embedding functions using the Hugging Face API.
"""
def __init__(
self,
model: str,
api_key: Optional[str] = None,
batch_size: int = 50,
api_url: Optional[str] = None,
):
"""
Initialize the EmbeddingFunction.
Args:
model (str): The model to use for embedding.
api_key (Optional[str]): The API key for the Hugging Face API. If not provided,
it will be fetched from the environment variable `HF_API_KEY`.
batch_size (int): The number of texts to process in a single batch. Default is 50.
api_url (Optional[str]): Custom API URL for Hugging Face inference endpoint.
"""
def sync_embed(texts: str, model: str, api_key: str) -> list:
"""
Extrait les embeddings d'un texte via l'API Inference de Hugging Face.
Args:
texts (str): Le texte à encoder.
model (str): Le modèle Hugging Face à utiliser.
api_key (str): La clé API Hugging Face.
Returns:
list: Les embeddings du texte.
"""
client = InferenceClient(provider="hf-inference", api_key=api_key)
result = client.feature_extraction(texts, model=model)
return result[0] # Retourne le premier embedding
|