-
Notifications
You must be signed in to change notification settings - Fork 3
Added schema validation #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dwnoble
wants to merge
20
commits into
datacommonsorg:main
Choose a base branch
from
dwnoble:schema-validation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
22bec9b
migrated to uv
dwnoble ee1854e
file formatting, more uv migrations
dwnoble 363ca4c
unit test fixes
dwnoble 0de6c30
python version fix
dwnoble ff20e87
test fixes
dwnoble 3c0fa7b
Added schema validation
dwnoble ca1b4bd
updated lockfile
dwnoble 2c25b95
Added initial schema validation service and in memory knowledge graph…
dwnoble d8d6f6f
merged
dwnoble 96bd55c
cleanup
dwnoble c3c8b66
test fixes
dwnoble b0c5955
Apply suggestions from code review
dwnoble b6b33e2
Apply suggestions from code review
dwnoble 08e0754
test cases
dwnoble 05a9386
refactor
dwnoble c3884f0
header
dwnoble 3cf2e15
fixed readme
dwnoble 8ae1388
readme fixes
dwnoble 0bce7e7
readme fixes
dwnoble 334411a
readme fixes
dwnoble File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
81 changes: 81 additions & 0 deletions
81
packages/datacommons-schema/datacommons_schema/knowledge_graph.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| # Copyright 2026 Google LLC. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from typing import List, Dict, Union, Optional | ||
| from rdflib import Graph | ||
| import json | ||
|
|
||
| from datacommons_schema.services.schema_validation_service import SchemaValidationService, SchemaReport, ValidationReport, ValidationError | ||
|
|
||
| class KnowledgeGraph: | ||
| """ | ||
| An in-memory Knowledge Graph using rdflib. | ||
| """ | ||
| def __init__(self, namespace: str, default_prefix: str = "ex"): | ||
| self.namespace = namespace | ||
| self.default_prefix = default_prefix | ||
| self._graph = Graph() | ||
| # Bind the default prefix to the namespace | ||
| self._graph.bind(self.default_prefix, self.namespace) | ||
|
|
||
| def validate(self, new_graph: Graph) -> ValidationReport: | ||
| # 1. Extract existing rules to serve as context | ||
| # Note: In a real high-perf scenario, we would cache the 'rules' | ||
| # instead of re-extracting them from self._graph every time. | ||
| main_validator = SchemaValidationService(self._graph) | ||
|
|
||
| # 2. Check Schema Integrity of NEW nodes | ||
| # Use existing classes as context so we don't flag references to existing classes as "Undefined" | ||
| temp_validator = SchemaValidationService(new_graph) | ||
| schema_report = temp_validator.validate_schema_integrity(context_classes=main_validator.rules.classes) | ||
|
|
||
| if not schema_report.is_valid: | ||
| # Map schema errors to validation errors | ||
| schem_errors = [] | ||
| for se in schema_report.errors: | ||
| schem_errors.append(ValidationError( | ||
| subject=se.subject, | ||
| predicate="N/A", | ||
| object="N/A", | ||
| message=f"Schema Integrity Error: {se.issue} - {se.message}", | ||
| rule_type="SchemaIntegrity" | ||
| )) | ||
| return ValidationReport( | ||
| is_valid=False, | ||
| error_count=len(schem_errors), | ||
| errors=schem_errors | ||
| ) | ||
|
|
||
| # 3. Check Data Validation | ||
| # Validates 'new_graph' against 'self._graph' rules and context | ||
| return main_validator.validate(new_graph, context_graph=self._graph) | ||
|
|
||
| def add(self, nodes: Union[Dict, List[Dict]]) -> None: | ||
| temp_graph = self._load_graph(nodes) | ||
| report = self.validate(temp_graph) | ||
| if not report.is_valid: | ||
| error_msgs = "\n".join([f"{e.subject}: {e.message}" for e in report.errors]) | ||
| raise ValueError(f"Cannot add invalid nodes:\n{error_msgs}") | ||
|
|
||
| # If valid, merge | ||
| self._graph += temp_graph | ||
|
|
||
| def _load_graph(self, jsonld_input: Union[Dict, List[Dict], str]) -> Graph: | ||
| g = Graph() | ||
| if isinstance(jsonld_input, (dict, list)): | ||
| data = json.dumps(jsonld_input) | ||
| else: | ||
| data = jsonld_input | ||
| g.parse(data=data, format="json-ld") | ||
| return g | ||
Empty file.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.