💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add API extensions #77 and Modularize the API #78
davidmezzettib71684734cda
diff --git a/src/python/txtai/api/__init__.py b/src/python/txtai/api/__init__.pyindex b3715b22..4778f974 100644--- a/src/python/txtai/api/__init__.py+++ b/src/python/txtai/api/__init__.py@@ -4,4 +4,5 @@ API importsfrom .application import app, startfrom .base import API+from .extension import Extensionfrom .factory import Factorydiff --git a/src/python/txtai/api/application.py b/src/python/txtai/api/application.pyindex b4e1d187..6b9d1da9 100644--- a/src/python/txtai/api/application.py+++ b/src/python/txtai/api/application.py@@ -4,15 +4,16 @@ FastAPI application moduleimport os-from typing import List-import yaml-from fastapi import Body, FastAPI, Request+from fastapi import FastAPIfrom .base import APIfrom .factory import Factory+# pylint: disable=R0401+from .routers import embeddings, extractor, labels, similarity, summary, textractor, transcription, translation+# API instanceapp = FastAPI()@@ -20,10 +21,23 @@ app = FastAPI()INSTANCE = None+def get():+ """+ Returns global API instance.++ Returns:+ API instance+ """++ # pylint: disable=W0603+ global INSTANCE+ return INSTANCE++@app.on_event("startup")def start():"""- FastAPI startup event. Pre-loads embeddings index.+ FastAPI startup event. Loads API instance."""# pylint: disable=W0603@@ -36,179 +50,33 @@ def start():# Instantiate API instanceapi = os.getenv("API_CLASS")- INSTANCE = Factory.get(api)(config) if api else API(config)--[email protected]("/search")-def search(query: str, request: Request):- """- Finds documents in the embeddings model most similar to the input query. Returns- a list of {id: value, score: value} sorted by highest score, where id is the- document id in the embeddings model.-- Args:- query: query text- request: FastAPI request-- Returns:- list of {id: value, score: value}- """-- 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: value, score: value} 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: value, score: value} per query- """-- return INSTANCE.batchsearch(queries, limit)--[email protected]("/add")-def add(documents: List[dict] = Body(...)):- """- Adds a batch of documents for indexing.-- Args:- documents: list of {id: value, text: value}- """-- INSTANCE.add(documents)--[email protected]("/index")-def index():- """- Builds an embeddings index for previously batched documents. No further documents can be added- after this call.- """-- INSTANCE.index()--[email protected]("/similarity")-def similarity(query: str = Body(...), texts: List[str] = Body(...)):- """- Computes the similarity between query and list of text. Returns a list of- {id: value, score: value} sorted by highest score, where id is the index- in texts.-- Args:- query: query text- texts: list of text-- Returns:- list of {id: value, score: value}- """-- 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 text. Returns a list- of {id: value, score: value} 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: value, score: value} per query- """-- return INSTANCE.batchsimilarity(queries, texts)--[email protected]("/transform")-def transform(text: str):- """- Transforms text into an embeddings array.-- Args:- text: input text-- Returns:- embeddings array- """-- return INSTANCE.transform(text)--[email protected]("/batchtransform")-def batchtransform(texts: List[str] = Body(...)):- """- Transforms list of text into embeddings arrays.-- Args:- texts: list of text-- Returns:- embeddings arrays- """-- return INSTANCE.batchtransform(texts)--[email protected]("/extract")-def extract(queue: List[dict] = Body(...), texts: List[str] = Body(...)):- """- Extracts answers to input questions.-- Args:- queue: list of {name: value, query: value, question: value, snippet: value}- texts: list of text-- Returns:- list of {name: value, answer: value}- """-- return INSTANCE.extract(queue, texts)--[email protected]("/label")-def label(text: str = Body(...), labels: List[str] = Body(...)):- """- Applies a zero shot classifier to text using a list of labels. Returns a list of- {id: value, score: value} sorted by highest score, where id is the index in labels.-- Args:- text: input text- labels: list of labels-- Returns:- list of {id: value, score: value} per text element- """-- 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: value, score: value} sorted by highest score, where id is the index in labels per- text element.-- Args:- texts: list of text- labels: list of labels-- Returns:- list of {id: value score: value} per text element- """-- return INSTANCE.label(texts, labels)+ INSTANCE = Factory.create(config, api) if api else API(config)++ # Router definitions+ routers = [+ ("embeddings", embeddings.router),+ ("extractor", extractor.router),+ ("labels", labels.router),+ ("similarity", similarity.router),+ ("summary", summary.router),+ ("textractor", textractor.router),+ ("transcription", transcription.router),+ ("translation", translation.router),+ ]++ # Conditionally add routes based on configuration+ for route, router in routers:+ if route in config:+ app.include_router(router)++ # Special case to add similarity instance for embeddings+ if "embeddings" in config and "similarity" not in config:+ app.include_router(similarity.router)++ # Execute extensions if present+ extensions = os.getenv("EXTENSIONS")+ if extensions:+ for extension in extensions.split(","):+ # Create instance and execute extension+ extension = Factory.get(extension.strip())()+ extension(app)diff --git a/src/python/txtai/api/base.py b/src/python/txtai/api/base.pyindex 13f538a7..e0191104 100644--- a/src/python/txtai/api/base.py+++ b/src/python/txtai/api/base.py@@ -3,12 +3,12 @@ API module"""from ..embeddings import Documents, Embeddings-from ..pipeline import Extractor, Labels, Similarity+from ..pipeline import Factoryclass API:"""- Base API template. Downstream applications can extend this base template to add custom search functionality.+ Base API template. Downstream applications can extend this base template to add/modify functionality."""def __init__(self, config):@@ -20,8 +20,7 @@ class API:"""# Initialize member variables- self.config, self.documents = config, None- self.embeddings, self.extractor, self.labels, self.similar = None, None, None, None+ self.config, self.documents, self.embeddings = config, None, None# Create/load embeddings index depending on writable flagif self.config.get("writable"):@@ -30,28 +29,29 @@ class API:self.embeddings = Embeddings()self.embeddings.load(self.config["path"])- # Create extractor instance- if "extractor" in self.config:- # Extractor settings- extractor = self.config["extractor"] if self.config["extractor"] else {}+ # Pipeline definitions+ self.pipelines = {}- self.extractor = Extractor(self.embeddings, extractor.get("path"), extractor.get("quantize"), extractor.get("gpu"))+ # Default pipelines+ pipelines = ["extractor", "labels", "similarity", "summary", "textractor", "transcription", "translation"]- # Create labels instance- if "labels" in self.config:- labels = self.config["labels"] if self.config["labels"] else {}+ # Add custom pipelines+ for key in self.config:+ if "." in key:+ pipelines.append(key)- self.labels = Labels(labels.get("path"), labels.get("quantize"), labels.get("gpu"))+ # Create pipelines+ for pipeline in pipelines:+ if pipeline in self.config:+ config = self.config[pipeline] if self.config[pipeline] else {}- # Creates similarity instance- if "similarity" in self.config:- similar = self.config["similarity"] if self.config["similarity"] else {}+ # Custom pipeline parameters+ if pipeline == "extractor":+ config["embeddings"] = self.embeddings+ elif pipeline == "similarity" and "path" not in config and "labels" in self.pipelines:+ config["model"] = self.pipelines["labels"]- # Share model with labels if separate model not specified- if "path" not in similar and self.labels:- self.similar = Similarity(model=self.labels)- else:- self.similar = Similarity(similar.get("path"), similar.get("quantize"), similar.get("gpu"))+ self.pipelines[pipeline] = Factory.create(config, pipeline)def limit(self, limit):"""@@ -164,8 +164,8 @@ class API:"""# Use similarity instance if available otherwise fall back to embeddings model- if self.similar:- return [{"id": uid, "score": float(score)} for uid, score in self.similar(query, texts)]+ if "similarity" in self.pipelines:+ return [{"id": uid, "score": float(score)} for uid, score in self.pipelines["similarity"](query, texts)]if self.embeddings:return [{"id": uid, "score": float(score)} for uid, score in self.embeddings.similarity(query, texts)]@@ -186,8 +186,8 @@ class API:"""# Use similarity instance if available otherwise fall back to embeddings model- if self.similar:- return [[{"id": uid, "score": float(score)} for uid, score in r] for r in self.similar(queries, texts)]+ if "similarity" in self.pipelines:+ return [[{"id": uid, "score": float(score)} for uid, score in r] for r in self.pipelines["similarity"](queries, texts)]if self.embeddings:return [[{"id": uid, "score": float(score)} for uid, score in r] for r in self.embeddings.batchsimilarity(queries, texts)]@@ -238,10 +238,10 @@ class API:list of {name: value, answer: value}"""- if self.extractor:+ if self.embeddings and "extractor" in self.pipelines:# Convert queue to tuplesqueue = [(x["name"], x["query"], x.get("question"), x.get("snippet")) for x in queue]- return [{"name": name, "answer": answer} for name, answer in self.extractor(queue, texts)]+ return [{"name": name, "answer": answer} for name, answer in self.pipelines["extractor"](queue, texts)]return None@@ -258,12 +258,26 @@ class API:list of {id: value, score: value} per text element"""- if self.labels:+ if "labels" in self.pipelines:# Text is a stringif isinstance(text, str):- return [{"id": uid, "score": float(score)} for uid, score in self.labels(text, labels)]+ return [{"id": uid, "score": float(score)} for uid, score in self.pipelines["labels"](text, labels)]# Text is a list- return [[{"id": uid, "score": float(score)} for uid, score in result] for result in self.labels(text, labels)]+ return [[{"id": uid, "score": float(score)} for uid, score in result] for result in self.pipelines["labels"](text, labels)]++ return None++ def pipeline(self, name, args):+ """+ Generic pipeline execution method.++ Args:+ name: pipeline name+ args: pipeline arguments+ """++ if name in self.pipelines:+ return self.pipelines[name](*args)return Nonediff --git a/src/python/txtai/api/extension.py b/src/python/txtai/api/extension.pynew file mode 100644index 00000000..337f8d3a--- /dev/null+++ b/src/python/txtai/api/extension.py@@ -0,0 +1,19 @@+"""+Extension module+"""+++class Extension:+ """+ Defines an API extension. API extensions can expose custom pipelines or other custom logic.+ """++ def __call__(self, app):+ """+ Hook to register custom routing logic and/or modify the FastAPI instance.++ Args:+ app: FastAPI application instance+ """++ returndiff --git a/src/python/txtai/api/factory.py b/src/python/txtai/api/factory.pyindex 766b6883..478555ab 100644--- a/src/python/txtai/api/factory.py+++ b/src/python/txtai/api/factory.py@@ -9,21 +9,36 @@ class Factory:"""@staticmethod- def get(atype):+ def get(api):"""- Gets a new instance of atype.+ Gets a new instance of api class.Args:- atype: API instance class+ api: API instance classReturns:- instance of atype+ API"""- parts = atype.split(".")+ parts = api.split(".")module = ".".join(parts[:-1])m = __import__(module)for comp in parts[1:]:m = getattr(m, comp)return m++ @staticmethod+ def create(config, api):+ """+ Creates a new API instance.++ Args:+ config: API configuration+ api: API instance class++ Returns:+ API instance+ """++ return Factory.get(api)(config)diff --git a/src/python/txtai/api/routers/__init__.py b/src/python/txtai/api/routers/__init__.pynew file mode 100644index 00000000..0f2e3f0b--- /dev/null+++ b/src/python/txtai/api/routers/__init__.py@@ -0,0 +1,11 @@+"""+Router imports+"""++from . import embeddings+from . import extractor+from . import similarity+from . import summary+from . import textractor+from . import transcription+from . import translationdiff --git a/src/python/txtai/api/routers/embeddings.py b/src/python/txtai/api/routers/embeddings.pynew file mode 100644index 00000000..8bf98dc7--- /dev/null+++ b/src/python/txtai/api/routers/embeddings.py@@ -0,0 +1,99 @@+"""+Defines API paths for embeddings endpoints.+"""++from typing import List++from fastapi import APIRouter, Body, Request++from .. import application++router = APIRouter()++[email protected]("/search")+def search(query: str, request: Request):+ """+ Finds documents in the embeddings model most similar to the input query. Returns+ a list of {id: value, score: value} sorted by highest score, where id is the+ document id in the embeddings model.++ Args:+ query: query text+ request: FastAPI request++ Returns:+ list of {id: value, score: value}+ """++ return application.get().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: value, score: value} 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: value, score: value} per query+ """++ return application.get().batchsearch(queries, limit)++[email protected]("/add")+def add(documents: List[dict] = Body(...)):+ """+ Adds a batch of documents for indexing.++ Args:+ documents: list of {id: value, text: value}+ """++ application.get().add(documents)++[email protected]("/index")+def index():+ """+ Builds an embeddings index for previously batched documents. No further documents can be added+ after this call.+ """++ application.get().index()++[email protected]("/transform")+def transform(text: str):+ """+ Transforms text into an embeddings array.++ Args:+ text: input text++ Returns:+ embeddings array+ """++ return application.get().transform(text)++[email protected]("/batchtransform")+def batchtransform(texts: List[str] = Body(...)):+ """+ Transforms list of text into embeddings arrays.++ Args:+ texts: list of text++ Returns:+ embeddings arrays+ """++ return application.get().batchtransform(texts)diff --git a/src/python/txtai/api/routers/extractor.py b/src/python/txtai/api/routers/extractor.pynew file mode 100644index 00000000..f5eb71c4--- /dev/null+++ b/src/python/txtai/api/routers/extractor.py@@ -0,0 +1,27 @@+"""+Defines API paths for extractor endpoints.+"""++from typing import List++from fastapi import APIRouter, Body++from .. import application++router = APIRouter()++[email protected]("/extract")+def extract(queue: List[dict] = Body(...), texts: List[str] = Body(...)):+ """+ Extracts answers to input questions.++ Args:+ queue: list of {name: value, query: value, question: value, snippet: value}+ texts: list of text++ Returns:+ list of {name: value, answer: value}+ """++ return application.get().extract(queue, texts)diff --git a/src/python/txtai/api/routers/labels.py b/src/python/txtai/api/routers/labels.pynew file mode 100644index 00000000..568b7bfd--- /dev/null+++ b/src/python/txtai/api/routers/labels.py@@ -0,0 +1,42 @@+"""+Defines API paths for labels endpoints.+"""++from typing import List++from fastapi import APIRouter, Body++from .. import application++router = APIRouter()++[email protected]("/label")+def label(text: str = Body(...), labels: List[str] = Body(...)):+ """+ Applies a zero shot classifier to text using a list of labels. Returns a list of+ {id: value, score: value} sorted by highest score, where id is the index in labels.+ Args:+ text: input text+ labels: list of labels+ Returns:+ list of {id: value, score: value} per text element+ """++ return application.get().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: value, score: value} sorted by highest score, where id is the index in labels per+ text element.+ Args:+ texts: list of text+ labels: list of labels+ Returns:+ list of {id: value score: value} per text element+ """++ return application.get().label(texts, labels)diff --git a/src/python/txtai/api/routers/similarity.py b/src/python/txtai/api/routers/similarity.pynew file mode 100644index 00000000..a68ec1f6--- /dev/null+++ b/src/python/txtai/api/routers/similarity.py@@ -0,0 +1,47 @@+"""+Defines API paths for similarity endpoints.+"""++from typing import List++from fastapi import APIRouter, Body++from .. import application++router = APIRouter()++[email protected]("/similarity")+def similarity(query: str = Body(...), texts: List[str] = Body(...)):+ """+ Computes the similarity between query and list of text. Returns a list of+ {id: value, score: value} sorted by highest score, where id is the index+ in texts.++ Args:+ query: query text+ texts: list of text++ Returns:+ list of {id: value, score: value}+ """++ return application.get().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 text. Returns a list+ of {id: value, score: value} 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: value, score: value} per query+ """++ return application.get().batchsimilarity(queries, texts)diff --git a/src/python/txtai/api/routers/summary.py b/src/python/txtai/api/routers/summary.pynew file mode 100644index 00000000..e644355f--- /dev/null+++ b/src/python/txtai/api/routers/summary.py@@ -0,0 +1,45 @@+"""+Defines API paths for summary endpoints.+"""++from typing import List, Optional++from fastapi import APIRouter, Body++from .. import application++router = APIRouter()++[email protected]("/summary")+def summary(text: str, minlength: Optional[int] = None, maxlength: Optional[int] = None):+ """+ Runs a summarization model against a block of text.++ Args:+ text: text to summarize+ minlength: minimum length for summary+ maxlength: maximum length for summary++ Returns:+ summary text+ """++ return application.get().pipeline("summary", (text, minlength, maxlength))++[email protected]("/batchsummary")+def batchsummary(texts: List[str] = Body(...), minlength: Optional[int] = Body(default=None), maxlength: Optional[int] = Body(default=None)):+ """+ Runs a summarization model against a block of text.++ Args:+ texts: list of text to summarize+ minlength: minimum length for summary+ maxlength: maximum length for summary++ Returns:+ list of summary text+ """++ return application.get().pipeline("summary", (texts, minlength, maxlength))diff --git a/src/python/txtai/api/routers/textractor.py b/src/python/txtai/api/routers/textractor.pynew file mode 100644index 00000000..b7a485e3--- /dev/null+++ b/src/python/txtai/api/routers/textractor.py@@ -0,0 +1,41 @@+"""+Defines API paths for textractor endpoints.+"""++from typing import List++from fastapi import APIRouter, Body++from .. import application++router = APIRouter()++[email protected]("/textract")+def textract(file: str):+ """+ Extracts text from a file at path.++ Args:+ file: file to extract text++ Returns:+ extracted text+ """++ return application.get().pipeline("textractor", (file,))++[email protected]("/batchtextract")+def batchtextract(files: List[str] = Body(...)):+ """+ Extracts text from a file at path.++ Args:+ files: list of files to extract text++ Returns:+ list of extracted text+ """++ return application.get().pipeline("textractor", (files,))diff --git a/src/python/txtai/api/routers/transcription.py b/src/python/txtai/api/routers/transcription.pynew file mode 100644index 00000000..e187590b--- /dev/null+++ b/src/python/txtai/api/routers/transcription.py@@ -0,0 +1,41 @@+"""+Defines API paths for transcription endpoints.+"""++from typing import List++from fastapi import APIRouter, Body++from .. import application++router = APIRouter()++[email protected]("/transcribe")+def transcribe(file: str):+ """+ Transcribes audio files to text.++ Args:+ file: file to transcribe++ Returns:+ list of transcribed text+ """++ return application.get().pipeline("transcription", (file,))++[email protected]("/batchtranscribe")+def batchtranscribe(files: List[str] = Body(...)):+ """+ Transcribes audio files to text.++ Args:+ file: list of files to transcribe++ Returns:+ list of transcribed text+ """++ return application.get().pipeline("transcription", (files,))diff --git a/src/python/txtai/api/routers/translation.py b/src/python/txtai/api/routers/translation.pynew file mode 100644index 00000000..5186e087--- /dev/null+++ b/src/python/txtai/api/routers/translation.py@@ -0,0 +1,45 @@+"""+Defines API paths for translation endpoints.+"""++from typing import List, Optional++from fastapi import APIRouter, Body++from .. import application++router = APIRouter()++[email protected]("/translate")+def translate(text: str, target: Optional[str] = "en", source: Optional[int] = None):+ """+ Translates text from source language into target language.++ Args:+ text: text to translate+ target: target language code, defaults to "en"+ source: source language code, detects language if not provided++ Returns:+ translated text+ """++ return application.get().pipeline("translation", (text, target, source))++[email protected]("/batchtranslate")+def batchtranslate(texts: List[str] = Body(...), target: Optional[str] = Body(default="en"), source: Optional[str] = Body(default=None)):+ """+ Translates text from source language into target language.++ Args:+ texts: list of text to translate+ target: target language code, defaults to "en"+ source: source language code, detects language if not provided++ Returns:+ list of translated text+ """++ return application.get().pipeline("translation", (texts, target, source))diff --git a/test/python/testapi/__init__.py b/test/python/testapi/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/test/python/testapi.py b/test/python/testapi/testembeddings.pysimilarity index 83%rename from test/python/testapi.pyrename to test/python/testapi/testembeddings.pyindex 76dd169b..5c504f55 100644--- a/test/python/testapi.py+++ b/test/python/testapi/testembeddings.py@@ -1,5 +1,5 @@"""-API module tests+Embeddings API module tests"""import os@@ -12,8 +12,8 @@ from fastapi.testclient import TestClientfrom txtai.api import API, app, start-# Full API configuration with similarity search, extractive QA and zero-shot labeling.-FULL = """+# Configuration for a read/write embeddings index+INDEX = """# Index file pathpath: %s@@ -28,16 +28,9 @@ embeddings:# Extractor settingsextractor:path: distilbert-base-cased-distilled-squad--# Labels settings-labels:- path: prajjwal1/bert-medium-mnli--# Enable pipeline similarity backed by zero shot classifier-similarity:"""-# Configuration that reads an existing similarity search index+# Configuration for a read-only embeddings indexREADONLY = """# Index file pathpath: %s@@ -47,9 +40,9 @@ writable: False"""-class TestAPI(unittest.TestCase):+class TestEmbeddings(unittest.TestCase):"""- API tests+ API tests for embeddings indices"""@staticmethod@@ -66,7 +59,7 @@ class TestAPI(unittest.TestCase):index = os.path.join(tempfile.gettempdir(), "testapi")with open(config, "w") as output:- output.write((FULL if full else READONLY) % (index))+ output.write((INDEX if full else READONLY) % (index))client = TestClient(app)start()@@ -79,7 +72,7 @@ class TestAPI(unittest.TestCase):Create API client on creation of class."""- cls.client = TestAPI.start(True)+ cls.client = TestEmbeddings.start(True)cls.data = ["US tops 5 million confirmed virus cases",@@ -108,7 +101,6 @@ class TestAPI(unittest.TestCase):self.assertIsNone(api.transform("test"))self.assertIsNone(api.batchtransform(["test"]))self.assertIsNone(api.extract(["test"], ["test"]))- self.assertIsNone(api.label("test", ["test"]))def testExtractor(self):"""@@ -149,27 +141,6 @@ class TestAPI(unittest.TestCase):).json()self.assertEqual("Flyers", answers[0]["answer"])- def testLabel(self):- """- Test label via API- """-- labels = self.client.post("label", json={"text": "this is the best sentence ever", "labels": ["positive", "negative"]}).json()-- self.assertEqual(labels[0]["id"], 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]["id"] for l in labels]- self.assertEqual(results, [0, 1])-def testSearch(self):"""Test search via API@@ -230,7 +201,7 @@ class TestAPI(unittest.TestCase):"""# Re-create read-only model- self.client = TestAPI.start(False)+ self.client = TestEmbeddings.start(False)# Test searchuid = self.client.get("search?query=feel%20good%20story&limit=1").json()[0]["id"]diff --git a/test/python/testapi/testextension.py b/test/python/testapi/testextension.pynew file mode 100644index 00000000..4d4ea9c8--- /dev/null+++ b/test/python/testapi/testextension.py@@ -0,0 +1,110 @@+"""+Extension module tests+"""++import os+import tempfile+import unittest++from unittest.mock import patch++from fastapi import APIRouter+from fastapi.testclient import TestClient++from txtai.api import application, Extension+from txtai.pipeline import Pipeline++# Example pipeline extension+PIPELINES = """+testapi.testextension.SamplePipeline:+"""+++class SampleRouter:+ """+ Sample API router+ """++ router = APIRouter()++ @staticmethod+ @router.get("/sample")+ def sample(text: str):+ """+ Calls sample pipeline.++ Args:+ text: input text++ Returns:+ formatted text+ """++ return application.get().pipeline("testapi.testextension.SamplePipeline", (text,))+++class SampleExtension(Extension):+ """+ Sample API extension+ """++ def __call__(self, app):+ app.include_router(SampleRouter().router)+++class SamplePipeline(Pipeline):+ """+ Sample pipeline+ """++ def __call__(self, text):+ return text.lower()+++class TestExtension(unittest.TestCase):+ """+ API tests for extensions+ """++ @staticmethod+ @patch.dict(+ os.environ,+ {+ "CONFIG": os.path.join(tempfile.gettempdir(), "testapi.yml"),+ "API_CLASS": "txtai.api.API",+ "EXTENSIONS": "testapi.testextension.SampleExtension",+ },+ )+ def start():+ """+ Starts a mock FastAPI client.++ Args:+ full: true if full api configuration should be loaded, otherwise a read-only configuration is used+ """++ config = os.path.join(tempfile.gettempdir(), "testapi.yml")++ with open(config, "w") as output:+ output.write(PIPELINES)++ client = TestClient(application.app)+ application.start()++ return client++ @classmethod+ def setUpClass(cls):+ """+ Create API client on creation of class.+ """++ cls.client = TestExtension.start()++ def testExtension(self):+ """+ Tests a pipeline extension.+ """++ text = self.client.get("sample?text=Test%20String").json()+ self.assertEqual(text, "test string")diff --git a/test/python/testapi/testpipelines.py b/test/python/testapi/testpipelines.pynew file mode 100644index 00000000..77f5c182--- /dev/null+++ b/test/python/testapi/testpipelines.py@@ -0,0 +1,215 @@+"""+Pipeline API module tests+"""++import os+import tempfile+import unittest+import urllib++from unittest.mock import patch++from fastapi.testclient import TestClient++from txtai.api import API, app, start++# pylint: disable = C0411+from utils import Utils++# Configuration for pipelines+PIPELINES = """+# Labels settings+labels:+ path: prajjwal1/bert-medium-mnli++# Enable pipeline similarity backed by zero shot classifier+similarity:++# Summarization+summary:+ path: sshleifer/distilbart-xsum-12-1++# Text extraction+textractor:++# Transcription+transcription:++# Translation:+translation:+"""+++class TestPipelines(unittest.TestCase):+ """+ API tests for pipelines+ """++ @staticmethod+ @patch.dict(os.environ, {"CONFIG": os.path.join(tempfile.gettempdir(), "testapi.yml"), "API_CLASS": "txtai.api.API"})+ def start():+ """+ Starts a mock FastAPI client.++ Args:+ full: true if full api configuration should be loaded, otherwise a read-only configuration is used+ """++ config = os.path.join(tempfile.gettempdir(), "testapi.yml")++ with open(config, "w") as output:+ output.write(PIPELINES)++ client = TestClient(app)+ start()++ return client++ @classmethod+ def setUpClass(cls):+ """+ Create API client on creation of class.+ """++ cls.client = TestPipelines.start()++ 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.text = (+ "Search is the base of many applications. Once data starts to pile up, users want to be able to find it. It’s the foundation "+ "of the internet and an ever-growing challenge that is never solved or done. The field of Natural Language Processing (NLP) is "+ "rapidly evolving with a number of new developments. Large-scale general language models are an exciting new capability "+ "allowing us to add amazing functionality quickly with limited compute and people. Innovation continues with new models "+ "and advancements coming in at what seems a weekly basis. This article introduces txtai, an AI-powered search engine "+ "that enables Natural Language Understanding (NLU) based search in any application."+ )++ def testEmpty(self):+ """+ Test empty API configuration+ """++ api = API({})++ self.assertIsNone(api.label("test", ["test"]))+ self.assertIsNone(api.pipeline("junk", "test"))++ def testLabel(self):+ """+ Test label via API+ """++ labels = self.client.post("label", json={"text": "this is the best sentence ever", "labels": ["positive", "negative"]}).json()++ self.assertEqual(labels[0]["id"], 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]["id"] for l in labels]+ self.assertEqual(results, [0, 1])++ def testSimilarity(self):+ """+ Test similarity via API+ """++ uid = self.client.post("similarity", json={"query": "feel good story", "texts": self.data}).json()[0]["id"]++ 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]["id"] for result in results]+ self.assertEqual(uids, [4, 1])++ def testSummary(self):+ """+ Test summary via API+ """++ summary = self.client.get("summary?text=%s&minlength=10&maxlength=10" % urllib.parse.quote(self.text)).json()+ self.assertEqual(summary, "AI-powered search engine in the world")++ def testSummaryBatch(self):+ """+ Test batch summary via API+ """++ summaries = self.client.post("batchsummary", json={"texts": [self.text, self.text], "maxlength": 10}).json()+ self.assertEqual(len(summaries), 2)++ def testTextractor(self):+ """+ Test textractor via API+ """++ text = self.client.get("textract?file=%s" % Utils.PATH + "/article.pdf").json()++ # Check length of text is as expected+ self.assertEqual(len(text), 2301)++ def testTextractorBatch(self):+ """+ Test batch textractor via API+ """++ path = Utils.PATH + "/article.pdf"++ texts = self.client.post("batchtextract", json=[path, path]).json()+ self.assertEqual(len(texts), 2)++ def testTranscribe(self):+ """+ Test transcribe via API+ """++ text = self.client.get("transcribe?file=%s" % Utils.PATH + "/Make_huge_profits.wav").json()++ # Check length of text is as expected+ self.assertEqual(text, "Make huge profits without working make up to one hundred thousand dollars a day")++ def testTranscribeBatch(self):+ """+ Test batch transcribe via API+ """++ path = Utils.PATH + "/Make_huge_profits.wav"++ texts = self.client.post("batchtranscribe", json=[path, path]).json()+ self.assertEqual(len(texts), 2)++ def testTranslate(self):+ """+ Test translate via API+ """++ translation = self.client.get("translate?text=%s&target=es" % urllib.parse.quote("This is a test translation into Spanish")).json()+ self.assertEqual(translation, "Esta es una traducción de prueba al español")++ def testTranslateBatch(self):+ """+ Test batch translate via API+ """++ text = "This is a test translation into Spanish"+ translations = self.client.post("batchtranslate", json={"texts": [text, text], "target": "es"}).json()+ self.assertEqual(len(translations), 2)