Skip to content

ner

Reusable entity mentions and an optional spaCy backend for prepared text.

NameRules dataclass

NameRules(name: str = 'identity', strip_person_titles: bool = False, strip_person_initials: bool = False, strip_person_suffixes: bool = False, organization_blocklist: frozenset[str] = frozenset(), person_aliases: Mapping[str, str] = dict(), organization_aliases: Mapping[str, str] = dict(), organization_weights: Mapping[str, float] = dict(), organization_intercept: float = 0.0, organization_threshold: float | None = None)

Named rules for output spelling, aliases, and organization filtering.

Rules affect serialized entity names while source spans retain their text.

from_json classmethod

from_json(path: StrPath | Traversable) -> NameRules

Load name-normalization rules from a UTF-8 JSON file or package resource.

Source code in src/gdelt_regkg/fields/ner.py
@classmethod
def from_json(cls, path: StrPath | Traversable) -> NameRules:
    """Load name-normalization rules from a UTF-8 JSON file or package resource."""
    source = Path(path) if isinstance(path, (str, PathLike)) else path
    payload = json.loads(source.read_text(encoding="utf-8"))
    if not isinstance(payload, dict):
        raise ValueError("Name rules must be a JSON object")
    allowed = {item.name for item in fields(cls)}
    extra = payload.keys() - allowed - {"schema", "$schema", "evaluation"}
    if extra:
        raise ValueError(f"Unknown name rule fields: {sorted(extra)}")
    return cls(**{key: value for key, value in payload.items() if key in allowed})

NERUnavailableError

Bases: RuntimeError

The requested optional NER dependency or trained model is unavailable.

EntityMention dataclass

EntityMention(text: str, label: str, start: int, end: int, source_label: str | None = None)

A recognized entity with source text and character offsets.

Attributes:

Name Type Description
text str

Exact source span.

label str

Normalized PERSON, ORG, or LOCATION label.

start int

Zero-based start offset.

end int

Exclusive end offset.

source_label str | None

Original recognizer label, when available.

NameMention dataclass

NameMention(text: str, start: int, end: int, source_label: str = 'PROPN')

A broad named span with source text, start, exclusive end, and source label.

Names can include events, laws, and products alongside entity categories.

NERResult dataclass

NERResult(text: str, mentions: tuple[EntityMention, ...], backend_name: str = 'supplied-mentions', name_policy: str = 'surface', name_rules: NameRules | None = None, name_mentions: tuple[NameMention, ...] | None = None)

Validated entity and name spans for an unchanged input body.

Attributes:

Name Type Description
text str

Analyzed body.

mentions tuple[EntityMention, ...]

Entities sorted by source position.

backend_name str

Recognizer identity.

name_policy str

Output spelling policy: surface, gdelt, or gdelt-full-names.

name_rules NameRules | None

Optional output normalization and filtering rules.

name_mentions tuple[NameMention, ...] | None

Broad name spans; defaults to the supplied entity spans.

all_names property

all_names: tuple[NameMention, ...]

Broad name spans in source order.

persons property

persons: tuple[EntityMention, ...]

Person mentions in source order.

organizations property

organizations: tuple[EntityMention, ...]

Organization mentions in source order.

locations property

locations: tuple[EntityMention, ...]

Place mentions awaiting geographic resolution.

to_gkg

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

Serialize person or organization names using the configured name policy.

Parameters:

Name Type Description Default
label str

PERSON or ORG.

required
enhanced bool

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

False

Returns:

Type Description
str

Semicolon-separated entries, or an empty string for no output names.

Raises:

Type Description
ValueError

If label is unsupported.

NotImplementedError

If label is LOCATION, which needs geocoding.

Source code in src/gdelt_regkg/fields/ner.py
def to_gkg(self, label: str, *, enhanced: bool = False) -> str:
    """Serialize person or organization names using the configured name policy.

    Args:
        label: `PERSON` or `ORG`.
        enhanced: Include offsets for every mention. Standard output keeps
            distinct names in first-match order.

    Returns:
        Semicolon-separated entries, or an empty string for no output names.

    Raises:
        ValueError: If `label` is unsupported.
        NotImplementedError: If `label` is `LOCATION`, which needs geocoding.
    """
    if label == "LOCATION":
        raise NotImplementedError(
            "Location mentions require geographic resolution before GKG serialization"
        )
    if label not in {"PERSON", "ORG"}:
        raise ValueError("GKG entity label must be PERSON or ORG")
    entries = []
    for mention in self.mentions:
        if mention.label != label:
            continue
        name = text_component(mention.text, separators=";,")
        if self.name_policy != "surface":
            name = canonical_entity_name(name)
            if self.name_rules is not None:
                name = self.name_rules.apply(name, label)
            if len(name.split()) < 2 and (
                label == "PERSON" or self.name_policy == "gdelt-full-names"
            ):
                continue
        if not name:
            continue
        entries.append(f"{name},{mention.start}" if enhanced else name)
    if not enhanced:
        entries = list(dict.fromkeys(entries))
    return ";".join(entries)

EntityRecognizer

Bases: Protocol

Interface for backends implementing analyze(text) with an NERResult.

SpacyNER

SpacyNER(nlp, *, name: str | None = None, filter_spans: bool = True, name_policy: str = 'surface', name_rules: NameRules | None = None)

Reusable entity recognizer backed by a loaded spaCy pipeline.

Parameters:

Name Type Description Default
nlp Language

Loaded pipeline containing ner or entity_ruler.

required
name str | None

Optional backend identity.

None
filter_spans bool

Apply built-in span quality filters.

True
name_policy str

surface, gdelt, or gdelt-full-names output policy.

'surface'
name_rules NameRules | None

Optional output normalization and filtering rules.

None
Source code in src/gdelt_regkg/fields/ner.py
def __init__(
    self,
    nlp,
    *,
    name: str | None = None,
    filter_spans: bool = True,
    name_policy: str = "surface",
    name_rules: NameRules | None = None,
):
    if not callable(nlp) or not {"ner", "entity_ruler"}.intersection(nlp.pipe_names):
        raise ValueError("Provide a spaCy pipeline with ner or entity_ruler")
    self.nlp = nlp
    self.filter_spans = filter_spans
    if name_policy not in _NAME_POLICIES:
        raise ValueError("Unknown entity name policy")
    self.name_policy = name_policy
    self.name_rules = name_rules
    meta = nlp.meta
    self.name = (
        name
        or f"spacy:{meta.get('lang', '')}:{meta.get('name', 'custom')}:{meta.get('version', '')}"
    )

from_model classmethod

from_model(model: str = 'en_core_web_sm', *, name_policy: str = 'gdelt-full-names', name_rules: NameRules | None = None, resources_dir: StrPath | None = None) -> SpacyNER

Load an installed spaCy model for entity and broad-name extraction.

Parameters:

Name Type Description Default
model str

Installed model name or path.

'en_core_web_sm'
name_policy str

Output spelling policy. Defaults to gdelt-full-names.

'gdelt-full-names'
name_rules NameRules | None

Custom name rules; the default full-name policy loads configured rules when omitted.

None
resources_dir StrPath | None

Local root for default name rules.

None

Returns:

Type Description
SpacyNER

A reusable recognizer.

Raises:

Type Description
OptionalDependencyError

If spaCy is unavailable.

NERUnavailableError

If the model cannot be loaded.

ResourceUnavailableError

If required default name rules are unavailable.

Source code in src/gdelt_regkg/fields/ner.py
@classmethod
def from_model(
    cls,
    model: str = "en_core_web_sm",
    *,
    name_policy: str = "gdelt-full-names",
    name_rules: NameRules | None = None,
    resources_dir: StrPath | None = None,
) -> SpacyNER:
    """Load an installed spaCy model for entity and broad-name extraction.

    Args:
        model: Installed model name or path.
        name_policy: Output spelling policy. Defaults to `gdelt-full-names`.
        name_rules: Custom name rules; the default full-name policy loads
            configured rules when omitted.
        resources_dir: Local root for default name rules.

    Returns:
        A reusable recognizer.

    Raises:
        OptionalDependencyError: If spaCy is unavailable.
        NERUnavailableError: If the model cannot be loaded.
        ResourceUnavailableError: If required default name rules are unavailable.
    """
    spacy = require_dependency("spacy", "ner")
    try:
        nlp = spacy.load(model)
    except OSError as error:
        raise NERUnavailableError(
            f"Install model {model!r} with python -m spacy download {model}, or provide a loaded pipeline"
        ) from error
    # POS tags also supply proper names outside the entity categories.
    nlp.disable_pipes(*[pipe for pipe in ("parser", "lemmatizer") if pipe in nlp.pipe_names])
    if name_rules is None and name_policy == "gdelt-full-names":
        name_rules = default_name_rules(resources_dir)
    return cls(nlp, name_policy=name_policy, name_rules=name_rules)

analyze

analyze(text: str) -> NERResult

Analyze one body, preserving its source text and character offsets.

Source code in src/gdelt_regkg/fields/ner.py
def analyze(self, text: str) -> NERResult:
    """Analyze one body, preserving its source text and character offsets."""
    if not isinstance(text, str):
        raise TypeError("text must be str")
    doc = self.nlp(text)
    return self._analyze_doc(text, doc)

analyze_many

analyze_many(texts: Iterable[str], *, batch_size: int = 32) -> Iterator[NERResult]

Analyze bodies in batches while preserving input order and offsets.

Parameters:

Name Type Description Default
texts Iterable[str]

Bodies to analyze.

required
batch_size int

Positive number of documents per model batch.

32

Yields:

Type Description
NERResult

One NER result per input body.

Raises:

Type Description
TypeError

If an input body is not a string.

ValueError

If batch_size is invalid or the backend alters source text.

Source code in src/gdelt_regkg/fields/ner.py
def analyze_many(self, texts: Iterable[str], *, batch_size: int = 32) -> Iterator[NERResult]:
    """Analyze bodies in batches while preserving input order and offsets.

    Args:
        texts: Bodies to analyze.
        batch_size: Positive number of documents per model batch.

    Yields:
        One NER result per input body.

    Raises:
        TypeError: If an input body is not a string.
        ValueError: If `batch_size` is invalid or the backend alters source text.
    """
    if type(batch_size) is not int or batch_size < 1:
        raise ValueError("batch_size must be a positive integer")
    texts = list(texts)
    if any(not isinstance(text, str) for text in texts):
        raise TypeError("texts must contain strings")
    for text, doc in zip(texts, self.nlp.pipe(texts, batch_size=batch_size), strict=True):
        yield self._analyze_doc(text, doc)

organization_features cached

organization_features(name: str) -> frozenset[str]

Binary word, bigram, and bounded character features for name filtering.

Source code in src/gdelt_regkg/fields/ner.py
@lru_cache(maxsize=16384)
def organization_features(name: str) -> frozenset[str]:
    """Binary word, bigram, and bounded character features for name filtering."""
    words = name.split()
    result = {"w:" + word for word in words}
    result.update("b:" + " ".join(words[i : i + 2]) for i in range(len(words) - 1))
    for word in words:
        marked = "^" + word + "$"
        for n in (3, 4):
            result.update("c:" + marked[i : i + n] for i in range(len(marked) - n + 1))
    result.add("length:" + str(min(len(words), 6)))
    return frozenset(result)

canonical_entity_name

canonical_entity_name(value: str) -> str

Approximate native name spelling without altering source spans.

Source code in src/gdelt_regkg/fields/ner.py
def canonical_entity_name(value: str) -> str:
    """Approximate native name spelling without altering source spans."""
    value = unicodedata.normalize("NFKC", value).casefold().replace("’", "'")
    value = re.sub(r"(?:'s|s')$", lambda m: "s" if m[0] == "s'" else "", value)
    value = re.sub(r"^(?:the|a|an)\s+", "", value)
    value = value.replace(".", " ").replace(",", " ")
    value = re.sub(r"[^\w\s\-']", " ", value)
    return " ".join(value.split())

default_name_rules

default_name_rules(resources_dir: StrPath | None = None) -> NameRules

Load the fixed development-selected cell normalization and ORG filter.

Source code in src/gdelt_regkg/fields/ner.py
def default_name_rules(resources_dir: StrPath | None = None) -> NameRules:
    """Load the fixed development-selected cell normalization and ORG filter."""
    return _cached_name_rules(ResourceStore(resources_dir).profile("ner"))

default_recognizer cached

default_recognizer() -> SpacyNER

Load the installed English model lazily; never download it automatically.

Source code in src/gdelt_regkg/fields/ner.py
@lru_cache(maxsize=1)
def default_recognizer() -> SpacyNER:
    """Load the installed English model lazily; never download it automatically."""
    return SpacyNER.from_model()

analyze_entities

analyze_entities(text: str, *, recognizer: EntityRecognizer | None = None, mentions: Iterable[EntityMention] | None = None) -> NERResult

Extract entities or validate supplied mentions against an input body.

Parameters:

Name Type Description Default
text str

Prepared body.

required
recognizer EntityRecognizer | None

Custom backend. Defaults to the installed English spaCy model.

None
mentions Iterable[EntityMention] | None

Existing entity spans; supply these instead of recognizer.

None

Returns:

Type Description
NERResult

Validated entity and broad-name spans for the unchanged body.

Raises:

Type Description
TypeError

If the body or supplied mentions have invalid types.

ValueError

If NER inputs conflict or spans do not match the body.

NERUnavailableError

If the default model is unavailable.

OptionalDependencyError

If the default recognizer's dependency is unavailable.

Source code in src/gdelt_regkg/fields/ner.py
def analyze_entities(
    text: str,
    *,
    recognizer: EntityRecognizer | None = None,
    mentions: Iterable[EntityMention] | None = None,
) -> NERResult:
    """Extract entities or validate supplied mentions against an input body.

    Args:
        text: Prepared body.
        recognizer: Custom backend. Defaults to the installed English spaCy model.
        mentions: Existing entity spans; supply these instead of `recognizer`.

    Returns:
        Validated entity and broad-name spans for the unchanged body.

    Raises:
        TypeError: If the body or supplied mentions have invalid types.
        ValueError: If NER inputs conflict or spans do not match the body.
        NERUnavailableError: If the default model is unavailable.
        OptionalDependencyError: If the default recognizer's dependency is unavailable.
    """
    if not isinstance(text, str):
        raise TypeError("text must be str")
    if mentions is not None:
        if recognizer is not None:
            raise ValueError("Supply a recognizer or mentions, not both")
        return NERResult(text, tuple(mentions))
    recognizer = default_recognizer() if recognizer is None else recognizer
    result = recognizer.analyze(text)
    if not isinstance(result, NERResult) or result.text != text:
        raise ValueError("Recognizer must return NERResult for the unchanged input text")
    return result