Skip to content

language

Optional local language identification for prepared article bodies.

LanguageDetection dataclass

LanguageDetection(language: str, confidence: float, margin: float, detector: str)

A language candidate with confidence and detector identity.

Attributes:

Name Type Description
language str

Lowercase ISO 639-3 code.

confidence float

Detector score for the best candidate.

margin float

Score difference between the best and second-best candidates.

detector str

Detector identity.

LanguageDetector

Bases: Protocol

Interface for backends implementing detect(text) with a LanguageDetection.

LanguageDetectionError

Bases: ValueError

No language candidate exists, or strict detection rejects weak evidence.

LinguaDetector

LinguaDetector(*, strict: bool = False, min_letters: int = 40, min_confidence: float = 0.8, min_margin: float = 0.2)

Local language identifier with optional confidence thresholds.

Parameters:

Name Type Description Default
strict bool

Reject short text and candidates below the configured thresholds.

False
min_letters int

Minimum alphabetic sample length in strict mode.

40
min_confidence float

Minimum candidate confidence in strict mode.

0.8
min_margin float

Minimum gap from the next candidate in strict mode.

0.2
Source code in src/gdelt_regkg/fields/language.py
def __init__(
    self,
    *,
    strict: bool = False,
    min_letters: int = 40,
    min_confidence: float = 0.8,
    min_margin: float = 0.2,
):
    if not isinstance(strict, bool):
        raise TypeError("strict must be bool")
    if type(min_letters) is not int or min_letters < 0:
        raise ValueError("min_letters must be a nonnegative integer")
    if not 0 <= min_confidence <= 1 or not 0 <= min_margin <= 1:
        raise ValueError("Language detection thresholds must be between 0 and 1")
    builder = require_dependency("lingua", "lang").LanguageDetectorBuilder
    self.backend = builder.from_all_spoken_languages().with_low_accuracy_mode().build()
    self.strict, self.min_letters = strict, min_letters
    self.min_confidence, self.min_margin = min_confidence, min_margin

detect

detect(text: str) -> LanguageDetection

Identify a language candidate using this detector's thresholds.

Source code in src/gdelt_regkg/fields/language.py
def detect(self, text: str) -> LanguageDetection:
    """Identify a language candidate using this detector's thresholds."""
    return self._detect_with(text, self.backend, "lingua/low-accuracy")

confirm

confirm(text: str, supplied: str, candidate: str) -> LanguageDetection

Use full models to compare a proposed correction with the supplied label.

Source code in src/gdelt_regkg/fields/language.py
def confirm(self, text: str, supplied: str, candidate: str) -> LanguageDetection:
    """Use full models to compare a proposed correction with the supplied label."""
    backend = _confirmation_backend(*sorted((supplied, candidate)))
    return self._detect_with(text, backend, "lingua/high-accuracy-confirmation")

detect_language

detect_language(text: str, *, detector: LanguageDetector | None = None) -> LanguageDetection

Identify a language candidate for a prepared article body.

Parameters:

Name Type Description Default
text str

Body to analyze.

required
detector LanguageDetector | None

Custom detector. Defaults to a permissive local Lingua detector.

None

Returns:

Type Description
LanguageDetection

A language code, confidence, margin, and detector identity.

Raises:

Type Description
TypeError

If text or the detector result has an invalid type.

LanguageDetectionError

If no candidate exists or strict thresholds fail.

OptionalDependencyError

If the default detector's dependency is unavailable.

Source code in src/gdelt_regkg/fields/language.py
def detect_language(text: str, *, detector: LanguageDetector | None = None) -> LanguageDetection:
    """Identify a language candidate for a prepared article body.

    Args:
        text: Body to analyze.
        detector: Custom detector. Defaults to a permissive local Lingua detector.

    Returns:
        A language code, confidence, margin, and detector identity.

    Raises:
        TypeError: If `text` or the detector result has an invalid type.
        LanguageDetectionError: If no candidate exists or strict thresholds fail.
        OptionalDependencyError: If the default detector's dependency is unavailable.
    """
    if not isinstance(text, str):
        raise TypeError("text must be str")
    result = (default_language_detector() if detector is None else detector).detect(text)
    if not isinstance(result, LanguageDetection):
        raise TypeError("Language detector must return LanguageDetection")
    return result

script_mismatch

script_mismatch(text: str, language: str) -> bool

Flag a dominant alphabet incompatible with a normalized language label.

Source code in src/gdelt_regkg/fields/language.py
def script_mismatch(text: str, language: str) -> bool:
    """Flag a dominant alphabet incompatible with a normalized language label."""
    expected = _SCRIPTS.get(language, {"LATIN"})
    letters = [unicodedata.name(char, "").split()[0] for char in text[:6000] if char.isalpha()]
    if len(letters) < 40:
        return False
    counts = Counter(letters)
    return sum(counts[script] for script in expected) / len(letters) < 0.3

verify_language

verify_language(text: str, language: str, *, check: LanguageCheck = 'script', detector: LanguageDetector | None = None) -> LanguageDetection | None

Check supplied labels; alphabet conflicts require a confident decision.

Source code in src/gdelt_regkg/fields/language.py
def verify_language(
    text: str,
    language: str,
    *,
    check: LanguageCheck = "script",
    detector: LanguageDetector | None = None,
) -> LanguageDetection | None:
    """Check supplied labels; alphabet conflicts require a confident decision."""
    if check not in {"none", "script", "all"}:
        raise ValueError("language_check must be none, script, or all")
    if check == "none":
        return None
    conflict = script_mismatch(text, language)
    if not conflict and check != "all":
        return None
    # Automatic corrections to a supplied label still need confident evidence.
    backend = default_language_detector(strict=True) if detector is None else detector
    try:
        result = detect_language(text, detector=backend)
        if result.language != language and result.detector == "lingua/low-accuracy":
            if isinstance(backend, LinguaDetector):
                result = backend.confirm(text, language, result.language)
        return result
    except LanguageDetectionError:
        if conflict:
            raise
        return None