Skip to content

locations

Offline resolution of NER place spans using GKG-compatible gazetteer records.

Place dataclass

Place(geo_type: str, full_name: str, country_code: str, adm1_code: str, latitude: str, longitude: str, feature_id: str, adm2_code: str = '', aliases: tuple[str, ...] = (), frequency: int = 1)

A gazetteer place with GKG geography codes and a native feature identifier.

Coordinates are strings. country_code uses FIPS codes, aliases supplies alternate names, and frequency provides a prior for ambiguous names.

Gazetteer dataclass

Gazetteer(name: str, places: tuple[Place, ...])

Named collection of places and aliases for offline geographic resolution.

from_json classmethod

from_json(path: str | Path) -> Gazetteer

Load a gazetteer from a UTF-8 JSON file, optionally gzip-compressed.

Source code in src/gdelt_regkg/fields/locations.py
@classmethod
def from_json(cls, path: str | Path) -> Gazetteer:
    """Load a gazetteer from a UTF-8 JSON file, optionally gzip-compressed."""
    path = Path(path)
    raw = gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes()
    return _load(json.loads(raw.decode("utf-8")))

LocationMention dataclass

LocationMention(text: str, start: int, end: int, place: Place)

A matched place name, source-text span, and resolved gazetteer record.

start is a zero-based character offset and end is exclusive.

LocationIssue dataclass

LocationIssue(text: str, start: int, reason: str)

An unresolved place name with its source offset and rejection reason.

LocationResult dataclass

LocationResult(text: str, mentions: tuple[LocationMention, ...], issues: tuple[LocationIssue, ...], gazetteer_name: str)

Resolved locations and diagnostics for an input body.

Attributes:

Name Type Description
text str

Analyzed body.

mentions tuple[LocationMention, ...]

Resolved places in source order.

issues tuple[LocationIssue, ...]

Unknown or ambiguous place candidates.

gazetteer_name str

Name of the geographic reference used.

count_locations property

count_locations

Resolved spans suitable for the locations argument of analyze_counts.

to_gkg

to_gkg(*, enhanced=False)

Serialize standard or enhanced locations as semicolon-separated entries.

An empty result produces an empty string.

Parameters:

Name Type Description Default
enhanced bool

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

False
Source code in src/gdelt_regkg/fields/locations.py
def to_gkg(self, *, enhanced=False):
    """Serialize standard or enhanced locations as semicolon-separated entries.

    An empty result produces an empty string.

    Args:
        enhanced (bool): Include ADM2 codes and offsets for every mention. Standard
            output keeps distinct entries in first-match order.
    """
    entries = [m.to_gkg(enhanced=enhanced) for m in self.mentions]
    return ";".join(entries if enhanced else dict.fromkeys(entries))

analyze_locations

analyze_locations(text: str, *, recognizer: EntityRecognizer | None = None, ner: NERResult | None = None, gazetteer: Gazetteer | None = None) -> LocationResult

Resolve recognized place names against an offline gazetteer.

Nearby country and ADM1 references guide ambiguous matches. Otherwise, a candidate needs at least 80% of the alias frequency to be selected.

Parameters:

Name Type Description Default
text str

Prepared body.

required
recognizer EntityRecognizer | None

Entity recognizer. Defaults to the installed English model.

None
ner NERResult | None

Precomputed NER for this exact body; supply it instead of recognizer.

None
gazetteer Gazetteer | None

Geographic reference. Defaults to the configured local profile.

None

Returns:

Type Description
LocationResult

Resolved places and diagnostics for unknown or ambiguous names.

Raises:

Type Description
TypeError

If text or gazetteer has an invalid type.

ValueError

If both NER inputs are supplied or the result describes another body.

NERUnavailableError

If the default recognizer model is unavailable.

OptionalDependencyError

If a recognizer dependency is unavailable.

ResourceUnavailableError

If a required default profile is unavailable.

Source code in src/gdelt_regkg/fields/locations.py
def analyze_locations(
    text: str,
    *,
    recognizer: EntityRecognizer | None = None,
    ner: NERResult | None = None,
    gazetteer: Gazetteer | None = None,
) -> LocationResult:
    """Resolve recognized place names against an offline gazetteer.

    Nearby country and ADM1 references guide ambiguous matches. Otherwise, a
    candidate needs at least 80% of the alias frequency to be selected.

    Args:
        text: Prepared body.
        recognizer: Entity recognizer. Defaults to the installed English model.
        ner: Precomputed NER for this exact body; supply it instead of `recognizer`.
        gazetteer: Geographic reference. Defaults to the configured local profile.

    Returns:
        Resolved places and diagnostics for unknown or ambiguous names.

    Raises:
        TypeError: If text or gazetteer has an invalid type.
        ValueError: If both NER inputs are supplied or the result describes another body.
        NERUnavailableError: If the default recognizer model is unavailable.
        OptionalDependencyError: If a recognizer dependency is unavailable.
        ResourceUnavailableError: If a required default profile is unavailable.
    """
    if not isinstance(text, str):
        raise TypeError("text must be str")
    if recognizer is not None and ner is not None:
        raise ValueError("Supply recognizer or ner, not both")
    ner = analyze_entities(text, recognizer=recognizer) if ner is None else ner
    if not isinstance(ner, NERResult) or ner.text != text:
        raise ValueError("NER result must refer to the unchanged body")
    gazetteer = default_gazetteer() if gazetteer is None else gazetteer
    if not isinstance(gazetteer, Gazetteer):
        raise TypeError("gazetteer must be Gazetteer")
    inputs = _candidate_inputs(ner, gazetteer)
    anchors = []
    for _, start, _, candidates in inputs:
        identities = {p.identity for p in candidates}
        if len(identities) == 1 and candidates[0].geo_type in {"1", "2", "5"}:
            anchors.append((start, candidates[0]))
    mentions, issues = [], []
    for value, start, end, raw in inputs:
        candidates = _resolve_candidates(raw, anchors, start)
        if len(candidates) == 1:
            mentions.append(LocationMention(value, start, end, candidates[0]))
        else:
            issues.append(
                LocationIssue(
                    value, start, "unknown-place" if not candidates else "ambiguous-place"
                )
            )
    return LocationResult(
        text, tuple(sorted(mentions, key=lambda m: m.start)), tuple(issues), gazetteer.name
    )