Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Refactor API definitions across modules (#54), add batch version of methods (#18, #53)

davidmezzettie84d7c003b02
diff --git a/src/python/txtai/ann.py b/src/python/txtai/ann.py
index 49c1a1e3..7d7a9a60 100644
--- a/src/python/txtai/ann.py
+++ b/src/python/txtai/ann.py
@@ -81,13 +81,16 @@ class ANN(object):
embeddings: embeddings array
"""
- def search(self, query, limit):
+ def search(self, queries, limit):
"""
Searches ANN model for query. Returns topn results.
Args:
- query: query vector
+ queries: queries array
limit: maximum results
+
+ Returns:
+ query results
"""
def save(self, path):
@@ -119,12 +122,17 @@ class Annoy(ANN):
# Build index
self.model.build(10)
- def search(self, query, limit):
- # Run the query
- ids, scores = self.model.get_nns_by_vector(query, n=limit, include_distances=True)
+ def search(self, queries, limit):
+ # Annoy doesn't have a built in batch query method
+ results = []
+ for query in queries:
+ # Run the query
+ ids, scores = self.model.get_nns_by_vector(query, n=limit, include_distances=True)
- # Map results to [(id, score)]
- return list(zip(ids, scores))
+ # Map results to [(id, score)]
+ results.append(list(zip(ids, scores)))
+
+ return results
def save(self, path):
# Write index
@@ -152,13 +160,17 @@ class Faiss(ANN):
self.model.train(embeddings)
self.model.add_with_ids(embeddings, np.array(range(embeddings.shape[0])))
- def search(self, query, limit):
+ def search(self, queries, limit):
# Run the query
self.model.nprobe = 6
- scores, ids = self.model.search(query.reshape(1, -1), limit)
+ scores, ids = self.model.search(queries, limit)
# Map results to [(id, score)]
- return list(zip(ids[0].tolist(), (scores[0]).tolist()))
+ results = []
+ for x, score in enumerate(scores):
+ results.append(list(zip(ids[x].tolist(), score.tolist())))
+
+ return results
def save(self, path):
# Write index
@@ -185,15 +197,19 @@ class HNSW(ANN):
# Add items
self.model.add_items(embeddings, np.array(range(embeddings.shape[0])))
- def search(self, query, limit):
+ def search(self, queries, limit):
# Run the query
- ids, distances = self.model.knn_query(query.reshape(1, -1), k=limit)
-
- # Convert distances to similarity scores
- scores = [1 - d for d in distances[0]]
+ ids, distances = self.model.knn_query(queries, k=limit)
# Map results to [(id, score)]
- return list(zip(ids[0], scores))
+ results = []
+ for x, distance in enumerate(distances):
+ # Convert distances to similarity scores
+ scores = [1 - d for d in distance]
+
+ results.append(list(zip(ids[x], scores)))
+
+ return results
def save(self, path):
# Write index
diff --git a/src/python/txtai/api.py b/src/python/txtai/api.py
index da54f89d..ccbc8e03 100644
--- a/src/python/txtai/api.py
+++ b/src/python/txtai/api.py
@@ -68,35 +68,57 @@ class API(object):
else:
self.similar = Similarity(similarity.get("path"), similarity.get("quantize"), similarity.get("gpu"))
- def size(self, request):
+ def limit(self, limit):
"""
Parses the number of results to return from the request. Allows range of 1-250, with a default of 10.
Args:
- request: FastAPI request
+ limit: limit parameter
Returns:
- size
+ bounded limit
"""
# Return between 1 and 250 results, defaults to 10
- return max(1, min(250, int(request.query_params["n"]) if "n" in request.query_params else 10))
+ return max(1, min(250, int(limit) if limit else 10))
def search(self, query, request):
"""
- Runs an embeddings search for query and request. Downstream applications can override this method
- to provide enriched search results.
+ Finds documents in the embeddings model most similar to the input query. Returns
+ a list of (id, score) sorted by highest score, where id is the document id in
+ the embeddings model.
+
+ Downstream applications can override this method to provide enriched search results.
Args:
- query: input query
+ query: query text
request: FastAPI request
Returns:
- list of (uid, score)
+ list of (id, score)
"""
if self.embeddings:
- return self.embeddings.search(query, self.size(request))
+ return self.embeddings.search(query, self.limit(request.query_params.get("limit")))
+
+ return None
+
+ def batchsearch(self, queries, limit):
+ """
+ Finds documents in the embeddings model most similar to the input queries. Returns
+ a list of (id, score) sorted by highest score per query, where id is the document id
+ in the embeddings model.
+
+ Args:
+ queries: queries text
+ limit: maximum results
+
+ Returns:
+ list of (id, score) per query
+ """
+
+ if self.embeddings:
+ return self.embeddings.batchsearch(queries, self.limit(limit))
return None
@@ -119,8 +141,10 @@ class API(object):
def index(self):
"""
- Builds an embeddings index. No further documents can be added after this call. Downstream applications can
- override this method to also store full documents in an external system.
+ Builds an embeddings index for previously batched documents. No further documents can be added
+ after this call.
+
+ Downstream applications can override this method to also store full documents in an external system.
"""
if self.embeddings and self.config.get("writable") and self.documents:
@@ -137,75 +161,94 @@ class API(object):
# Clear buffer
self.documents = None
- def similarity(self, search, data):
+ def similarity(self, query, texts):
"""
- Calculates the similarity between text1 and list of elements in text2.
+ Computes the similarity between query and list of strings. Returns a list of
+ (id, score) sorted by highest score, where id is the index in texts.
Args:
- search: text
- data: list of text to compare against
+ query: query text
+ texts: list of text
Returns:
- list of similarity scores
+ list of (id, score)
"""
# Use similarity instance if available otherwise fall back to embeddings model
if self.similar:
- return [float(x) for x in self.similar(search, data)]
+ return [(uid, float(text)) for uid, text in self.similar(query, texts)]
if self.embeddings:
- return [float(x) for x in self.embeddings.similarity(search, data)]
+ return [(uid, float(text)) for uid, text in self.embeddings.similarity(query, texts)]
return None
- def transform(self, text):
+ def batchsimilarity(self, queries, texts):
"""
- Transforms text into an embeddings array.
+ Computes the similarity between list of queries and list of strings. Returns a list
+ of (id, score) sorted by highest score per query, where id is the index in texts.
Args:
- text: input text
+ queries: queries text
+ texts: list of text
Returns:
- embeddings array
+ list of (id, score) per query
"""
+ # Use similarity instance if available otherwise fall back to embeddings model
+ if self.similar:
+ return [[(uid, float(text)) for uid, text in r] for r in self.similar(queries, texts)]
if self.embeddings:
- return [float(x) for x in self.embeddings.transform((None, text, None))]
+ return [[(uid, float(text)) for uid, text in r] for r in self.embeddings.batchsimilarity(queries, texts)]
return None
- def extract(self, documents, queue):
+ def transform(self, texts):
"""
- Extracts answers to input questions
+ Transforms list of texts into embeddings arrays.
Args:
- documents: list of {id: value, text: value}
- queue: list of {name: value, query: value, question: value, snippet: value)
+ texts: list of strings
Returns:
- extracted answers
+ embeddings arrays
"""
- if self.extractor:
- # Convert to a list of (id, text)
- sections = [(document["id"], document["text"]) for document in documents]
+ if self.embeddings:
+ return [[float(x) for x in self.embeddings.transform((None, text, None))] for text in texts]
+
+ return None
+
+ def extract(self, queue, texts):
+ """
+ Extracts answers to input questions.
+
+ Args:
+ queue: list of {name: value, query: value, question: value, snippet: value}
+ texts: list of strings
+ Returns:
+ list of (name, answer)
+ """
+
+ if self.extractor:
# Convert queue to tuples
queue = [(x["name"], x["query"], x.get("question"), x.get("snippet")) for x in queue]
-
- return self.extractor(sections, queue)
+ return self.extractor(queue, texts)
return None
def label(self, text, labels):
"""
- Applies a zero shot classifier to a text section using a list of labels.
+ Applies a zero shot classifier to text using a list of labels. Returns a list of
+ (id, score) sorted by highest score, where id is the index in labels.
Args:
- text: input text
+ text: text|list
labels: list of labels
Returns:
- list of (label, score) for section
+ list of (id, score) per text element
"""
if self.labels:
@@ -257,27 +300,46 @@ def start():
INSTANCE = Factory.get(api)(config) if api else API(config)
@app.get("/search")
-def search(q: str, request: Request):
+def search(query: str, request: Request):
"""
- Runs an embeddings search.
+ Finds documents in the embeddings model most similar to the input query. Returns
+ a list of (id, score) sorted by highest score, where id is the document id in
+ the embeddings model.
Args:
- q: query string
+ query: query text
request: FastAPI request
Returns:
- query results
+ list of (id, score)
+ """
+
+ return INSTANCE.search(query, request)
+
[email protected]("/batchsearch")
+def batchsearch(queries: List[str] = Body(...), limit: int = Body(...)):
+ """
+ Finds documents in the embeddings model most similar to the input queries. Returns
+ a list of (id, score) sorted by highest score per query, where id is the document id
+ in the embeddings model.
+
+ Args:
+ queries: queries text
+ limit: maximum results
+
+ Returns:
+ list of (id, score) per query
"""
- return INSTANCE.search(q, request)
+ return INSTANCE.batchsearch(queries, limit)
@app.post("/add")
-def add(documents: List[dict]):
+def add(documents: List[dict] = Body(...)):
"""
Adds a batch of documents for indexing.
Args:
- documents: list of dicts with each entry containing an id and text element
+ documents: list of {id: value, text: value}
"""
INSTANCE.add(documents)
@@ -285,66 +347,115 @@ def add(documents: List[dict]):
@app.get("/index")
def index():
"""
- Builds an index for previously batched documents.
+ Builds an embeddings index for previously batched documents. No further documents can be added
+ after this call.
"""
INSTANCE.index()
@app.post("/similarity")
-def similarity(search: str = Body(None), data: List[str] = Body(None)):
+def similarity(query: str = Body(...), texts: List[str] = Body(...)):
"""
- Calculates the similarity between text1 and list of elements in text2.
+ Computes the similarity between query and list of strings. Returns a list of
+ (id, score) sorted by highest score, where id is the index in texts.
Args:
- search: search text
- data: list of text to compare against
+ query: query text
+ texts: list of text
Returns:
- list of similarity scores
+ list of (id, score)
"""
- return INSTANCE.similarity(search, data)
+ return INSTANCE.similarity(query, texts)
+
[email protected]("/batchsimilarity")
+def batchsimilarity(queries: List[str] = Body(...), texts: List[str] = Body(...)):
+ """
+ Computes the similarity between list of queries and list of strings. Returns a list
+ of (id, score) sorted by highest score per query, where id is the index in texts.
+
+ Args:
+ queries: queries text
+ texts: list of text
+
+ Returns:
+ list of (id, score) per query
+ """
+
+ return INSTANCE.batchsimilarity(queries, texts)
@app.get("/embeddings")
-def embeddings(t: str):
+def embeddings(text: str):
"""
Transforms text into an embeddings array.
Args:
- t: input text
+ text: input text
Returns:
embeddings array
"""
- return INSTANCE.transform(t)
+ return INSTANCE.transform([text])[0]
+
[email protected]("/batchembeddings")
+def batchembeddings(texts: List[str] = Body(...)):
+ """
+ Transforms list of text into embeddings arrays.
+
+ Args:
+ texts: list of strings
+
+ Returns:
+ embeddings arrays
+ """
+
+ return INSTANCE.transform(texts)
@app.post("/extract")
-def extract(documents: List[dict], queue: List[dict]):
+def extract(queue: List[dict] = Body(...), texts: List[str] = Body(...)):
"""
- Extracts answers to input questions
+ Extracts answers to input questions.
Args:
- documents: list of {id: value, text: value}
queue: list of {name: value, query: value, question: value, snippet: value)
+ texts: list of strings
Returns:
- extracted answers
+ list of (name, answer)
"""
- return INSTANCE.extract(documents, queue)
+ return INSTANCE.extract(queue, texts)
@app.post("/label")
-def label(text: str = Body(None), labels: List[str] = Body(None)):
+def label(text: str = Body(...), labels: List[str] = Body(...)):
"""
- Applies a zero shot classifier to a text section using a list of labels.
+ Applies a zero shot classifier to text using a list of labels. Returns a list of
+ (id, score) sorted by highest score, where id is the index in labels.
Args:
text: input text
labels: list of labels
Returns:
- list of (label, score) for section
+ list of (id, score)
"""
return INSTANCE.label(text, labels)
+
[email protected]("/batchlabel")
+def batchlabel(texts: List[str] = Body(...), labels: List[str] = Body(...)):
+ """
+ Applies a zero shot classifier to list of text using a list of labels. Returns a list of
+ (id, score) sorted by highest score, where id is the index in labels per text element.
+
+ Args:
+ texts: list of texts
+ labels: list of labels
+
+ Returns:
+ list of (id, score) per text element
+ """
+
+ return INSTANCE.label(texts, labels)
diff --git a/src/python/txtai/embeddings.py b/src/python/txtai/embeddings.py
index d038ff87..fb5ab4fa 100644
--- a/src/python/txtai/embeddings.py
+++ b/src/python/txtai/embeddings.py
@@ -50,7 +50,7 @@ class Embeddings(object):
def loadVectors(self):
"""
- Loads a word vector model set in config.
+ Loads a vector model set in config.
Returns:
vector model
@@ -190,46 +190,84 @@ class Embeddings(object):
def search(self, query, limit=3):
"""
- Finds documents in the vector model most similar to the input document.
+ Finds documents in the embeddings model most similar to the input query. Returns
+ a list of (id, score) sorted by highest score, where id is the document id in
+ the embeddings model.
Args:
query: query text|tokens
limit: maximum results
Returns:
- list of topn matched (id, score)
+ list of (id, score)
"""
- # Convert tokens to embedding vector
- embedding = self.transform((None, query, None))
+ return self.batchsearch([query], limit)[0]
+
+ def batchsearch(self, queries, limit=3):
+ """
+ Finds documents in the embeddings model most similar to the input queries. Returns
+ a list of (id, score) sorted by highest score per query, where id is the document id
+ in the embeddings model.
+
+ Args:
+ queries: queries text|tokens
+ limit: maximum results
+
+ Returns:
+ list of (id, score) per query
+ """
+
+ # Convert queries to embedding vectors
+ embeddings = np.array([self.transform((None, query, None)) for query in queries])
# Search embeddings index
- results = self.embeddings.search(embedding, limit)
+ results = self.embeddings.search(embeddings, limit)
# Map ids if id mapping available
lookup = self.config.get("ids")
if lookup:
- return [(lookup[i], score) for i, score in results]
+ results = [[(lookup[i], score) for i, score in r] for r in results]
return results
- def similarity(self, query, documents):
+ def similarity(self, query, texts):
"""
- Computes the similarity between a query and a set of documents
+ Computes the similarity between query and list of strings. Returns a list of
+ (id, score) sorted by highest score, where id is the index in texts.
Args:
query: query text|tokens
- documents: document text|tokens
+ texts: list of text|tokens
Returns:
- [computed similarity (0 - 1 with 1 being most similar)]
+ list of (id, score)
"""
- query = self.transform((None, query, None)).reshape(1, -1)
- documents = np.array([self.transform((None, text, None)) for text in documents])
+ return self.batchsimilarity([query], texts)[0]
+
+ def batchsimilarity(self, queries, texts):
+ """
+ Computes the similarity between list of queries and list of strings. Returns a list
+ of (id, score) sorted by highest score per query, where id is the index in texts.
+
+ Args:
+ queries: queries text|tokens
+ texts: list of text|tokens
+
+ Returns:
+ list of (id, score) per query
+ """
+
+ # Convert queries to embedding vectors
+ queries = np.array([self.transform((None, query, None)) for query in queries])
+ texts = np.array([self.transform((None, text, None)) for text in texts])
# Dot product on normalized vectors is equal to cosine similarity
- return np.dot(query, documents.T)[0]
+ scores = np.dot(queries, texts.T).tolist()
+
+ # Add index id and sort desc based on score
+ return [sorted(enumerate(score), key=lambda x: x[1], reverse=True) for score in scores]
def load(self, path):
"""
@@ -240,7 +278,7 @@ class Embeddings(object):
embeddings - sentence embeddings index
lsa - LSA model, used to remove the principal component(s)
scoring - scoring model used to weigh word vectors
- vectors - word vectors model
+ vectors - vectors model
Args:
path: input directory path
@@ -250,7 +288,7 @@ class Embeddings(object):
with open("%s/config" % path, "rb") as handle:
self.config = pickle.load(handle)
- # Build full path to embedded vectors file
+ # Build full path to embedding vectors file
if self.config.get("storevectors"):
self.config["path"] = os.path.join(path, self.config["path"])
diff --git a/src/python/txtai/extractor.py b/src/python/txtai/extractor.py
index 555de40b..d0d2a25e 100644
--- a/src/python/txtai/extractor.py
+++ b/src/python/txtai/extractor.py
@@ -32,22 +32,22 @@ class Extractor(object):
# Tokenizer class use default method if not set
self.tokenizer = tokenizer if tokenizer else Tokenizer
- def __call__(self, sections, queue):
+ def __call__(self, queue, texts):
"""
- Extracts answers to input questions. This method runs queries against a list of text sections, finds the top n best matches
+ Extracts answers to input questions. This method runs queries against a list of text, finds the top n best matches
and uses that as the question context. A question-answering model is then run against the context for the input question,
with the answer returned.
Args:
- sections: list of (id, text) sections
queue: input queue (name, query, question, snippet)
+ texts: list of strings
Returns:
- extracted answers
+ list of (name, answer)
"""
# Execute embeddings query
- results = self.query(sections, [query for _, query, _, _ in queue])
+ results = self.query([query for _, query, _, _ in queue], texts)
# Build question-context pairs
names, questions, contexts, snippets = [], [], [], []
@@ -64,23 +64,29 @@ class Extractor(object):
# Run qa pipeline and return answers
return self.answers(names, questions, contexts, snippets)
- def query(self, sections, queries):
+ def query(self, queries, texts):
"""
Executes the extractor embeddings query. Returns results sorted by best match.
Args:
- sections: list of (id, text) sections
queries: list of embedding queries to run
+ texts: list of strings
+
+ Returns:
+ list of (id, text, score)
"""
# Tokenize text
segments, tokenlist = [], []
- for sid, text in sections:
+ for text in texts:
tokens = self.tokenizer.tokenize(text)
if tokens:
- segments.append((sid, text))
+ segments.append(text)
tokenlist.append(tokens)
+ # Add index id to segments to preserver ordering after filters
+ segments = list(enumerate(segments))
+
# Build question-context pairs
results = []
for query in queries:
@@ -94,8 +100,9 @@ class Extractor(object):
# List of matches
matches = []
+ # Get list of (id, score) - sorted by highest score
scores = self.embeddings.similarity(query, tokenlist)
- for x, score in enumerate(scores):
+ for x, score in scores:
# Get segment text
text = segments[x][1]
@@ -106,8 +113,8 @@ class Extractor(object):
(not mnot or all([token.lower() not in text.lower() for token in mnot])):
matches.append(segments[x] + (score,))
- # Sort results by score
- results.append(sorted(matches, key=lambda x: x[2], reverse=True))
+ # Add query matches sorted by highest score
+ results.append(matches)
return results
@@ -120,6 +127,9 @@ class Extractor(object):
questions: questions
contexts: question context
snippets: flags to enable answer snippets per answer
+
+ Returns:
+ list of (name, answer)
"""
results = []
@@ -129,14 +139,11 @@ class Extractor(object):
# Extract and format answer
for x, answer in enumerate(answers):
- # Extract answer
- value = answer["answer"]
-
# Resolve snippet if necessary
if answer and snippets[x]:
- value = self.snippet(contexts[x], value)
+ answer = self.snippet(contexts[x], answer)
- results.append((names[x], value))
+ results.append((names[x], answer))
return results
diff --git a/src/python/txtai/pipeline.py b/src/python/txtai/pipeline.py
index 8527d415..8a9f54a3 100644
--- a/src/python/txtai/pipeline.py
+++ b/src/python/txtai/pipeline.py
@@ -2,6 +2,7 @@
Pipeline module
"""
+import numpy as np
import torch
from transformers import pipeline
@@ -70,68 +71,88 @@ class Questions(Pipeline):
# Get answer and score
answer, score = result["answer"], result["score"]
- # Require best score to be at least 0.05
+ # Require score to be at least 0.05
if score < 0.05:
answer = None
# Add answer
- answers.append({"answer": answer, "score": score})
+ answers.append(answer)
else:
- answers.append({"answer": None, "score": 0.0})
+ answers.append(None)
return answers
class Labels(Pipeline):
"""
- Applies labels to text sections using a zero shot classifier.
+ Applies a zero shot classifier to text using a list of labels.
"""
def __init__(self, path=None, quantize=False, gpu=True, model=None):
super().__init__("zero-shot-classification", path, quantize, gpu, model)
- def __call__(self, section, labels):
+ def __call__(self, text, labels, multiclass=False):
"""
- Applies a zero shot classifier to a text section using a list of labels.
+ Applies a zero shot classifier to text using a list of labels. Returns a list of
+ (id, score) sorted by highest score, where id is the index in labels.
+
+ This method supports text as a string or a list. If the input is a string, the return
+ type is a 1D list of (id, score). If text is a list, a 2D list of (id, score) is
+ returned with a row per string.
Args:
- section: text|list
+ text: text|list
labels: list of labels
Returns:
- list of (label, score) for each text section
+ list of (id, score)
"""
- # Run pipeline
- results = self.pipeline(section, labels)
+ # Run ZSL pipeline
+ results = self.pipeline(text, labels, multi_class=multiclass)
- # Pipeline returns a dict for single element inputs
+ # Convert results to a list if necessary
if not isinstance(results, list):
- return list(zip(results["labels"], results["scores"]))
+ results = [results]
- return [list(zip(result["labels"], result["scores"])) for result in results]
+ # Build list of (id, score)
+ scores = []
+ for result in results:
+ scores.append([(labels.index(label), result["scores"][x]) for x, label in enumerate(result["labels"])])
+
+ return scores[0] if isinstance(text, str) else scores
class Similarity(Labels):
"""
- Computes similarity between a query and a set of documents using a zero shot classifier.
+ Computes similarity between query and list of strings using a zero shot classifier.
"""
- def __call__(self, query, documents):
+ def __call__(self, query, texts, multiclass=True):
"""
- Computes the similarity between a query and a set of documents
+ Computes the similarity between query and list of strings. Returns a list of
+ (id, score) sorted by highest score, where id is the index in texts.
+
+ This method supports query as a string or a list. If the input is a string,
+ the return type is a 1D list of (id, score). If text is a list, a 2D list
+ of (id, score) is returned with a row per string.
Args:
- query: query text
- documents: document text
+ query: query text|list
+ texts: list of texts
Returns:
- [computed similarity (0 - 1 with 1 being most similar)]
+ list of (id, score)
"""
- # Call Labels pipeline for documents using input query as the candidate label
- results = super().__call__(documents, [query])
+ # Call Labels pipeline for texts using input query as the candidate label
+ scores = super().__call__(texts, [query] if isinstance(query, str) else query, multiclass)
- # Convert results to a list when documents only has a single input
- if not isinstance(results[0], list):
- results = [results]
+ # Sort on query index id
+ scores = [[score for _, score in sorted(row)] for row in scores]
+
+ # Transpose axes to get a list of text scores for each query
+ scores = np.array(scores).T.tolist()
+
+ # Build list of (id, score) per query sorted by highest score
+ scores = [sorted(enumerate(row), key=lambda x: x[1], reverse=True) for row in scores]
- return [r[0][1] for r in results]
+ return scores[0] if isinstance(query, str) else scores
diff --git a/src/python/txtai/tokenizer.py b/src/python/txtai/tokenizer.py
index 52728aa4..44531629 100644
--- a/src/python/txtai/tokenizer.py
+++ b/src/python/txtai/tokenizer.py
@@ -1,5 +1,5 @@
"""
-Text tokenization methods
+Tokenizer module
"""
import re
@@ -7,7 +7,7 @@ import string
class Tokenizer(object):
"""
- Text tokenization methods
+ Text tokenization methods.
"""
# English Stop Word List (Standard stop words used by Apache Lucene)
diff --git a/test/python/testann.py b/test/python/testann.py
index 12f8eb49..f877b323 100644
--- a/test/python/testann.py
+++ b/test/python/testann.py
@@ -87,7 +87,7 @@ class TestANN(unittest.TestCase):
self.normalize(query)
# Ensure top result has similarity > 0
- return model.search(query, 1)[0][1]
+ return model.search(np.array([query]), 1)[0][0][1]
def normalize(self, embeddings):
"""
diff --git a/test/python/testapi.py b/test/python/testapi.py
index bc0bd2b0..58c3c13b 100644
--- a/test/python/testapi.py
+++ b/test/python/testapi.py
@@ -8,8 +8,6 @@ import unittest
from unittest.mock import patch
-import numpy as np
-
from fastapi.testclient import TestClient
from txtai.api import API, app, start
@@ -89,29 +87,26 @@ class TestAPI(unittest.TestCase):
"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)])
+ cls.client.get("index")
+
def testEmbeddings(self):
"""
- Test embeddings via API
+ Test embeddings transform via API
"""
- # Test similarity
- uid = np.argmax(self.client.post("similarity", json={
- "search": "feel good story",
- "data": self.data
- }).json())
-
- self.assertEqual(self.data[uid], self.data[4])
+ self.assertEqual(len(self.client.get("embeddings?text=testembed").json()), 768)
- # Test indexing
- self.client.post("add", json=[{"id": x, "text": row} for x, row in enumerate(self.data)])
- self.client.get("index")
+ def testEmbeddingsBatch(self):
+ """
+ Test batch embeddings transform via API
+ """
- # Test search
- uid = self.client.get("search?q=feel%20good%20story&n=1").json()[0][0]
- self.assertEqual(self.data[uid], self.data[4])
+ embeddings = self.client.post("batchembeddings", json=self.data).json()
- # Test embeddings
- self.assertIsNotNone(self.client.get("embeddings?t=testembed").json())
+ self.assertEqual(len(embeddings), len(self.data))
+ self.assertEqual(len(embeddings[0]), 768)
def testEmpty(self):
"""
@@ -121,8 +116,10 @@ class TestAPI(unittest.TestCase):
api = API({})
self.assertIsNone(api.search("test", None))
+ self.assertIsNone(api.batchsearch(["test"], None))
self.assertIsNone(api.similarity("test", ["test"]))
- self.assertIsNone(api.transform("test"))
+ self.assertIsNone(api.batchsimilarity(["test"], ["test"]))
+ self.assertIsNone(api.transform(["test"]))
self.assertIsNone(api.extract(["test"], ["test"]))
self.assertIsNone(api.label("test", ["test"]))
@@ -131,27 +128,24 @@ class TestAPI(unittest.TestCase):
Test qa extraction via API
"""
- sections = ["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"]
-
- # Add unique id to each section to assist with qa extraction
- sections = [{"id": uid, "text": section} for uid, section in enumerate(sections)]
+ 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={
- "documents": sections,
- "queue": [{"name": question, "query": query, "question": question, "snippet": False} for question in questions]
+ "queue": [{"name": question, "query": query, "question": question, "snippet": False} for question in questions],
+ "texts": data
}).json()
answers = execute("Red Sox - Blue Jays")
@@ -162,14 +156,14 @@ class TestAPI(unittest.TestCase):
question = "What hockey team won?"
answers = self.client.post("extract", json={
- "documents": sections,
- "queue": [{"name": question, "query": question, "question": question, "snippet": False}]
+ "queue": [{"name": question, "query": question, "question": question, "snippet": False}],
+ "texts": data
}).json()
self.assertEqual("Flyers", answers[0][1])
- def testLabels(self):
+ def testLabel(self):
"""
- Test labels via API
+ Test label via API
"""
labels = self.client.post("label", json={
@@ -177,9 +171,68 @@ class TestAPI(unittest.TestCase):
"labels": ["positive", "negative"]
}).json()
- self.assertEqual(labels[0][0], "positive")
+ self.assertEqual(labels[0][0], 0)
+
+ def testLabelBatch(self):
+ """
+ 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()
+
+ results = [l[0][0] for l in labels]
+ self.assertEqual(results, [0, 1])
+
+ def testSearch(self):
+ """
+ Test search via API
+ """
+
+ uid = self.client.get("search?query=feel%20good%20story&limit=1").json()[0][0]
+ self.assertEqual(self.data[uid], self.data[4])
+
+ def testSearchBatch(self):
+ """
+ Test batch search via API
+ """
+
+ results = self.client.post("batchsearch", json={
+ "queries": ["feel good story", "climate change"],
+ "limit": 1
+ }).json()
+
+ uids = [result[0][0] for result in results]
+ self.assertEqual(uids, [4, 1])
+
+ def testSimilarity(self):
+ """
+ Test similarity via API
+ """
+
+ uid = self.client.post("similarity", json={
+ "query": "feel good story",
+ "texts": self.data
+ }).json()[0][0]
+
+ self.assertEqual(self.data[uid], self.data[4])
+
+ def testSimilarityBatch(self):
+ """
+ Test batch similarity via API
+ """
+
+ results = self.client.post("batchsimilarity", json={
+ "queries": ["feel good story", "climate change"],
+ "texts": self.data
+ }).json()
+
+ uids = [result[0][0] for result in results]
+ self.assertEqual(uids, [4, 1])
- def testReadOnly(self):
+ def testViewOnly(self):
"""
Test read-only API instance
"""
@@ -188,13 +241,13 @@ class TestAPI(unittest.TestCase):
self.client = TestAPI.start(False)
# Test search
- uid = self.client.get("search?q=feel%20good%20story&n=1").json()[0][0]
+ uid = self.client.get("search?query=feel%20good%20story&limit=1").json()[0][0]
self.assertEqual(uid, 4)
# Test similarity
- uid = np.argmax(self.client.post("similarity", json={
- "search": "feel good story",
- "data": self.data
- }).json())
+ uid = self.client.post("similarity", json={
+ "query": "feel good story",
+ "texts": self.data
+ }).json()[0][0]
self.assertEqual(uid, 4)
diff --git a/test/python/testembeddings.py b/test/python/testembeddings.py
index 8c9774ab..05ef5851 100644
--- a/test/python/testembeddings.py
+++ b/test/python/testembeddings.py
@@ -6,8 +6,6 @@ import os
import tempfile
import unittest
-import numpy as np
-
from txtai.embeddings import Embeddings
from txtai.vectors import WordVectors
@@ -38,7 +36,7 @@ class TestEmbeddings(unittest.TestCase):
Test index
"""
- # Create an index for the list of sections
+ # Create an index for the list of text
self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
# Search for best match
@@ -51,7 +49,7 @@ class TestEmbeddings(unittest.TestCase):
Test save
"""
- # Create an index for the list of sections
+ # Create an index for the list of text
self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
# Generate temp file path
@@ -71,7 +69,7 @@ class TestEmbeddings(unittest.TestCase):
"""
# Get best matching id
- uid = np.argmax(self.embeddings.similarity("feel good story", self.data))
+ uid = self.embeddings.similarity("feel good story", self.data)[0][0]
self.assertEqual(self.data[uid], self.data[4])
diff --git a/test/python/testextractor.py b/test/python/testextractor.py
index b6d7a761..92413e8f 100644
--- a/test/python/testextractor.py
+++ b/test/python/testextractor.py
@@ -19,7 +19,7 @@ class TestExtractor(unittest.TestCase):
Create single extractor instance.
"""
- sections = ["Giants hit 3 HRs to down Dodgers",
+ 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",
@@ -32,9 +32,6 @@ class TestExtractor(unittest.TestCase):
"Flyers 4 Lightning 1 final",
"Flyers win 4-1"]
- # Add unique id to each section to assist with qa extraction
- cls.sections = [(uid, section) for uid, section in enumerate(sections)]
-
# Create embeddings model, backed by sentence-transformers & transformers
cls.embeddings = Embeddings({"method": "transformers", "path": "sentence-transformers/bert-base-nli-mean-tokens"})
@@ -48,7 +45,7 @@ class TestExtractor(unittest.TestCase):
questions = ["What team won the game?", "What was score?"]
- execute = lambda query: self.extractor(self.sections, [(question, query, question, False) for question in questions])
+ execute = lambda query: self.extractor([(question, query, question, False) for question in questions], self.data)
answers = execute("Red Sox - Blue Jays")
self.assertEqual("Blue Jays", answers[0][1])
@@ -57,7 +54,7 @@ class TestExtractor(unittest.TestCase):
# Ad-hoc questions
question = "What hockey team won?"
- answers = self.extractor(self.sections, [(question, question, question, False)])
+ answers = self.extractor([(question, question, question, False)], self.data)
self.assertEqual("Flyers", answers[0][1])
def testNoAnswer(self):
@@ -67,7 +64,7 @@ class TestExtractor(unittest.TestCase):
question = ""
- answers = self.extractor(self.sections, [(question, question, question, False)])
+ answers = self.extractor([(question, question, question, False)], self.data)
self.assertIsNone(answers[0][1])
@unittest.skipIf(platform.system() == "Darwin", "Quantized models not supported on macOS")
@@ -80,7 +77,7 @@ class TestExtractor(unittest.TestCase):
question = "How many home runs?"
- answers = extractor(self.sections, [(question, question, question, True)])
+ answers = extractor([(question, question, question, True)], self.data)
self.assertTrue(answers[0][1].startswith("Giants hit 3 HRs"))
def testSnippet(self):
@@ -90,7 +87,7 @@ class TestExtractor(unittest.TestCase):
question = "How many home runs?"
- answers = self.extractor(self.sections, [(question, question, question, True)])
+ answers = self.extractor([(question, question, question, True)], self.data)
self.assertTrue(answers[0][1].startswith("Giants hit 3 HRs"))
def testSnippetEmpty(self):
diff --git a/test/python/testlabels.py b/test/python/testlabels.py
index 76664fc0..c92e71ed 100644
--- a/test/python/testlabels.py
+++ b/test/python/testlabels.py
@@ -4,8 +4,6 @@ Labels module tests
import unittest
-import numpy as np
-
from txtai.pipeline import Labels, Similarity
class TestLabels(unittest.TestCase):
@@ -19,31 +17,44 @@ 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.labels = Labels("prajjwal1/bert-medium-mnli")
+ cls.similarity = Similarity(model=cls.labels)
def testLabel(self):
"""
- Test labels
+ Test labels with single text input
"""
- self.assertEqual(self.labels("This is the best sentence ever", ["positive", "negative"])[0][0], "positive")
+ self.assertEqual(self.labels("This is the best sentence ever", ["positive", "negative"])[0][0], 0)
- def testSimilarity(self):
+ def testLabelBatch(self):
"""
- Test similarity
+ Test labels with multiple text inputs
"""
- similarity = Similarity(model=self.labels)
+ 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])
- 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 testSimilarity(self):
+ """
+ Test similarity with single query
+ """
+
+ uid = self.similarity("feel good story", self.data)[0][0]
+ self.assertEqual(self.data[uid], self.data[4])
- uid = np.argmax(similarity("feel good story", data))
- self.assertEqual(data[uid], data[4])
+ def testSimilarityBatch(self):
+ """
+ Test similarity with multiple queries
+ """
- uid = np.argmax(similarity("feel good story", data[4]))
- self.assertEqual(uid, 0)
+ results = [r[0][0] for r in self.similarity(["feel good story", "climate change"], self.data)]
+ self.assertEqual(results, [4, 1])
diff --git a/test/python/testtransformers.py b/test/python/testtransformers.py
index 2540615e..eb80c168 100644
--- a/test/python/testtransformers.py
+++ b/test/python/testtransformers.py
@@ -36,6 +36,19 @@ class TestTransformersVectors(unittest.TestCase):
self.assertEqual(dimension, 768)
self.assertIsNotNone(os.path.exists(stream))
+ def testText(self):
+ """
+ Test transformers text conversion
+ """
+
+ self.model.tokenize = True
+ self.assertEqual(self.model.text("Y 123 This is a test!"), "test")
+ self.assertEqual(self.model.text(["This", "is", "a", "test"]), "This is a test")
+
+ self.model.tokenize = False
+ self.assertEqual(self.model.text("Y 123 This is a test!"), "Y 123 This is a test!")
+ self.assertEqual(self.model.text(["This", "is", "a", "test"]), "This is a test")
+
def testTransform(self):
"""
Test transformers transform
@@ -55,16 +68,3 @@ class TestTransformersVectors(unittest.TestCase):
self.assertFalse(np.array_equal(embeddings1[0], embeddings2[0]))
self.assertTrue(np.array_equal(embeddings1[1], embeddings2[1]))
-
- def testText(self):
- """
- Test transformers text conversion
- """
-
- self.model.tokenize = True
- self.assertEqual(self.model.text("Y 123 This is a test!"), "test")
- self.assertEqual(self.model.text(["This", "is", "a", "test"]), "This is a test")
-
- self.model.tokenize = False
- self.assertEqual(self.model.text("Y 123 This is a test!"), "Y 123 This is a test!")
- self.assertEqual(self.model.text(["This", "is", "a", "test"]), "This is a test")
diff --git a/test/python/testwordvectors.py b/test/python/testwordvectors.py
index 46df1b04..5ebf1762 100644
--- a/test/python/testwordvectors.py
+++ b/test/python/testwordvectors.py
@@ -28,6 +28,22 @@ class TestWordVectors(unittest.TestCase):
# Build word vectors
WordVectors.build("README.md", 300, 3, path)
+ def testBlocking(self):
+ """
+ Test blocking load of vector model
+ """
+
+ config = {"path": self.path}
+ model = Vectors.create(config, None)
+
+ self.assertFalse(model.initialized)
+
+ config["ids"] = ["0", "1"]
+ config["dimensions"] = 300
+ model = Vectors.create(config, None)
+
+ self.assertTrue(model.initialized)
+
def testIndex(self):
"""
Test word vector indexing
@@ -44,13 +60,13 @@ class TestWordVectors(unittest.TestCase):
self.assertEqual(dimension, 300)
self.assertIsNotNone(os.path.exists(stream))
- def testTransform(self):
+ def testLookup(self):
"""
- Test word vector transform
+ Test word vector lookup
"""
model = Vectors.create({"path": self.path}, None)
- self.assertEqual(len(model.transform((None, ["txtai"], None))), 300)
+ self.assertEqual(model.lookup(["txtai", "embeddings", "sentence"]).shape, (3, 300))
def testNoExist(self):
"""
@@ -61,26 +77,10 @@ class TestWordVectors(unittest.TestCase):
with self.assertRaises(IOError):
Vectors.create({"path": os.path.join(tempfile.gettempdir(), "noexist")}, None)
- def testLookup(self):
+ def testTransform(self):
"""
- Test word vector lookup
+ Test word vector transform
"""
model = Vectors.create({"path": self.path}, None)
- self.assertEqual(model.lookup(["txtai", "embeddings", "sentence"]).shape, (3, 300))
-
- def testBlocking(self):
- """
- Test blocking load of vector model
- """
-
- config = {"path": self.path}
- model = Vectors.create(config, None)
-
- self.assertFalse(model.initialized)
-
- config["ids"] = ["0", "1"]
- config["dimensions"] = 300
- model = Vectors.create(config, None)
-
- self.assertTrue(model.initialized)
+ self.assertEqual(len(model.transform((None, ["txtai"], None))), 300)