Skip to content

gdelt_regkg

GDELT GKG reconstruction from prepared text and supplied metadata.

GKG_COLUMNS module-attribute

GKG_COLUMNS: list[str] = list(_COLUMN_FIELDS)

GKG column names in serialization order, also exported by gdelt_regkg.utils.

OptionalDependencyError

Bases: ImportError

An optional feature dependency is absent from the installation.

RecordMetadata dataclass

RecordMetadata(identifier: str, batch_time: Timestamp, sequence: int, published_at: Timestamp | None = None, source_collection: int = 1, source_name: str | None = None, sharing_image: str | None = None, related_images: Iterable[str] | None = None, social_image_embeds: Iterable[str] | None = None, social_video_embeds: Iterable[str] | None = None, extras: Mapping[str, XMLValue] | None = None, source_language: str | None = None, translation_engine: str | None = None)

Document identity, timestamps, media, and translation provenance.

None media values mark unavailable data. Empty values mark known absence.

Parameters:

Name Type Description Default
identifier str

Document URL, DOI, or citation.

required
batch_time Timestamp

Record batch timestamp.

required
sequence int

Caller-managed positive sequence number within the batch.

required
published_at Timestamp | None

Optional precise publication timestamp for extras.

None
source_collection int

GKG source collection code, from 1 through 6.

1
source_name str | None

Explicit source label; defaults to a web URL's hostname.

None
sharing_image str | None

Selected sharing-image URL.

None
related_images Iterable[str] | None

Selected article image URLs.

None
social_image_embeds Iterable[str] | None

Social-post URLs containing images.

None
social_video_embeds Iterable[str] | None

Selected video URLs.

None
extras Mapping[str, XMLValue] | None

Additional XML extension elements.

None
source_language str | None

Original language code for translated bodies.

None
translation_engine str | None

Engine citation, supplied with source_language.

None

from_translation classmethod

from_translation(result: TranslationResult, metadata: RecordMetadata) -> RecordMetadata

Copy translation provenance into a new metadata instance.

Parameters:

Name Type Description Default
result TranslationResult

Translation result whose English text will be analyzed.

required
metadata RecordMetadata

Existing document metadata.

required

Returns:

Type Description
RecordMetadata

Updated metadata with source language and engine for translated input.

Raises:

Type Description
TypeError

If argument types are invalid.

ValueError

If translation provenance conflicts with existing metadata.

Source code in src/gdelt_regkg/fields/metadata.py
@classmethod
def from_translation(
    cls, result: TranslationResult, metadata: RecordMetadata
) -> RecordMetadata:
    """Copy translation provenance into a new metadata instance.

    Args:
        result: Translation result whose English text will be analyzed.
        metadata: Existing document metadata.

    Returns:
        Updated metadata with source language and engine for translated input.

    Raises:
        TypeError: If argument types are invalid.
        ValueError: If translation provenance conflicts with existing metadata.
    """
    if not isinstance(result, TranslationResult) or not isinstance(metadata, cls):
        raise TypeError("Expected TranslationResult and RecordMetadata")
    language = normalize_language(result.source_language)
    translation_info = (language, result.engine) if language != "eng" else (None, None)
    if (metadata.source_language, metadata.translation_engine) not in (
        (None, None),
        translation_info,
    ):
        raise ValueError(
            "Existing metadata conflicts with the source language or translation engine"
        )
    format_translation_info(*translation_info)
    return replace(
        metadata, source_language=translation_info[0], translation_engine=translation_info[1]
    )

to_mapping

to_mapping() -> dict[str, str | None]

Format the record identity, source, batch date, and translation cells.

Source code in src/gdelt_regkg/fields/metadata.py
def to_mapping(self) -> dict[str, str | None]:
    """Format the record identity, source, batch date, and translation cells."""
    stamp = format_date(self.batch_time)
    translation = format_translation_info(self.source_language, self.translation_engine)
    return {
        "GKGRECORDID": format_record_id(stamp, self.sequence, translated=bool(translation)),
        "V2.1DATE": stamp,
        "V2SOURCECOLLECTIONIDENTIFIER": format_source_collection(self.source_collection),
        "V2SOURCECOMMONNAME": source_common_name(self.identifier, name=self.source_name),
        "V2DOCUMENTIDENTIFIER": document_identifier(self.identifier),
        "V2.1TRANSLATIONINFO": translation,
    }

IncompleteGKGError

Bases: ValueError

Strict generation requires every field to be available.

IncompleteGKGWarning

Bases: UserWarning

The record contains unavailable fields.

Resources dataclass

Resources(resources_dir: StrPath | None = None, tone_lexicon: ToneLexicon | None = None, theme_lexicon: ThemeLexicon | None = None, count_rules: CountRules | None = None, gazetteer: Gazetteer | None = None, gcam_lexicon: GCAMLexicon | None = None, recognizer: EntityRecognizer | None = None)

Configure resource overrides and lazily loaded default profiles.

Supplied objects take precedence. Default profiles are loaded when an accessor is called.

Parameters:

Name Type Description Default
resources_dir StrPath | None

Local resource root. Defaults to local-resources under the current working directory.

None
tone_lexicon ToneLexicon | None

Custom tone lexicon.

None
theme_lexicon ThemeLexicon | None

Custom theme lexicon.

None
count_rules CountRules | None

Custom count extraction rules.

None
gazetteer Gazetteer | None

Custom geographic reference.

None
gcam_lexicon GCAMLexicon | None

Custom GCAM lexicon.

None
recognizer EntityRecognizer | None

Entity recognizer used during record generation.

None

tone

tone() -> ToneLexicon

Return the supplied tone lexicon or load the default profile.

Raises:

Type Description
ResourceUnavailableError

If the default profile is missing.

Source code in src/gdelt_regkg/profiles.py
def tone(self) -> ToneLexicon:
    """Return the supplied tone lexicon or load the default profile.

    Raises:
        ResourceUnavailableError: If the default profile is missing.
    """
    return (
        self.tone_lexicon
        if self.tone_lexicon is not None
        else default_tone_lexicon(self.resources_dir)
    )

themes

themes() -> ThemeLexicon

Return the supplied theme lexicon or load the default profile.

Raises:

Type Description
ResourceUnavailableError

If the default profile is missing.

Source code in src/gdelt_regkg/profiles.py
def themes(self) -> ThemeLexicon:
    """Return the supplied theme lexicon or load the default profile.

    Raises:
        ResourceUnavailableError: If the default profile is missing.
    """
    return (
        self.theme_lexicon
        if self.theme_lexicon is not None
        else default_theme_lexicon(self.resources_dir)
    )

counts

counts() -> CountRules

Return the supplied count rules or load the default profile.

Raises:

Type Description
ResourceUnavailableError

If the default profile is missing.

Source code in src/gdelt_regkg/profiles.py
def counts(self) -> CountRules:
    """Return the supplied count rules or load the default profile.

    Raises:
        ResourceUnavailableError: If the default profile is missing.
    """
    return (
        self.count_rules
        if self.count_rules is not None
        else default_count_rules(self.resources_dir)
    )

places

places() -> Gazetteer

Return the supplied gazetteer or load the default profile.

Raises:

Type Description
ResourceUnavailableError

If the default profile is missing.

Source code in src/gdelt_regkg/profiles.py
def places(self) -> Gazetteer:
    """Return the supplied gazetteer or load the default profile.

    Raises:
        ResourceUnavailableError: If the default profile is missing.
    """
    return (
        self.gazetteer if self.gazetteer is not None else default_gazetteer(self.resources_dir)
    )

gcam

gcam() -> GCAMLexicon

Return the supplied GCAM lexicon or load the default profile.

Raises:

Type Description
ResourceUnavailableError

If the default profile is missing.

Source code in src/gdelt_regkg/profiles.py
def gcam(self) -> GCAMLexicon:
    """Return the supplied GCAM lexicon or load the default profile.

    Raises:
        ResourceUnavailableError: If the default profile is missing.
    """
    return (
        self.gcam_lexicon
        if self.gcam_lexicon is not None
        else default_gcam_lexicon(self.resources_dir)
    )

GKGRecord dataclass

GKGRecord(recordid: str, date: str, source_collection: str, source: str, document: str, counts: str | None, enhanced_counts: str | None, themes: str | None, enhanced_themes: str | None, locations: str | None, enhanced_locations: str | None, persons: str | None, enhanced_persons: str | None, organizations: str | None, enhanced_organizations: str | None, tone: str | None, enhanced_dates: str | None, gcam: str | None, sharing_image: str | None, related_images: str | None, social_image_embeds: str | None, social_video_embeds: str | None, quotations: str | None, all_names: str | None, amounts: str | None, translation: str, extras_xml: str | None)

Bases: Mapping[str, str | None]

Typed record; mapping access uses native wire column names.

ResourceUnavailableError

Bases: FileNotFoundError

Required local resource is missing.

Prepare the resource in the selected resource directory or supply an explicit lexicon or gazetteer to the extraction function. The exception message identifies the missing path and provides setup guidance.

generate_gkg

generate_gkg(text: str, metadata: RecordMetadata, resources: Resources | None = None, *, overrides: Mapping[str, str | None] | None = None, ner_result: NERResult | None = None, count_locations: Iterable[CountLocation] = (), numeric_date_order: NumericDateOrder | None = None, gcam_disabled_dictionaries: Iterable[int | str] = (), gcam_original_text: str | None = None, strict: bool = False) -> GKGRecord

Build a GKG record from prepared English text and supplied metadata.

Enhanced offsets refer to text. For translated input, copy language and engine metadata with RecordMetadata.from_translation. Overridden cells may share analysis dependencies with other fields.

Parameters:

Name Type Description Default
text str

Prepared English body to analyze.

required
metadata RecordMetadata

Document identity, timestamps, media, and translation metadata.

required
resources Resources | None

Resource configuration. Defaults to Resources().

None
overrides Mapping[str, str | None] | None

Encoded output cells keyed by names in OVERRIDABLE_COLUMNS.

None
ner_result NERResult | None

Precomputed entities for this exact body, taking precedence over the configured recognizer.

None
count_locations Iterable[CountLocation]

Explicit count geography. Nonempty input takes precedence over locations derived from entities.

()
numeric_date_order NumericDateOrder | None

mdy or dmy for ambiguous dates; None leaves them unresolved. Also applies to amounts containing dates.

None
gcam_disabled_dictionaries Iterable[int | str]

GCAM dictionary names or IDs to exclude.

()
gcam_original_text str | None

Original body for native-language GCAM scoring, paired with metadata.source_language.

None
strict bool

Raise an error if any output field is unavailable.

False

Returns:

Type Description
GKGRecord

A 27-field record. None marks unavailable fields; an empty string marks an available field with no results.

Raises:

Type Description
TypeError

If argument types or output cell types are invalid.

ValueError

If metadata, overrides, date order, or analysis inputs are invalid. A supplied NER result must describe text exactly.

IncompleteGKGError

If strict is true and any field is unavailable.

ResourceUnavailableError

If a required default resource is missing.

Warns:

Type Description
IncompleteGKGWarning

If fields are unavailable and strict is false.

Source code in src/gdelt_regkg/pipeline.py
def generate_gkg(
    text: str,
    metadata: RecordMetadata,
    resources: Resources | None = None,
    *,
    overrides: Mapping[str, str | None] | None = None,
    ner_result: NERResult | None = None,
    count_locations: Iterable[CountLocation] = (),
    numeric_date_order: NumericDateOrder | None = None,
    gcam_disabled_dictionaries: Iterable[int | str] = (),
    gcam_original_text: str | None = None,
    strict: bool = False,
) -> GKGRecord:
    """Build a GKG record from prepared English text and supplied metadata.

    Enhanced offsets refer to `text`. For translated input, copy language and
    engine metadata with `RecordMetadata.from_translation`. Overridden cells may
    share analysis dependencies with other fields.

    Args:
        text: Prepared English body to analyze.
        metadata: Document identity, timestamps, media, and translation metadata.
        resources: Resource configuration. Defaults to `Resources()`.
        overrides: Encoded output cells keyed by names in `OVERRIDABLE_COLUMNS`.
        ner_result: Precomputed entities for this exact body, taking precedence
            over the configured recognizer.
        count_locations: Explicit count geography. Nonempty input takes precedence
            over locations derived from entities.
        numeric_date_order: `mdy` or `dmy` for ambiguous dates; `None` leaves them
            unresolved. Also applies to amounts containing dates.
        gcam_disabled_dictionaries: GCAM dictionary names or IDs to exclude.
        gcam_original_text: Original body for native-language GCAM scoring, paired
            with `metadata.source_language`.
        strict: Raise an error if any output field is unavailable.

    Returns:
        A 27-field record. `None` marks unavailable fields; an empty string marks
            an available field with no results.

    Raises:
        TypeError: If argument types or output cell types are invalid.
        ValueError: If metadata, overrides, date order, or analysis inputs are
            invalid. A supplied NER result must describe `text` exactly.
        IncompleteGKGError: If `strict` is true and any field is unavailable.
        ResourceUnavailableError: If a required default resource is missing.

    Warns:
        IncompleteGKGWarning: If fields are unavailable and `strict` is false.
    """
    if not isinstance(text, str):
        raise TypeError("text must be str")
    if not isinstance(metadata, RecordMetadata):
        raise TypeError("metadata must be RecordMetadata")
    resources = Resources() if resources is None else resources
    if not isinstance(resources, Resources):
        raise TypeError("resources must be Resources")
    if numeric_date_order not in (None, "mdy", "dmy"):
        raise ValueError("numeric_date_order must be mdy, dmy, or None")
    supplied = dict(overrides or {})
    if unknown := supplied.keys() - OVERRIDABLE_COLUMNS:
        raise ValueError(f"Unsupported overrides keys: {sorted(unknown)}")
    values = metadata.to_mapping()
    entities, locations = _entity_fields(
        text, resources, supplied, ner_result, tuple(count_locations)
    )
    values.update(entities)
    values.update(_paired_fields(text, resources, supplied, locations))
    values.update(
        _scalar_fields(
            text,
            resources,
            supplied,
            numeric_date_order,
            gcam_disabled_dictionaries,
            gcam_original_text,
            metadata.source_language,
        )
    )
    values.update(_metadata_fields(metadata, supplied))
    values.update(supplied)
    record = GKGRecord.from_mapping(values)
    missing = [column for column, value in record.items() if value is None]
    if missing:
        message = f"Unavailable GKG fields: {', '.join(missing)}"
        if strict:
            raise IncompleteGKGError(message)
        warnings.warn(message, IncompleteGKGWarning, stacklevel=2)
    return record

serialize_gkg

serialize_gkg(record: Mapping[str, str | None], *, allow_incomplete: bool = False) -> str

Serialize one record as an unquoted 27-column TSV line.

Parameters:

Name Type Description Default
record Mapping[str, str | None]

Mapping with exactly the column names in GKG_COLUMNS.

required
allow_incomplete bool

Convert unavailable (None) cells to empty strings.

False

Returns:

Type Description
str

A tab-separated line in GKG column order, ending with a newline.

Raises:

Type Description
TypeError

If a cell has an invalid type.

ValueError

If keys are incorrect, a cell contains row separators, or unavailable cells are present while allow_incomplete is false.

Source code in src/gdelt_regkg/pipeline.py
def serialize_gkg(record: Mapping[str, str | None], *, allow_incomplete: bool = False) -> str:
    """Serialize one record as an unquoted 27-column TSV line.

    Args:
        record: Mapping with exactly the column names in `GKG_COLUMNS`.
        allow_incomplete: Convert unavailable (`None`) cells to empty strings.

    Returns:
        A tab-separated line in GKG column order, ending with a newline.

    Raises:
        TypeError: If a cell has an invalid type.
        ValueError: If keys are incorrect, a cell contains row separators, or
            unavailable cells are present while `allow_incomplete` is false.
    """
    return "\t".join(mapping_row(record, allow_incomplete=allow_incomplete)) + "\n"

write_gkg

write_gkg(records: Iterable[Mapping[str, str | None]], stream: TextIO, *, allow_incomplete: bool = False) -> int

Write GKG records to a text stream as headerless TSV rows.

Each row is validated before writing. Earlier rows remain if a later row fails.

Parameters:

Name Type Description Default
records Iterable[Mapping[str, str | None]]

Record mappings in output order.

required
stream TextIO

Writable text stream, which remains open after writing.

required
allow_incomplete bool

Convert unavailable (None) cells to empty strings.

False

Returns:

Type Description
int

The number of records written.

Raises:

Type Description
TypeError

If a cell has an invalid type.

ValueError

If record validation fails.

OSError

If writing to the stream fails.

Source code in src/gdelt_regkg/pipeline.py
def write_gkg(
    records: Iterable[Mapping[str, str | None]], stream: TextIO, *, allow_incomplete: bool = False
) -> int:
    """Write GKG records to a text stream as headerless TSV rows.

    Each row is validated before writing. Earlier rows remain if a later row fails.

    Args:
        records: Record mappings in output order.
        stream: Writable text stream, which remains open after writing.
        allow_incomplete: Convert unavailable (`None`) cells to empty strings.

    Returns:
        The number of records written.

    Raises:
        TypeError: If a cell has an invalid type.
        ValueError: If record validation fails.
        OSError: If writing to the stream fails.
    """
    count = 0
    for record in records:
        stream.write(serialize_gkg(record, allow_incomplete=allow_incomplete))
        count += 1
    return count