Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Update formatting to comply with pylint/black for #50

davidmezzetti64e5eb4a3899
diff --git a/.pylintrc b/.pylintrc
index 7d65d670..dcb45ddc 100644
--- a/.pylintrc
+++ b/.pylintrc
@@ -17,4 +17,4 @@ min-public-methods=0
max-line-length=150
[MESSAGES CONTROL]
-disable=I0011,R0201,W0105,W0108,W0110,W0141,W0621,W0640
+disable=R0201
diff --git a/examples/demo.py b/examples/demo.py
index 18d67ea5..17a56829 100644
--- a/examples/demo.py
+++ b/examples/demo.py
@@ -6,13 +6,14 @@ from cmd import Cmd
from txtai.embeddings import Embeddings
+
class Shell(Cmd):
"""
Query shell.
"""
def __init__(self):
- super(Shell, self).__init__()
+ super().__init__()
self.intro = "query shell"
self.prompt = "(search) "
@@ -24,12 +25,14 @@ class Shell(Cmd):
# Create embeddings model, backed by sentence-transformers & transformers
self.embeddings = Embeddings({"method": "transformers", "path": "sentence-transformers/bert-base-nli-mean-tokens"})
- self.data = ["US tops 5 million confirmed virus cases",
- "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
- "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
- "The National Park Service warns against sacrificing slower friends in a bear attack",
- "Maine man wins $1M from $25 lottery ticket",
- "Make huge profits without work, earn up to $100,000 a day"]
+ self.data = [
+ "US tops 5 million confirmed virus cases",
+ "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
+ "The National Park Service warns against sacrificing slower friends in a bear attack",
+ "Maine man wins $1M from $25 lottery ticket",
+ "Make huge profits without work, earn up to $100,000 a day",
+ ]
def default(self, line):
# Get index of best section that best matches query
@@ -37,6 +40,7 @@ class Shell(Cmd):
print(self.data[uid])
print()
+
def main():
"""
Shell execution loop.
@@ -44,5 +48,6 @@ def main():
Shell().cmdloop()
+
if __name__ == "__main__":
main()
diff --git a/setup.py b/setup.py
index 2d2eaba1..595ce4ff 100644
--- a/setup.py
+++ b/setup.py
@@ -4,55 +4,50 @@ from setuptools import find_packages, setup
with open("README.md", "r") as f:
DESCRIPTION = f.read()
-setup(name="txtai",
- version="2.1.0",
- author="NeuML",
- description="AI-powered search engine",
- long_description=DESCRIPTION,
- long_description_content_type="text/markdown",
- url="https://github.com/neuml/txtai",
- project_urls={
- "Documentation": "https://github.com/neuml/txtai",
- "Issue Tracker": "https://github.com/neuml/txtai/issues",
- "Source Code": "https://github.com/neuml/txtai",
- },
- license="Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0",
- packages=find_packages(where="src/python"),
- package_dir={"": "src/python"},
- keywords="search embedding machine-learning nlp",
- python_requires=">=3.6",
- install_requires=[
- "annoy>=1.16.3",
- "faiss-cpu>=1.6.3; os_name != 'nt'",
- "fastapi>=0.61.1",
- "fasttext>=0.9.2",
- "hnswlib>=0.4.0",
- "nltk>=3.5",
- "numpy>=1.18.4",
- "pymagnitude-lite>=0.1.43",
- "PyYAML>=5.3",
- "regex>=2020.5.14",
- "scikit-learn>=0.23.1",
- "torch>=1.4.0",
- "tqdm>=4.46.0",
- "sentence-transformers>=0.4.0",
- "transformers>=4.1.1",
- "uvicorn>=0.12.1"
- ],
- extras_require={
- "dev": [
- "black",
- "coverage",
- "pre-commit",
- "pylint"
- ]
- },
- classifiers=[
- "License :: OSI Approved :: Apache Software License",
- "Operating System :: OS Independent",
- "Programming Language :: Python :: 3",
- "Topic :: Scientific/Engineering :: Artificial Intelligence",
- "Topic :: Software Development",
- "Topic :: Text Processing :: Indexing",
- "Topic :: Utilities"
- ])
+setup(
+ name="txtai",
+ version="2.1.0",
+ author="NeuML",
+ description="AI-powered search engine",
+ long_description=DESCRIPTION,
+ long_description_content_type="text/markdown",
+ url="https://github.com/neuml/txtai",
+ project_urls={
+ "Documentation": "https://github.com/neuml/txtai",
+ "Issue Tracker": "https://github.com/neuml/txtai/issues",
+ "Source Code": "https://github.com/neuml/txtai",
+ },
+ license="Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0",
+ packages=find_packages(where="src/python"),
+ package_dir={"": "src/python"},
+ keywords="search embedding machine-learning nlp",
+ python_requires=">=3.6",
+ install_requires=[
+ "annoy>=1.16.3",
+ "faiss-cpu>=1.6.3; os_name != 'nt'",
+ "fastapi>=0.61.1",
+ "fasttext>=0.9.2",
+ "hnswlib>=0.4.0",
+ "nltk>=3.5",
+ "numpy>=1.18.4",
+ "pymagnitude-lite>=0.1.43",
+ "PyYAML>=5.3",
+ "regex>=2020.5.14",
+ "scikit-learn>=0.23.1",
+ "torch>=1.4.0",
+ "tqdm>=4.46.0",
+ "sentence-transformers>=0.4.0",
+ "transformers>=4.1.1",
+ "uvicorn>=0.12.1",
+ ],
+ extras_require={"dev": ["black", "coverage", "pre-commit", "pylint"]},
+ classifiers=[
+ "License :: OSI Approved :: Apache Software License",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python :: 3",
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
+ "Topic :: Software Development",
+ "Topic :: Text Processing :: Indexing",
+ "Topic :: Utilities",
+ ],
+)
diff --git a/src/python/txtai/ann.py b/src/python/txtai/ann.py
index c7cb314b..eb473c2c 100644
--- a/src/python/txtai/ann.py
+++ b/src/python/txtai/ann.py
@@ -11,11 +11,13 @@ from hnswlib import Index
# Conditionally import Faiss as it's only supported on Linux/macOS
try:
import faiss
+
FAISS = True
except ImportError:
FAISS = False
-class ANN(object):
+
+class ANN:
"""
Base class for ANN models.
"""
@@ -117,6 +119,7 @@ class ANN(object):
setting = backend.get(name) if backend else None
return setting if setting else default
+
class Annoy(ANN):
"""
Builds an ANN model using the Annoy library.
@@ -149,8 +152,7 @@ class Annoy(ANN):
results = []
for query in queries:
# Run the query
- ids, scores = self.model.get_nns_by_vector(query, n=limit, search_k=searchk,
- include_distances=True)
+ ids, scores = self.model.get_nns_by_vector(query, n=limit, search_k=searchk, include_distances=True)
# Map results to [(id, score)]
results.append(list(zip(ids, scores)))
@@ -161,6 +163,7 @@ class Annoy(ANN):
# Write index
self.model.save(path)
+
class Faiss(ANN):
"""
Builds an ANN model using the Faiss library.
@@ -204,6 +207,7 @@ class Faiss(ANN):
# Write index
faiss.write_index(self.model, path)
+
class HNSW(ANN):
"""
Builds an ANN model using the hnswlib library.
@@ -225,8 +229,7 @@ class HNSW(ANN):
# Create index
self.model = Index(dim=self.config["dimensions"], space=self.config["metric"])
- self.model.init_index(max_elements=embeddings.shape[0], ef_construction=efconstruction,
- M=m, random_seed=seed)
+ self.model.init_index(max_elements=embeddings.shape[0], ef_construction=efconstruction, M=m, random_seed=seed)
# Add items
self.model.add_items(embeddings, np.array(range(embeddings.shape[0])))
diff --git a/src/python/txtai/api.py b/src/python/txtai/api.py
index 4055a24d..68e03f2a 100644
--- a/src/python/txtai/api.py
+++ b/src/python/txtai/api.py
@@ -22,7 +22,8 @@ app = FastAPI()
# Global API instance
INSTANCE = None
-class API(object):
+
+class API:
"""
Base API template. Downstream applications can extend this base template to add custom search functionality.
"""
@@ -51,8 +52,7 @@ class API(object):
# Extractor settings
extractor = self.config["extractor"] if self.config["extractor"] else {}
- self.extractor = Extractor(self.embeddings, extractor.get("path"), extractor.get("quantize"),
- extractor.get("gpu"))
+ self.extractor = Extractor(self.embeddings, extractor.get("path"), extractor.get("quantize"), extractor.get("gpu"))
# Create labels instance
if "labels" in self.config:
@@ -62,13 +62,13 @@ class API(object):
# Creates similarity instance
if "similarity" in self.config:
- similarity = self.config["similarity"] if self.config["similarity"] else {}
+ similar = self.config["similarity"] if self.config["similarity"] else {}
# Share model with labels if separate model not specified
- if "path" not in similarity and self.labels:
+ if "path" not in similar and self.labels:
self.similar = Similarity(model=self.labels)
else:
- self.similar = Similarity(similarity.get("path"), similarity.get("quantize"), similarity.get("gpu"))
+ self.similar = Similarity(similar.get("path"), similar.get("quantize"), similar.get("gpu"))
def limit(self, limit):
"""
@@ -307,7 +307,8 @@ class API(object):
return None
-class Factory(object):
+
+class Factory:
"""
API factory. Creates new API instances.
"""
@@ -324,7 +325,7 @@ class Factory(object):
instance of atype
"""
- parts = atype.split('.')
+ parts = atype.split(".")
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
@@ -332,6 +333,7 @@ class Factory(object):
return m
+
@app.on_event("startup")
def start():
"""
@@ -350,6 +352,7 @@ def start():
api = os.getenv("API_CLASS")
INSTANCE = Factory.get(api)(config) if api else API(config)
+
@app.get("/search")
def search(query: str, request: Request):
"""
@@ -367,6 +370,7 @@ def search(query: str, request: Request):
return INSTANCE.search(query, request)
+
@app.post("/batchsearch")
def batchsearch(queries: List[str] = Body(...), limit: int = Body(...)):
"""
@@ -384,6 +388,7 @@ def batchsearch(queries: List[str] = Body(...), limit: int = Body(...)):
return INSTANCE.batchsearch(queries, limit)
+
@app.post("/add")
def add(documents: List[dict] = Body(...)):
"""
@@ -395,6 +400,7 @@ def add(documents: List[dict] = Body(...)):
INSTANCE.add(documents)
+
@app.get("/index")
def index():
"""
@@ -404,6 +410,7 @@ def index():
INSTANCE.index()
+
@app.post("/similarity")
def similarity(query: str = Body(...), texts: List[str] = Body(...)):
"""
@@ -421,6 +428,7 @@ def similarity(query: str = Body(...), texts: List[str] = Body(...)):
return INSTANCE.similarity(query, texts)
+
@app.post("/batchsimilarity")
def batchsimilarity(queries: List[str] = Body(...), texts: List[str] = Body(...)):
"""
@@ -438,6 +446,7 @@ def batchsimilarity(queries: List[str] = Body(...), texts: List[str] = Body(...)
return INSTANCE.batchsimilarity(queries, texts)
+
@app.get("/transform")
def transform(text: str):
"""
@@ -452,6 +461,7 @@ def transform(text: str):
return INSTANCE.transform(text)
+
@app.post("/batchtransform")
def batchtransform(texts: List[str] = Body(...)):
"""
@@ -466,6 +476,7 @@ def batchtransform(texts: List[str] = Body(...)):
return INSTANCE.batchtransform(texts)
+
@app.post("/extract")
def extract(queue: List[dict] = Body(...), texts: List[str] = Body(...)):
"""
@@ -481,6 +492,7 @@ def extract(queue: List[dict] = Body(...), texts: List[str] = Body(...)):
return INSTANCE.extract(queue, texts)
+
@app.post("/label")
def label(text: str = Body(...), labels: List[str] = Body(...)):
"""
@@ -497,6 +509,7 @@ def label(text: str = Body(...), labels: List[str] = Body(...)):
return INSTANCE.label(text, labels)
+
@app.post("/batchlabel")
def batchlabel(texts: List[str] = Body(...), labels: List[str] = Body(...)):
"""
diff --git a/src/python/txtai/embeddings.py b/src/python/txtai/embeddings.py
index aca9d4fa..8efffc2d 100644
--- a/src/python/txtai/embeddings.py
+++ b/src/python/txtai/embeddings.py
@@ -14,7 +14,8 @@ from .ann import ANN
from .scoring import Scoring
from .vectors import Vectors
-class Embeddings(object):
+
+class Embeddings:
"""
Model that builds sentence embeddings from a list of tokens.
diff --git a/src/python/txtai/extractor.py b/src/python/txtai/extractor.py
index c5c1bca2..98a7bf49 100644
--- a/src/python/txtai/extractor.py
+++ b/src/python/txtai/extractor.py
@@ -7,7 +7,8 @@ from nltk.tokenize import sent_tokenize
from .pipeline import Questions
from .tokenizer import Tokenizer
-class Extractor(object):
+
+class Extractor:
"""
Class that uses an extractive question-answering model to extract content from a given text context.
"""
@@ -111,8 +112,9 @@ class Extractor(object):
# Add result if:
# - all required tokens are present or there are not required tokens AND
# - all prohibited tokens are not present or there are not prohibited tokens
- if (not must or all([token.lower() in text.lower() for token in must])) and \
- (not mnot or all([token.lower() not in text.lower() for token in mnot])):
+ if (not must or all([token.lower() in text.lower() for token in must])) and (
+ not mnot or all([token.lower() not in text.lower() for token in mnot])
+ ):
matches.append(segments[x] + (score,))
# Add query matches sorted by highest score
diff --git a/src/python/txtai/pipeline.py b/src/python/txtai/pipeline.py
index 4a2b1c52..535698bf 100644
--- a/src/python/txtai/pipeline.py
+++ b/src/python/txtai/pipeline.py
@@ -7,7 +7,8 @@ import torch
from transformers import pipeline
-class Pipeline(object):
+
+class Pipeline:
"""
Light wrapper around Hugging Face's pipeline component for selected tasks. Adds support for model
quantization and minor interface changes.
@@ -41,6 +42,7 @@ class Pipeline(object):
# pylint: disable=E1101
self.pipeline.model = torch.quantization.quantize_dynamic(self.pipeline.model, {torch.nn.Linear}, dtype=torch.qint8)
+
class Questions(Pipeline):
"""
Runs extractive QA for a series of questions and contexts.
@@ -82,6 +84,7 @@ class Questions(Pipeline):
return answers
+
class Labels(Pipeline):
"""
Applies a zero shot classifier to text using a list of labels.
@@ -121,6 +124,7 @@ class Labels(Pipeline):
return scores[0] if isinstance(text, str) else scores
+
class Similarity(Labels):
"""
Computes similarity between query and list of text using a zero shot classifier.
diff --git a/src/python/txtai/scoring.py b/src/python/txtai/scoring.py
index 420f2c59..3b5958dd 100644
--- a/src/python/txtai/scoring.py
+++ b/src/python/txtai/scoring.py
@@ -9,7 +9,8 @@ from collections import Counter
from .tokenizer import Tokenizer
-class Scoring(object):
+
+class Scoring:
"""
Base scoring object. Default method scores documents using TF-IDF.
"""
@@ -28,9 +29,9 @@ class Scoring(object):
if method == "bm25":
return BM25()
- elif method == "sif":
+ if method == "sif":
return SIF()
- elif method == "tfidf":
+ if method == "tfidf":
# Default scoring object implements tf-idf
return Scoring()
@@ -102,7 +103,7 @@ class Scoring(object):
self.avgidf = sum(self.idf.values()) / len(self.idf)
# Filter for tags that appear in at least 1% of the documents
- self.tags = {tag:number for tag, number in self.tags.items() if number >= self.total * 0.005}
+ self.tags = {tag: number for tag, number in self.tags.items() if number >= self.total * 0.005}
def weights(self, document):
"""
@@ -139,8 +140,7 @@ class Scoring(object):
maxWeight = max(weights)
maxTag = max(tags.values())
- weights = [max(maxWeight * (tags[tokens[x]] / maxTag), weight)
- if tokens[x] in tags else weight for x, weight in enumerate(weights)]
+ weights = [max(maxWeight * (tags[tokens[x]] / maxTag), weight) if tokens[x] in tags else weight for x, weight in enumerate(weights)]
return weights
@@ -195,6 +195,7 @@ class Scoring(object):
return idf
+
class BM25(Scoring):
"""
BM25 scoring. Scores using Apache Lucene's version of BM25 which adds 1 to prevent
@@ -202,7 +203,7 @@ class BM25(Scoring):
"""
def __init__(self, k1=0.1, b=0.75):
- super(BM25, self).__init__()
+ super().__init__()
# BM25 configurable parameters
self.k1 = k1
@@ -210,24 +211,25 @@ class BM25(Scoring):
def computeIDF(self, freq):
# Calculate BM25 IDF score
- return math.log(1 + (self.total - freq + 0.5)/(freq + 0.5))
+ return math.log(1 + (self.total - freq + 0.5) / (freq + 0.5))
def score(self, freq, idf, length):
# Calculate BM25 score
k = self.k1 * ((1 - self.b) + self.b * length / self.avgdl)
return idf * (freq * (self.k1 + 1)) / (freq + k)
+
class SIF(Scoring):
"""
Smooth Inverse Frequency (SIF) scoring.
"""
def __init__(self, a=0.001):
- super(SIF, self).__init__()
+ super().__init__()
# SIF configurable parameters
self.a = a
def score(self, freq, idf, length):
# Calculate SIF score
- return self.a / (self.a + freq/self.tokens)
+ return self.a / (self.a + freq / self.tokens)
diff --git a/src/python/txtai/tokenizer.py b/src/python/txtai/tokenizer.py
index 44531629..00db5568 100644
--- a/src/python/txtai/tokenizer.py
+++ b/src/python/txtai/tokenizer.py
@@ -5,15 +5,50 @@ Tokenizer module
import re
import string
-class Tokenizer(object):
+
+class Tokenizer:
"""
Text tokenization methods.
"""
+ # fmt off
# English Stop Word List (Standard stop words used by Apache Lucene)
- STOP_WORDS = {"a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it",
- "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these",
- "they", "this", "to", "was", "will", "with"}
+ STOP_WORDS = {
+ "a",
+ "an",
+ "and",
+ "are",
+ "as",
+ "at",
+ "be",
+ "but",
+ "by",
+ "for",
+ "if",
+ "in",
+ "into",
+ "is",
+ "it",
+ "no",
+ "not",
+ "of",
+ "on",
+ "or",
+ "such",
+ "that",
+ "the",
+ "their",
+ "then",
+ "there",
+ "these",
+ "they",
+ "this",
+ "to",
+ "was",
+ "will",
+ "with",
+ }
+ # fmt on
@staticmethod
def tokenize(text):
diff --git a/src/python/txtai/vectors.py b/src/python/txtai/vectors.py
index 33640b7b..bccd710a 100644
--- a/src/python/txtai/vectors.py
+++ b/src/python/txtai/vectors.py
@@ -22,6 +22,7 @@ from .tokenizer import Tokenizer
# pylint: disable=W0603
VECTORS = None
+
def create(config, scoring):
"""
Multiprocessing helper method. Creates a global embeddings object to be accessed in a new subprocess.
@@ -36,6 +37,7 @@ def create(config, scoring):
# Create a global embedding object using configuration and saved
VECTORS = WordVectors(config, scoring)
+
def transform(document):
"""
Multiprocessing helper method. Transforms document into an embeddings vector.
@@ -51,7 +53,8 @@ def transform(document):
return (document[0], VECTORS.transform(document))
-class Vectors(object):
+
+class Vectors:
"""
Base class for sentence embeddings/vector models.
"""
@@ -120,6 +123,7 @@ class Vectors(object):
embeddings vector
"""
+
class WordVectors(Vectors):
"""
Builds sentence embeddings/vectors using weighted word embeddings.
@@ -221,6 +225,7 @@ class WordVectors(Vectors):
print("Converting vectors to magnitude format")
converter.convert(path + ".txt", path + ".magnitude", subword=True)
+
class TransformersVectors(Vectors):
"""
Builds sentence embeddings/vectors using the transformers library.
diff --git a/test/python/testann.py b/test/python/testann.py
index 2fa9066c..6386b631 100644
--- a/test/python/testann.py
+++ b/test/python/testann.py
@@ -10,6 +10,7 @@ import numpy as np
from txtai.ann import ANN
+
class TestANN(unittest.TestCase):
"""
ANN tests
diff --git a/test/python/testapi.py b/test/python/testapi.py
index 3912c792..76dd169b 100644
--- a/test/python/testapi.py
+++ b/test/python/testapi.py
@@ -46,6 +46,7 @@ path: %s
writable: False
"""
+
class TestAPI(unittest.TestCase):
"""
API tests
@@ -80,12 +81,14 @@ class TestAPI(unittest.TestCase):
cls.client = TestAPI.start(True)
- cls.data = ["US tops 5 million confirmed virus cases",
- "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
- "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
- "The National Park Service warns against sacrificing slower friends in a bear attack",
- "Maine man wins $1M from $25 lottery ticket",
- "Make huge profits without work, earn up to $100,000 a day"]
+ cls.data = [
+ "US tops 5 million confirmed virus cases",
+ "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
+ "The National Park Service warns against sacrificing slower friends in a bear attack",
+ "Maine man wins $1M from $25 lottery ticket",
+ "Make huge profits without work, earn up to $100,000 a day",
+ ]
# Index data
cls.client.post("add", json=[{"id": x, "text": row} for x, row in enumerate(cls.data)])
@@ -112,25 +115,27 @@ class TestAPI(unittest.TestCase):
Test qa extraction via API
"""
- data = ["Giants hit 3 HRs to down Dodgers",
- "Giants 5 Dodgers 4 final",
- "Dodgers drop Game 2 against the Giants, 5-4",
- "Blue Jays 2 Red Sox 1 final",
- "Red Sox lost to the Blue Jays, 2-1",
- "Blue Jays at Red Sox is over. Score: 2-1",
- "Phillies win over the Braves, 5-0",
- "Phillies 5 Braves 0 final",
- "Final: Braves lose to the Phillies in the series opener, 5-0",
- "Final score: Flyers 4 Lightning 1",
- "Flyers 4 Lightning 1 final",
- "Flyers win 4-1"]
+ data = [
+ "Giants hit 3 HRs to down Dodgers",
+ "Giants 5 Dodgers 4 final",
+ "Dodgers drop Game 2 against the Giants, 5-4",
+ "Blue Jays 2 Red Sox 1 final",
+ "Red Sox lost to the Blue Jays, 2-1",
+ "Blue Jays at Red Sox is over. Score: 2-1",
+ "Phillies win over the Braves, 5-0",
+ "Phillies 5 Braves 0 final",
+ "Final: Braves lose to the Phillies in the series opener, 5-0",
+ "Final score: Flyers 4 Lightning 1",
+ "Flyers 4 Lightning 1 final",
+ "Flyers win 4-1",
+ ]
questions = ["What team won the game?", "What was score?"]
- execute = lambda query: self.client.post("extract", json={
- "queue": [{"name": question, "query": query, "question": question, "snippet": False} for question in questions],
- "texts": data
- }).json()
+ execute = lambda query: self.client.post(
+ "extract",
+ json={"queue": [{"name": question, "query": query, "question": question, "snippet": False} for question in questions], "texts": data},
+ ).json()
answers = execute("Red Sox - Blue Jays")
self.assertEqual("Blue Jays", answers[0]["answer"])
@@ -139,10 +144,9 @@ class TestAPI(unittest.TestCase):
# Ad-hoc questions
question = "What hockey team won?"
- answers = self.client.post("extract", json={
- "queue": [{"name": question, "query": question, "question": question, "snippet": False}],
- "texts": data
- }).json()
+ answers = self.client.post(
+ "extract", json={"queue": [{"name": question, "query": question, "question": question, "snippet": False}], "texts": data}
+ ).json()
self.assertEqual("Flyers", answers[0]["answer"])
def testLabel(self):
@@ -150,10 +154,7 @@ class TestAPI(unittest.TestCase):
Test label via API
"""
- labels = self.client.post("label", json={
- "text": "this is the best sentence ever",
- "labels": ["positive", "negative"]
- }).json()
+ labels = self.client.post("label", json={"text": "this is the best sentence ever", "labels": ["positive", "negative"]}).json()
self.assertEqual(labels[0]["id"], 0)
@@ -162,10 +163,9 @@ class TestAPI(unittest.TestCase):
Test batch label via API
"""
- labels = self.client.post("batchlabel", json={
- "texts": ["this is the best sentence ever", "This is terrible"],
- "labels": ["positive", "negative"]
- }).json()
+ labels = self.client.post(
+ "batchlabel", json={"texts": ["this is the best sentence ever", "This is terrible"], "labels": ["positive", "negative"]}
+ ).json()
results = [l[0]["id"] for l in labels]
self.assertEqual(results, [0, 1])
@@ -183,10 +183,7 @@ class TestAPI(unittest.TestCase):
Test batch search via API
"""
- results = self.client.post("batchsearch", json={
- "queries": ["feel good story", "climate change"],
- "limit": 1
- }).json()
+ results = self.client.post("batchsearch", json={"queries": ["feel good story", "climate change"], "limit": 1}).json()
uids = [result[0]["id"] for result in results]
self.assertEqual(uids, [4, 1])
@@ -196,10 +193,7 @@ class TestAPI(unittest.TestCase):
Test similarity via API
"""
- uid = self.client.post("similarity", json={
- "query": "feel good story",
- "texts": self.data
- }).json()[0]["id"]
+ uid = self.client.post("similarity", json={"query": "feel good story", "texts": self.data}).json()[0]["id"]
self.assertEqual(self.data[uid], self.data[4])
@@ -208,10 +202,7 @@ class TestAPI(unittest.TestCase):
Test batch similarity via API
"""
- results = self.client.post("batchsimilarity", json={
- "queries": ["feel good story", "climate change"],
- "texts": self.data
- }).json()
+ results = self.client.post("batchsimilarity", json={"queries": ["feel good story", "climate change"], "texts": self.data}).json()
uids = [result[0]["id"] for result in results]
self.assertEqual(uids, [4, 1])
@@ -246,9 +237,6 @@ class TestAPI(unittest.TestCase):
self.assertEqual(uid, 4)
# Test similarity
- uid = self.client.post("similarity", json={
- "query": "feel good story",
- "texts": self.data
- }).json()[0]["id"]
+ uid = self.client.post("similarity", json={"query": "feel good story", "texts": self.data}).json()[0]["id"]
self.assertEqual(uid, 4)
diff --git a/test/python/testembeddings.py b/test/python/testembeddings.py
index 05ef5851..beaffdb5 100644
--- a/test/python/testembeddings.py
+++ b/test/python/testembeddings.py
@@ -9,6 +9,7 @@ import unittest
from txtai.embeddings import Embeddings
from txtai.vectors import WordVectors
+
class TestEmbeddings(unittest.TestCase):
"""
Embeddings tests
@@ -20,16 +21,17 @@ class TestEmbeddings(unittest.TestCase):
Initialize test data.
"""
- cls.data = ["US tops 5 million confirmed virus cases",
- "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
- "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
- "The National Park Service warns against sacrificing slower friends in a bear attack",
- "Maine man wins $1M from $25 lottery ticket",
- "Make huge profits without work, earn up to $100,000 a day"]
+ cls.data = [
+ "US tops 5 million confirmed virus cases",
+ "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
+ "The National Park Service warns against sacrificing slower friends in a bear attack",
+ "Maine man wins $1M from $25 lottery ticket",
+ "Make huge profits without work, earn up to $100,000 a day",
+ ]
# Create embeddings model, backed by sentence-transformers & transformers
- cls.embeddings = Embeddings({"method": "transformers",
- "path": "sentence-transformers/bert-base-nli-mean-tokens"})
+ cls.embeddings = Embeddings({"method": "transformers", "path": "sentence-transformers/bert-base-nli-mean-tokens"})
def testIndex(self):
"""
@@ -98,11 +100,7 @@ class TestEmbeddings(unittest.TestCase):
data = [(x, row, None) for x, row in enumerate(self.data)]
# Create embeddings model, backed by word vectors
- embeddings = Embeddings({"path": vectors + ".magnitude",
- "storevectors": True,
- "scoring": "bm25",
- "pca": 3,
- "quantize": True})
+ embeddings = Embeddings({"path": vectors + ".magnitude", "storevectors": True, "scoring": "bm25", "pca": 3, "quantize": True})
# Call scoring and index methods
embeddings.score(data)
diff --git a/test/python/testextractor.py b/test/python/testextractor.py
index 92413e8f..9f92ce9a 100644
--- a/test/python/testextractor.py
+++ b/test/python/testextractor.py
@@ -8,6 +8,7 @@ import unittest
from txtai.embeddings import Embeddings
from txtai.extractor import Extractor
+
class TestExtractor(unittest.TestCase):
"""
Extractor tests
@@ -19,18 +20,20 @@ class TestExtractor(unittest.TestCase):
Create single extractor instance.
"""
- cls.data = ["Giants hit 3 HRs to down Dodgers",
- "Giants 5 Dodgers 4 final",
- "Dodgers drop Game 2 against the Giants, 5-4",
- "Blue Jays 2 Red Sox 1 final",
- "Red Sox lost to the Blue Jays, 2-1",
- "Blue Jays at Red Sox is over. Score: 2-1",
- "Phillies win over the Braves, 5-0",
- "Phillies 5 Braves 0 final",
- "Final: Braves lose to the Phillies in the series opener, 5-0",
- "Final score: Flyers 4 Lightning 1",
- "Flyers 4 Lightning 1 final",
- "Flyers win 4-1"]
+ cls.data = [
+ "Giants hit 3 HRs to down Dodgers",
+ "Giants 5 Dodgers 4 final",
+ "Dodgers drop Game 2 against the Giants, 5-4",
+ "Blue Jays 2 Red Sox 1 final",
+ "Red Sox lost to the Blue Jays, 2-1",
+ "Blue Jays at Red Sox is over. Score: 2-1",
+ "Phillies win over the Braves, 5-0",
+ "Phillies 5 Braves 0 final",
+ "Final: Braves lose to the Phillies in the series opener, 5-0",
+ "Final score: Flyers 4 Lightning 1",
+ "Flyers 4 Lightning 1 final",
+ "Flyers win 4-1",
+ ]
# Create embeddings model, backed by sentence-transformers & transformers
cls.embeddings = Embeddings({"method": "transformers", "path": "sentence-transformers/bert-base-nli-mean-tokens"})
diff --git a/test/python/testlabels.py b/test/python/testlabels.py
index ef070bcb..c204f928 100644
--- a/test/python/testlabels.py
+++ b/test/python/testlabels.py
@@ -6,6 +6,7 @@ import unittest
from txtai.pipeline import Labels, Similarity
+
class TestLabels(unittest.TestCase):
"""
Labels tests
@@ -17,12 +18,14 @@ class TestLabels(unittest.TestCase):
Create single labels instance.
"""
- cls.data = ["US tops 5 million confirmed virus cases",
- "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
- "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
- "The National Park Service warns against sacrificing slower friends in a bear attack",
- "Maine man wins $1M from $25 lottery ticket",
- "Make huge profits without work, earn up to $100,000 a day"]
+ cls.data = [
+ "US tops 5 million confirmed virus cases",
+ "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
+ "The National Park Service warns against sacrificing slower friends in a bear attack",
+ "Maine man wins $1M from $25 lottery ticket",
+ "Make huge profits without work, earn up to $100,000 a day",
+ ]
cls.labels = Labels("prajjwal1/bert-medium-mnli")
cls.similarity = Similarity(model=cls.labels)
@@ -39,8 +42,7 @@ class TestLabels(unittest.TestCase):
Test labels with multiple text inputs
"""
- results = [l[0][0] for l in self.labels(["This is the best sentence ever", "This is terrible"],
- ["positive", "negative"])]
+ results = [l[0][0] for l in self.labels(["This is the best sentence ever", "This is terrible"], ["positive", "negative"])]
self.assertEqual(results, [0, 1])
def testSimilarity(self):
diff --git a/test/python/testscoring.py b/test/python/testscoring.py
index a0eb1855..d4beeabf 100644
--- a/test/python/testscoring.py
+++ b/test/python/testscoring.py
@@ -8,6 +8,7 @@ import unittest
from txtai.scoring import Scoring
+
class TestScoring(unittest.TestCase):
"""
Scoring tests
@@ -19,13 +20,15 @@ class TestScoring(unittest.TestCase):
Initialize test data.
"""
- cls.data = ["US tops 5 million confirmed virus cases",
- "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
- "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
- "The National Park Service warns against sacrificing slower friends in a bear attack",
- "Maine man wins $1M from $25 lottery ticket",
- "wins wins wins",
- "Make huge profits without work, earn up to $100,000 a day"]
+ cls.data = [
+ "US tops 5 million confirmed virus cases",
+ "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
+ "The National Park Service warns against sacrificing slower friends in a bear attack",
+ "Maine man wins $1M from $25 lottery ticket",
+ "wins wins wins",
+ "Make huge profits without work, earn up to $100,000 a day",
+ ]
cls.data = [(uid, x, None) for uid, x in enumerate(cls.data)]
diff --git a/test/python/testtokenizer.py b/test/python/testtokenizer.py
index d5960d6d..4ab035b7 100644
--- a/test/python/testtokenizer.py
+++ b/test/python/testtokenizer.py
@@ -6,6 +6,7 @@ import unittest
from txtai.tokenizer import Tokenizer
+
class TestTokenizer(unittest.TestCase):
"""
Tokenizer tests
diff --git a/test/python/testtransformers.py b/test/python/testtransformers.py
index 78ce3813..e63f5740 100644
--- a/test/python/testtransformers.py
+++ b/test/python/testtransformers.py
@@ -9,6 +9,7 @@ import numpy as np
from txtai.vectors import Vectors
+
class TestTransformersVectors(unittest.TestCase):
"""
TransformerVectors tests
@@ -55,8 +56,7 @@ class TestTransformersVectors(unittest.TestCase):
"""
# Sample documents: one where tokenizer changes text and one with no changes to text
- documents = [(0, "This is a test and has no tokenization", None),
- (1, "test tokenization", None)]
+ documents = [(0, "This is a test and has no tokenization", None), (1, "test tokenization", None)]
# Run with tokenization enabled
self.model.tokenize = True
diff --git a/test/python/testwordvectors.py b/test/python/testwordvectors.py
index 975251bb..9b23062c 100644
--- a/test/python/testwordvectors.py
+++ b/test/python/testwordvectors.py
@@ -8,6 +8,7 @@ import unittest
from txtai.vectors import WordVectors, Vectors
+
class TestWordVectors(unittest.TestCase):
"""
Vectors tests