Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Add scoring-based search, closes #327

davidmezzetti215196a74810
diff --git a/src/python/txtai/scoring/base.py b/src/python/txtai/scoring/base.py
index d220fee8..9a7d09d9 100644
--- a/src/python/txtai/scoring/base.py
+++ b/src/python/txtai/scoring/base.py
@@ -14,19 +14,29 @@ from ..pipeline import Tokenizer
class Scoring:
"""
- Base scoring object. Default method scores documents using TF-IDF.
+ Base scoring. Uses term frequency-inverse document frequency (TF-IDF).
"""
- def __init__(self):
+ def __init__(self, config=None):
"""
Initializes backing statistic objects.
+
+ Args:
+ config: input configuration
"""
+ # Scoring configuration
+ self.config = config if config else {}
+
# Document stats
self.total = 0
self.tokens = 0
self.avgdl = 0
+ # Document data
+ self.documents = {} if self.config.get("content") else None
+ self.docterms = {} if self.config.get("terms") else None
+
# Word frequency
self.docfreq = Counter()
self.wordfreq = Counter()
@@ -47,11 +57,60 @@ class Scoring:
documents: list of (id, dict|text|tokens, tags)
"""
+ # Parse documents
+ tokenlists = self.parse(documents)
+
+ # 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}
+
+ # Process document terms, if necessary
+ self.terms(tokenlists)
+
+ def parse(self, documents):
+ """
+ Parses document stats, word frequencies and data from documents.
+
+ Args:
+ docments: list of (id, dict|text|tokens, tags)
+
+ Returns:
+ tokenlists: list of parsed documents when term parsing is enabled, empty dict otherwise
+ """
+
+ # Store tokenlists when term indexing enabled
+ tokenlists = {}
+
# 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)
+ for uid, data, tags in documents:
+ if self.documents is not None:
+ self.documents[uid] = data
+
+ # Extract text, if necessary
+ if isinstance(data, dict):
+ data = data.get("text")
+
+ # Convert to tokens, if necessary
+ tokens = Tokenizer.tokenize(data) if isinstance(data, str) else data
+
+ # Save tokens for term indexing
+ if self.docterms is not None:
+ tokenlists[uid] = tokens
# Total number of times token appears, count all tokens
self.wordfreq.update(tokens)
@@ -66,24 +125,25 @@ class Scoring:
# Total document count
self.total += 1
- # Calculate total token frequency
- self.tokens = sum(self.wordfreq.values())
+ return tokenlists
- # Calculate average frequency per token
- self.avgfreq = self.tokens / len(self.wordfreq.values())
+ def terms(self, tokenlist):
+ """
+ Add term weights for each tokenized document in tokenlist.
- # Calculate average document length in tokens
- self.avgdl = self.tokens / self.total
+ Args:
+ tokenlist: list of tokenized documents
+ """
- # Compute IDF scores
- for word, freq in self.docfreq.items():
- self.idf[word] = self.computeidf(freq)
+ for uid in tokenlist:
+ tokens = tokenlist[uid]
+ weights = self.weights(tokens)
- # Average IDF score per token
- self.avgidf = sum(self.idf.values()) / len(self.idf)
+ for x, token in enumerate(tokens):
+ if token not in self.docterms:
+ self.docterms[token] = {}
- # Filter for tags that appear in at least 1% of the documents
- self.tags = {tag: number for tag, number in self.tags.items() if number >= self.total * 0.005}
+ self.docterms[token][uid] = weights[x]
def weights(self, tokens):
"""
@@ -102,13 +162,15 @@ class Scoring:
# Document length
length = len(tokens)
+ # Calculate token counts
+ freq = self.computefreq(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
+ # Lookup idf score
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))
+ weights.append(self.score(freq[token], idf, length))
# Boost weights of tag tokens to match the largest weight in the list
if self.tags:
@@ -121,6 +183,64 @@ class Scoring:
return weights
+ def search(self, query, limit=3):
+ """
+ Search index for documents matching query. Request terms config parameter to be enabled.
+
+ Args:
+ query: input query
+ limit: maximum results
+
+ Returns:
+ list of (id, score) or (data, score) if content is enabled
+ """
+
+ # Check if document terms available
+ if self.docterms:
+ query = Tokenizer.tokenize(query)
+
+ scores = {}
+ for token in query:
+ if token in self.docterms:
+ for x in self.docterms[token]:
+ if x not in scores:
+ scores[x] = 0.0
+
+ scores[x] += self.docterms[token][x]
+
+ # Sort and get topn results
+ topn = sorted(scores.items(), key=lambda x: x[1], reverse=True)[:limit]
+
+ # Format results and add content if available
+ return self.results(topn)
+
+ return None
+
+ def results(self, topn):
+ """
+ Resolves a list of (id, score) with document content, if available. Otherwise, the original input is returned.
+
+ Args:
+ topn: list of (id, score)
+
+ Returns:
+ resolved results
+ """
+
+ if self.documents:
+ results = []
+ for x, score in topn:
+ if self.documents:
+ data = self.documents[x]
+ if isinstance(data, dict):
+ results.append({"id": x, "text": data.get("text"), "score": score, "data": data})
+ else:
+ results.append({"id": x, "text": data, "score": score})
+
+ return results
+
+ return topn
+
def load(self, path):
"""
Loads a saved Scoring object from path.
@@ -156,6 +276,19 @@ class Scoring:
return math.log(self.total / (1 + freq))
+ def computefreq(self, tokens):
+ """
+ Computes token frequency.
+
+ Args:
+ tokens: input tokens
+
+ Returns:
+ {token: count}
+ """
+
+ return Counter(tokens)
+
# pylint: disable=W0613
def score(self, freq, idf, length):
"""
@@ -170,4 +303,4 @@ class Scoring:
token score
"""
- return idf
+ return (freq / length) * idf
diff --git a/src/python/txtai/scoring/bm25.py b/src/python/txtai/scoring/bm25.py
index 3fca5f01..266cba8f 100644
--- a/src/python/txtai/scoring/bm25.py
+++ b/src/python/txtai/scoring/bm25.py
@@ -9,16 +9,15 @@ from .base import Scoring
class BM25(Scoring):
"""
- BM25 scoring. Scores using Apache Lucene's version of BM25 which adds 1 to prevent
- negative scores.
+ Best matching (BM25) scoring.
"""
- def __init__(self, k1=0.1, b=0.75):
- super().__init__()
+ def __init__(self, config=None):
+ super().__init__(config)
# BM25 configurable parameters
- self.k1 = k1
- self.b = b
+ self.k1 = self.config.get("k1", 0.1)
+ self.b = self.config.get("b", 0.75)
def computeidf(self, freq):
# Calculate BM25 IDF score
diff --git a/src/python/txtai/scoring/factory.py b/src/python/txtai/scoring/factory.py
index 413c69b5..015e93b0 100644
--- a/src/python/txtai/scoring/factory.py
+++ b/src/python/txtai/scoring/factory.py
@@ -13,23 +13,29 @@ class ScoringFactory:
"""
@staticmethod
- def create(method):
+ def create(config):
"""
Factory method to construct a Scoring object.
Args:
- method: scoring method (bm25, sif, tfidf)
+ config: scoring configuration parameters - supports bm25, sif, tfidf
Returns:
Scoring
"""
+ # Support string and dict configuration
+ if isinstance(config, str):
+ config = {"method": config}
+
+ method = config.get("method") if config else None
+
if method == "bm25":
- return BM25()
+ return BM25(config)
if method == "sif":
- return SIF()
+ return SIF(config)
if method == "tfidf":
# Default scoring object implements tf-idf
- return Scoring()
+ return Scoring(config)
return None
diff --git a/src/python/txtai/scoring/sif.py b/src/python/txtai/scoring/sif.py
index 308ee899..d222ce58 100644
--- a/src/python/txtai/scoring/sif.py
+++ b/src/python/txtai/scoring/sif.py
@@ -10,11 +10,16 @@ class SIF(Scoring):
Smooth Inverse Frequency (SIF) scoring.
"""
- def __init__(self, a=0.001):
- super().__init__()
+ def __init__(self, config=None):
+ super().__init__(config)
# SIF configurable parameters
- self.a = a
+ self.a = self.config.get("a", 0.001)
+
+ def computefreq(self, tokens):
+ # Default method computes frequency for a single entry
+ # SIF uses word probabilities across entire index
+ return self.wordfreq
def score(self, freq, idf, length):
# Calculate SIF score
diff --git a/test/python/testscoring.py b/test/python/testscoring.py
index 7435a0bd..0636d7fe 100644
--- a/test/python/testscoring.py
+++ b/test/python/testscoring.py
@@ -37,24 +37,21 @@ class TestScoring(unittest.TestCase):
Test bm25
"""
- self.method("bm25")
- self.weights("bm25")
+ self.runTests("bm25")
def testSIF(self):
"""
Test sif
"""
- self.method("sif")
- self.weights("sif")
+ self.runTests("sif")
def testTFIDF(self):
"""
Test tfidf
"""
- self.method("tfidf")
- self.weights("tfidf")
+ self.runTests("tfidf")
def testUnknown(self):
"""
@@ -63,12 +60,27 @@ class TestScoring(unittest.TestCase):
self.assertIsNone(ScoringFactory.create("unknown"))
- def method(self, method, data=None):
+ def runTests(self, method):
"""
- Runs scoring method.
+ Runs a series of tests for a scoring method.
Args:
method: scoring method
+ """
+
+ config = {"method": method}
+
+ self.index(config)
+ self.weights(config)
+ self.search(config)
+ self.content(config)
+
+ def index(self, config, data=None):
+ """
+ Test scoring index method.
+
+ Args:
+ config: scoring config
data: data to index with scoring method
Returns:
@@ -78,7 +90,7 @@ class TestScoring(unittest.TestCase):
# Derive input data
data = data if data else self.data
- model = ScoringFactory.create(method)
+ model = ScoringFactory.create(config)
model.index(data)
keys = [k for k, v in sorted(model.idf.items(), key=lambda x: x[1])]
@@ -89,6 +101,9 @@ class TestScoring(unittest.TestCase):
# Test save/load
self.assertIsNotNone(self.save(model))
+ # Test search returns none when terms disabled (default)
+ self.assertIsNone(model.search("query"))
+
return model
def save(self, model):
@@ -111,17 +126,17 @@ class TestScoring(unittest.TestCase):
return model
- def weights(self, method):
+ def weights(self, config):
"""
Test standard and tag weighted scores.
Args:
- method: scoring method
+ config: scoring config
"""
document = (1, ["bear", "wins"], None)
- model = self.method(method)
+ model = self.index(config)
weights = model.weights(document[1])
# Default weights
@@ -132,8 +147,50 @@ class TestScoring(unittest.TestCase):
uid, text, _ = data[3]
data[3] = (uid, text, "wins")
- model = self.method(method, data)
+ model = self.index(config, data)
weights = model.weights(document[1])
# Modified weights
self.assertEqual(weights[0], weights[1])
+
+ def search(self, config):
+ """
+ Test scoring search.
+
+ Args:
+ method: scoring method
+ """
+
+ model = ScoringFactory.create({**config, **{"terms": True}})
+ model.index(self.data)
+
+ # Run search and validate correct result returned
+ index, _ = model.search("bear", 1)[0]
+ self.assertEqual(index, 3)
+
+ def content(self, config):
+ """
+ Test scoring search with content.
+
+ Args:
+ config: scoring config
+ """
+
+ model = ScoringFactory.create({**config, **{"terms": True, "content": True}})
+ model.index(self.data)
+
+ # Test text with content
+ text = "Great news today"
+ model.index([(model.total, text, None)])
+
+ # Run search and validate correct result returned
+ result = model.search("great news", 1)[0]["text"]
+ self.assertEqual(result, text)
+
+ # Test reading text from dictionary
+ text = "Feel good story: baby panda born"
+ model.index([(model.total, {"text": text}, None)])
+
+ # Run search and validate correct result returned
+ result = model.search("feel good story", 1)[0]["text"]
+ self.assertEqual(result, text)