2023-12-11 21:53:30 +00:00
|
|
|
import importlib.util
|
2024-01-30 04:30:34 +00:00
|
|
|
from typing import Any, Dict, List, Optional
|
2023-12-11 21:53:30 +00:00
|
|
|
|
|
|
|
from langchain_core.embeddings import Embeddings
|
|
|
|
from langchain_core.pydantic_v1 import BaseModel, Extra, root_validator
|
|
|
|
|
|
|
|
|
|
|
|
class SpacyEmbeddings(BaseModel, Embeddings):
|
2024-01-30 04:30:34 +00:00
|
|
|
"""Embeddings by spaCy models.
|
2023-12-11 21:53:30 +00:00
|
|
|
|
|
|
|
Attributes:
|
2024-01-30 04:30:34 +00:00
|
|
|
model_name (str): Name of a spaCy model.
|
|
|
|
nlp (Any): The spaCy model loaded into memory.
|
2023-12-11 21:53:30 +00:00
|
|
|
|
|
|
|
Methods:
|
|
|
|
embed_documents(texts: List[str]) -> List[List[float]]:
|
|
|
|
Generates embeddings for a list of documents.
|
|
|
|
embed_query(text: str) -> List[float]:
|
|
|
|
Generates an embedding for a single piece of text.
|
|
|
|
"""
|
|
|
|
|
2024-01-30 04:30:34 +00:00
|
|
|
model_name: str = "en_core_web_sm"
|
|
|
|
nlp: Optional[Any] = None
|
2023-12-11 21:53:30 +00:00
|
|
|
|
|
|
|
class Config:
|
|
|
|
"""Configuration for this pydantic object."""
|
|
|
|
|
|
|
|
extra = Extra.forbid # Forbid extra attributes during model initialization
|
|
|
|
|
|
|
|
@root_validator(pre=True)
|
|
|
|
def validate_environment(cls, values: Dict) -> Dict:
|
|
|
|
"""
|
2024-01-30 04:30:34 +00:00
|
|
|
Validates that the spaCy package and the model are installed.
|
2023-12-11 21:53:30 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
values (Dict): The values provided to the class constructor.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The validated values.
|
|
|
|
|
|
|
|
Raises:
|
2024-01-30 04:30:34 +00:00
|
|
|
ValueError: If the spaCy package or the
|
2023-12-11 21:53:30 +00:00
|
|
|
model are not installed.
|
|
|
|
"""
|
2024-01-30 04:30:34 +00:00
|
|
|
if values.get("model_name") is None:
|
|
|
|
values["model_name"] = "en_core_web_sm"
|
|
|
|
|
|
|
|
model_name = values.get("model_name")
|
|
|
|
|
|
|
|
# Check if the spaCy package is installed
|
2023-12-11 21:53:30 +00:00
|
|
|
if importlib.util.find_spec("spacy") is None:
|
|
|
|
raise ValueError(
|
2024-01-30 04:30:34 +00:00
|
|
|
"SpaCy package not found. "
|
2023-12-11 21:53:30 +00:00
|
|
|
"Please install it with `pip install spacy`."
|
|
|
|
)
|
|
|
|
try:
|
2024-01-30 04:30:34 +00:00
|
|
|
# Try to load the spaCy model
|
2023-12-11 21:53:30 +00:00
|
|
|
import spacy
|
|
|
|
|
2024-01-30 04:30:34 +00:00
|
|
|
values["nlp"] = spacy.load(model_name)
|
2023-12-11 21:53:30 +00:00
|
|
|
except OSError:
|
|
|
|
# If the model is not found, raise a ValueError
|
|
|
|
raise ValueError(
|
2024-01-30 04:30:34 +00:00
|
|
|
f"SpaCy model '{model_name}' not found. "
|
|
|
|
f"Please install it with"
|
|
|
|
f" `python -m spacy download {model_name}`"
|
|
|
|
"or provide a valid spaCy model name."
|
2023-12-11 21:53:30 +00:00
|
|
|
)
|
|
|
|
return values # Return the validated values
|
|
|
|
|
|
|
|
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
|
|
|
"""
|
|
|
|
Generates embeddings for a list of documents.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
texts (List[str]): The documents to generate embeddings for.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A list of embeddings, one for each document.
|
|
|
|
"""
|
2024-02-05 19:22:06 +00:00
|
|
|
return [self.nlp(text).vector.tolist() for text in texts] # type: ignore[misc]
|
2023-12-11 21:53:30 +00:00
|
|
|
|
|
|
|
def embed_query(self, text: str) -> List[float]:
|
|
|
|
"""
|
|
|
|
Generates an embedding for a single piece of text.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
text (str): The text to generate an embedding for.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The embedding for the text.
|
|
|
|
"""
|
2024-02-05 19:22:06 +00:00
|
|
|
return self.nlp(text).vector.tolist() # type: ignore[misc]
|
2023-12-11 21:53:30 +00:00
|
|
|
|
|
|
|
async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
|
|
|
|
"""
|
|
|
|
Asynchronously generates embeddings for a list of documents.
|
|
|
|
This method is not implemented and raises a NotImplementedError.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
texts (List[str]): The documents to generate embeddings for.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
NotImplementedError: This method is not implemented.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError("Asynchronous embedding generation is not supported.")
|
|
|
|
|
|
|
|
async def aembed_query(self, text: str) -> List[float]:
|
|
|
|
"""
|
|
|
|
Asynchronously generates an embedding for a single piece of text.
|
|
|
|
This method is not implemented and raises a NotImplementedError.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
text (str): The text to generate an embedding for.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
NotImplementedError: This method is not implemented.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError("Asynchronous embedding generation is not supported.")
|