💡 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 additional tokenization methods for keyword search, closes #1006
davidmezzetti7132f63c4662
diff --git a/src/python/txtai/pipeline/data/tokenizer.py b/src/python/txtai/pipeline/data/tokenizer.pyindex c7a401aa..f731aaa2 100644--- a/src/python/txtai/pipeline/data/tokenizer.py+++ b/src/python/txtai/pipeline/data/tokenizer.py@@ -14,10 +14,15 @@ class Tokenizer(Pipeline):"""Tokenizes text into tokens using one of the following methods.- 1. Backwards compatible tokenization that only accepts alphanumeric tokens from the Latin alphabet.-- 2. Split using word boundary rules from the Unicode Text Segmentation algorithm (see Unicode Standard Annex #29).+ 1. Split using word boundary rules from the Unicode Text Segmentation algorithm (see Unicode Standard Annex #29).This is similar to the standard tokenizer in Apache Lucene and works well for most languages.++ 2. Tokenization method that only accepts alphanumeric tokens from the Latin alphabet. This is a backwards compatible mode+ that was the default with older versions of txtai.++ 3. Tokenize on whitespace++ 4. Tokenize using a provided regular expression"""# fmt: off@@ -28,7 +33,7 @@ class Tokenizer(Pipeline):# fmt: on@staticmethod- def tokenize(text, lowercase=True, emoji=True, alphanum=True, stopwords=True):+ def tokenize(text, lowercase=True, emoji=True, alphanum=True, stopwords=True, whitespace=False, regexp=None):"""Tokenizes text into a list of tokens. The default backwards compatible parameters filter out English stop words and onlyaccept alphanumeric tokens.@@ -39,15 +44,17 @@ class Tokenizer(Pipeline):emoji: tokenize emoji in text if True, defaults to Truealphanum: requires 2+ character alphanumeric tokens if True, defaults to Truestopwords: removes provided stop words if a list, removes default English stop words if True, defaults to True+ whitespace: tokenize on whitespace if True, defaults to False+ regexp: tokenize using the provided regular expression, defaults to NoneReturns:list of tokens"""# Create a tokenizer with backwards compatible settings- return Tokenizer(lowercase, emoji, alphanum, stopwords)(text)+ return Tokenizer(lowercase, emoji, alphanum, stopwords, whitespace, regexp)(text)- def __init__(self, lowercase=True, emoji=True, alphanum=False, stopwords=False):+ def __init__(self, lowercase=True, emoji=True, alphanum=False, stopwords=False, whitespace=False, regexp=None):"""Creates a new tokenizer. The default parameters segment text per Unicode Standard Annex #29.@@ -56,19 +63,24 @@ class Tokenizer(Pipeline):emoji: tokenize emoji in text if True, defaults to Truealphanum: requires 2+ character alphanumeric tokens if True, defaults to Falsestopwords: removes provided stop words if a list, removes default English stop words if True, defaults to False+ whitespace: tokenize on whitespace if True, defaults to False+ regexp: tokenize using the provided regular expression, defaults to None"""# Lowercaseself.lowercase = lowercase# Text segmentation- self.alphanum, self.segment = None, None+ self.alphanum, self.whitespace, self.regexp, self.segment = None, whitespace, None, Noneif alphanum:# Alphanumeric regex that accepts tokens that meet following rules:# - Strings to be at least 2 characters long AND# - At least 1 non-trailing alpha character in string# Note: The standard Python re module is much faster than regex for this expressionself.alphanum = re.compile(r"^\d*[a-z][\-.0-9:_a-z]{1,}$")+ elif regexp:+ # Regular expression for tokenization+ self.regexp = regex.compile(regexp)else:# Text segmentation per Unicode Standard Annex #29pattern = r"\w\p{Extended_Pictographic}\p{WB:RegionalIndicator}" if emoji else r"\w"@@ -101,6 +113,12 @@ class Tokenizer(Pipeline):# Filter on alphanumeric strings.tokens = [token for token in tokens if re.match(self.alphanum, token)]+ elif self.whitespace:+ # Text segmentation using whitespace+ tokens = text.split()+ elif self.regexp:+ # Text segmentation using a custom regular expression+ tokens = regex.findall(self.regexp, text)else:# Text segmentation per Unicode Standard Annex #29tokens = regex.findall(self.segment, text)diff --git a/test/python/testscoring/testkeyword.py b/test/python/testscoring/testkeyword.pyindex 8b84a537..71d53a01 100644--- a/test/python/testscoring/testkeyword.py+++ b/test/python/testscoring/testkeyword.py@@ -150,6 +150,7 @@ class TestKeyword(unittest.TestCase):self.empty(config)self.copy(config)self.settings(config)+ self.tokenization(config)def index(self, config, data=None):"""@@ -419,3 +420,30 @@ class TestKeyword(unittest.TestCase):# Validate countsself.assertEqual(scoring.count(), len(self.data))++ def tokenization(self, config):+ """+ Test tokenization methods.++ Args:+ config: scoring config+ """++ # Test whitespace tokenization+ config = {**config, **{"terms": True, "tokenizer": {"whitespace": True}}}++ # Create scoring instance+ scoring = ScoringFactory.create(config)+ scoring.index([(0, "abc-def-123", None)])++ self.assertEqual(scoring.search("abc-def-123")[0][0], 0)++ # Test regular expression tokenization+ config = {**config, **{"tokenizer": {"regexp": r"\w{5,}"}}}++ # Create scoring instance+ scoring = ScoringFactory.create(config)+ scoring.index([(0, "hello test", None)])++ self.assertEqual(scoring.search("hello")[0][0], 0)+ self.assertFalse(scoring.search("test"))