Skip to content

counts

Event-related quantity extraction from English text.

CountRules dataclass

CountRules(name: str, triggers: Mapping[str, str | tuple[str, ...]], active_triggers: tuple[str, ...], object_nouns: tuple[str, ...], auxiliaries: tuple[str, ...], unsafe_phrases: tuple[str, ...], unsafe_suffixes: tuple[str, ...], bad_object_words: tuple[str, ...], max_object_modifiers: int = 3, context_words: int = 10, patterns: tuple[dict, ...] = (), allow_bare_active: bool = False, reject_time_objects: bool = False, empty_object_nouns: tuple[str, ...] = ())

Named vocabulary, context bounds, and templates for count extraction.

Trigger phrases map to one or more count labels. Load custom rule files with from_json and reuse the compiled rules across documents.

from_json classmethod

from_json(path: str | Path) -> CountRules

Load source-neutral rule input or the legacy count-rules object.

Source code in src/gdelt_regkg/fields/counts.py
@classmethod
def from_json(cls, path: str | Path) -> CountRules:
    """Load source-neutral rule input or the legacy count-rules object."""
    data = json.loads(Path(path).read_text(encoding="utf-8"))
    if "schema" in data:
        from .rule_inputs import count_rules_from_input

        return count_rules_from_input(data)
    return cls.from_dict(data)

CountLocation dataclass

CountLocation(start: int, end: int, geo_type: str = '', full_name: str = '', country_code: str = '', adm1_code: str = '', latitude: str = '', longitude: str = '', feature_id: str = '')

Resolved geography for attaching a location to a count mention.

start and end delimit a source-text span. Geographic components use GKG location types and compatible FIPS/GNS/GNIS identifiers; empty values are allowed.

CountMention dataclass

CountMention(count_type: str, number: int, object_type: str, start: int, end: int, trigger_start: int, location: CountLocation | None = None)

An event label, exact quantity, object description, and optional geography.

start identifies the quantity, end ends the matched construction, and trigger_start identifies its trigger. Offsets are zero-based characters.

CountIssue dataclass

CountIssue(start: int, end: int, reason: str)

A rejected count candidate's start, exclusive end, and rejection reason.

CountResult dataclass

CountResult(mentions: tuple[CountMention, ...], issues: tuple[CountIssue, ...], profile_name: str = PROFILE, empty_object_nouns: tuple[str, ...] = ())

Count mentions, rejected candidates, and the extraction profile name.

empty_object_nouns identifies object labels omitted during serialization.

to_gkg

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

Serialize standard or enhanced count entries.

Parameters:

Name Type Description Default
enhanced bool

Append each quantity's source character offset.

False

Returns:

Type Description
str

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

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

    Args:
        enhanced: Append each quantity's source character offset.

    Returns:
        Semicolon-terminated entries, or an empty string for no matches.
    """
    return "".join(
        (
            replace(m, object_type="")
            if m.object_type.casefold() in self.empty_object_nouns
            else m
        ).to_gkg(enhanced=enhanced)
        + ";"
        for m in self.mentions
    )

analyze_counts

analyze_counts(text: str, *, locations: Iterable[CountLocation] = (), rules: CountRules | None = None) -> CountResult

Extract event-related quantities using English vocabulary and templates.

Parameters:

Name Type Description Default
text str

Prepared English body.

required
locations Iterable[CountLocation]

Resolved geographic spans for this body. Counts use the nearest supplied location.

()
rules CountRules | None

Reusable count rules. Defaults to the configured profile.

None

Returns:

Type Description
CountResult

Count mentions and diagnostics for rejected trigger matches.

Raises:

Type Description
TypeError

If text, rules, or locations have invalid types.

ValueError

If a supplied location extends beyond the body.

ResourceUnavailableError

If the default profile is unavailable.

Source code in src/gdelt_regkg/fields/counts.py
def analyze_counts(
    text: str, *, locations: Iterable[CountLocation] = (), rules: CountRules | None = None
) -> CountResult:
    """Extract event-related quantities using English vocabulary and templates.

    Args:
        text: Prepared English body.
        locations: Resolved geographic spans for this body. Counts use the nearest
            supplied location.
        rules: Reusable count rules. Defaults to the configured profile.

    Returns:
        Count mentions and diagnostics for rejected trigger matches.

    Raises:
        TypeError: If text, rules, or locations have invalid types.
        ValueError: If a supplied location extends beyond the body.
        ResourceUnavailableError: If the default profile is unavailable.
    """
    if not isinstance(text, str):
        raise TypeError("text must be str")
    rules = default_count_rules() if rules is None else rules
    if not isinstance(rules, CountRules):
        raise TypeError("rules must be CountRules")
    locations = tuple(locations)
    for supplied_location in locations:
        if not isinstance(supplied_location, CountLocation):
            raise TypeError("locations must contain CountLocation instances")
        if supplied_location.end > len(text):
            raise ValueError("Location span is outside the input text")
    mentions = {}
    rejected = {}
    for pattern, active in ((rules._passive, False), (rules._active, True)):
        for match in pattern.finditer(text):
            trigger = match.start("trigger")
            if reason := _rejection(text, match, active, rules):
                rejected[trigger] = reason
                continue
            start = match.start("number")
            location = _nearest_location(locations, start)
            for label in rules.triggers[" ".join(match.group("trigger").lower().split())]:
                mention = CountMention(
                    label,
                    _integer(match.group("number")),
                    " ".join((match.group("object") or "").split()),
                    start,
                    match.end(),
                    trigger,
                    location,
                )
                mentions[start, label, trigger] = mention
    # Templates add nominal and trigger-before-number constructions. Deduplicate
    # equivalent label/quantity spans across rules; source duplicates can be
    # preserved losslessly with the wire parser, but their extraction cause is unknown.
    for _identifier, pattern, labels in rules._patterns:
        for match in pattern.finditer(text):
            if _rejection(text, match, False, rules, template=True):
                continue
            start = match.start("number")
            location = _nearest_location(locations, start)
            for label in labels:
                if any(m.start == start and m.count_type == label for m in mentions.values()):
                    continue
                mentions[start, label, match.start()] = CountMention(
                    label,
                    _integer(match.group("number")),
                    "",
                    start,
                    max(match.end(), match.end("number")),
                    match.start(),
                    location,
                )
    accepted = {m.trigger_start for m in mentions.values()}
    issues = tuple(
        CountIssue(m.start(), m.end(), rejected.get(m.start(), "unsupported_construction"))
        for m in rules._trigger_re.finditer(text)
        if m.start() not in accepted
    )
    return CountResult(
        tuple(mentions[key] for key in sorted(mentions)),
        issues,
        rules.name,
        rules.empty_object_nouns,
    )