Skip to content

pipeline

Generate and serialize GKG records from prepared English text and metadata.

OVERRIDABLE_COLUMNS module-attribute

OVERRIDABLE_COLUMNS = frozenset((*TEXT_COLUMNS, *METADATA_COLUMNS))

GKG column names accepted by the overrides argument of generate_gkg.

IncompleteGKGWarning

Bases: UserWarning

The record contains unavailable fields.

IncompleteGKGError

Bases: ValueError

Strict generation requires every field to be available.

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