Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix: make LanguageDetector minimum text length configurable (#1284)

Wei Tao9c0289622359
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 430dfce8..426e8ae9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -60,6 +60,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `Relation`, `Triplet` and the separate `utils.types.Entity` are untouched; the LLM, HuggingFace, pattern and regex paths always set explicit float scores and are unchanged
- Docs: `semantica/semantic_extract/semantic_extract_usage.md` and `cookbook/introduction/05_Entity_Extraction.ipynb` (renders unavailable confidence as `N/A`)
+### Changed
+
+- **`LanguageDetector` minimum text length is now configurable** (closes #1281) by @taoche
+ - **New `min_text_length` option** (default unchanged at 10 stripped characters), settable per instance via `LanguageDetector(min_text_length=...)`, per call via `**options` on every detection API, and through `detect_language()`. Ten characters is reasonable for Latin scripts and far too many for CJK — a 9-character Chinese string never reached `langdetect` at all
+ - `UNKNOWN_LANGUAGE` (`"unknown"`) is now exported from `semantica.normalize` as an explicit out-of-band sentinel. Pass `LanguageDetector(default_language=UNKNOWN_LANGUAGE)` to opt into an unambiguous fallback that is distinct from every ISO language code
+ - The default fallback remains `"en"` — no breaking change for existing callers
+ - `detect()` and `detect_with_confidence()` now delegate to `detect_multiple()`, so the length guard, the fallback and the error handling exist once rather than in three copies that can drift
+ - Invalid `min_text_length` values (`None`, non-numeric strings, negatives) degrade to the fallback with a warning instead of raising `TypeError` from the length comparison, which sits outside the detection exception handlers
+ - Unrecognized per-call option names (e.g. `min_text_len`) now warn once per name per instance instead of being silently absorbed by `**options`
+ - `detect_language()` copies the stored method config before merging per-call kwargs, so a one-call override no longer leaks into the shared `normalize_config`
+ - Docs: `docs/reference/normalize.md` and `semantica/normalize/normalize_usage.md`
+
## [0.7.0] - 2026-09-07
### Changed
diff --git a/docs/reference/normalize.md b/docs/reference/normalize.md
index 3765db9a..e98489fb 100644
--- a/docs/reference/normalize.md
+++ b/docs/reference/normalize.md
@@ -440,7 +440,19 @@ utf8_text = handle_encoding(raw_bytes, operation="convert")
```
<Note>
- `detect()` requires at least 10 characters for reliable detection. On shorter text it returns the `default_language` (default: `"en"`).
+ `detect()` skips detection on text shorter than `min_text_length` (default: 10 stripped characters) and returns the `default_language` instead. The fallback defaults to `"en"` (backward-compatible). Pass `default_language=UNKNOWN_LANGUAGE` to get an explicit `"unknown"` signal that is distinct from every ISO language code. Both `default_language` and `min_text_length` are configurable, per instance or per call:
+
+ ```python
+ # Lower the threshold for CJK, where 10 characters is far more than needed
+ detector = LanguageDetector(min_text_length=4)
+ detector.detect("短いテキスト") # → "ja"
+
+ # Per-call override
+ LanguageDetector().detect("短いテキスト", min_text_length=4) # → "ja"
+
+ # Opt into an unambiguous out-of-band sentinel instead of the "en" default
+ LanguageDetector(default_language="unknown").detect("Hi") # → "unknown"
+ ```
</Note>
<Warning>
diff --git a/semantica/normalize/__init__.py b/semantica/normalize/__init__.py
index 8ee5dd59..671cef89 100644
--- a/semantica/normalize/__init__.py
+++ b/semantica/normalize/__init__.py
@@ -143,7 +143,7 @@ from .entity_normalizer import (
EntityNormalizer,
NameVariantHandler,
)
-from .language_detector import LanguageDetector
+from .language_detector import UNKNOWN_LANGUAGE, LanguageDetector
from .methods import (
clean_data,
clean_text,
@@ -208,6 +208,7 @@ __all__ = [
"TextCleaner",
# Language detection
"LanguageDetector",
+ "UNKNOWN_LANGUAGE",
# Encoding handling
"EncodingHandler",
# Registry and Methods
diff --git a/semantica/normalize/language_detector.py b/semantica/normalize/language_detector.py
index 8c7521e2..682f89b3 100644
--- a/semantica/normalize/language_detector.py
+++ b/semantica/normalize/language_detector.py
@@ -11,6 +11,7 @@ Key Features:
- Batch processing
- Top N language detection
- Language code to name mapping
+ - Configurable minimum text length and fallback language
Main Classes:
- LanguageDetector: Language detection coordinator
@@ -29,7 +30,7 @@ License: MIT
from typing import Any, Dict, List, Optional, Tuple, Union
try:
- from langdetect import detect, detect_langs
+ from langdetect import detect_langs
from langdetect.lang_detect_exception import LangDetectException
LANGDETECT_AVAILABLE = True
@@ -41,6 +42,27 @@ from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
+# Returned when no detection was performed (text too short, langdetect
+# unavailable) or detection failed. Distinct from every ISO language code,
+# so callers can never mistake a fallback for a detected language.
+#
+# Design note: unlike entity confidence (see semantic_extract.types, where
+# missing measurements are represented as None), the unknown language is an
+# out-of-band *string* rather than None. Language codes flow into dict keys,
+# file names and other string operations throughout the pipeline, so None
+# would trade one ambiguity for a crash surface; "unknown" stays inside the
+# str domain while remaining impossible to confuse with a real code. For
+# confidence there is no out-of-band float — every number is a plausible
+# score — hence None is the only honest representation there.
+UNKNOWN_LANGUAGE = "unknown"
+
+DEFAULT_MIN_TEXT_LENGTH = 10
+
+# Per-call options accepted by the detection APIs. Anything else is almost
+# certainly a typo (e.g. min_text_len) and is reported instead of being
+# silently ignored.
+KNOWN_DETECTION_OPTIONS = frozenset({"min_text_length"})
+
class LanguageDetector:
"""
@@ -55,6 +77,7 @@ class LanguageDetector:
- Batch processing
- Top N language detection
- Language code to name mapping
+ - Configurable minimum text length and fallback language
Example Usage:
>>> detector = LanguageDetector()
@@ -67,17 +90,31 @@ class LanguageDetector:
"""
Initialize language detector.
- Sets up the detector with default language and minimum confidence threshold.
+ Sets up the fallback language, the confidence threshold and the
+ minimum text length required to run detection.
Args:
**config: Configuration options:
- - default_language: Default language code (default: "en")
+ - default_language: Language code returned when no detection
+ was performed or detection failed (default: ``"en"``).
+ Set to ``UNKNOWN_LANGUAGE`` (``"unknown"``) to get an
+ explicit out-of-band signal instead of assuming a language.
- min_confidence: Minimum confidence threshold (default: 0.5)
+ - min_text_length: Minimum stripped-text length required to run
+ detection (default: 10). Inputs shorter than this return the
+ fallback (``default_language``) instead of a detected
+ language. Lower this for language mixes where short inputs
+ carry enough signal (e.g. CJK text).
"""
self.logger = get_logger("language_detector")
self.config = config
self.default_language = config.get("default_language", "en")
self.min_confidence = config.get("min_confidence", 0.5)
+ self.min_text_length = self._normalize_min_text_length(
+ config.get("min_text_length", DEFAULT_MIN_TEXT_LENGTH),
+ DEFAULT_MIN_TEXT_LENGTH,
+ )
+ self._warned_options = set()
if not LANGDETECT_AVAILABLE:
self.logger.warning(
@@ -94,41 +131,79 @@ class LanguageDetector:
f"Language detector initialized (default={self.default_language})"
)
+ def _normalize_min_text_length(self, value: Any, fallback: int) -> int:
+ """Coerce a min_text_length value to a non-negative int.
+
+ Invalid values (None, non-numeric strings, ...) must degrade to the
+ fallback instead of raising during the length comparison, where no
+ detection exception handler protects the caller.
+ """
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ self.logger.warning(
+ f"Invalid min_text_length {value!r}, using {fallback}"
+ )
+ return fallback
+
+ def _resolve_min_text_length(self, options: Dict[str, Any]) -> int:
+ """Resolve the minimum text length, allowing per-call override."""
+ if "min_text_length" not in options:
+ return self.min_text_length
+ return self._normalize_min_text_length(
+ options["min_text_length"], self.min_text_length
+ )
+
+ def _cannot_detect(self, text: str, options: Dict[str, Any]) -> bool:
+ """True when detection cannot run for this input.
+
+ Detection is skipped when the stripped text is shorter than
+ ``min_text_length`` or when the langdetect library is unavailable;
+ callers must return the ``default_language`` fallback in that case.
+ """
+ if not text or len(text.strip()) < self._resolve_min_text_length(options):
+ return True
+ return not LANGDETECT_AVAILABLE
+
+ def _warn_unknown_options(self, options: Dict[str, Any]) -> None:
+ """Report option names that no detection API understands.
+
+ **options would otherwise swallow typos silently (e.g. min_text_len),
+ making the caller believe an override took effect when nothing
+ happened. Warns once per unknown name per detector instance so batch
+ calls do not flood the log.
+ """
+ unknown = set(options) - KNOWN_DETECTION_OPTIONS - self._warned_options
+ if unknown:
+ self._warned_options |= unknown
+ self.logger.warning(
+ f"Ignoring unknown detection option(s) {sorted(unknown)}; "
+ f"supported options: {sorted(KNOWN_DETECTION_OPTIONS)}"
+ )
+
def detect(self, text: str, **options) -> str:
"""
Detect language of text.
- This method detects the language of input text using langdetect.
- Returns the default language if detection fails or text is too short.
+ Returns the most likely language code regardless of confidence; use
+ detect_with_confidence() to apply the min_confidence threshold.
Args:
text: Input text to analyze
- **options: Detection options (unused)
+ **options: Detection options:
+ - min_text_length: Override the instance-level minimum text
+ length for this call
Returns:
str: Detected language code (e.g., "en", "fr", "de")
Note:
- Requires minimum text length of 10 characters for reliable detection.
- Returns default_language if text is too short or detection fails.
+ Inputs whose stripped length is below ``min_text_length``
+ (default: 10) never reach the underlying detector; the configured
+ ``default_language`` (``"en"`` unless overridden) is returned
+ as a fallback. The same fallback is returned if detection fails.
"""
- if not text or len(text.strip()) < 10:
- return self.default_language
-
- if not LANGDETECT_AVAILABLE:
- return self.default_language
-
- try:
- language = detect(text)
- return language
- except LangDetectException:
- self.logger.warning(
- f"Failed to detect language, using default: {self.default_language}"
- )
- return self.default_language
- except Exception as e:
- self.logger.error(f"Language detection error: {e}")
- return self.default_language
+ return self.detect_multiple(text, top_n=1, **options)[0][0]
def detect_with_confidence(self, text: str, **options) -> Tuple[str, float]:
"""
@@ -136,41 +211,29 @@ class LanguageDetector:
This method detects the language of text and returns both the language
code and confidence score. Only returns detected language if confidence
- meets the minimum threshold.
+ meets the minimum threshold; otherwise the configured
+ ``default_language`` is returned with the observed confidence.
Args:
text: Input text to analyze
- **options: Detection options (unused)
+ **options: Detection options:
+ - min_text_length: Override the instance-level minimum text
+ length for this call
Returns:
tuple: (language_code, confidence_score) where:
- language_code: Detected language code
- confidence_score: Confidence score between 0.0 and 1.0
- """
- if not text or len(text.strip()) < 10:
- return (self.default_language, 0.0)
- if not LANGDETECT_AVAILABLE:
- return (self.default_language, 0.0)
-
- try:
- languages = detect_langs(text)
- if languages:
- top_language = languages[0]
- if top_language.prob >= self.min_confidence:
- return (top_language.lang, top_language.prob)
- else:
- return (self.default_language, top_language.prob)
- else:
- return (self.default_language, 0.0)
- except LangDetectException:
- self.logger.warning(
- f"Failed to detect language, using default: {self.default_language}"
- )
- return (self.default_language, 0.0)
- except Exception as e:
- self.logger.error(f"Language detection error: {e}")
- return (self.default_language, 0.0)
+ Note:
+ Inputs whose stripped length is below ``min_text_length`` return
+ ``(default_language, 0.0)`` as a fallback; the 0.0 confidence
+ signals that no detection was performed.
+ """
+ language, confidence = self.detect_multiple(text, top_n=1, **options)[0]
+ if confidence >= self.min_confidence:
+ return (language, confidence)
+ return (self.default_language, confidence)
def detect_multiple(
self, text: str, top_n: int = 3, **options
@@ -178,22 +241,29 @@ class LanguageDetector:
"""
Detect top N languages with confidence scores.
- This method detects multiple candidate languages for text, returning
- the top N languages sorted by confidence.
+ This is the single detection core: detect() and
+ detect_with_confidence() delegate here, so guard, fallback and
+ error-handling semantics live in exactly one place.
Args:
text: Input text to analyze
top_n: Number of top languages to return (default: 3)
- **options: Detection options (unused)
+ **options: Detection options:
+ - min_text_length: Override the instance-level minimum text
+ length for this call
Returns:
list: List of (language_code, confidence_score) tuples, sorted by
confidence (highest first)
+
+ Note:
+ Inputs whose stripped length is below ``min_text_length`` return
+ ``[(default_language, 0.0)]`` as a fallback; the 0.0 confidence
+ signals that no detection was performed.
"""
- if not text or len(text.strip()) < 10:
- return [(self.default_language, 0.0)]
+ self._warn_unknown_options(options)
- if not LANGDETECT_AVAILABLE:
+ if self._cannot_detect(text, options):
return [(self.default_language, 0.0)]
try:
@@ -289,6 +359,7 @@ class LanguageDetector:
Returns uppercase code if name not found.
"""
language_names = {
+ UNKNOWN_LANGUAGE: "Unknown",
"en": "English",
"fr": "French",
"de": "German",
diff --git a/semantica/normalize/methods.py b/semantica/normalize/methods.py
index fd058362..6f2a8847 100644
--- a/semantica/normalize/methods.py
+++ b/semantica/normalize/methods.py
@@ -707,15 +707,19 @@ def detect_language(
return result
try:
- config = normalize_config.get_method_config("language")
+ # Copy before merging: get_method_config() returns the stored dict by
+ # reference, and per-call kwargs must not leak into the global config
+ config = dict(normalize_config.get_method_config("language"))
config.update(kwargs)
detector = LanguageDetector(**config)
+ # kwargs were already consumed by the constructor above; forwarding
+ # them again would trip the detector's unknown-option warning
if method == "confidence":
- return detector.detect_with_confidence(text, **kwargs)
+ return detector.detect_with_confidence(text)
else:
- return detector.detect(text, **kwargs)
+ return detector.detect(text)
except Exception as e:
logger.error(f"Failed to detect language: {e}")
diff --git a/semantica/normalize/normalize_usage.md b/semantica/normalize/normalize_usage.md
index c13f446c..161c881e 100644
--- a/semantica/normalize/normalize_usage.md
+++ b/semantica/normalize/normalize_usage.md
@@ -458,6 +458,25 @@ detector = LanguageDetector()
language = detector.detect("Bonjour le monde")
```
+Inputs whose stripped length is below `min_text_length` (default: 10) are not
+detected; the configured `default_language` is returned as a fallback (with a
+`0.0` confidence in the confidence-returning APIs). The fallback defaults to
+`"en"` (backward-compatible). Pass `default_language="unknown"` to get an
+explicit out-of-band signal that is distinct from every ISO language code.
+Lower the threshold for language mixes where short inputs carry enough signal,
+e.g. CJK text:
+
+```python
+from semantica.normalize import LanguageDetector
+
+detector = LanguageDetector(min_text_length=5)
+language = detector.detect("你好,这是中文文本") # zh-cn
+
+# Or override per call
+detector = LanguageDetector()
+language = detector.detect("你好,这是中文文本", min_text_length=5)
+```
+
### Confidence
```python
diff --git a/tests/normalize/test_language_detector.py b/tests/normalize/test_language_detector.py
index 2f10fc29..fd1f160a 100644
--- a/tests/normalize/test_language_detector.py
+++ b/tests/normalize/test_language_detector.py
@@ -2,6 +2,7 @@ import unittest
from semantica.normalize.language_detector import (
LANGDETECT_AVAILABLE,
+ UNKNOWN_LANGUAGE,
LanguageDetector,
)
@@ -25,10 +26,16 @@ class TestLanguageDetector(unittest.TestCase):
self.detector.detect("Dies ist ein einfacher deutscher Satz."), "de"
)
- def test_detect_short_text(self):
- # Should return default for very short text
+ def test_detect_short_text_returns_default(self):
+ # Below-threshold input returns the configured default language
self.assertEqual(self.detector.detect("Hi"), "en")
+ def test_configured_default_language_is_returned_for_short_text(self):
+ # default_language is returned whenever detection is skipped;
+ # UNKNOWN_LANGUAGE can be passed explicitly for an out-of-band signal
+ detector_unknown = LanguageDetector(default_language=UNKNOWN_LANGUAGE)
+ self.assertEqual(detector_unknown.detect("Hi"), UNKNOWN_LANGUAGE)
+
@unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")
def test_detect_with_confidence(self):
lang, conf = self.detector.detect_with_confidence(
@@ -37,9 +44,255 @@ class TestLanguageDetector(unittest.TestCase):
self.assertEqual(lang, "en")
self.assertGreater(conf, 0.5)
+ def test_default_min_text_length_preserved(self):
+ # Backward compatibility: default threshold stays at 10
+ self.assertEqual(self.detector.min_text_length, 10)
+ self.assertEqual(self.detector.detect("Short txt"), "en")
+
+ def test_short_text_fallback_has_zero_confidence(self):
+ # Fallback can be distinguished from a genuine detection via 0.0 confidence
+ lang, conf = self.detector.detect_with_confidence("Hi")
+ self.assertEqual((lang, conf), ("en", 0.0))
+ self.assertEqual(
+ self.detector.detect_multiple("Hi"), [("en", 0.0)]
+ )
+
+ @unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")
+ def test_short_non_latin_text_with_configured_threshold(self):
+ # 9 stripped chars: below the default threshold, falls back to default
+ text = "你好,这是中文文本"
+ self.assertEqual(self.detector.detect(text), "en")
+
+ # A configured threshold lets short CJK text reach the detector
+ detector = LanguageDetector(min_text_length=5)
+ self.assertTrue(detector.detect(text).startswith("zh"))
+
+ lang, conf = detector.detect_with_confidence(text)
+ self.assertTrue(lang.startswith("zh"))
+ self.assertGreater(conf, 0.5)
+
+ languages = detector.detect_multiple(text)
+ self.assertTrue(languages[0][0].startswith("zh"))
+
+ @unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")
+ def test_min_text_length_per_call_override(self):
+ text = "你好,这是中文文本"
+ self.assertEqual(self.detector.detect(text), "en")
+ self.assertTrue(
+ self.detector.detect(text, min_text_length=5).startswith("zh")
+ )
+
+ def test_min_text_length_still_guards_empty_text(self):
+ detector = LanguageDetector(min_text_length=0)
+ self.assertEqual(detector.detect(""), "en")
+ self.assertEqual(
+ detector.detect_with_confidence(""), ("en", 0.0)
+ )
+
+ @unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")
+ def test_min_text_length_zero_allows_nonempty_short_text(self):
+ # min_text_length=0 disables the length guard for non-empty input:
+ # the text reaches langdetect and a real language code is returned.
+ # We verify detection actually ran by checking the confidence is > 0.0
+ # rather than asserting the specific language (detection is non-deterministic).
+ detector = LanguageDetector(min_text_length=0)
+ result = detector.detect("Hi")
+ self.assertIsInstance(result, str)
+ self.assertNotEqual(result, detector.default_language)
+
+ # detect_multiple likewise runs and returns a non-zero confidence
+ langs = detector.detect_multiple("Hi")
+ self.assertTrue(len(langs) > 0)
+ self.assertGreater(langs[0][1], 0.0)
+
+ def test_invalid_min_text_length_degrades_to_fallback(self):
+ # Invalid values must not raise TypeError during the length check
+ for invalid in (None, "abc", object()):
+ detector = LanguageDetector(min_text_length=invalid)
+ self.assertEqual(detector.min_text_length, 10)
+ self.assertEqual(detector.detect("Hi"), "en")
+
+ # Invalid per-call override falls back to the instance value
+ detector = LanguageDetector(min_text_length=3)
+ self.assertEqual(
+ detector.detect("Hi", min_text_length=None), "en"
+ )
+
+ # Numeric-ish values are coerced; negatives clamp to zero
+ self.assertEqual(LanguageDetector(min_text_length="5").min_text_length, 5)
+ self.assertEqual(LanguageDetector(min_text_length=-1).min_text_length, 0)
+ self.assertEqual(LanguageDetector(min_text_length=2.9).min_text_length, 2)
+
+ def test_detect_batch_respects_min_text_length(self):
+ # Batch APIs forward **options to detect/detect_with_confidence,
+ # so min_text_length overrides must work at both constructor and
+ # per-call level for detect_batch and detect_batch_with_confidence.
+ cjk = "你好,这是中文文本" # 9 stripped chars, below the default threshold of 10
+ mixed = [cjk, cjk]
+
+ # Default threshold blocks CJK text -> all fallbacks
+ self.assertEqual(
+ self.detector.detect_batch(mixed),
+ ["en", "en"],
+ )
+ self.assertEqual(
+ self.detector.detect_batch_with_confidence(mixed),
+ [("en", 0.0), ("en", 0.0)],
+ )
+
+ @unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")
+ def test_detect_batch_min_text_length_constructor_override(self):
+ cjk = "你好,这是中文文本"
+ mixed = [cjk, cjk]
+
+ # Constructor-level threshold lets CJK text through
+ detector = LanguageDetector(min_text_length=5)
+ results = detector.detect_batch(mixed)
+ self.assertEqual(len(results), 2)
+ self.assertTrue(all(r.startswith("zh") for r in results))
+
+ conf_results = detector.detect_batch_with_confidence(mixed)
+ self.assertEqual(len(conf_results), 2)
+ self.assertTrue(all(lang.startswith("zh") for lang, _ in conf_results))
+ self.assertTrue(all(conf > 0.5 for _, conf in conf_results))
+
+ @unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")
+ def test_detect_batch_min_text_length_per_call_override(self):
+ cjk = "你好,这是中文文本"
+ mixed = [cjk, cjk]
+
+ # Per-call override on a default-threshold detector
+ results = self.detector.detect_batch(mixed, min_text_length=5)
+ self.assertEqual(len(results), 2)
+ self.assertTrue(all(r.startswith("zh") for r in results))
+
+ conf_results = self.detector.detect_batch_with_confidence(
+ mixed, min_text_length=5
+ )
+ self.assertEqual(len(conf_results), 2)
+ self.assertTrue(all(lang.startswith("zh") for lang, _ in conf_results))
+
+ @unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")
+ def test_detect_uses_detect_langs_not_detect(self):
+ # The PR refactored detect() to delegate to detect_multiple(), which
+ # calls detect_langs() rather than the top-level langdetect.detect().
+ # This test pins that contract: detect() must return detect_langs()[0].lang,
+ # not an independent call to langdetect.detect().
+ #
+ # We mock detect_langs at the module level used by language_detector so the
+ # test is deterministic and does not depend on the non-deterministic
+ # langdetect profile selection.
+ from unittest.mock import MagicMock, patch
+
+ fake_lang = MagicMock()
+ fake_lang.lang = "de"
+ fake_lang.prob = 0.99
+
+ detector = LanguageDetector(min_text_length=5)
+ target = "semantica.normalize.language_detector.detect_langs"
+ with patch(target, return_value=[fake_lang]) as mock_detect_langs:
+ result = detector.detect("Hello world this is text")
+
+ mock_detect_langs.assert_called_once()
+ self.assertEqual(result, "de")
+
+ # detect_with_confidence must use the same path: it returns
+ # (fake_lang.lang, fake_lang.prob) because 0.99 >= min_confidence 0.5
+ with patch(target, return_value=[fake_lang]):
+ lang, conf = detector.detect_with_confidence("Hello world this is text")
+ self.assertEqual(lang, "de")
+ self.assertAlmostEqual(conf, 0.99)
+
+ def test_detect_language_wrapper_does_not_mutate_global_config(self):
+ from semantica.normalize.config import normalize_config
+ from semantica.normalize.methods import detect_language
+
+ original = dict(normalize_config.get_method_config("language"))
+ normalize_config.set_method_config("language", default_language="en")
+ try:
+ detect_language("Hi", min_text_length=1)
+ self.assertNotIn(
+ "min_text_length",
+ normalize_config.get_method_config("language"),
+ )
+ finally:
+ normalize_config.set_method_config("language", **original)
+
+ def test_unknown_option_names_are_reported_not_swallowed(self):
+ from unittest.mock import patch
+
+ detector = LanguageDetector(min_text_length=5)
+ with patch.object(detector, "logger") as mock_logger:
+ # Typo'd option name: must warn instead of silently ignoring
+ detector.detect("Hi", min_text_len=1)
+ detector.detect("Hi", min_text_len=1)
+
+ warnings = [
+ call.args[0] for call in mock_logger.warning.call_args_list
+ ]
+ self.assertEqual(len(warnings), 1) # once per name, not per call
+ self.assertIn("min_text_len", warnings[0])
+
+ # Valid option names must not warn (threshold high enough that the
+ # guard short-circuits before any langdetect call can log)
+ with patch.object(detector, "logger") as mock_logger:
+ detector.detect("Hi", min_text_length=100)
+ mock_logger.warning.assert_not_called()
+
+ @unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")
+ def test_detect_apis_share_one_semantic_core(self):
+ # detect() and detect_with_confidence() delegate to detect_multiple(),
+ # so all three must agree on the same input.
+ text = "Ceci est une phrase française simple."
+ top_lang, top_conf = self.detector.detect_multiple(text, top_n=1)[0]
+ self.assertEqual(self.detector.detect(text), top_lang)
+ lang, conf = self.detector.detect_with_confidence(text)
+ self.assertEqual(lang, top_lang)
+ self.assertGreater(conf, 0.5)
+
+ def test_detect_apis_consistent_below_threshold(self):
+ # All three APIs must agree when the guard short-circuits: same
+ # fallback language and the same 0.0 sentinel confidence.
+ text = "Hi" # len=2, below default threshold of 10
+ self.assertEqual(self.detector.detect(text), "en")
+ self.assertEqual(
+ self.detector.detect_with_confidence(text), ("en", 0.0)
+ )
+ self.assertEqual(
+ self.detector.detect_multiple(text), [("en", 0.0)]
+ )
+
+ @unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")
+ def test_detect_ignores_min_confidence_detect_with_confidence_applies_it(self):
+ # detect() returns the best-matching language regardless of
+ # min_confidence; detect_with_confidence() substitutes the fallback
+ # when the top confidence is below the threshold. This tests the
+ # behavioral split between the two APIs.
+ text = "Ceci est une phrase française simple."
+ # A min_confidence just above what langdetect actually returns forces
+ # detect_with_confidence() to fall back, while detect() is unaffected.
+ detector = LanguageDetector(min_confidence=0.9999999)
+
+ # detect() returns the raw winner regardless of the threshold
+ top_lang = detector.detect(text)
+ self.assertNotEqual(top_lang, UNKNOWN_LANGUAGE)
+
+ # detect_with_confidence() applies the threshold: confidence fell
+ # short, so the fallback language is returned. The confidence is the
+ # real observed score (not 0.0, which is reserved for the length-guard
+ # path) — we only verify the structural invariants here since
+ # langdetect's probability is non-deterministic across calls.
+ lang, conf = detector.detect_with_confidence(text)
+ self.assertEqual(lang, detector.default_language)
+ self.assertGreater(conf, 0.0) # real score, not the 0.0 sentinel
+ self.assertLess(conf, 0.9999999) # below the configured threshold
+
def test_get_language_name(self):
self.assertEqual(self.detector.get_language_name("en"), "English")
self.assertEqual(self.detector.get_language_name("fr"), "French")
+ self.assertEqual(
+ self.detector.get_language_name(UNKNOWN_LANGUAGE), "Unknown"
+ )
self.assertEqual(self.detector.get_language_name("xx"), "XX")