💡 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
Resolve label filters by label id (#1216)
Morgan Carr396b3b80659d
diff --git a/src/python/txtai/pipeline/text/labels.py b/src/python/txtai/pipeline/text/labels.pyindex e43d3661..5afd49ea 100644--- a/src/python/txtai/pipeline/text/labels.py+++ b/src/python/txtai/pipeline/text/labels.py@@ -120,19 +120,17 @@ class Labels(HFPipeline):result = [(config.label2id.get(x["label"], 0), x["score"]) for x in result]if labels:+ # Map lowercase label names to label ids+ names = {x.lower(): uid for x, uid in config.label2id.items()}+matches = []for label in labels:- # Lookup label keys from model config- if label.isdigit():- label = int(label)- keys = list(config.id2label.keys())- else:- label = label.lower()- keys = [x.lower() for x in config.label2id.keys()]+ # Resolve label to a label id, by id or by name+ uid = int(label) if label.isdigit() else names.get(label.lower())- # Find and add label match- if label in keys:- matches.append(keys.index(label))+ # Add label match, if found+ if uid in config.id2label:+ matches.append(uid)return [(label, score) for label, score in result if label in matches]diff --git a/test/python/testpipeline/testtext/testlabels.py b/test/python/testpipeline/testtext/testlabels.pyindex 029316f1..6b050574 100644--- a/test/python/testpipeline/testtext/testlabels.py+++ b/test/python/testpipeline/testtext/testlabels.py@@ -83,3 +83,21 @@ class TestLabels(unittest.TestCase):# Verify resultsself.assertEqual(labels("This is the best sentence ever", flatten=True)[0], "POSITIVE")self.assertEqual(labels("This is the best sentence ever", multilabel=True, flatten=True)[0], "POSITIVE")++ def testLabelFixedLimit(self):+ """+ Test labels with a fixed label text classification model, limited to requested labels by name and by id+ """++ labels = Labels(dynamic=False)++ # Rotate the config label mappings so insertion order no longer matches label ids+ config = labels.pipeline.model.config+ ids = list(config.id2label)+ config.id2label = {x: config.id2label[x] for x in ids[1:] + ids[:1]}+ config.label2id = {label: x for x, label in config.id2label.items()}++ # Verify requested labels resolve to label ids, not positions in the config label mappings+ for label, uid in config.label2id.items():+ self.assertEqual(labels("This is the best sentence ever", labels=[label.lower()])[0][0], uid)+ self.assertEqual(labels("This is the best sentence ever", labels=[str(uid)])[0][0], uid)diff --git a/test/python/testpipeline/testtext/testsimilarity.py b/test/python/testpipeline/testtext/testsimilarity.pyindex 9bb3c0c7..47b881fd 100644--- a/test/python/testpipeline/testtext/testsimilarity.py+++ b/test/python/testpipeline/testtext/testsimilarity.py@@ -69,6 +69,29 @@ class TestSimilarity(unittest.TestCase):uid = similarity(premise, [entailment, contradiction], labels=["1"])[0][0]self.assertEqual(uid, 0)+ def testCrossEncoderLabelsOrder(self):+ """+ Test cross-encoder labels resolve to label ids when the model config's label order differs from id order+ """++ similarity = Similarity("prajjwal1/bert-medium-mnli", crossencode=True)++ premise = "A dog is running in the park."+ texts = ["An animal is outside.", "The park is empty and there are no animals."]++ # Scores restricted to LABEL_1 with the model config as loaded+ expected = similarity(premise, texts, labels=["1"])++ # Rotate the config label mappings so insertion order no longer matches label ids+ config = similarity.pipeline.model.config+ ids = list(config.id2label)+ config.id2label = {x: config.id2label[x] for x in ids[1:] + ids[:1]}+ config.label2id = {label: x for x, label in config.id2label.items()}++ # Verify the same label is scored when requested by name and by id+ self.assertEqual(similarity(premise, texts, labels=["LABEL_1"]), expected)+ self.assertEqual(similarity(premise, texts, labels=["1"]), expected)+def testCrossEncoderLabelsInvalid(self):"""Test cross-encoder raises an error when no requested label matches the model