Skip to content

themes

Literal theme matching with source-text character offsets.

ThemeRule dataclass

ThemeRule(theme: str, phrase: str, requires_all: tuple[tuple[str, ...], ...] = (), exclude_any: tuple[str, ...] = ())

A theme label and literal phrase with document-wide context conditions.

Each requires_all group needs at least one matching phrase. Any matching exclude_any phrase suppresses the rule.

ThemeLexicon dataclass

ThemeLexicon(name: str, rules: tuple[ThemeRule, ...])

Reusable named collection of literal theme rules.

Matching uses casefolded token sequences, including punctuation, and ignores whitespace between tokens. Context conditions apply across the document.

from_mapping classmethod

from_mapping(themes: Mapping[str, Iterable[str]], *, name: str = 'custom') -> ThemeLexicon

Build a lexicon from theme codes mapped to collections of phrases.

Parameters:

Name Type Description Default
themes Mapping[str, Iterable[str]]

Theme codes and their literal matching phrases.

required
name str

Source or version identifier.

'custom'

Returns:

Type Description
ThemeLexicon

A compiled lexicon ready for analyze_themes.

Source code in src/gdelt_regkg/fields/themes.py
@classmethod
def from_mapping(
    cls, themes: Mapping[str, Iterable[str]], *, name: str = "custom"
) -> ThemeLexicon:
    """Build a lexicon from theme codes mapped to collections of phrases.

    Args:
        themes: Theme codes and their literal matching phrases.
        name: Source or version identifier.

    Returns:
        A compiled lexicon ready for `analyze_themes`.
    """
    rules: list[ThemeRule] = []
    for theme, phrases in themes.items():
        if isinstance(phrases, str):
            raise TypeError("Each theme must map to a collection of phrases, not a string")
        rules.extend(ThemeRule(theme, phrase) for phrase in phrases)
    return cls(name, tuple(rules))

from_json classmethod

from_json(path: str | Path) -> ThemeLexicon

Load source-neutral rules or a legacy theme-code mapping.

Source code in src/gdelt_regkg/fields/themes.py
@classmethod
def from_json(cls, path: str | Path) -> ThemeLexicon:
    """Load source-neutral rules or a legacy theme-code mapping."""
    data = json.loads(Path(path).read_text(encoding="utf-8"))
    if "schema" in data:
        from .rule_inputs import theme_lexicon_from_input

        return theme_lexicon_from_input(data)
    return cls.from_mapping(data["themes"], name=data["name"])

ThemeMention dataclass

ThemeMention(theme: str, start: int, end: int, text: str)

A theme code and matched text with zero-based start and exclusive end offsets.

ThemeResult dataclass

ThemeResult(mentions: tuple[ThemeMention, ...], lexicon_name: str)

Theme matches in source order and the name of the lexicon used.

to_gkg

to_gkg(*, enhanced: bool = False) -> str

Serialize standard or enhanced theme entries.

Parameters:

Name Type Description Default
enhanced bool

Include offsets for every mention. Standard output keeps distinct theme codes in first-match order.

False

Returns:

Type Description
str

Semicolon-terminated entries, or an empty string for no matches.

Source code in src/gdelt_regkg/fields/themes.py
def to_gkg(self, *, enhanced: bool = False) -> str:
    """Serialize standard or enhanced theme entries.

    Args:
        enhanced: Include offsets for every mention. Standard output keeps
            distinct theme codes in first-match order.

    Returns:
        Semicolon-terminated entries, or an empty string for no matches.
    """
    if enhanced:
        return "".join(f"{m.theme},{m.start};" for m in self.mentions)
    return "".join(code + ";" for code in dict.fromkeys(m.theme for m in self.mentions))

analyze_themes

analyze_themes(text: str, *, lexicon: ThemeLexicon | None = None) -> ThemeResult

Match literal theme phrases while preserving source character offsets.

Repeated and overlapping matches are retained. Context conditions inspect the whole document; offsets identify each rule's matching phrase.

Parameters:

Name Type Description Default
text str

Prepared body in the lexicon's language.

required
lexicon ThemeLexicon | None

Reusable theme rules. Defaults to the configured local profile.

None

Returns:

Type Description
ThemeResult

Theme mentions in source order and the lexicon identity.

Raises:

Type Description
TypeError

If text or lexicon has an invalid type.

ResourceUnavailableError

If the default local profile is unavailable.

Source code in src/gdelt_regkg/fields/themes.py
def analyze_themes(text: str, *, lexicon: ThemeLexicon | None = None) -> ThemeResult:
    """Match literal theme phrases while preserving source character offsets.

    Repeated and overlapping matches are retained. Context conditions inspect
    the whole document; offsets identify each rule's matching phrase.

    Args:
        text: Prepared body in the lexicon's language.
        lexicon: Reusable theme rules. Defaults to the configured local profile.

    Returns:
        Theme mentions in source order and the lexicon identity.

    Raises:
        TypeError: If `text` or `lexicon` has an invalid type.
        ResourceUnavailableError: If the default local profile is unavailable.
    """
    if not isinstance(text, str):
        raise TypeError("text must be str")
    lexicon = default_theme_lexicon() if lexicon is None else lexicon
    if not isinstance(lexicon, ThemeLexicon):
        raise TypeError("lexicon must be ThemeLexicon")
    tokens = list(_TOKEN.finditer(text))
    values = [m.group().casefold() for m in tokens]
    present = set()
    if lexicon._context_trie:
        for i in range(len(tokens)):
            node = lexicon._context_trie
            for j in range(i, len(tokens)):
                child = node.get(values[j])
                if child is None:
                    break
                node = child
                present.update(node.get(None, ()))
    allowed = []
    for rule in lexicon.rules:

        def seen(phrase):
            return tuple(token.casefold() for token in _TOKEN.findall(phrase)) in present

        allowed.append(
            all(any(seen(p) for p in group) for group in rule.requires_all)
            and not any(seen(p) for p in rule.exclude_any)
        )
    mentions = {}
    for i, token in enumerate(tokens):
        node = lexicon._trie
        for j in range(i, len(tokens)):
            child = node.get(values[j])
            if child is None:
                break
            node = child
            for index in node.get(None, ()):
                if not allowed[index]:
                    continue
                theme = lexicon.rules[index].theme
                end = tokens[j].end()
                mentions[theme, token.start(), end] = ThemeMention(
                    theme, token.start(), end, text[token.start() : end]
                )
    return ThemeResult(
        tuple(sorted(mentions.values(), key=lambda m: (m.start, m.theme, m.end))), lexicon.name
    )