💡 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
Initial commit
davidmezzetti319bda5c5cb5
diff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..bf2ad57d--- /dev/null+++ b/.gitignore@@ -0,0 +1,6 @@+build/+dist/+*egg-info/+__pycache__/+.coverage+*.pycdiff --git a/.pylintrc b/.pylintrcnew file mode 100644index 00000000..7d65d670--- /dev/null+++ b/.pylintrc@@ -0,0 +1,20 @@+[BASIC]+module-rgx=[a-z_][a-zA-Z0-9_]{2,30}$+method-rgx=[a-z_][a-zA-Z0-9_]{2,30}$+function-rgx=[a-z_][a-zA-Z0-9_]{2,30}$+argument-rgx=[a-z_][a-zA-Z0-9_]{0,30}$+variable-rgx=[a-z_][a-zA-Z0-9_]{0,30}$+attr-rgx=[a-z_][a-zA-Z0-9_]{0,30}$++[DESIGN]+max-args=10+max-locals=40+max-returns=10+max-attributes=20+min-public-methods=0++[FORMAT]+max-line-length=150++[MESSAGES CONTROL]+disable=I0011,R0201,W0105,W0108,W0110,W0141,W0621,W0640diff --git a/LICENSE b/LICENSEnew file mode 100644index 00000000..f0f9a676--- /dev/null+++ b/LICENSE@@ -0,0 +1,190 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ Copyright 2020 NeuML LLC++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.\ No newline at end of filediff --git a/README.md b/README.mdnew file mode 100644index 00000000..20513edf--- /dev/null+++ b/README.md@@ -0,0 +1,20 @@+# txtai: AI-powered search engine++txtai build an AI-powered index over sets of text.++## Installation+You can install txtai directly from GitHub using pip. Using a Python Virtual Environment is recommended.++ pip install git+https://github.com/neuml/txtai++Python 3.6+ is supported++### Notes for Windows+This project has dependencies that require compiling native code. Linux enviroments usually work without an issue. Windows requires the following extra steps.++- Install C++ Build Tools - https://visualstudio.microsoft.com/visual-cpp-build-tools/+- If PyTorch errors are encountered, run the following command before installing paperai. See [pytorch.org](https://pytorch.org) for more information.++ ```+ pip install torch===1.6.0 torchvision===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html+ ```diff --git a/setup.py b/setup.pynew file mode 100644index 00000000..cef4d985--- /dev/null+++ b/setup.py@@ -0,0 +1,45 @@+# pylint: disable = C0111+from setuptools import find_packages, setup++with open("README.md", "r") as f:+ DESCRIPTION = f.read()++setup(name="txtai",+ version="1.0.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=[+ "faiss-gpu>=1.6.3",+ "fasttext>=0.9.2",+ "nltk>=3.5",+ "numpy>=1.18.4",+ "pymagnitude @ git+https://github.com/neuml/magnitude",+ "regex>=2020.5.14",+ "scikit-learn>=0.23.1",+ "torch>=1.4.0",+ "tqdm>=4.46.0",+ "sentence-transformers>=0.3.3",+ "transformers>=3.0.2"+ ],+ 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/__init__.py b/src/python/txtai/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/python/txtai/embeddings.py b/src/python/txtai/embeddings.pynew file mode 100644index 00000000..be93a680--- /dev/null+++ b/src/python/txtai/embeddings.py@@ -0,0 +1,284 @@+"""+Embeddings module+"""++import pickle+import os++import faiss+import numpy as np++from sklearn.decomposition import TruncatedSVD++from .scoring import Scoring+from .vectors import Factory++class Embeddings(object):+ """+ Model that builds sentence embeddings from a list of tokens.++ Optional scoring method can be created to weigh tokens when creating embeddings. Averaging used if no scoring method provided.++ The model also applies principal component analysis using a LSA model. This reduces the noise of common but less+ relevant terms.+ """++ # pylint: disable = W0231+ def __init__(self, config=None):+ """+ Creates a new Embeddings model.++ Args:+ config: embeddings configuration+ """++ # Configuration+ self.config = config++ # Embeddings model+ self.embeddings = None++ # Dimensionality reduction model+ self.lsa = None++ # Embedding scoring method - weighs each word in a sentence+ self.scoring = Scoring.create(self.config["scoring"]) if self.config and self.config.get("scoring") else None++ # Sentence vectors model+ self.model = self.loadVectors(self.config["path"]) if self.config else None++ def loadVectors(self, path):+ """+ Loads a word vector model at path.++ Args:+ path: path to word vector model++ Returns:+ vector model+ """++ return Factory.create(self.config.get("method"), path, True if not self.embeddings else False, self.scoring)++ def score(self, documents):+ """+ Builds a scoring index. Documents are tuples of (id, text|tokens, tags).++ Args:+ documents: list of documents+ """++ if self.scoring:+ # Build scoring index over documents+ self.scoring.index(documents)++ def index(self, documents):+ """+ Builds an embeddings index. Documents are tuples of (id, text|tokens, tags).++ Args:+ documents: list of documents+ """++ # Transform documents to embeddings vectors+ ids, dimensions, stream = self.model.index(documents)++ # Load streamed embeddings back to memory+ embeddings = np.empty((len(ids), dimensions), dtype=np.float32)+ with open(stream, "rb") as queue:+ for x in range(embeddings.shape[0]):+ embeddings[x] = pickle.load(queue)++ # Remove temporary file+ os.remove(stream)++ # Build LSA model (if enabled). Remove principal components from embeddings.+ if self.config.get("pca"):+ self.lsa = self.buildLSA(embeddings, self.config["pca"])+ self.removePC(embeddings)++ # Normalize embeddings+ self.normalize(embeddings)++ # pylint: disable=E1136+ # Create embeddings index. Inner product is equal to cosine similarity on normalized vectors.+ params = "IVF100,SQ8" if embeddings.shape[0] >= 5000 else "IDMap,SQ8"+ self.embeddings = faiss.index_factory(embeddings.shape[1], params, faiss.METRIC_INNER_PRODUCT)++ # Train on embeddings model+ self.embeddings.train(embeddings)+ self.embeddings.add_with_ids(embeddings, np.array(ids))++ def buildLSA(self, embeddings, components):+ """+ Builds a LSA model. This model is used to remove the principal component within embeddings. This helps to+ smooth out noisy embeddings (common words with less value).++ Args:+ embeddings: input embeddings matrix+ components: number of model components++ Returns:+ LSA model+ """++ svd = TruncatedSVD(n_components=components, random_state=0)+ svd.fit(embeddings)++ return svd++ def removePC(self, embeddings):+ """+ Applies a LSA model to embeddings, removed the top n principal components. Operation applied+ directly on array.++ Args:+ embeddings: input embeddings matrix+ """++ pc = self.lsa.components_+ factor = embeddings.dot(pc.transpose())++ # Apply LSA model+ # Calculation is different if n_components = 1+ if pc.shape[0] == 1:+ embeddings -= factor * pc+ elif len(embeddings.shape) > 1:+ # Apply model on a row-wise basis to limit memory usage+ for x in range(embeddings.shape[0]):+ embeddings[x] -= factor[x].dot(pc)+ else:+ # Single embedding+ embeddings -= factor.dot(pc)++ def normalize(self, embeddings):+ """+ Normalizes embeddings using L2 normalization. Operation applied directly on array.++ Args:+ embeddings: input embeddings matrix+ """++ # Calculation is different for matrices vs vectors+ if len(embeddings.shape) > 1:+ embeddings /= np.linalg.norm(embeddings, axis=1)[:, np.newaxis]+ else:+ embeddings /= np.linalg.norm(embeddings)++ def transform(self, document):+ """+ Transforms document into an embeddings vector. Document text will be tokenized if not pre-tokenized.++ Args:+ document: (id, text|tokens, tags)++ Returns:+ embeddings vector+ """++ # Convert document into sentence embedding+ embedding = self.model.transform(document)++ # Reduce the dimensionality of the embeddings. Scale the embeddings using this+ # model to reduce the noise of common but less relevant terms.+ if self.lsa:+ self.removePC(embedding)++ # Normalize embeddings+ self.normalize(embedding)++ return embedding++ def search(self, query, limit=3):+ """+ Finds documents in the vector model most similar to the input document.++ Args:+ query: query text|tokens+ limit: maximum results++ Returns:+ list of topn matched (id, score)+ """++ # Convert tokens to embedding vector+ embedding = self.transform((None, query, None))++ # Search embeddings index+ self.embeddings.nprobe = 6+ results = self.embeddings.search(embedding.reshape(1, -1), limit)++ # Map results to [(id, score)]+ return list(zip(results[1][0].tolist(), (results[0][0]).tolist()))++ def similarity(self, query, documents):+ """+ Computes the similarity between a query and a set of documents++ Args:+ query: query text|tokens+ documents: document text|tokens++ Returns:+ [computed similarity (0 - 1 with 1 being most similar)]+ """++ query = self.transform((None, query, None)).reshape(1, -1)+ documents = np.array([self.transform((None, text, None)) for text in documents])++ # Dot product on normalized vectors is equal to cosine similarity+ return np.dot(query, documents.T)[0]++ def load(self, path):+ """+ Loads a pre-trained model.++ Models have the following files:+ config - configuration+ 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++ Args:+ path: input directory path+ """++ with open("%s/config" % path, "rb") as handle:+ self.config = pickle.load(handle)++ # Sentence embeddings index+ self.embeddings = faiss.read_index("%s/embeddings" % path)++ with open("%s/lsa" % path, "rb") as handle:+ self.lsa = pickle.load(handle)++ # Embedding scoring+ if self.config.get("scoring"):+ self.scoring = Scoring.create(self.config["scoring"])+ self.scoring.load(path)++ # Sentence vectors model+ self.model = self.loadVectors(self.config["path"])++ def save(self, path):+ """+ Saves a model.++ Args:+ path: output directory path+ """++ if self.config:+ with open("%s/config" % path, "wb") as handle:+ pickle.dump(self.config, handle, protocol=pickle.HIGHEST_PROTOCOL)++ # Write sentence embeddings+ faiss.write_index(self.embeddings, "%s/embeddings" % path)++ with open("%s/lsa" % path, "wb") as handle:+ pickle.dump(self.lsa, handle, protocol=pickle.HIGHEST_PROTOCOL)++ # Save embedding scoring+ if self.scoring:+ self.scoring.save(path)diff --git a/src/python/txtai/extractor.py b/src/python/txtai/extractor.pynew file mode 100644index 00000000..08883ded--- /dev/null+++ b/src/python/txtai/extractor.py@@ -0,0 +1,137 @@+"""+Extractor module+"""++from nltk.tokenize import sent_tokenize++from .pipeline import Pipeline+from .tokenizer import Tokenizer++class Extractor(object):+ """+ Class that uses an extractive question-answering model to extract content from a given text context.+ """++ def __init__(self, embeddings, path, quantize=False, tokenizer=None):+ """+ Builds a new extractor.++ Args:+ embeddings: embeddings model+ path: path to qa model+ quantize: True if model should be quantized before inference, False otherwise.+ tokenizer: Tokenizer class+ """++ # Embeddings model and open database cursor+ self.embeddings = embeddings++ # QA Pipeline+ self.pipeline = Pipeline(path, quantize)++ # Tokenizer class use default method if not set+ self.tokenizer = tokenizer if tokenizer else Tokenizer++ def __call__(self, sections, queue):+ """+ Extracts answers to input questions. This method runs queries against a list of text sections, 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)++ Returns:+ extracted answers+ """++ # Tokenize text+ segments, tokenlist = [], []+ for sid, text in sections:+ tokens = self.tokenizer.tokenize(text)+ if tokens:+ segments.append((sid, text))+ tokenlist.append(tokens)++ # Build question-context pairs+ names, questions, contexts, snippets = [], [], [], []+ for name, query, question, snippet in queue:+ # Get list of required tokens+ must = [token.strip("+") for token in query.split() if token.startswith("+")]++ # Tokenize search query+ query = self.tokenizer.tokenize(query)++ # List of matches+ matches = []++ scores = self.embeddings.similarity(query, tokenlist)+ for x, score in enumerate(scores):+ # Get segment text+ text = segments[x][1]++ # Add result if all required tokens are present or there are not required tokens+ if not must or all([token.lower() in text.lower() for token in must]):+ matches.append(segments[x] + (score,))++ # Build context using top n best matching segments+ topn = sorted(matches, key=lambda x: x[2], reverse=True)[:3]+ context = " ".join([text for _, text, _ in sorted(topn, key=lambda x: x[0])])++ names.append(name)+ questions.append(question)+ contexts.append(context)+ snippets.append(snippet)++ # Run qa pipeline and return answers+ return self.answers(names, questions, contexts, snippets)++ def answers(self, names, questions, contexts, snippets):+ """+ Executes QA pipeline and formats extracted answers.++ Args:+ names: column names+ questions: questions+ contexts: question context+ snippets: flags to enable answer snippets per answer+ """++ results = []++ # Run qa pipeline+ answers = self.pipeline(questions, contexts)++ # 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)++ results.append((names[x], value))++ return results++ def snippet(self, context, answer):+ """+ Extracts text surrounding the answer within context.++ Args:+ context: full context+ answer: answer within context++ Returns:+ text surrounding answer as a snippet+ """++ # Searches for first sentence to contain answer+ if answer:+ for x in sent_tokenize(context):+ if answer in x:+ return x++ return answerdiff --git a/src/python/txtai/pipeline.py b/src/python/txtai/pipeline.pynew file mode 100644index 00000000..2d75c8da--- /dev/null+++ b/src/python/txtai/pipeline.py@@ -0,0 +1,146 @@+"""+Pipeline module+"""++import numpy as np+import regex as re+import torch++from transformers import AutoModelForQuestionAnswering, AutoTokenizer++class Pipeline(object):+ """+ Extractive question-answering model.++ Logic based on HuggingFace's transformers QuestionAnswering pipeline.+ """++ def __init__(self, path, quantize):+ """+ Loads a new pipeline model.++ Args:+ path: path to model+ quantize: if model should be quantized+ """++ self.model = AutoModelForQuestionAnswering.from_pretrained(path)+ self.tokenizer = AutoTokenizer.from_pretrained(path)++ if quantize:+ # pylint: disable=E1101+ self.model = torch.quantization.quantize_dynamic(self.model, {torch.nn.Linear}, dtype=torch.qint8)++ def __call__(self, questions, contexts):+ """+ Runs a extractive question-answering model against each question-context pair, finding the best answers.++ Args:+ questions: list of questions+ contexts: list of contexts to pull answers from++ Returns:+ list of answers+ """++ answers = []++ for x, question in enumerate(questions):+ # Encode question and context using model tokenizer+ inputs = self.tokenizer.encode_plus(question, contexts[x], add_special_tokens=True, return_tensors="pt")+ input_ids = inputs["input_ids"].tolist()[0]++ try:+ # Run the input against the model, get candidate start-end pairs+ start, end = self.model(**inputs)+ start, end = start.detach().numpy(), end.detach().numpy()++ # Normalize start and end logits+ start = np.exp(start) / np.sum(np.exp(start))+ end = np.exp(end) / np.sum(np.exp(end))++ # Tokenized questions for BERT models take the format:+ # [CLS] Question [SEP] Answer [SEP]+ # This logic prevents the answer coming from the question+ separator = input_ids.index(self.tokenizer.sep_token_id)+ pmask = np.array([1 if x <= separator else 0 for x in range(len(input_ids))])++ # Mask the question tokens+ start, end = (start * np.abs(np.array(pmask) - 1), end * np.abs(np.array(pmask) - 1))++ tokens, answer = [], None++ start, end, score = self.score(start, end, 15)++ # Require best score to be at least 0.05+ if score >= 0.05:+ # Get span tokens+ tokens = self.tokenizer.convert_ids_to_tokens(input_ids[start:(end + 1)], skip_special_tokens=True)++ # Build regex to match original string+ answer = re.search(self.regex(tokens), contexts[x], re.IGNORECASE)+ answer = answer[0]++ # Add answer+ answers.append({"answer": answer, "score": score})++ # pylint: disable=W0702+ except:+ answers.append({"answer": None, "score": 0.0})++ return answers++ def score(self, start, end, maxlength):+ """+ Scores all possible combinations of start and end index up to maxlength. Returns+ the best match.++ Args:+ start: start index scores+ end: end index scores+ maxlength: max number of tokens to allow in a match++ Returns:+ (start index, end index, score) of best scoring combination+ """++ # Score all possible combinations of start, end indices+ scores = np.matmul(np.expand_dims(start, -1), np.expand_dims(end, 1))++ # Zero out candidates with end < start and end - start > maxlength+ candidates = np.tril(np.triu(scores), maxlength - 1)++ # Get index of best rated combination+ # pylint: disable=E1101+ index = np.argmax(candidates.flatten())++ # Get (start, end, score) of best rated combination+ # pylint: disable=E1126, W0632+ start, end = np.unravel_index(index, candidates.shape)[1:]+ return start, end, candidates[0, start, end]++ def regex(self, tokens):+ """+ Builds a regular expression from tokens.++ Args:+ tokens: input tokens++ Returns:+ regex to use to extract match in original text+ """++ regex = []++ for token in tokens:+ # Escape regex characters+ token = re.escape(token)++ # Handle subwords+ if token.startswith("\\#\\#"):+ token = re.sub(r"^\\#\\#", "", token)++ regex.append(token)++ # Build and return complete regular expression+ return "\\s?".join(regex)diff --git a/src/python/txtai/scoring.py b/src/python/txtai/scoring.pynew file mode 100644index 00000000..46d157f7--- /dev/null+++ b/src/python/txtai/scoring.py@@ -0,0 +1,233 @@+"""+Scoring module+"""++import math+import pickle++from collections import Counter++from .tokenizer import Tokenizer++class Scoring(object):+ """+ Base scoring object. Default method scores documents using TF-IDF.+ """++ @staticmethod+ def create(method):+ """+ Factory method to construct a Scoring object.++ Args:+ method: scoring method (bm25, sif, tfidf)++ Returns:+ Scoring object+ """++ if method == "bm25":+ return BM25()+ elif method == "sif":+ return SIF()+ elif method == "tfidf":+ # Default scoring object implements tf-idf+ return Scoring()++ return None++ def __init__(self):+ """+ Initializes backing statistic objects.+ """++ # Document stats+ self.total = 0+ self.tokens = 0+ self.avgdl = 0++ # Word frequency+ self.docfreq = Counter()+ self.wordfreq = Counter()+ self.avgfreq = 0++ # IDF index+ self.idf = {}+ self.avgidf = 0++ # Tag boosting+ self.tags = Counter()++ def index(self, documents):+ """+ Indexes a collection of documents using a scoring method. Documents are tuples of (id, text|tokens, tags).++ Args:+ documents: input documents+ """++ # Calculate word frequency, total tokens and total documents+ for _, tokens, tags in documents:+ # Convert to tokens if necessary+ if isinstance(tokens, str):+ tokens = Tokenizer.tokenize(tokens)++ # Total number of times token appears, count all tokens+ self.wordfreq.update(tokens)++ # Total number of documents a token is in, count unique tokens+ self.docfreq.update(set(tokens))++ # Get list of unique tags+ if tags:+ self.tags.update(tags.split())++ # Total document count+ self.total += 1++ # Calculate total token frequency+ self.tokens = sum(self.wordfreq.values())++ # Calculate average frequency per token+ self.avgfreq = self.tokens / len(self.wordfreq.values())++ # Calculate average document length in tokens+ self.avgdl = self.tokens / self.total++ # Compute IDF scores+ for word, freq in self.docfreq.items():+ self.idf[word] = self.computeIDF(freq)++ # Average IDF score per token+ 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}++ def weights(self, document):+ """+ Builds weight vector for each token in the input token.++ Args:+ document: (id, tokens, tags)++ Returns:+ list of weights for each token+ """++ # Weights array+ weights = []++ # Unpack document+ _, tokens, _ = document++ # Document length+ length = len(tokens)++ for token in tokens:+ # Lookup frequency and idf score - default to averages if not in repository+ freq = self.wordfreq[token] if token in self.wordfreq else self.avgfreq+ idf = self.idf[token] if token in self.idf else self.avgidf++ # Calculate score for each token, use as weight+ weights.append(self.score(freq, idf, length))++ # Boost weights of tag tokens to match the largest weight in the list+ if self.tags:+ tags = {token: self.tags[token] for token in tokens if token in self.tags}+ if tags:+ 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)]++ return weights++ def load(self, path):+ """+ Loads a saved Scoring object from path.++ Args:+ path: directory path to load model+ """++ with open("%s/scoring" % path, "rb") as handle:+ self.__dict__.update(pickle.load(handle))++ def save(self, path):+ """+ Saves a Scoring object to path.++ Args:+ path: directory path to save model+ """++ with open("%s/scoring" % path, "wb") as handle:+ pickle.dump(self.__dict__, handle, protocol=pickle.HIGHEST_PROTOCOL)++ def computeIDF(self, freq):+ """+ Computes an idf score for word frequency.++ Args:+ freq: word frequency++ Returns:+ idf score+ """++ return math.log(self.total / (1 + freq))++ # pylint: disable=W0613+ def score(self, freq, idf, length):+ """+ Calculates a score for each token.++ Args:+ freq: token frequency+ idf: token idf score+ length: total number of tokens in source document++ Returns:+ token score+ """++ return idf++class BM25(Scoring):+ """+ BM25 scoring. Scores using Apache Lucene's version of BM25 which adds 1 to prevent+ negative scores.+ """++ def __init__(self, k1=0.1, b=0.75):+ super(BM25, self).__init__()++ # BM25 configurable parameters+ self.k1 = k1+ self.b = b++ def computeIDF(self, freq):+ # Calculate BM25 IDF score+ 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__()++ # SIF configurable parameters+ self.a = a++ def score(self, freq, idf, length):+ # Calculate SIF score+ return self.a / (self.a + freq/self.tokens)diff --git a/src/python/txtai/tokenizer.py b/src/python/txtai/tokenizer.pynew file mode 100644index 00000000..52728aa4--- /dev/null+++ b/src/python/txtai/tokenizer.py@@ -0,0 +1,36 @@+"""+Text tokenization methods+"""++import re+import string++class Tokenizer(object):+ """+ Text tokenization methods+ """++ # 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"}++ @staticmethod+ def tokenize(text):+ """+ Tokenizes input text into a list of tokens. Filters tokens that match a specific pattern and removes stop words.++ Args:+ text: input text++ Returns:+ list of tokens+ """++ # Convert to all lowercase, split on whitespace, strip punctuation+ tokens = [token.strip(string.punctuation) for token in text.lower().split()]++ # Tokenize on alphanumeric strings.+ # Require strings to be at least 2 characters long.+ # Require at least 1 alpha character in string.+ return [token for token in tokens if re.match(r"^\d*[a-z][\-.0-9:_a-z]{1,}$", token) and token not in Tokenizer.STOP_WORDS]diff --git a/src/python/txtai/vectors.py b/src/python/txtai/vectors.pynew file mode 100644index 00000000..ca65d641--- /dev/null+++ b/src/python/txtai/vectors.py@@ -0,0 +1,263 @@+"""+Vectors module+"""++import os+import pickle+import tempfile++from errno import ENOENT+from multiprocessing import Pool++import fasttext+import numpy as np++from pymagnitude import converter, Magnitude+from sentence_transformers import SentenceTransformer+from sentence_transformers.models import Pooling, Transformer++from .tokenizer import Tokenizer++# Multiprocessing helper methods+# pylint: disable=W0603+VECTORS = None++def create(path, scoring, blocking):+ """+ Multiprocessing helper method. Creates a global embeddings object to be accessed in a new+ subprocess.++ Args:+ config: configuration+ scoring: scoring instance+ """++ global VECTORS++ # Create a global embedding object using configuration and saved+ VECTORS = WordVectors(path, blocking, scoring)++def transform(document):+ """+ Multiprocessing helper method. Transforms document tokens into an embedding.++ Args:+ document: (id, text|tokens, tags)++ Returns:+ (id, embedding)+ """++ global VECTORS++ return (document[0], VECTORS.transform(document))++class Factory(object):+ """+ Creates a new Vectors model instance.+ """++ @staticmethod+ def create(method, path, blocking, scoring):+ """+ Create a Vectors model instance.++ Args:+ path: path to word vector model+ blocking: True if method should wait until vectors fully loaded before returning, false otherwise+ """++ # Create vector model instance+ return TransformersVectors(path) if method == "transformers" else WordVectors(path, blocking, scoring)++class Vectors(object):+ """+ Base class for sentence embeddings/vector models.+ """++ def load(self, path, blocking):+ """+ Loads vector model at path.++ Args:+ path: path to word vector model+ blocking: True if method should wait until vectors fully loaded before returning, false otherwise++ Returns:+ vector model+ """++ def index(self, documents):+ """+ Converts a list of document tokens to a temporary file with embeddings arrays. Documents are tuples of (id, text|tokens, tags).+ Returns a tuple of document ids, number of dimensions and temporary file with embeddings.++ Args:+ documents: list of documents++ Returns:+ (ids, dimensions, stream)+ """++ def transform(self, document):+ """+ Transforms document into an embeddings vector.++ Args:+ document: (id, text|tokens, tags)++ Returns:+ embeddings vector+ """++class WordVectors(Vectors):+ """+ Builds sentence embeddings/vectors using weighted word embeddings.+ """++ def __init__(self, path, blocking, scoring):+ self.model = self.load(path, blocking)++ # Store parameters+ self.path = path+ self.blocking = blocking+ self.scoring = scoring++ def load(self, path, blocking):+ # Require that vector path exists, if a path is provided and it's not found, Magnitude will try download from it's servers+ if not path or not os.path.isfile(path):+ raise IOError(ENOENT, "Vector model file not found", path)++ # Load magnitude model. If this is a training run (no embeddings yet), block until the vectors are fully loaded+ return Magnitude(path, case_insensitive=True, blocking=blocking)++ def index(self, documents):+ ids, dimensions, stream = [], None, None++ # Shared objects with Pool+ args = (self.path, self.scoring, self.blocking)++ # Convert all documents to embedding arrays, stream embeddings to disk to control memory usage+ with Pool(os.cpu_count(), initializer=create, initargs=args) as pool:+ with tempfile.NamedTemporaryFile(mode="wb", suffix=".npy", delete=False) as output:+ stream = output.name+ for uid, embedding in pool.imap(transform, documents):+ if not dimensions:+ # Set number of dimensions for embeddings+ dimensions = embedding.shape[0]++ ids.append(uid)+ pickle.dump(embedding, output)++ return (ids, dimensions, stream)++ def transform(self, document):+ # Convert to tokens if necessary+ if isinstance(document[1], str):+ document = (document[0], Tokenizer.tokenize(document[1]), document[2])++ # Generate weights for each vector using a scoring method+ weights = self.scoring.weights(document) if self.scoring else None++ # pylint: disable=E1133+ if weights and [x for x in weights if x > 0]:+ # Build weighted average embeddings vector. Create weights array os float32 to match embeddings precision.+ embedding = np.average(self.lookup(document[1]), weights=np.array(weights, dtype=np.float32), axis=0)+ else:+ # If no weights, use mean+ embedding = np.mean(self.lookup(document[1]), axis=0)++ return embedding++ def lookup(self, tokens):+ """+ Queries word vectors for given list of input tokens.++ Args:+ tokens: list of tokens to query++ Returns:+ word vectors array+ """++ return self.model.query(tokens)++ @staticmethod+ def build(data, size, mincount, path):+ """+ Builds fastText vectors from a file.++ Args:+ data: path to input data file+ size: number of vector dimensions+ mincount: minimum number of occurrences required to register a token+ path: path to output file+ """++ # Train on data file using largest dimension size+ model = fasttext.train_unsupervised(data, dim=size, minCount=mincount)++ # Output file path+ print("Building %d dimension model" % size)++ # Output vectors in vec/txt format+ with open(path + ".txt", "w") as output:+ words = model.get_words()+ output.write("%d %d\n" % (len(words), model.get_dimension()))++ for word in words:+ # Skip end of line token+ if word != "</s>":+ vector = model.get_word_vector(word)+ data = ""+ for v in vector:+ data += " " + str(v)++ output.write(word + data + "\n")++ # Build magnitude vectors database+ 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.+ """++ def __init__(self, path):+ # Sentence transformer model+ self.model = self.load(path, True)++ # Store parameters+ self.path = path++ def load(self, path, blocking):+ model = Transformer(path)+ pooling = Pooling(model.get_word_embedding_dimension())++ return SentenceTransformer(modules=[model, pooling])++ def index(self, documents):+ ids, dimensions, stream = [], None, None++ # Convert all documents to embedding arrays, stream embeddings to disk to control memory usage+ with tempfile.NamedTemporaryFile(mode="wb", suffix=".npy", delete=False) as output:+ stream = output.name+ for document in documents:+ embedding = self.transform(document)+ if not dimensions:+ # Set number of dimensions for embeddings+ dimensions = embedding.shape[0]++ ids.append(document[0])+ pickle.dump(embedding, output)++ return (ids, dimensions, stream)++ def transform(self, document):+ # Convert to tokens if necessary+ if isinstance(document[1], str):+ document = (document[0], Tokenizer.tokenize(document[1]), document[2])++ return self.model.encode([" ".join(document[1])])[0]+\ No newline at end of file