Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Make txtai install modular, base install is now a minimal set of libraries to support most commonly used functionality, closes #97

davidmezzetti1f82d54009bc
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index bbebeec3..7056588a 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -34,7 +34,7 @@ jobs:
- name: Build
run: |
pip install -U pip wheel coverage coveralls
- pip install .
+ pip install .[all]
python -c "import nltk; nltk.download('punkt')"
python --version
make data coverage
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index 65d83bb4..c2d48e38 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -11,6 +11,6 @@ jobs:
- uses: actions/setup-python@v2
with:
python-version: 3.6
- - run: pip install mkdocs-material mkdocstrings git+https://github.com/neuml/txtai
+ - run: pip install mkdocs-material mkdocstrings git+https://github.com/neuml/txtai#egg=txtai[all]
- run: mkdocs gh-deploy --force
\ No newline at end of file
diff --git a/README.md b/README.md
index bb999794..0915b918 100644
--- a/README.md
+++ b/README.md
@@ -63,7 +63,28 @@ You can also install txtai directly from GitHub. Using a Python Virtual Environm
pip install git+https://github.com/neuml/txtai
-Python 3.6+ is supported. txtai has the following environment specific prerequisites.
+Python 3.6+ is supported.
+
+txtai has the following optional dependencies that can be installed as extras.
+
+```
+# Install all dependencies (mirrors txtai < 3.2)
+pip install txtai[all]
+
+# Serve txtai via a web API
+pip install txtai[api]
+
+# All pipelines - default install comes with most common pipelines
+pip install txtai[pipeline]
+
+# Word vectors, support for sentence-transformer models not on the HF Hub and additional ANN libraries
+pip install txtai[similarity]
+
+# All workflow tasks - default install comes with most common workflow tasks
+pip install txtai[workflow]
+```
+
+Additional environment specific prerequisites are below.
### Linux
@@ -81,7 +102,9 @@ Install [C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-to
The examples directory has a series of notebooks and applications giving an overview of txtai. See the sections below.
-### Notebooks
+### Similarity Search
+
+Build similarity/semantic/vector search applications with txtai.
| Notebook | Description | |
|:----------|:-------------|------:|
@@ -89,20 +112,29 @@ The examples directory has a series of notebooks and applications giving an over
| [Build an Embeddings index with Hugging Face Datasets](https://github.com/neuml/txtai/blob/master/examples/02_Build_an_Embeddings_index_with_Hugging_Face_Datasets.ipynb) | Index and search Hugging Face Datasets | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/02_Build_an_Embeddings_index_with_Hugging_Face_Datasets.ipynb) |
| [Build an Embeddings index from a data source](https://github.com/neuml/txtai/blob/master/examples/03_Build_an_Embeddings_index_from_a_data_source.ipynb) | Index and search a data source with word embeddings | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/03_Build_an_Embeddings_index_from_a_data_source.ipynb) |
| [Add semantic search to Elasticsearch](https://github.com/neuml/txtai/blob/master/examples/04_Add_semantic_search_to_Elasticsearch.ipynb) | Add semantic search to existing search systems | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/04_Add_semantic_search_to_Elasticsearch.ipynb) |
+| [API Gallery](https://github.com/neuml/txtai/blob/master/examples/08_API_Gallery.ipynb) | Using txtai in JavaScript, Java, Rust and Go | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/08_API_Gallery.ipynb) |
+| [Similarity search with images](https://github.com/neuml/txtai/blob/master/examples/13_Similarity_search_with_images.ipynb) | Embed images and text into the same space for search | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/13_Similarity_search_with_images.ipynb) |
+| [Distributed embeddings cluster](https://github.com/neuml/txtai/blob/master/examples/15_Distributed_embeddings_cluster.ipynb) | Distribute an embeddings index across multiple data nodes | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/15_Distributed_embeddings_cluster.ipynb) |
+
+### Pipelines and Workflows
+
+NLP-backed data transformation pipelines and workflows. Run existing models and train new ones.
+
+| Notebook | Description | |
+|:----------|:-------------|------:|
| [Extractive QA with txtai](https://github.com/neuml/txtai/blob/master/examples/05_Extractive_QA_with_txtai.ipynb) | Introduction to extractive question-answering with txtai | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/05_Extractive_QA_with_txtai.ipynb) |
| [Extractive QA with Elasticsearch](https://github.com/neuml/txtai/blob/master/examples/06_Extractive_QA_with_Elasticsearch.ipynb) | Run extractive question-answering queries with Elasticsearch | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/06_Extractive_QA_with_Elasticsearch.ipynb) |
| [Apply labels with zero shot classification](https://github.com/neuml/txtai/blob/master/examples/07_Apply_labels_with_zero_shot_classification.ipynb) | Use zero shot learning for labeling, classification and topic modeling | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/07_Apply_labels_with_zero_shot_classification.ipynb) |
-| [API Gallery](https://github.com/neuml/txtai/blob/master/examples/08_API_Gallery.ipynb) | Using txtai in JavaScript, Java, Rust and Go | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/08_API_Gallery.ipynb) |
| [Building abstractive text summaries](https://github.com/neuml/txtai/blob/master/examples/09_Building_abstractive_text_summaries.ipynb) | Run abstractive text summarization | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/09_Building_abstractive_text_summaries.ipynb) |
| [Extract text from documents](https://github.com/neuml/txtai/blob/master/examples/10_Extract_text_from_documents.ipynb) | Extract text from PDF, Office, HTML and more | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/10_Extract_text_from_documents.ipynb) |
| [Transcribe audio to text](https://github.com/neuml/txtai/blob/master/examples/11_Transcribe_audio_to_text.ipynb) | Convert audio files to text | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/11_Transcribe_audio_to_text.ipynb) |
| [Translate text between languages](https://github.com/neuml/txtai/blob/master/examples/12_Translate_text_between_languages.ipynb) | Streamline machine translation and language detection | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/12_Translate_text_between_languages.ipynb) |
-| [Similarity search with images](https://github.com/neuml/txtai/blob/master/examples/13_Similarity_search_with_images.ipynb) | Embed images and text into the same space for search | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/13_Similarity_search_with_images.ipynb) |
| [Run pipeline workflows](https://github.com/neuml/txtai/blob/master/examples/14_Run_pipeline_workflows.ipynb) | Simple yet powerful constructs to efficiently process data | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/14_Run_pipeline_workflows.ipynb) |
-| [Distributed embeddings cluster](https://github.com/neuml/txtai/blob/master/examples/15_Distributed_embeddings_cluster.ipynb) | Distribute an embeddings index across multiple data nodes | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/15_Distributed_embeddings_cluster.ipynb) |
### Applications
+Series of example applications with txtai.
+
| Application | Description |
|:----------|:-------------|
| [Demo query shell](https://github.com/neuml/txtai/blob/master/examples/demo.py) | Basic similarity search example. Used in the original txtai demo. |
diff --git a/setup.py b/setup.py
index 1f9f6d1d..f41ff59d 100644
--- a/setup.py
+++ b/setup.py
@@ -4,6 +4,33 @@ from setuptools import find_packages, setup
with open("README.md", "r", encoding="utf-8") as f:
DESCRIPTION = f.read()
+# Optional dependencies
+extras = {}
+
+extras["dev"] = ["black", "coverage", "pre-commit", "pylint"]
+
+extras["api"] = [
+ "aiohttp>=3.7.4",
+ "fastapi>=0.61.1",
+ "PyYAML>=5.3",
+ "uvicorn>=0.12.1",
+]
+
+extras["pipeline"] = ["fasttext>=0.9.2", "nltk>=3.5", "soundfile>=0.10.3.post1", "tika>=1.24"]
+
+extras["similarity"] = [
+ "annoy>=1.16.3",
+ "fasttext>=0.9.2",
+ "hnswlib>=0.5.0",
+ "pymagnitude-lite>=0.1.43",
+ "scikit-learn>=0.23.1",
+ "sentence-transformers>=1.0.3",
+]
+
+extras["workflow"] = ["apache-libcloud>=3.3.1", "pillow>=7.2.0", "requests>=2.24.0"]
+
+extras["all"] = extras["api"] + extras["pipeline"] + extras["similarity"] + extras["workflow"]
+
setup(
name="txtai",
version="3.2.0",
@@ -22,32 +49,8 @@ setup(
package_dir={"": "src/python"},
keywords="search embedding machine-learning nlp",
python_requires=">=3.6",
- install_requires=[
- "aiohttp>=3.7.4",
- "annoy>=1.16.3",
- "apache-libcloud>=3.3.1",
- "faiss-cpu>=1.7.0; os_name != 'nt'",
- "fastapi>=0.61.1",
- "fasttext>=0.9.2",
- "hnswlib>=0.5.0",
- "nltk>=3.5",
- "numpy>=1.18.4",
- "pymagnitude-lite>=0.1.43",
- "pillow>=7.2.0",
- "PyYAML>=5.3",
- "regex>=2020.5.14",
- "requests>=2.24.0",
- "scikit-learn>=0.23.1",
- "sentence-transformers>=1.0.3",
- "sentencepiece>=0.1.91",
- "soundfile>=0.10.3.post1",
- "tika>=1.24",
- "torch>=1.4.0",
- "tqdm>=4.46.0",
- "transformers>=4.8.2",
- "uvicorn>=0.12.1",
- ],
- extras_require={"dev": ["black", "coverage", "pre-commit", "pylint"]},
+ install_requires=["annoy>=1.16.3; os_name == 'nt'", "faiss-cpu>=1.7.0; os_name != 'nt'", "numpy>=1.18.4", "torch>=1.4.0", "transformers>=4.8.2"],
+ extras_require=extras,
classifiers=[
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
diff --git a/src/python/txtai/ann/annoy.py b/src/python/txtai/ann/annoy.py
index cdb2bf1d..58c29261 100644
--- a/src/python/txtai/ann/annoy.py
+++ b/src/python/txtai/ann/annoy.py
@@ -2,7 +2,13 @@
Annoy module
"""
-from annoy import AnnoyIndex
+# Conditional import
+try:
+ from annoy import AnnoyIndex
+
+ ANNOY = True
+except ImportError:
+ ANNOY = False
from .base import ANN
diff --git a/src/python/txtai/ann/factory.py b/src/python/txtai/ann/factory.py
index 1274e09d..8f84ea70 100644
--- a/src/python/txtai/ann/factory.py
+++ b/src/python/txtai/ann/factory.py
@@ -2,9 +2,9 @@
Factory module
"""
-from .annoy import Annoy
+from .annoy import Annoy, ANNOY
from .faiss import Faiss, FAISS
-from .hnsw import HNSW
+from .hnsw import HNSW, HNSWLIB
class ANNFactory:
@@ -34,13 +34,18 @@ class ANNFactory:
# Create ANN instance
if backend == "annoy":
+ if not ANNOY:
+ raise ImportError('annoy library is not available - install "similarity" extra to enable')
+
model = Annoy(config)
elif backend == "hnsw":
+ if not HNSWLIB:
+ raise ImportError('hnswlib library is not available - install "similarity" extra to enable')
+
model = HNSW(config)
else:
- # Raise error if trying to create a Faiss index without Faiss installed
if not FAISS:
- raise ImportError("Faiss library is not installed")
+ raise ImportError("Faiss library is not available for this platform")
model = Faiss(config)
diff --git a/src/python/txtai/ann/faiss.py b/src/python/txtai/ann/faiss.py
index b4ff770e..ed63696c 100644
--- a/src/python/txtai/ann/faiss.py
+++ b/src/python/txtai/ann/faiss.py
@@ -6,7 +6,7 @@ import numpy as np
from .base import ANN
-# Conditionally import Faiss as it's only supported on Linux/macOS
+# Conditional import
try:
from faiss import index_factory, METRIC_INNER_PRODUCT, read_index, write_index
diff --git a/src/python/txtai/ann/hnsw.py b/src/python/txtai/ann/hnsw.py
index dc018480..7dc1e98b 100644
--- a/src/python/txtai/ann/hnsw.py
+++ b/src/python/txtai/ann/hnsw.py
@@ -4,8 +4,14 @@ HNSW module
import numpy as np
-# pylint: disable=E0611
-from hnswlib import Index
+# Conditional import
+try:
+ # pylint: disable=E0611
+ from hnswlib import Index
+
+ HNSWLIB = True
+except ImportError:
+ HNSWLIB = False
from .base import ANN
diff --git a/src/python/txtai/api/__init__.py b/src/python/txtai/api/__init__.py
index b8195ff3..4143c621 100644
--- a/src/python/txtai/api/__init__.py
+++ b/src/python/txtai/api/__init__.py
@@ -2,8 +2,13 @@
API imports
"""
-from .application import app, start
-from .base import API
-from .cluster import Cluster
-from .extension import Extension
-from .factory import Factory
+# Conditional import
+try:
+ from .application import app, start
+ from .base import API
+ from .cluster import Cluster
+ from .extension import Extension
+ from .factory import Factory
+except ImportError as missing:
+ # pylint: disable=W0707
+ raise ImportError('API is not available - install "api" extra to enable') from missing
diff --git a/src/python/txtai/embeddings/__init__.py b/src/python/txtai/embeddings/__init__.py
index b70d4ba7..d6fc1ff6 100644
--- a/src/python/txtai/embeddings/__init__.py
+++ b/src/python/txtai/embeddings/__init__.py
@@ -4,3 +4,4 @@ Embeddings imports
from .base import Embeddings
from .documents import Documents
+from .reducer import Reducer
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index b008f2f2..109df00a 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -8,12 +8,12 @@ import shutil
import numpy as np
-from sklearn.decomposition import TruncatedSVD
-
from ..ann import ANNFactory
from ..scoring import ScoringFactory
from ..vectors import VectorsFactory
+from .reducer import Reducer
+
class Embeddings:
"""
@@ -40,11 +40,14 @@ class Embeddings:
# Embeddings model
self.embeddings = None
- # Dimensionality reduction model
- self.lsa = None
+ if self.config and self.config.get("method") != "transformers":
+ # Dimensionality reduction model
+ self.reducer = None
- # Embedding scoring method - weighs each word in a sentence
- self.scoring = ScoringFactory.create(self.config["scoring"]) if self.config and self.config.get("scoring") else None
+ # Embedding scoring method - weighs each word in a sentence
+ self.scoring = ScoringFactory.create(self.config["scoring"]) if self.config and self.config.get("scoring") else None
+ else:
+ self.reducer, self.scoring = None, None
# Sentence vectors model
self.model = self.loadVectors() if self.config else None
@@ -74,8 +77,8 @@ class Embeddings:
# Build LSA model (if enabled). Remove principal components from embeddings.
if self.config.get("pca"):
- self.lsa = self.buildLSA(embeddings, self.config["pca"])
- self.removePC(embeddings)
+ self.reducer = Reducer(embeddings, self.config["pca"])
+ self.reducer(embeddings)
# Normalize embeddings
self.normalize(embeddings)
@@ -172,8 +175,8 @@ class Embeddings:
# Reduce the dimensionality of the embeddings. Scale the embeddings using this
# model to reduce the noise of common but less relevant terms.
- if self.lsa:
- self.removePC(embedding)
+ if self.reducer:
+ self.reducer(embedding)
# Normalize embeddings
self.normalize(embedding)
@@ -314,7 +317,8 @@ class Embeddings:
# Dimensionality reduction
if self.config.get("pca"):
with open("%s/lsa" % path, "rb") as handle:
- self.lsa = pickle.load(handle)
+ self.reducer = Reducer()
+ self.reducer.load(path)
# Embedding scoring
if self.config.get("scoring"):
@@ -363,9 +367,8 @@ class Embeddings:
self.embeddings.save("%s/embeddings" % path)
# Save dimensionality reduction
- if self.lsa:
- with open("%s/lsa" % path, "wb") as handle:
- pickle.dump(self.lsa, handle, protocol=pickle.HIGHEST_PROTOCOL)
+ if self.reducer:
+ self.reducer.save(path)
# Save embedding scoring
if self.scoring:
@@ -406,48 +409,6 @@ class Embeddings:
return (ids, dimensions, embeddings)
- def buildLSA(self, embeddings, components):
- """
- Builds a LSA model. This model is used to remove the principal component within embeddings. This helps to
- smooth out noisy embeddings (common words with less value).
-
- Args:
- embeddings: input embeddings matrix
- components: number of model components
-
- Returns:
- LSA model
- """
-
- svd = TruncatedSVD(n_components=components, random_state=0)
- svd.fit(embeddings)
-
- return svd
-
- def removePC(self, embeddings):
- """
- Applies a LSA model to embeddings, removed the top n principal components. Operation applied
- directly on array.
-
- Args:
- embeddings: input embeddings matrix
- """
-
- pc = self.lsa.components_
- factor = embeddings.dot(pc.transpose())
-
- # Apply LSA model
- # Calculation is different if n_components = 1
- if pc.shape[0] == 1:
- embeddings -= factor * pc
- elif len(embeddings.shape) > 1:
- # Apply model on a row-wise basis to limit memory usage
- for x in range(embeddings.shape[0]):
- embeddings[x] -= factor[x].dot(pc)
- else:
- # Single embedding
- embeddings -= factor.dot(pc)
-
def normalize(self, embeddings):
"""
Normalizes embeddings using L2 normalization. Operation applied directly on array.
diff --git a/src/python/txtai/embeddings/reducer.py b/src/python/txtai/embeddings/reducer.py
new file mode 100644
index 00000000..2b691eaf
--- /dev/null
+++ b/src/python/txtai/embeddings/reducer.py
@@ -0,0 +1,95 @@
+"""
+Reducer module
+"""
+
+import pickle
+
+# Conditionally import dimensionality reduction libraries as they aren't installed by default
+try:
+ from sklearn.decomposition import TruncatedSVD
+
+ REDUCER = True
+except ImportError:
+ REDUCER = False
+
+
+class Reducer:
+ """
+ LSA dimensionality reduction model
+ """
+
+ def __init__(self, embeddings=None, components=None):
+ """
+ Creates a dimensionality reduction model.
+
+ Args:
+ embeddings: input embeddings matrix
+ components: number of model components
+ """
+
+ self.model = self.build(embeddings, components) if embeddings is not None and components else None
+
+ def __call__(self, embeddings):
+ """
+ Applies a dimensionality reduction model to embeddings, removed the top n principal components. Operation applied
+ directly on array.
+
+ Args:
+ embeddings: input embeddings matrix
+ """
+
+ pc = self.model.components_
+ factor = embeddings.dot(pc.transpose())
+
+ # Apply LSA model
+ # Calculation is different if n_components = 1
+ if pc.shape[0] == 1:
+ embeddings -= factor * pc
+ elif len(embeddings.shape) > 1:
+ # Apply model on a row-wise basis to limit memory usage
+ for x in range(embeddings.shape[0]):
+ embeddings[x] -= factor[x].dot(pc)
+ else:
+ # Single embedding
+ embeddings -= factor.dot(pc)
+
+ def build(self, embeddings, components):
+ """
+ Builds a LSA model. This model is used to remove the principal component within embeddings. This helps to
+ smooth out noisy embeddings (common words with less value).
+
+ Args:
+ embeddings: input embeddings matrix
+ components: number of model components
+
+ Returns:
+ LSA model
+ """
+
+ model = TruncatedSVD(n_components=components, random_state=0)
+ model.fit(embeddings)
+
+ return model
+
+ def load(self, path):
+ """
+ Loads a Reducer object from path.
+
+ Args:
+ path: directory path to load model
+ """
+
+ # Dimensionality reduction
+ with open("%s/lsa" % path, "rb") as handle:
+ self.model = pickle.load(handle)
+
+ def save(self, path):
+ """
+ Saves a Reducer object to path.
+
+ Args:
+ path: directory path to save model
+ """
+
+ with open("%s/lsa" % path, "wb") as handle:
+ pickle.dump(self.model, handle, protocol=pickle.HIGHEST_PROTOCOL)
diff --git a/src/python/txtai/models/models.py b/src/python/txtai/models/models.py
index 6cd3b813..92e197f6 100644
--- a/src/python/txtai/models/models.py
+++ b/src/python/txtai/models/models.py
@@ -2,6 +2,8 @@
Models module
"""
+import torch
+
class Models:
"""
@@ -26,3 +28,56 @@ class Models:
if hasattr(config, "max_position_embeddings") and tokenizer.model_max_length == int(1e30):
tokenizer.model_max_length = config.max_position_embeddings
+
+ @staticmethod
+ def deviceid(gpu):
+ """
+ Translates a gpu flag into a device id.
+
+ Args:
+ gpu: True/False if GPU should be enabled, also supports a GPU device id
+
+ Returns:
+ device id
+ """
+
+ # Always return -1 if gpu is None or CUDA is unavailable
+ if gpu is None or not torch.cuda.is_available():
+ return -1
+
+ # Default to device 0 if gpu is True and not otherwise specified
+ if isinstance(gpu, bool):
+ return 0 if gpu else -1
+
+ # Return gpu as device id if gpu flag is an int
+ return int(gpu)
+
+ @staticmethod
+ def device(deviceid):
+ """
+ Gets a tensor device.
+
+ Args:
+ deviceid: device id
+
+ Returns:
+ tensor device
+ """
+
+ # Torch device
+ # pylint: disable=E1101
+ return torch.device(Models.reference(deviceid))
+
+ @staticmethod
+ def reference(deviceid):
+ """
+ Gets a tensor device reference.
+
+ Args:
+ deviceid: device id
+
+ Returns:
+ device reference
+ """
+
+ return "cpu" if deviceid < 0 else "cuda:{}".format(deviceid)
diff --git a/src/python/txtai/pipeline/extractor.py b/src/python/txtai/pipeline/extractor.py
index 40bc7fc8..e9d1c134 100644
--- a/src/python/txtai/pipeline/extractor.py
+++ b/src/python/txtai/pipeline/extractor.py
@@ -2,8 +2,6 @@
Extractor module
"""
-from nltk.tokenize import sent_tokenize
-
from .base import Pipeline
from .questions import Questions
from .tokenizer import Tokenizer
@@ -54,7 +52,7 @@ class Extractor(Pipeline):
results = self.query([query for _, query, _, _ in queue], texts)
# Build question-context pairs
- names, questions, contexts, snippets = [], [], [], []
+ names, questions, contexts, topns, snippets = [], [], [], [], []
for x, (name, _, question, snippet) in enumerate(queue):
# Build context using top n best matching segments
topn = sorted(results[x], key=lambda y: y[2], reverse=True)[:3]
@@ -63,10 +61,11 @@ class Extractor(Pipeline):
names.append(name)
questions.append(question)
contexts.append(context)
+ topns.append([text for _, text, _ in topn])
snippets.append(snippet)
# Run qa pipeline and return answers
- return self.answers(names, questions, contexts, snippets)
+ return self.answers(names, questions, contexts, topns, snippets)
def query(self, queries, texts):
"""
@@ -123,7 +122,7 @@ class Extractor(Pipeline):
return results
- def answers(self, names, questions, contexts, snippets):
+ def answers(self, names, questions, contexts, topns, snippets):
"""
Executes QA pipeline and formats extracted answers.
@@ -131,6 +130,7 @@ class Extractor(Pipeline):
names: question identifiers/names
questions: questions
contexts: question context
+ topns: same as question context but as a list with each candidate element
snippets: flags to enable answer snippets per answer
Returns:
@@ -146,18 +146,18 @@ class Extractor(Pipeline):
for x, answer in enumerate(answers):
# Resolve snippet if necessary
if answer and snippets[x]:
- answer = self.snippet(contexts[x], answer)
+ answer = self.snippet(topns[x], answer)
results.append((names[x], answer))
return results
- def snippet(self, context, answer):
+ def snippet(self, topn, answer):
"""
Extracts text surrounding the answer within context.
Args:
- context: full context
+ topn: topn items used as a context
answer: answer within context
Returns:
@@ -166,7 +166,7 @@ class Extractor(Pipeline):
# Searches for first sentence to contain answer
if answer:
- for x in sent_tokenize(context):
+ for x in topn:
if answer in x:
return x
diff --git a/src/python/txtai/pipeline/hfmodel.py b/src/python/txtai/pipeline/hfmodel.py
index 9613208a..82351506 100644
--- a/src/python/txtai/pipeline/hfmodel.py
+++ b/src/python/txtai/pipeline/hfmodel.py
@@ -2,6 +2,7 @@
Hugging Face Transformers model wrapper module
"""
+from ..models import Models
from .tensors import Tensors
@@ -29,8 +30,8 @@ class HFModel(Tensors):
self.quantization = quantize
# Get tensor device reference
- self.deviceid = self.deviceid(gpu)
- self.device = self.reference(self.deviceid)
+ self.deviceid = Models.deviceid(gpu)
+ self.device = Models.reference(self.deviceid)
# Process batch size
self.batchsize = batch
diff --git a/src/python/txtai/pipeline/hfpipeline.py b/src/python/txtai/pipeline/hfpipeline.py
index 5e781156..0a968900 100644
--- a/src/python/txtai/pipeline/hfpipeline.py
+++ b/src/python/txtai/pipeline/hfpipeline.py
@@ -32,7 +32,7 @@ class HFPipeline(Tensors):
self.pipeline = model.pipeline if isinstance(model, HFPipeline) else model
else:
# Get device id
- deviceid = self.deviceid(gpu)
+ deviceid = Models.deviceid(gpu)
# Transformer pipeline task
if isinstance(path, tuple):
diff --git a/src/python/txtai/pipeline/segmentation.py b/src/python/txtai/pipeline/segmentation.py
index 5c051813..f9c2159b 100644
--- a/src/python/txtai/pipeline/segmentation.py
+++ b/src/python/txtai/pipeline/segmentation.py
@@ -4,7 +4,13 @@ Segmentation module
import re
-from nltk import sent_tokenize
+# Conditional import
+try:
+ from nltk import sent_tokenize
+
+ NLTK = True
+except ImportError:
+ NLTK = False
from .base import Pipeline
@@ -26,6 +32,9 @@ class Segmentation(Pipeline):
join: joins tokenized sections back together if True, defaults to False
"""
+ if not NLTK:
+ raise ImportError('Segmentation pipeline is not available - install "pipeline" extra to enable')
+
self.sentences = sentences
self.lines = lines
self.paragraphs = paragraphs
diff --git a/src/python/txtai/pipeline/tensors.py b/src/python/txtai/pipeline/tensors.py
index d4d360d1..86564cac 100644
--- a/src/python/txtai/pipeline/tensors.py
+++ b/src/python/txtai/pipeline/tensors.py
@@ -12,43 +12,6 @@ class Tensors(Pipeline):
Pipeline backed by a tensor processing framework. Currently supports PyTorch.
"""
- def deviceid(self, gpu):
- """
- Translates a gpu flag into a device id.
-
- Args:
- gpu: True/False if GPU should be enabled, also supports a GPU device id
-
- Returns:
- device id
- """
-
- # Always return -1 if gpu is None or CUDA is unavailable
- if gpu is None or not torch.cuda.is_available():
- return -1
-
- # Default to device 0 if gpu is True and not otherwise specified
- if isinstance(gpu, bool):
- return 0 if gpu else -1
-
- # Return gpu as device id if gpu flag is an int
- return int(gpu)
-
- def reference(self, device):
- """
- Gets a tensor device reference.
-
- Args:
- device: device id
-
- Returns:
- tensor device
- """
-
- # Torch device
- # pylint: disable=E1101
- return torch.device("cpu" if device < 0 else "cuda:{}".format(device))
-
def quantize(self, model):
"""
Quantizes input model and returns. This only is supported for CPU devices.
diff --git a/src/python/txtai/pipeline/textractor.py b/src/python/txtai/pipeline/textractor.py
index 89c88b00..c0a501d5 100644
--- a/src/python/txtai/pipeline/textractor.py
+++ b/src/python/txtai/pipeline/textractor.py
@@ -2,7 +2,13 @@
Textractor module
"""
-from tika import parser
+# Conditional import
+try:
+ from tika import parser
+
+ TIKA = True
+except ImportError:
+ TIKA = False
from .segmentation import Segmentation
@@ -12,6 +18,12 @@ class Textractor(Segmentation):
Extracts text from files.
"""
+ def __init__(self, sentences=False, lines=False, paragraphs=False, minlength=None, join=False):
+ if not TIKA:
+ raise ImportError('Textractor pipeline is not available - install "pipeline" extra to enable')
+
+ super().__init__(sentences, lines, paragraphs, minlength, join)
+
def text(self, text):
# text is a path to a file
parsed = parser.from_file(text)
diff --git a/src/python/txtai/pipeline/translation.py b/src/python/txtai/pipeline/translation.py
index be340d2d..5598cafa 100644
--- a/src/python/txtai/pipeline/translation.py
+++ b/src/python/txtai/pipeline/translation.py
@@ -2,7 +2,13 @@
Translation module
"""
-import fasttext
+# Conditional import
+try:
+ import fasttext
+
+ FASTTEXT = True
+except ImportError:
+ FASTTEXT = False
from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer, MarianMTModel, MarianTokenizer
from transformers.file_utils import cached_path
@@ -107,6 +113,9 @@ class Translation(HFModel):
list of languages
"""
+ if not FASTTEXT:
+ raise ImportError('Language detection is not available - install "pipeline" extra to enable')
+
if not self.detector:
# Suppress unnecessary warning
fasttext.FastText.eprint = lambda x: None
diff --git a/src/python/txtai/vectors/factory.py b/src/python/txtai/vectors/factory.py
index 41417fe7..413036e9 100644
--- a/src/python/txtai/vectors/factory.py
+++ b/src/python/txtai/vectors/factory.py
@@ -3,7 +3,7 @@ Factory module
"""
from .transformers import TransformersVectors
-from .words import WordVectors
+from .words import WordVectors, WORDS
class VectorsFactory:
@@ -27,5 +27,12 @@ class VectorsFactory:
# Derive vector type
transformers = config.get("method") == "transformers"
+ if not transformers and not WORDS:
+ # Raise error if trying to create Word Vectors without similarity extra
+ raise ImportError(
+ 'Word vector models are not available - install "similarity" extra to enable. Otherwise, specify '
+ + 'method="transformers" to use transformer backed models'
+ )
+
# Create vector model instance
return TransformersVectors(config, scoring) if transformers else WordVectors(config, scoring)
diff --git a/src/python/txtai/vectors/transformers.py b/src/python/txtai/vectors/transformers.py
index 2f3f9fb2..5c5b6de4 100644
--- a/src/python/txtai/vectors/transformers.py
+++ b/src/python/txtai/vectors/transformers.py
@@ -5,8 +5,17 @@ Transformers module
import pickle
import tempfile
-from sentence_transformers import SentenceTransformer
-from sentence_transformers.models import Pooling, Transformer
+import torch
+
+# Conditional import
+try:
+ from sentence_transformers import SentenceTransformer
+
+ SENTENCE_TRANSFORMERS = True
+except ImportError:
+ SENTENCE_TRANSFORMERS = False
+
+from transformers import AutoModel, AutoTokenizer
from ..pipeline.tokenizer import Tokenizer
@@ -20,20 +29,27 @@ class TransformersVectors(Vectors):
"""
def load(self, path):
+ # Flag that determines if transformers or sentence-transformers should be used to run model
modelhub = self.config.get("modelhub", True)
- # Download model from the model hub (default)
+ # Tensor device id
+ deviceid = Models.deviceid(self.config.get("gpu", True))
+
+ # Use transformers model directly (default)
if modelhub:
- model = Transformer(path)
- pooling = Pooling(model.get_word_embedding_dimension())
+ model = AutoModel.from_pretrained(path)
+ tokenizer = AutoTokenizer.from_pretrained(path)
# Detect unbounded tokenizer typically found in older models
- Models.checklength(model.auto_model, model.tokenizer)
+ Models.checklength(model, tokenizer)
- return SentenceTransformer(modules=[model, pooling])
+ return (model, tokenizer, Models.device(deviceid))
+
+ if not SENTENCE_TRANSFORMERS:
+ raise ImportError('sentence-transformers is not available - install "similarity" extra to enable')
# Download model directly from sentence transformers if model hub disabled
- return SentenceTransformer(path)
+ return SentenceTransformer(path, device=Models.reference(deviceid))
def index(self, documents):
ids, dimensions, stream = [], None, None
@@ -61,7 +77,7 @@ class TransformersVectors(Vectors):
def transform(self, document):
# Convert input document to text and build embeddings
- return self.model.encode([self.text(document[1])], show_progress_bar=False)[0]
+ return self.encode([self.text(document[1])])[0]
def batch(self, documents, output):
"""
@@ -81,7 +97,7 @@ class TransformersVectors(Vectors):
dimensions = None
# Build embeddings
- embeddings = self.model.encode(documents, show_progress_bar=False)
+ embeddings = self.encode(documents)
for embedding in embeddings:
if not dimensions:
# Set number of dimensions for embeddings
@@ -109,3 +125,54 @@ class TransformersVectors(Vectors):
text = " ".join(text)
return text
+
+ def encode(self, documents):
+ """
+ Builds embeddings for input documents.
+
+ Args:
+ documents: list of text to build embeddings for
+
+ Returns:
+ embeddings
+ """
+
+ # Build embeddings using transformers
+ if isinstance(self.model, tuple):
+ # Unpack model
+ model, tokenizer, device = self.model
+
+ # Tokenize input
+ inputs = tokenizer(documents, padding=True, truncation="longest_first", return_tensors="pt")
+
+ # Move model and inputs to device
+ model = model.to(device)
+ inputs = inputs.to(device)
+
+ # Run inputs through model
+ outputs = model(**inputs)
+
+ # Run pooling logic on outputs
+ outputs = self.pooling(outputs, inputs["attention_mask"])
+
+ # Get NumPy array and return
+ return outputs.detach().cpu().numpy()
+
+ # Build embeddings using sentence transformers
+ return self.model.encode(documents, show_progress_bar=False)
+
+ def pooling(self, outputs, mask):
+ """
+ Runs mean pooling on token embeddings taking the input mask into account.
+
+ Args:
+ outputs: model outputs
+ mask: input attention mask
+
+ Returns:
+ mean pooled vector using output token embeddings (i.e. last hidden state)
+ """
+
+ # pylint: disable=E1101
+ mask = mask.unsqueeze(-1).expand(outputs[0].size()).float()
+ return torch.sum(outputs[0] * mask, 1) / torch.clamp(mask.sum(1), min=1e-9)
diff --git a/src/python/txtai/vectors/words.py b/src/python/txtai/vectors/words.py
index d73f11d2..6593c216 100644
--- a/src/python/txtai/vectors/words.py
+++ b/src/python/txtai/vectors/words.py
@@ -9,10 +9,16 @@ import tempfile
from errno import ENOENT
from multiprocessing import Pool
-import fasttext
import numpy as np
-from pymagnitude import converter, Magnitude
+# Conditionally import Word Vector libraries as they aren't installed by default
+try:
+ import fasttext
+ from pymagnitude import converter, Magnitude
+
+ WORDS = True
+except ImportError:
+ WORDS = False
from .base import Vectors
from ..pipeline.tokenizer import Tokenizer
diff --git a/src/python/txtai/workflow/task/image.py b/src/python/txtai/workflow/task/image.py
index 398cd5bf..68c7a732 100644
--- a/src/python/txtai/workflow/task/image.py
+++ b/src/python/txtai/workflow/task/image.py
@@ -4,7 +4,13 @@ ImageTask module
import re
-from PIL import Image
+# Conditional import
+try:
+ from PIL import Image
+
+ PIL = True
+except ImportError:
+ PIL = False
from .file import FileTask
@@ -14,6 +20,12 @@ class ImageTask(FileTask):
Task that processes image file urls
"""
+ def __init__(self, action=None, select=None, unpack=True):
+ if not PIL:
+ raise ImportError('ImageTask is not available - install "workflow" extra to enable')
+
+ super().__init__(action, select, unpack)
+
def accept(self, element):
# Only accept file URLs
return super().accept(element) and re.search(r"\.(gif|bmp|jpg|jpeg|png|webp)$", element.lower())
diff --git a/src/python/txtai/workflow/task/storage.py b/src/python/txtai/workflow/task/storage.py
index 8a796a02..c0ea66a8 100644
--- a/src/python/txtai/workflow/task/storage.py
+++ b/src/python/txtai/workflow/task/storage.py
@@ -5,7 +5,13 @@ StorageTask module
import os
import re
-from libcloud.storage.providers import get_driver
+# Conditional import
+try:
+ from libcloud.storage.providers import get_driver
+
+ LIBCLOUD = True
+except ImportError:
+ LIBCLOUD = False
from .base import Task
@@ -20,6 +26,9 @@ class StorageTask(Task):
PATH = r"\w+:\/\/(.*)"
def __init__(self, action=None, select=None, unpack=True, ids=True):
+ if not LIBCLOUD:
+ raise ImportError('StorageTask is not available - install "workflow" extra to enable')
+
super().__init__(action, select, unpack)
# If true, elements returned will be tagged with ids and converted into (id, data, tag) tuples
diff --git a/test/python/testann.py b/test/python/testann.py
index f82797b5..a2b7eaf8 100644
--- a/test/python/testann.py
+++ b/test/python/testann.py
@@ -94,6 +94,7 @@ class TestANN(unittest.TestCase):
if update:
self.assertEqual(self.append(name, params, 500).count(), 10500)
self.assertEqual(self.delete(name, params, [0, 1]).count(), 9998)
+ self.assertEqual(self.delete(name, params, [100000]).count(), 10000)
self.assertGreater(self.search(name, params), 0)
diff --git a/test/python/testoptional.py b/test/python/testoptional.py
new file mode 100644
index 00000000..0c198523
--- /dev/null
+++ b/test/python/testoptional.py
@@ -0,0 +1,112 @@
+"""
+Optional module tests
+"""
+
+import unittest
+
+import txtai.ann.factory
+
+from txtai.ann import ANNFactory
+from txtai.pipeline import Segmentation, Textractor, Transcription, Translation
+from txtai.vectors import VectorsFactory
+from txtai.workflow.task.image import ImageTask
+from txtai.workflow.task.storage import StorageTask
+
+
+class TestOptional(unittest.TestCase):
+ """
+ Optional tests
+ """
+
+ @staticmethod
+ def toggle():
+ """
+ Toggles parameters used to determine the presence of optional libraries
+ """
+
+ txtai.ann.factory.ANNOY = not txtai.ann.factory.ANNOY
+ txtai.ann.factory.FAISS = not txtai.ann.factory.FAISS
+ txtai.ann.factory.HNSWLIB = not txtai.ann.factory.HNSWLIB
+
+ txtai.pipeline.segmentation.NLTK = not txtai.pipeline.segmentation.NLTK
+ txtai.pipeline.textractor.TIKA = not txtai.pipeline.textractor.TIKA
+ txtai.pipeline.transcription.SOUNDFILE = not txtai.pipeline.transcription.SOUNDFILE
+ txtai.pipeline.translation.FASTTEXT = not txtai.pipeline.translation.FASTTEXT
+
+ txtai.vectors.factory.WORDS = not txtai.vectors.factory.WORDS
+ txtai.vectors.transformers.SENTENCE_TRANSFORMERS = not txtai.vectors.transformers.SENTENCE_TRANSFORMERS
+
+ txtai.workflow.task.image.PIL = not txtai.workflow.task.image.PIL
+ txtai.workflow.task.storage.LIBCLOUD = not txtai.workflow.task.storage.LIBCLOUD
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ Simulate optional packages not being installed
+ """
+
+ # Toggle parameters
+ TestOptional.toggle()
+
+ @classmethod
+ def tearDownClass(cls):
+ """
+ Reset global parameters
+ """
+
+ # Toggle parameters back
+ TestOptional.toggle()
+
+ def testAnn(self):
+ """
+ Test missing ann dependencies
+ """
+
+ with self.assertRaises(ImportError):
+ ANNFactory.create({"backend": "annoy"})
+
+ if not txtai.ann.factory.FAISS:
+ with self.assertRaises(ImportError):
+ ANNFactory.create({"backend": "faiss"})
+
+ with self.assertRaises(ImportError):
+ ANNFactory.create({"backend": "hnsw"})
+
+ def testPipeline(self):
+ """
+ Test missing pipeline dependencies
+ """
+
+ with self.assertRaises(ImportError):
+ Segmentation()
+
+ with self.assertRaises(ImportError):
+ Textractor()
+
+ with self.assertRaises(ImportError):
+ Transcription()
+
+ with self.assertRaises(ImportError):
+ Translation().detect(["test"])
+
+ def testVectors(self):
+ """
+ Test missing vectors dependencies
+ """
+
+ with self.assertRaises(ImportError):
+ VectorsFactory.create({"method": "words"}, None)
+
+ with self.assertRaises(ImportError):
+ VectorsFactory.create({"method": "transformers", "path": "", "modelhub": False}, None)
+
+ def testWorkflow(self):
+ """
+ Test missing workflow dependencies
+ """
+
+ with self.assertRaises(ImportError):
+ ImageTask()
+
+ with self.assertRaises(ImportError):
+ StorageTask()
diff --git a/test/python/testtransformers.py b/test/python/testtransformers.py
index b3ea51b8..160cea2e 100644
--- a/test/python/testtransformers.py
+++ b/test/python/testtransformers.py
@@ -37,6 +37,14 @@ class TestTransformersVectors(unittest.TestCase):
self.assertEqual(dimension, 768)
self.assertIsNotNone(os.path.exists(stream))
+ def testSentenceTransformers(self):
+ """
+ Test creating a direct sentence transformers model
+ """
+
+ model = VectorsFactory.create({"method": "transformers", "path": "paraphrase-MiniLM-L3-v2", "modelhub": False}, None)
+ self.assertIsNotNone(model.transform("This is a test"))
+
def testText(self):
"""
Test transformers text conversion
diff --git a/test/python/testworkflow.py b/test/python/testworkflow.py
index a4c5e0bb..99f6b9b5 100644
--- a/test/python/testworkflow.py
+++ b/test/python/testworkflow.py
@@ -77,7 +77,7 @@ class TestWorkflow(unittest.TestCase):
Tests an image task
"""
- workflow = Workflow([ImageTask()])
+ workflow = Workflow([ImageTask()], 1)
results = list(workflow(["file://" + Utils.PATH + "/books.jpg"]))