Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Fix same-language translation with showmodels enabled

leeshengis4d6cf3d09571
diff --git a/src/python/txtai/pipeline/text/translation.py b/src/python/txtai/pipeline/text/translation.py
index e1d045c4..281a8ac9 100644
--- a/src/python/txtai/pipeline/text/translation.py
+++ b/src/python/txtai/pipeline/text/translation.py
@@ -65,6 +65,7 @@ class Translation(HFModel):
texts: text|list
target: target language code, defaults to "en"
source: source language code, detects language if not provided
+ showmodels: return (text, language, model) tuples, with model set to None when no translation is needed
Returns:
list of translated text
@@ -176,7 +177,7 @@ class Translation(HFModel):
# Return original if already in target language
if source == target:
- return texts
+ return [(None, text) for text in texts] if showmodels else texts
# Load model and tokenizer
path, model, tokenizer = self.lookup(source, target)
diff --git a/test/python/testpipeline/testtext/testtranslation.py b/test/python/testpipeline/testtext/testtranslation.py
index e42b69f4..c6ce369c 100644
--- a/test/python/testpipeline/testtext/testtranslation.py
+++ b/test/python/testpipeline/testtext/testtranslation.py
@@ -4,6 +4,7 @@ Translation module tests
import unittest
import time
+from unittest.mock import patch
import requests
@@ -173,3 +174,29 @@ class TestTranslation(unittest.TestCase):
self.assertEqual(language, "es")
# Validate model
self.assertEqual(modelpath, "Helsinki-NLP/opus-mt-es-en")
+
+
+class TestTranslationSameLanguage(unittest.TestCase):
+ """
+ Model-free same-language translation tests.
+ """
+
+ def testSameLanguage(self):
+ """
+ Test scalar and batched inputs with and without model metadata.
+ """
+
+ translate = Translation(gpu=False, findmodels=False, batch=2)
+ texts = ["hello", "hi", "a", "", " hello ", "This is a long text. " * 100]
+
+ with patch.object(translate, "lookup") as lookup:
+ for showmodels in (False, True):
+ expected = [(text.strip(), "en", None) if showmodels else text.strip() for text in texts]
+ with self.subTest(showmodels=showmodels):
+ self.assertEqual(translate(texts, source="en", target="en", showmodels=showmodels), expected)
+ self.assertEqual(translate([], source="en", target="en", showmodels=showmodels), [])
+ for text, result in zip(texts, expected):
+ with self.subTest(text=text, showmodels=showmodels):
+ self.assertEqual(translate(text, source="en", target="en", showmodels=showmodels), result)
+
+ lookup.assert_not_called()