Skip to content

Profiles API

Overview

The profiles module provides YAML-first entity profiles that drive validation, form schema generation, and profile-aware data workflows.

Current implementations: YAML loading, JSON Schema validation, Pydantic model generation, form schema generation, Wikidata validation
Future implementations: profile registry, code generation, broader datatype support

Quick Start

from gkc.profiles import ProfileLoader, ProfileValidator

profile = ProfileLoader().load_from_file(
    "/path/to/SpiritSafe/profiles/TribalGovernmentUS/profile.yaml"
)
validator = ProfileValidator(profile)
result = validator.validate_item(item_json, policy="lenient")

Classes

ProfileLoader

Load YAML profile definitions into ProfileDefinition objects.

Parameters:

Name Type Description Default
schema_path Optional[Path]

Optional path to the JSON schema used for validation.

None
Side effects

Reads the JSON schema from disk during initialization.

Example

loader = ProfileLoader() profile = loader.load_from_file("profiles/TribalGovernmentUS.yaml")

Plain meaning: Read a YAML profile and validate its structure.

Source code in gkc/profiles/loaders/yaml_loader.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
class ProfileLoader:
    """Load YAML profile definitions into ProfileDefinition objects.

    Args:
        schema_path: Optional path to the JSON schema used for validation.

    Side effects:
        Reads the JSON schema from disk during initialization.

    Example:
        >>> loader = ProfileLoader()
        >>> profile = loader.load_from_file("profiles/TribalGovernmentUS.yaml")

    Plain meaning: Read a YAML profile and validate its structure.
    """

    def __init__(self, schema_path: Optional[Path] = None):
        self._schema_path = schema_path or self._default_schema_path()
        self._validator = Draft202012Validator(self._load_schema())

    def load_from_file(self, path: Union[str, Path]) -> ProfileDefinition:
        """Load a YAML profile from a file.

        Args:
            path: Path to the YAML profile file.

        Returns:
            Parsed ProfileDefinition instance.

        Raises:
            ValueError: If the profile fails schema validation.
            FileNotFoundError: If the file does not exist.
            yaml.YAMLError: If the YAML cannot be parsed.

        Side effects:
            Reads a YAML file from disk.

        Example:
            >>> profile = loader.load_from_file(".dev/TribalGovernmentUS.yaml")

        Plain meaning: Read and validate a profile file.
        """
        yaml_text = Path(path).read_text(encoding="utf-8")
        return self.load_from_text(yaml_text)

    def load_from_text(self, text: str) -> ProfileDefinition:
        """Load a YAML profile from text.

        Args:
            text: YAML text contents.

        Returns:
            Parsed ProfileDefinition instance.

        Raises:
            ValueError: If the profile fails schema validation.
            yaml.YAMLError: If the YAML cannot be parsed.

        Side effects:
            None.

        Example:
            >>> profile = loader.load_from_text("name: Example\nstatements: []")

        Plain meaning: Parse YAML content into a profile object.
        """
        data = yaml.safe_load(text) or {}
        return self.load_from_dict(data)

    def load_from_dict(self, data: Dict[str, Any]) -> ProfileDefinition:
        """Load a profile from a Python dictionary.

        Args:
            data: Profile data dictionary.

        Returns:
            Parsed ProfileDefinition instance.

        Raises:
            ValueError: If the profile fails schema validation.

        Side effects:
            None.

        Example:
            >>> profile = loader.load_from_dict({"name": "Demo", "statements": []})

        Plain meaning: Validate and convert profile data to a typed object.
        """
        errors = list(self.validate_data(data))
        if errors:
            message = "Profile schema validation failed: " + "; ".join(errors)
            raise ValueError(message)
        return ProfileDefinition.model_validate(data)

    def validate_data(self, data: Dict[str, Any]) -> Iterable[str]:
        """Validate profile data against the JSON schema.

        Args:
            data: Profile data dictionary.

        Returns:
            Iterable of error messages (empty if valid).

        Side effects:
            None.

        Example:
            >>> errors = list(loader.validate_data({"name": "Demo"}))

        Plain meaning: Check if the profile matches the required structure.
        """
        for error in sorted(self._validator.iter_errors(data), key=str):
            path = ".".join([str(item) for item in error.path]) or "<root>"
            yield f"{path}: {error.message}"

    def _load_schema(self) -> dict[str, Any]:
        schema_text = self._schema_path.read_text(encoding="utf-8")
        return json.loads(schema_text)

    @staticmethod
    def _default_schema_path() -> Path:
        return Path(__file__).resolve().parents[1] / "schemas" / "profile.schema.json"

load_from_dict(data)

Load a profile from a Python dictionary.

Parameters:

Name Type Description Default
data Dict[str, Any]

Profile data dictionary.

required

Returns:

Type Description
ProfileDefinition

Parsed ProfileDefinition instance.

Raises:

Type Description
ValueError

If the profile fails schema validation.

Side effects

None.

Example

profile = loader.load_from_dict({"name": "Demo", "statements": []})

Plain meaning: Validate and convert profile data to a typed object.

Source code in gkc/profiles/loaders/yaml_loader.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def load_from_dict(self, data: Dict[str, Any]) -> ProfileDefinition:
    """Load a profile from a Python dictionary.

    Args:
        data: Profile data dictionary.

    Returns:
        Parsed ProfileDefinition instance.

    Raises:
        ValueError: If the profile fails schema validation.

    Side effects:
        None.

    Example:
        >>> profile = loader.load_from_dict({"name": "Demo", "statements": []})

    Plain meaning: Validate and convert profile data to a typed object.
    """
    errors = list(self.validate_data(data))
    if errors:
        message = "Profile schema validation failed: " + "; ".join(errors)
        raise ValueError(message)
    return ProfileDefinition.model_validate(data)

load_from_file(path)

Load a YAML profile from a file.

Parameters:

Name Type Description Default
path Union[str, Path]

Path to the YAML profile file.

required

Returns:

Type Description
ProfileDefinition

Parsed ProfileDefinition instance.

Raises:

Type Description
ValueError

If the profile fails schema validation.

FileNotFoundError

If the file does not exist.

YAMLError

If the YAML cannot be parsed.

Side effects

Reads a YAML file from disk.

Example

profile = loader.load_from_file(".dev/TribalGovernmentUS.yaml")

Plain meaning: Read and validate a profile file.

Source code in gkc/profiles/loaders/yaml_loader.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def load_from_file(self, path: Union[str, Path]) -> ProfileDefinition:
    """Load a YAML profile from a file.

    Args:
        path: Path to the YAML profile file.

    Returns:
        Parsed ProfileDefinition instance.

    Raises:
        ValueError: If the profile fails schema validation.
        FileNotFoundError: If the file does not exist.
        yaml.YAMLError: If the YAML cannot be parsed.

    Side effects:
        Reads a YAML file from disk.

    Example:
        >>> profile = loader.load_from_file(".dev/TribalGovernmentUS.yaml")

    Plain meaning: Read and validate a profile file.
    """
    yaml_text = Path(path).read_text(encoding="utf-8")
    return self.load_from_text(yaml_text)

load_from_text(text)

Load a YAML profile from text.

    Args:
        text: YAML text contents.

    Returns:
        Parsed ProfileDefinition instance.

    Raises:
        ValueError: If the profile fails schema validation.
        yaml.YAMLError: If the YAML cannot be parsed.

    Side effects:
        None.

    Example:
        >>> profile = loader.load_from_text("name: Example

statements: []")

    Plain meaning: Parse YAML content into a profile object.
Source code in gkc/profiles/loaders/yaml_loader.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def load_from_text(self, text: str) -> ProfileDefinition:
    """Load a YAML profile from text.

    Args:
        text: YAML text contents.

    Returns:
        Parsed ProfileDefinition instance.

    Raises:
        ValueError: If the profile fails schema validation.
        yaml.YAMLError: If the YAML cannot be parsed.

    Side effects:
        None.

    Example:
        >>> profile = loader.load_from_text("name: Example\nstatements: []")

    Plain meaning: Parse YAML content into a profile object.
    """
    data = yaml.safe_load(text) or {}
    return self.load_from_dict(data)

validate_data(data)

Validate profile data against the JSON schema.

Parameters:

Name Type Description Default
data Dict[str, Any]

Profile data dictionary.

required

Returns:

Type Description
Iterable[str]

Iterable of error messages (empty if valid).

Side effects

None.

Example

errors = list(loader.validate_data({"name": "Demo"}))

Plain meaning: Check if the profile matches the required structure.

Source code in gkc/profiles/loaders/yaml_loader.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def validate_data(self, data: Dict[str, Any]) -> Iterable[str]:
    """Validate profile data against the JSON schema.

    Args:
        data: Profile data dictionary.

    Returns:
        Iterable of error messages (empty if valid).

    Side effects:
        None.

    Example:
        >>> errors = list(loader.validate_data({"name": "Demo"}))

    Plain meaning: Check if the profile matches the required structure.
    """
    for error in sorted(self._validator.iter_errors(data), key=str):
        path = ".".join([str(item) for item in error.path]) or "<root>"
        yield f"{path}: {error.message}"

ProfileDefinition

Bases: BaseModel

Define a YAML profile and its statements.

Attributes:

Name Type Description
name str

Profile name.

description str

Profile description.

labels dict[str, MetadataDefinition]

Per-language label definitions.

descriptions dict[str, MetadataDefinition]

Per-language description definitions.

aliases dict[str, MetadataDefinition]

Per-language alias definitions.

sitelinks Optional[SitelinksDefinition]

Sitelink definitions for wiki projects.

statements List[ProfileFieldDefinition]

List of statement definitions.

Example

ProfileDefinition(name="Example", description="Demo", statements=[])

Plain meaning: The complete YAML profile definition.

Source code in gkc/profiles/models.py
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
class ProfileDefinition(BaseModel):
    """Define a YAML profile and its statements.

    Attributes:
        name: Profile name.
        description: Profile description.
        labels: Per-language label definitions.
        descriptions: Per-language description definitions.
        aliases: Per-language alias definitions.
        sitelinks: Sitelink definitions for wiki projects.
        statements: List of statement definitions.

    Example:
        >>> ProfileDefinition(name="Example", description="Demo", statements=[])

    Plain meaning: The complete YAML profile definition.
    """

    name: str = Field(..., description="Profile name")
    description: str = Field(..., description="Profile description")
    labels: dict[str, MetadataDefinition] = Field(
        default_factory=dict, description="Per-language labels"
    )
    descriptions: dict[str, MetadataDefinition] = Field(
        default_factory=dict, description="Per-language descriptions"
    )
    aliases: dict[str, MetadataDefinition] = Field(
        default_factory=dict, description="Per-language aliases"
    )
    sitelinks: Optional[SitelinksDefinition] = Field(
        default=None, description="Sitelinks configuration"
    )
    statements: List[ProfileFieldDefinition] = Field(
        default_factory=list,
        validation_alias=AliasChoices("statements", "fields"),
        serialization_alias="statements",
        description="Profile statements",
    )

    @property
    def fields(self) -> List[ProfileFieldDefinition]:
        """Backward-compatible alias for statements."""
        return self.statements

    def statement_by_id(self, statement_id: str) -> Optional[ProfileFieldDefinition]:
        """Get a statement definition by its identifier.

        Args:
            statement_id: Statement identifier to locate.

        Returns:
            Matching ProfileFieldDefinition or None if not found.

        Side effects:
            None.

        Example:
            >>> profile.statement_by_id("instance_of")

        Plain meaning: Find a statement configuration by its ID.
        """
        for statement in self.statements:
            if statement.id == statement_id:
                return statement
        return None

    def statement_by_property(
        self, property_id: str
    ) -> Optional[ProfileFieldDefinition]:
        """Get a statement definition by property ID from configured routes.

        Args:
            property_id: Property ID (e.g., ``P31``).

        Returns:
            Matching ProfileFieldDefinition or None if not found.

        Side effects:
            None.

        Example:
            >>> profile.statement_by_property("P31")

        Plain meaning: Find the statement that maps to a property ID.
        """
        for statement in self.statements:
            if statement.property_id() == property_id.upper():
                return statement
        return None

    def field_by_id(self, field_id: str) -> Optional[ProfileFieldDefinition]:
        """Backward-compatible alias for statement_by_id."""
        return self.statement_by_id(field_id)

    def field_by_property(self, property_id: str) -> Optional[ProfileFieldDefinition]:
        """Backward-compatible alias for statement_by_property."""
        return self.statement_by_property(property_id)

    def get_statement_linkages(self) -> List[ProfileFieldDefinition]:
        """Get all statements that have linkage metadata.

        Returns:
            List of ProfileFieldDefinition instances with linkage metadata.

        Side effects:
            None.

        Example:
            >>> linked_statements = profile.get_statement_linkages()
            >>> for stmt in linked_statements:
            ...     print(stmt.linkage.target_profile)

        Plain meaning: Find all statements that link to other profiles.
        """
        return [stmt for stmt in self.statements if stmt.linkage is not None]

    def get_linked_profile_names(self) -> List[str]:
        """Get a list of all profile names linked from this profile.

        Returns:
            List of unique profile names referenced in linkage metadata.

        Side effects:
            None.

        Example:
            >>> profile.get_linked_profile_names()
            ['OfficeHeldByHeadOfState']

        Plain meaning: Find all other profiles this one can link to.
        """
        names = {stmt.linkage.target_profile for stmt in self.get_statement_linkages()}
        return sorted(names)

    def get_link_definition(self, target_profile: str) -> Optional[StatementLinkage]:
        """Get linkage metadata for a specific target profile.

        Args:
            target_profile: Name of the target profile to find linkage for.

        Returns:
            StatementLinkage instance or None if no linkage to that profile.

        Side effects:
            None.

        Example:
            >>> linkage = profile.get_link_definition("OfficeHeldByHeadOfState")
            >>> linkage.cardinality.max
            1

        Plain meaning: Get the linkage rules for a specific connected profile.
        """
        for stmt in self.get_statement_linkages():
            if stmt.linkage.target_profile == target_profile:
                return stmt.linkage
        return None

fields property

Backward-compatible alias for statements.

field_by_id(field_id)

Backward-compatible alias for statement_by_id.

Source code in gkc/profiles/models.py
741
742
743
def field_by_id(self, field_id: str) -> Optional[ProfileFieldDefinition]:
    """Backward-compatible alias for statement_by_id."""
    return self.statement_by_id(field_id)

field_by_property(property_id)

Backward-compatible alias for statement_by_property.

Source code in gkc/profiles/models.py
745
746
747
def field_by_property(self, property_id: str) -> Optional[ProfileFieldDefinition]:
    """Backward-compatible alias for statement_by_property."""
    return self.statement_by_property(property_id)

Get linkage metadata for a specific target profile.

Parameters:

Name Type Description Default
target_profile str

Name of the target profile to find linkage for.

required

Returns:

Type Description
Optional[StatementLinkage]

StatementLinkage instance or None if no linkage to that profile.

Side effects

None.

Example

linkage = profile.get_link_definition("OfficeHeldByHeadOfState") linkage.cardinality.max 1

Plain meaning: Get the linkage rules for a specific connected profile.

Source code in gkc/profiles/models.py
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
def get_link_definition(self, target_profile: str) -> Optional[StatementLinkage]:
    """Get linkage metadata for a specific target profile.

    Args:
        target_profile: Name of the target profile to find linkage for.

    Returns:
        StatementLinkage instance or None if no linkage to that profile.

    Side effects:
        None.

    Example:
        >>> linkage = profile.get_link_definition("OfficeHeldByHeadOfState")
        >>> linkage.cardinality.max
        1

    Plain meaning: Get the linkage rules for a specific connected profile.
    """
    for stmt in self.get_statement_linkages():
        if stmt.linkage.target_profile == target_profile:
            return stmt.linkage
    return None

get_linked_profile_names()

Get a list of all profile names linked from this profile.

Returns:

Type Description
List[str]

List of unique profile names referenced in linkage metadata.

Side effects

None.

Example

profile.get_linked_profile_names() ['OfficeHeldByHeadOfState']

Plain meaning: Find all other profiles this one can link to.

Source code in gkc/profiles/models.py
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
def get_linked_profile_names(self) -> List[str]:
    """Get a list of all profile names linked from this profile.

    Returns:
        List of unique profile names referenced in linkage metadata.

    Side effects:
        None.

    Example:
        >>> profile.get_linked_profile_names()
        ['OfficeHeldByHeadOfState']

    Plain meaning: Find all other profiles this one can link to.
    """
    names = {stmt.linkage.target_profile for stmt in self.get_statement_linkages()}
    return sorted(names)

get_statement_linkages()

Get all statements that have linkage metadata.

Returns:

Type Description
List[ProfileFieldDefinition]

List of ProfileFieldDefinition instances with linkage metadata.

Side effects

None.

Example

linked_statements = profile.get_statement_linkages() for stmt in linked_statements: ... print(stmt.linkage.target_profile)

Plain meaning: Find all statements that link to other profiles.

Source code in gkc/profiles/models.py
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
def get_statement_linkages(self) -> List[ProfileFieldDefinition]:
    """Get all statements that have linkage metadata.

    Returns:
        List of ProfileFieldDefinition instances with linkage metadata.

    Side effects:
        None.

    Example:
        >>> linked_statements = profile.get_statement_linkages()
        >>> for stmt in linked_statements:
        ...     print(stmt.linkage.target_profile)

    Plain meaning: Find all statements that link to other profiles.
    """
    return [stmt for stmt in self.statements if stmt.linkage is not None]

statement_by_id(statement_id)

Get a statement definition by its identifier.

Parameters:

Name Type Description Default
statement_id str

Statement identifier to locate.

required

Returns:

Type Description
Optional[ProfileFieldDefinition]

Matching ProfileFieldDefinition or None if not found.

Side effects

None.

Example

profile.statement_by_id("instance_of")

Plain meaning: Find a statement configuration by its ID.

Source code in gkc/profiles/models.py
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
def statement_by_id(self, statement_id: str) -> Optional[ProfileFieldDefinition]:
    """Get a statement definition by its identifier.

    Args:
        statement_id: Statement identifier to locate.

    Returns:
        Matching ProfileFieldDefinition or None if not found.

    Side effects:
        None.

    Example:
        >>> profile.statement_by_id("instance_of")

    Plain meaning: Find a statement configuration by its ID.
    """
    for statement in self.statements:
        if statement.id == statement_id:
            return statement
    return None

statement_by_property(property_id)

Get a statement definition by property ID from configured routes.

Parameters:

Name Type Description Default
property_id str

Property ID (e.g., P31).

required

Returns:

Type Description
Optional[ProfileFieldDefinition]

Matching ProfileFieldDefinition or None if not found.

Side effects

None.

Example

profile.statement_by_property("P31")

Plain meaning: Find the statement that maps to a property ID.

Source code in gkc/profiles/models.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
def statement_by_property(
    self, property_id: str
) -> Optional[ProfileFieldDefinition]:
    """Get a statement definition by property ID from configured routes.

    Args:
        property_id: Property ID (e.g., ``P31``).

    Returns:
        Matching ProfileFieldDefinition or None if not found.

    Side effects:
        None.

    Example:
        >>> profile.statement_by_property("P31")

    Plain meaning: Find the statement that maps to a property ID.
    """
    for statement in self.statements:
        if statement.property_id() == property_id.upper():
            return statement
    return None

ProfileValidator

Validate Wikidata item data against a ProfileDefinition.

Parameters:

Name Type Description Default
profile ProfileDefinition

Parsed ProfileDefinition instance.

required
Side effects

None.

Example

validator = ProfileValidator(profile) result = validator.validate_item(entity_data)

Plain meaning: Apply profile rules to a Wikidata item.

Source code in gkc/profiles/validation/validator.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
class ProfileValidator:
    """Validate Wikidata item data against a ProfileDefinition.

    Args:
        profile: Parsed ProfileDefinition instance.

    Side effects:
        None.

    Example:
        >>> validator = ProfileValidator(profile)
        >>> result = validator.validate_item(entity_data)

    Plain meaning: Apply profile rules to a Wikidata item.
    """

    def __init__(self, profile: ProfileDefinition):
        self.profile = profile
        self._generator = ProfilePydanticGenerator(profile)
        self._normalizer = WikidataNormalizer()

    def validate_item(
        self, entity_data: dict, policy: ValidationPolicy = "lenient"
    ) -> ValidationResult:
        """Validate a Wikidata item against the profile.

        Args:
            entity_data: Wikidata JSON entity data.
            policy: Validation policy ("strict" or "lenient").

        Returns:
            ValidationResult with errors, warnings, and normalized data.

        Side effects:
            None.

        Example:
            >>> result = validator.validate_item(item, policy="lenient")

        Plain meaning: Check a Wikidata item for profile compliance.
        """
        normalization = self._normalizer.normalize(entity_data, self.profile)
        model = self._generator.build_model()

        errors: List[ValidationIssue] = []
        warnings: List[ValidationIssue] = []

        self._add_normalization_issues(normalization, warnings, errors)

        try:
            model.model_validate(normalization.data, context={"policy": policy})
        except ValidationError as exc:
            errors.extend(self._errors_from_validation(exc, model))

        if policy == "lenient":
            warnings.extend(self._collect_lenient_warnings(normalization))

        ok = len(errors) == 0
        return ValidationResult(
            ok=ok,
            errors=errors,
            warnings=warnings,
            normalized=normalization.data,
        )

    def _add_normalization_issues(
        self,
        normalization: NormalizationResult,
        warnings: List[ValidationIssue],
        errors: List[ValidationIssue],
    ) -> None:
        for issue in normalization.issues:
            target = warnings if issue.severity == "warning" else errors
            target.append(
                ValidationIssue(
                    severity=issue.severity,
                    message=issue.message,
                    statement_id=issue.statement_id,
                    property_id=issue.property_id,
                )
            )

    def _errors_from_validation(
        self, exc: ValidationError, model: type[BaseModel]
    ) -> list[ValidationIssue]:
        issues: List[ValidationIssue] = []
        field_aliases = {
            name: (field.alias or name) for name, field in model.model_fields.items()
        }

        for err in exc.errors():
            loc = err.get("loc", [])
            field_name = loc[0] if loc else None
            statement_id = field_aliases.get(field_name) if field_name else None
            issues.append(
                ValidationIssue(
                    severity="error",
                    message=err.get("msg", "Validation error"),
                    statement_id=statement_id,
                )
            )
        return issues

    def _collect_lenient_warnings(
        self, normalization: NormalizationResult
    ) -> list[ValidationIssue]:
        warnings: list[ValidationIssue] = []

        for field in self.profile.statements:
            statements = normalization.data.get(field.id, [])
            violations = _evaluate_field(field, statements)
            for violation, category in violations:
                if category == "field":
                    if field.validation_policy != "allow_existing_nonconforming":
                        continue
                if category == "reference" and field.references:
                    if (
                        field.references.validation_policy
                        != "allow_existing_nonconforming"
                    ):
                        continue
                warnings.append(
                    ValidationIssue(
                        severity="warning",
                        message=f"{field.id}: {violation}",
                        statement_id=field.id,
                        property_id=field.property_id(),
                    )
                )

        return warnings

validate_item(entity_data, policy='lenient')

Validate a Wikidata item against the profile.

Parameters:

Name Type Description Default
entity_data dict

Wikidata JSON entity data.

required
policy ValidationPolicy

Validation policy ("strict" or "lenient").

'lenient'

Returns:

Type Description
ValidationResult

ValidationResult with errors, warnings, and normalized data.

Side effects

None.

Example

result = validator.validate_item(item, policy="lenient")

Plain meaning: Check a Wikidata item for profile compliance.

Source code in gkc/profiles/validation/validator.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def validate_item(
    self, entity_data: dict, policy: ValidationPolicy = "lenient"
) -> ValidationResult:
    """Validate a Wikidata item against the profile.

    Args:
        entity_data: Wikidata JSON entity data.
        policy: Validation policy ("strict" or "lenient").

    Returns:
        ValidationResult with errors, warnings, and normalized data.

    Side effects:
        None.

    Example:
        >>> result = validator.validate_item(item, policy="lenient")

    Plain meaning: Check a Wikidata item for profile compliance.
    """
    normalization = self._normalizer.normalize(entity_data, self.profile)
    model = self._generator.build_model()

    errors: List[ValidationIssue] = []
    warnings: List[ValidationIssue] = []

    self._add_normalization_issues(normalization, warnings, errors)

    try:
        model.model_validate(normalization.data, context={"policy": policy})
    except ValidationError as exc:
        errors.extend(self._errors_from_validation(exc, model))

    if policy == "lenient":
        warnings.extend(self._collect_lenient_warnings(normalization))

    ok = len(errors) == 0
    return ValidationResult(
        ok=ok,
        errors=errors,
        warnings=warnings,
        normalized=normalization.data,
    )

ValidationResult

Bases: BaseModel

Result of validating an item against a profile.

Attributes:

Name Type Description
ok bool

Whether validation passed without errors.

errors List[ValidationIssue]

Validation errors.

warnings List[ValidationIssue]

Validation warnings.

normalized Dict[str, List[StatementData]]

Normalized statement data.

Plain meaning: Validation status and issues found.

Source code in gkc/profiles/validation/validator.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class ValidationResult(BaseModel):
    """Result of validating an item against a profile.

    Attributes:
        ok: Whether validation passed without errors.
        errors: Validation errors.
        warnings: Validation warnings.
        normalized: Normalized statement data.

    Plain meaning: Validation status and issues found.
    """

    ok: bool
    errors: List[ValidationIssue]
    warnings: List[ValidationIssue]
    normalized: Dict[str, List[StatementData]]

    def is_valid(self) -> bool:
        """Return True when validation has no errors.

        Returns:
            True if no errors are present.

        Side effects:
            None.

        Example:
            >>> result.is_valid()

        Plain meaning: Check if validation succeeded.
        """
        return self.ok

is_valid()

Return True when validation has no errors.

Returns:

Type Description
bool

True if no errors are present.

Side effects

None.

Example

result.is_valid()

Plain meaning: Check if validation succeeded.

Source code in gkc/profiles/validation/validator.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def is_valid(self) -> bool:
    """Return True when validation has no errors.

    Returns:
        True if no errors are present.

    Side effects:
        None.

    Example:
        >>> result.is_valid()

    Plain meaning: Check if validation succeeded.
    """
    return self.ok

FormSchemaGenerator

Generate form/CLI schemas from YAML profiles.

Parameters:

Name Type Description Default
profile ProfileDefinition

Parsed ProfileDefinition instance.

required
Side effects

None.

Example

schema = FormSchemaGenerator(profile).build_schema()

Plain meaning: Convert a profile into a form-friendly schema.

Source code in gkc/profiles/generators/form_generator.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
class FormSchemaGenerator:
    """Generate form/CLI schemas from YAML profiles.

    Args:
        profile: Parsed ProfileDefinition instance.

    Side effects:
        None.

    Example:
        >>> schema = FormSchemaGenerator(profile).build_schema()

    Plain meaning: Convert a profile into a form-friendly schema.
    """

    def __init__(self, profile: ProfileDefinition):
        self.profile = profile

    def build_schema(self) -> dict[str, Any]:
        """Build a form schema dictionary for the profile.

        Returns:
            Dictionary describing statements, qualifiers, and references.

        Side effects:
            None.

        Example:
            >>> schema = FormSchemaGenerator(profile).build_schema()

        Plain meaning: Export statement definitions for CLI or UI prompts.
        """
        return {
            "name": self.profile.name,
            "description": self.profile.description,
            "statements": [
                self._field_schema(field) for field in self.profile.statements
            ],
        }

    def _field_schema(self, field) -> dict[str, Any]:
        value = {
            "type": field.value.type,
            "fixed": getattr(field.value, "fixed", None),
            "label": field.value.label,
            "constraints": [c.model_dump() for c in field.value.constraints],
        }

        qualifiers = []
        for qualifier in field.qualifiers:
            qualifiers.append(
                {
                    "id": qualifier.id,
                    "label": qualifier.label,
                    "input_prompt": qualifier.input_prompt,
                    "io_map": [
                        entry.model_dump(by_alias=True) for entry in qualifier.io_map
                    ],
                    "required": qualifier.required,
                    "min_count": qualifier.min_count,
                    "max_count": qualifier.max_count,
                    "value": {
                        "type": qualifier.value.type,
                        "fixed": getattr(qualifier.value, "fixed", None),
                        "label": qualifier.value.label,
                        "constraints": [
                            c.model_dump() for c in qualifier.value.constraints
                        ],
                    },
                }
            )

        references = None
        if field.references:
            references = {
                "required": field.references.required,
                "min_count": field.references.min_count,
                "input_prompt": field.references.input_prompt,
                "validation_policy": field.references.validation_policy,
                "form_policy": field.references.form_policy,
                "allowed": [
                    self._reference_target_schema(target)
                    for target in field.references.allowed
                ],
                "target": (
                    self._reference_target_schema(field.references.target)
                    if field.references.target
                    else None
                ),
            }

        return {
            "id": field.id,
            "label": field.label,
            "input_prompt": field.input_prompt,
            "io_map": [entry.model_dump(by_alias=True) for entry in field.io_map],
            "required": field.required,
            "max_count": field.max_count,
            "validation_policy": field.validation_policy,
            "form_policy": field.form_policy,
            "value": value,
            "qualifiers": qualifiers,
            "references": references,
        }

    @staticmethod
    def _reference_target_schema(target) -> dict[str, Any]:
        if target is None:
            return {}
        return {
            "id": target.id,
            "label": target.label,
            "input_prompt": target.input_prompt,
            "io_map": [entry.model_dump(by_alias=True) for entry in target.io_map],
            "type": target.type,
            "description": target.description,
            "value_source": target.value_source,
            "allowed_items": (
                target.allowed_items.model_dump() if target.allowed_items else None
            ),
        }

build_schema()

Build a form schema dictionary for the profile.

Returns:

Type Description
dict[str, Any]

Dictionary describing statements, qualifiers, and references.

Side effects

None.

Example

schema = FormSchemaGenerator(profile).build_schema()

Plain meaning: Export statement definitions for CLI or UI prompts.

Source code in gkc/profiles/generators/form_generator.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def build_schema(self) -> dict[str, Any]:
    """Build a form schema dictionary for the profile.

    Returns:
        Dictionary describing statements, qualifiers, and references.

    Side effects:
        None.

    Example:
        >>> schema = FormSchemaGenerator(profile).build_schema()

    Plain meaning: Export statement definitions for CLI or UI prompts.
    """
    return {
        "name": self.profile.name,
        "description": self.profile.description,
        "statements": [
            self._field_schema(field) for field in self.profile.statements
        ],
    }

Examples

Load a YAML Profile

from gkc.profiles import ProfileLoader

loader = ProfileLoader()
profile = loader.load_from_file(
    "/path/to/SpiritSafe/profiles/TribalGovernmentUS/profile.yaml"
)
print(profile.name)

Generate a Form Schema

from gkc.profiles import FormSchemaGenerator, ProfileLoader

profile = ProfileLoader().load_from_file(
    "/path/to/SpiritSafe/profiles/TribalGovernmentUS/profile.yaml"
)
form_schema = FormSchemaGenerator(profile).build_schema()
print(form_schema["statements"][0]["label"])

Validate a Wikidata Item (Lenient)

from gkc.profiles import ProfileLoader, ProfileValidator

profile = ProfileLoader().load_from_file(
    "/path/to/SpiritSafe/profiles/TribalGovernmentUS/profile.yaml"
)
validator = ProfileValidator(profile)
result = validator.validate_item(item_json, policy="lenient")

if result.ok:
    print("Valid (lenient)")
    for warning in result.warnings:
        print(warning.message)

Validate a Wikidata Item (Strict)

from gkc.profiles import ProfileLoader, ProfileValidator

profile = ProfileLoader().load_from_file(
    "/path/to/SpiritSafe/profiles/TribalGovernmentUS/profile.yaml"
)
validator = ProfileValidator(profile)
result = validator.validate_item(item_json, policy="strict")

if not result.ok:
    for error in result.errors:
        print(error.message)

Error Handling

Profile Schema Validation Errors

from gkc.profiles import ProfileLoader

loader = ProfileLoader()
try:
    loader.load_from_file("bad_profile.yaml")
except ValueError as exc:
    print(f"Schema error: {exc}")

See Also

  • Mash - Load Wikidata items for validation
  • ShEx - Schema validation against EntitySchemas
  • CLI Profiles - Profile commands