""" 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