-
Notifications
You must be signed in to change notification settings - Fork 115
Function to visualize a GraphSchema object or dict #398
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
stellasia
wants to merge
4
commits into
neo4j:main
Choose a base branch
from
stellasia:feature/schema-viz
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
4 commits
Select commit
Hold shift + click to select a range
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
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
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
Large diffs are not rendered by default.
Oops, something went wrong.
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
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,14 @@ | ||
# Copyright (c) "Neo4j" | ||
# Neo4j Sweden AB [https://neo4j.com] | ||
# # | ||
# 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 | ||
# # | ||
# https://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. |
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,115 @@ | ||
# Copyright (c) "Neo4j" | ||
# Neo4j Sweden AB [https://neo4j.com] | ||
# # | ||
# 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 | ||
# # | ||
# https://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 Any, Union | ||
|
||
try: | ||
from neo4j_viz import VisualizationGraph, Node, Relationship | ||
except ImportError: | ||
VisualizationGraph = Node = Relationship = None # type: ignore | ||
|
||
from neo4j_graphrag.experimental.components.schema import ( | ||
GraphSchema, | ||
NodeType, | ||
PropertyType, | ||
) | ||
|
||
|
||
def schema_visualization( | ||
schema: Union[dict[str, Any], GraphSchema], | ||
) -> VisualizationGraph: | ||
"""Helper function to visualize a GraphSchema using the neo4j-viz library. | ||
|
||
Usage: | ||
|
||
.. code:: python | ||
|
||
VG = schema_visualization(schema) | ||
html = VG.render() | ||
|
||
# in Jupyter: | ||
display(html) | ||
|
||
# to save the generated HTML | ||
with open("my_schema.html", "w") as f: | ||
f.write(html.data) | ||
""" | ||
if VisualizationGraph is None: | ||
raise ImportError( | ||
"Please install neo4j-viz to use the graph schema visualization feature: pip install neo4j-viz" | ||
) | ||
|
||
schema_object = GraphSchema.model_validate(schema) | ||
|
||
def _format_property_name(p: PropertyType) -> str: | ||
""" | ||
|
||
Args: | ||
p (PropertyType): the property to be formatted | ||
|
||
Returns: | ||
str: the property name, suffixed with '*' if the property is required | ||
|
||
""" | ||
return p.name + ("*" if p.required else "") | ||
|
||
def _relationship_properties(rel_type: str) -> dict[str, str]: | ||
"""Returns a dict {prop_name: prop_type} for all relationship properties. | ||
|
||
Args: | ||
rel_type (str): the relationship type | ||
|
||
Returns: | ||
dict[str, str]: the relationship properties {name: type} mapping for display | ||
""" | ||
for relationship_type in schema_object.relationship_types: | ||
if relationship_type.label != rel_type: | ||
continue | ||
return { | ||
_format_property_name(p): p.type for p in relationship_type.properties | ||
} | ||
return {} | ||
|
||
def _node_properties(node_type: NodeType) -> dict[str, str]: | ||
"""Returns a dict {prop_name: prop_type} for all node properties. | ||
|
||
Args: | ||
node_type (NodeType): the node type object | ||
|
||
Returns: | ||
dict[str, str]: the node properties {name: type} mapping for display | ||
""" | ||
return {_format_property_name(p): p.type for p in node_type.properties} | ||
|
||
nodes = [ | ||
Node( # type: ignore | ||
id=node_type.label, | ||
caption=node_type.label, | ||
properties=_node_properties(node_type), | ||
) | ||
for node_type in schema_object.node_types | ||
] | ||
relationships = [ | ||
Relationship( # type: ignore | ||
source=pattern[0], | ||
target=pattern[2], | ||
caption=pattern[1], | ||
properties=_relationship_properties(pattern[1]), | ||
) | ||
for pattern in schema_object.patterns | ||
] | ||
|
||
VG = VisualizationGraph(nodes=nodes, relationships=relationships) | ||
VG.color_nodes(field="caption") | ||
return VG |
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,14 @@ | ||
# Copyright (c) "Neo4j" | ||
# Neo4j Sweden AB [https://neo4j.com] | ||
# # | ||
# 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 | ||
# # | ||
# https://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. |
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,107 @@ | ||
# Copyright (c) "Neo4j" | ||
# Neo4j Sweden AB [https://neo4j.com] | ||
# # | ||
# 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 | ||
# # | ||
# https://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 Any | ||
from unittest.mock import patch | ||
|
||
import pytest | ||
from pydantic import ValidationError | ||
|
||
from neo4j_viz import VisualizationGraph | ||
from neo4j_graphrag.experimental.components.schema import GraphSchema | ||
from neo4j_graphrag.experimental.utils.schema import schema_visualization | ||
|
||
|
||
@pytest.fixture(scope="module") | ||
def valid_schema_dict() -> dict[str, Any]: | ||
return { | ||
"node_types": [ | ||
"Location", | ||
{ | ||
"label": "Person", | ||
"properties": [ | ||
{"name": "name", "type": "STRING", "required": True}, | ||
{"name": "birthYear", "type": "INTEGER"}, | ||
], | ||
}, | ||
], | ||
"relationship_types": [ | ||
"BORN_IN", | ||
{ | ||
"label": "KNOWS", | ||
"properties": [ | ||
{"name": "since", "type": "LOCAL_DATETIME"}, | ||
], | ||
}, | ||
], | ||
"patterns": [ | ||
("Person", "BORN_IN", "Location"), | ||
("Person", "KNOWS", "Person"), | ||
], | ||
} | ||
|
||
|
||
@pytest.fixture(scope="module") | ||
def invalid_schema_dict() -> dict[str, Any]: | ||
return { | ||
"node_types": [ | ||
{ | ||
"label": "Person", | ||
"properties": [ | ||
{"name": "name", "type": "STRING", "required": True}, | ||
{"name": "birthYear", "type": "INTEGER"}, | ||
], | ||
}, | ||
], | ||
"relationship_types": [ | ||
"BORN_IN", | ||
], | ||
"patterns": [ | ||
( | ||
"Person", | ||
"BORN_IN", | ||
"Location", | ||
), # invalid pattern, "Location" node type not defined | ||
], | ||
} | ||
|
||
|
||
@patch("neo4j_graphrag.experimental.utils.schema.neo4j_viz", None) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should patch |
||
def test_schema_visualization_import_error() -> None: | ||
with pytest.raises(ImportError): | ||
schema_visualization({}) | ||
|
||
|
||
def test_schema_visualization_invalid_schema_dict( | ||
invalid_schema_dict: dict[str, Any], | ||
) -> None: | ||
with pytest.raises(ValidationError): | ||
schema_visualization(invalid_schema_dict) | ||
|
||
|
||
def test_schema_visualization_valid_schema_dict( | ||
valid_schema_dict: dict[str, Any], | ||
) -> None: | ||
g = schema_visualization(valid_schema_dict) | ||
assert isinstance(g, VisualizationGraph) | ||
assert len(g.nodes) == 2 | ||
assert len(g.relationships) == 2 | ||
|
||
|
||
def test_schema_visualization_schema_object(valid_schema_dict: dict[str, Any]) -> None: | ||
schema = GraphSchema.model_validate(valid_schema_dict) | ||
g = schema_visualization(schema) | ||
assert isinstance(g, VisualizationGraph) | ||
assert len(g.nodes) == 2 | ||
assert len(g.relationships) == 2 |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
should we use
TYPE_CHECKING
instead? what should be a rule of thumb for cases like this to avoid handling them differently across the package?