feat: Add PyVis graph visualization for lineage
Browse files- .vscode/launch.json +15 -0
- README.md +5 -0
- requirements.txt +29 -0
- scribe_python_client/cli.py +4 -0
- scribe_python_client/client.py +14 -1
- scribe_python_client/lineage_graph.py +302 -0
- scribe_python_client/version.py +1 -1
.vscode/launch.json
CHANGED
|
@@ -11,6 +11,21 @@
|
|
| 11 |
"request": "launch",
|
| 12 |
"program": "${file}",
|
| 13 |
"console": "internalConsole"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
}
|
| 15 |
]
|
| 16 |
}
|
|
|
|
| 11 |
"request": "launch",
|
| 12 |
"program": "${file}",
|
| 13 |
"console": "internalConsole"
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"name": "Query Lineage",
|
| 17 |
+
"type": "debugpy",
|
| 18 |
+
"request": "launch",
|
| 19 |
+
"module": "scribe_python_client.cli",
|
| 20 |
+
"console": "internalConsole",
|
| 21 |
+
"args": [
|
| 22 |
+
"--api-call",
|
| 23 |
+
"query-lineage",
|
| 24 |
+
"--query",
|
| 25 |
+
"{\"columns\": [\"asset_name\", \"asset_type\", \"parent_name\", \"parent_type\", \"external_id\", \"parent_external_id\", \"uri\"], \"filters\": [{\"col\": \"logical_app\", \"op\": \"==\", \"val\": \"Astro-Analytics-Discovery\"}, {\"col\": \"logical_app_version\", \"op\": \"==\", \"val\": \"36\"}], \"orderby\": []}",
|
| 26 |
+
"--lineage-graph-file",
|
| 27 |
+
"lineage_graph.html",
|
| 28 |
+
]
|
| 29 |
}
|
| 30 |
]
|
| 31 |
}
|
README.md
CHANGED
|
@@ -98,6 +98,11 @@ Run a custom query on the lineage dataset:
|
|
| 98 |
scribe-client --api-call query-lineage --query "{\"columns\": [\"asset_name\", \"asset_type\"], \"filters\": [{\"col\": \"asset_type\", \"op\": \"==\", \"val\": \"repo\"}], \"orderby\": [], \"row_limit\": 10}"
|
| 99 |
```
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
### Notes
|
| 102 |
- Replace the `--query` argument with your desired query in JSON format.
|
| 103 |
- Ensure that the query structure matches the dataset schema for accurate results.
|
|
|
|
| 98 |
scribe-client --api-call query-lineage --query "{\"columns\": [\"asset_name\", \"asset_type\"], \"filters\": [{\"col\": \"asset_type\", \"op\": \"==\", \"val\": \"repo\"}], \"orderby\": [], \"row_limit\": 10}"
|
| 99 |
```
|
| 100 |
|
| 101 |
+
Run a custom query on the lineage dataset and create a graph of the lineage:
|
| 102 |
+
```bash
|
| 103 |
+
scribe-client --api-call query-lineage --query "{\"columns\": [\"asset_name\", \"asset_type\", \"parent_name\", \"parent_type\", \"external_id\", \"parent_external_id\", \"uri\"], \"filters\": [{\"col\": \"logical_app\", \"op\": \"==\", \"val\": \"Astro-Analytics-Discovery\"}, {\"col\": \"logical_app_version\", \"op\": \"==\", \"val\": \"36\"}], \"orderby\": []}" --lineage-graph-file lineage-graph.html
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
### Notes
|
| 107 |
- Replace the `--query` argument with your desired query in JSON format.
|
| 108 |
- Ensure that the query structure matches the dataset schema for accurate results.
|
requirements.txt
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
asttokens==3.0.0
|
| 2 |
+
certifi==2025.1.31
|
| 3 |
+
charset-normalizer==3.4.1
|
| 4 |
+
decorator==5.2.1
|
| 5 |
+
exceptiongroup==1.3.0
|
| 6 |
+
executing==2.2.0
|
| 7 |
+
idna==3.10
|
| 8 |
+
ipython==8.37.0
|
| 9 |
+
jedi==0.19.2
|
| 10 |
+
Jinja2==3.1.6
|
| 11 |
+
jsonpickle==4.1.1
|
| 12 |
+
MarkupSafe==3.0.2
|
| 13 |
+
matplotlib-inline==0.1.7
|
| 14 |
+
networkx==3.4.2
|
| 15 |
+
parso==0.8.4
|
| 16 |
+
pexpect==4.9.0
|
| 17 |
+
prompt_toolkit==3.0.51
|
| 18 |
+
ptyprocess==0.7.0
|
| 19 |
+
pure_eval==0.2.3
|
| 20 |
+
Pygments==2.19.2
|
| 21 |
+
PyJWT==2.10.1
|
| 22 |
+
pyvis==0.3.2
|
| 23 |
+
requests==2.32.3
|
| 24 |
+
-e git+ssh://git@github.com/scribe-security/scribe-python-client.git@21e95e1bdd4f7b25b506baa4cd03174e1301ba12#egg=scribe_python_client
|
| 25 |
+
stack-data==0.6.3
|
| 26 |
+
traitlets==5.14.3
|
| 27 |
+
typing_extensions==4.14.0
|
| 28 |
+
urllib3==2.4.0
|
| 29 |
+
wcwidth==0.2.13
|
scribe_python_client/cli.py
CHANGED
|
@@ -25,6 +25,7 @@ def main():
|
|
| 25 |
parser.add_argument("--product-name", required=False, help="The name of the product (required for specific API calls)")
|
| 26 |
parser.add_argument("--attestation-id", required=False, help="The ID of the attestation (required for get-attestation API call)")
|
| 27 |
parser.add_argument("--query", required=False, help="The query to run on the dataset (required for query commands)")
|
|
|
|
| 28 |
|
| 29 |
args = parser.parse_args()
|
| 30 |
|
|
@@ -75,6 +76,9 @@ def main():
|
|
| 75 |
print(client.query_policy_results(querystr=args.query))
|
| 76 |
elif args.api_call == "query-lineage":
|
| 77 |
print(client.query_lineage(querystr=args.query))
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
if __name__ == "__main__":
|
| 80 |
main()
|
|
|
|
| 25 |
parser.add_argument("--product-name", required=False, help="The name of the product (required for specific API calls)")
|
| 26 |
parser.add_argument("--attestation-id", required=False, help="The ID of the attestation (required for get-attestation API call)")
|
| 27 |
parser.add_argument("--query", required=False, help="The query to run on the dataset (required for query commands)")
|
| 28 |
+
parser.add_argument("--lineage-graph-file", required=False, help="The file to save the lineage graph to (optional)")
|
| 29 |
|
| 30 |
args = parser.parse_args()
|
| 31 |
|
|
|
|
| 76 |
print(client.query_policy_results(querystr=args.query))
|
| 77 |
elif args.api_call == "query-lineage":
|
| 78 |
print(client.query_lineage(querystr=args.query))
|
| 79 |
+
if args.lineage_graph_file:
|
| 80 |
+
client.query_lineage(args.query, graph_filename=args.lineage_graph_file)
|
| 81 |
+
# logging.info(f"Lineage graph saved to {args.lineage_graph_file}")
|
| 82 |
|
| 83 |
if __name__ == "__main__":
|
| 84 |
main()
|
scribe_python_client/client.py
CHANGED
|
@@ -7,6 +7,7 @@ import jwt
|
|
| 7 |
import urllib #Needed for avoiding using requests, which modified the S3 presigned URL
|
| 8 |
|
| 9 |
from .utils import convert_timestamps, send_post_request, send_get_request, decode_jwt_token, querystr_to_json, att2statement
|
|
|
|
| 10 |
|
| 11 |
from .constants import (
|
| 12 |
SCRIBE_VULNERABILITIES_DATASET,
|
|
@@ -1033,12 +1034,24 @@ class ScribeClient:
|
|
| 1033 |
return f"{title}\n{self.format_query_result_table(r)}"
|
| 1034 |
return "Error running query"
|
| 1035 |
|
| 1036 |
-
def query_lineage(self, querystr, title="") -> str:
|
| 1037 |
logging.debug(f"Query lineage with: {querystr}")
|
| 1038 |
query = self.querystr_to_json(querystr)
|
| 1039 |
if query:
|
| 1040 |
r = self.query_superset(self.scribe_lineage_dataset, query, time_tokens=["timestamp"])
|
| 1041 |
if r:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1042 |
return f"{title}\n{self.format_query_result_table(r)}"
|
| 1043 |
return "Error running query"
|
| 1044 |
|
|
|
|
| 7 |
import urllib #Needed for avoiding using requests, which modified the S3 presigned URL
|
| 8 |
|
| 9 |
from .utils import convert_timestamps, send_post_request, send_get_request, decode_jwt_token, querystr_to_json, att2statement
|
| 10 |
+
from .lineage_graph import create_lineage_graph
|
| 11 |
|
| 12 |
from .constants import (
|
| 13 |
SCRIBE_VULNERABILITIES_DATASET,
|
|
|
|
| 1034 |
return f"{title}\n{self.format_query_result_table(r)}"
|
| 1035 |
return "Error running query"
|
| 1036 |
|
| 1037 |
+
def query_lineage(self, querystr, title="", graph_filename=None) -> str:
|
| 1038 |
logging.debug(f"Query lineage with: {querystr}")
|
| 1039 |
query = self.querystr_to_json(querystr)
|
| 1040 |
if query:
|
| 1041 |
r = self.query_superset(self.scribe_lineage_dataset, query, time_tokens=["timestamp"])
|
| 1042 |
if r:
|
| 1043 |
+
if graph_filename:
|
| 1044 |
+
required_fields = ["asset_name", "asset_type", "parent_name", "parent_type", "external_id", "parent_external_id", "uri"]
|
| 1045 |
+
columns = query.get("columns", [])
|
| 1046 |
+
if not all(field in columns for field in required_fields):
|
| 1047 |
+
logging.error(f"Query must include the following fields: {', '.join(required_fields)}")
|
| 1048 |
+
return "Error: Query must include required fields for lineage graph generation."
|
| 1049 |
+
|
| 1050 |
+
lineage_data = r["result"][0]["data"]
|
| 1051 |
+
full_path_filename = create_lineage_graph(lineage_data, output_file=graph_filename)
|
| 1052 |
+
logging.info(f"Lineage graph saved to {full_path_filename}")
|
| 1053 |
+
else:
|
| 1054 |
+
logging.warning("No graph filename provided, lineage graph will not be generated.")
|
| 1055 |
return f"{title}\n{self.format_query_result_table(r)}"
|
| 1056 |
return "Error running query"
|
| 1057 |
|
scribe_python_client/lineage_graph.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import networkx as nx
|
| 3 |
+
# import plotly.graph_objects as go
|
| 4 |
+
from pyvis.network import Network
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def create_network(data, include_types, type_to_position):
|
| 9 |
+
G = nx.DiGraph()
|
| 10 |
+
for record in data:
|
| 11 |
+
asset_type = record.get("asset_type")
|
| 12 |
+
parent_type = record.get("parent_type")
|
| 13 |
+
child = record.get("external_id")
|
| 14 |
+
parent = record.get("parent_external_id")
|
| 15 |
+
# Filter nodes based on allowed types.
|
| 16 |
+
add_child = include_types is None or asset_type in include_types
|
| 17 |
+
add_parent = include_types is None or parent_type in include_types
|
| 18 |
+
|
| 19 |
+
if add_child and child:
|
| 20 |
+
node_attrs = {"type": asset_type, "label": record.get("asset_name")}
|
| 21 |
+
if record.get("uri"):
|
| 22 |
+
node_attrs["uri"] = record.get("uri")
|
| 23 |
+
G.add_node(child, **node_attrs)
|
| 24 |
+
if parent and add_parent:
|
| 25 |
+
node_attrs = {"type": parent_type, "label": record.get("parent_name")}
|
| 26 |
+
if record.get("uri"):
|
| 27 |
+
node_attrs["uri"] = record.get("uri")
|
| 28 |
+
G.add_node(parent, **node_attrs)
|
| 29 |
+
if child and parent and add_child and add_parent:
|
| 30 |
+
G.add_edge(parent, child)
|
| 31 |
+
|
| 32 |
+
# Assign 'layer' attribute for each node based on its type.
|
| 33 |
+
for node in G.nodes():
|
| 34 |
+
node_type = G.nodes[node].get('type')
|
| 35 |
+
G.nodes[node]['layer'] = type_to_position.get(node_type, 1)
|
| 36 |
+
return G
|
| 37 |
+
|
| 38 |
+
# def visualize_network_plotly(data, include_types, type_to_position):
|
| 39 |
+
# """
|
| 40 |
+
# Build and return a Plotly figure of a network graph.
|
| 41 |
+
|
| 42 |
+
# Parameters:
|
| 43 |
+
# data (list): JSON array of records.
|
| 44 |
+
# include_types (set): Allowed asset types.
|
| 45 |
+
# type_to_position (dict): Mapping of asset types to numeric layer positions.
|
| 46 |
+
|
| 47 |
+
# Returns:
|
| 48 |
+
# go.Figure: The Plotly figure with the network visualization.
|
| 49 |
+
# """
|
| 50 |
+
# # Create network graph
|
| 51 |
+
|
| 52 |
+
# G = create_network(data, include_types, type_to_position)
|
| 53 |
+
# # Compute positions using a multipartite layout (vertical alignment)
|
| 54 |
+
# pos = nx.multipartite_layout(G, subset_key="layer", align="vertical")
|
| 55 |
+
|
| 56 |
+
# # Build edge coordinates for Plotly
|
| 57 |
+
# edge_x, edge_y = [], []
|
| 58 |
+
# for source, target in G.edges():
|
| 59 |
+
# x0, y0 = pos[source]
|
| 60 |
+
# x1, y1 = pos[target]
|
| 61 |
+
# edge_x.extend([x0, x1, None])
|
| 62 |
+
# edge_y.extend([y0, y1, None])
|
| 63 |
+
# edge_trace = go.Scatter(
|
| 64 |
+
# x=edge_x, y=edge_y,
|
| 65 |
+
# line=dict(width=1, color='#888'),
|
| 66 |
+
# hoverinfo='none',
|
| 67 |
+
# mode='lines'
|
| 68 |
+
# )
|
| 69 |
+
|
| 70 |
+
# # Build node coordinates and text lists.
|
| 71 |
+
# node_x, node_y = [], []
|
| 72 |
+
# node_text_trunc, node_text_hover, node_color = [], [], []
|
| 73 |
+
# for node in G.nodes():
|
| 74 |
+
# x, y = pos[node]
|
| 75 |
+
# node_x.append(x)
|
| 76 |
+
# node_y.append(y)
|
| 77 |
+
# full_label = G.nodes[node].get('label', str(node))
|
| 78 |
+
# truncated_label = full_label[0:30] # truncated version for display
|
| 79 |
+
# # Check for a "uri" attribute (lowercase) and create a clickable link if present.
|
| 80 |
+
# uri = G.nodes[node].get('uri')
|
| 81 |
+
# uri_link = f'<br><a href="{uri}" target="_blank">{uri}</a>' if uri else ""
|
| 82 |
+
# node_text_trunc.append(f"{truncated_label}<br>Type: {G.nodes[node].get('type')}")
|
| 83 |
+
# node_text_hover.append(f"{full_label}<br>Type: {G.nodes[node].get('type')}{uri_link}")
|
| 84 |
+
# node_color.append(G.nodes[node]['layer'])
|
| 85 |
+
|
| 86 |
+
# node_trace = go.Scatter(
|
| 87 |
+
# x=node_x, y=node_y,
|
| 88 |
+
# mode='markers+text',
|
| 89 |
+
# textposition="bottom center",
|
| 90 |
+
# hoverinfo='text',
|
| 91 |
+
# marker=dict(
|
| 92 |
+
# showscale=True,
|
| 93 |
+
# colorscale='YlGnBu',
|
| 94 |
+
# reversescale=True,
|
| 95 |
+
# color=node_color,
|
| 96 |
+
# size=15,
|
| 97 |
+
# colorbar=dict(title='Layer')
|
| 98 |
+
# ),
|
| 99 |
+
# text=node_text_trunc, # Display truncated text on the plot.
|
| 100 |
+
# hovertext=node_text_hover # Full text (with clickable URL if present) for hover.
|
| 101 |
+
# )
|
| 102 |
+
|
| 103 |
+
# # Create the Plotly figure.
|
| 104 |
+
# fig = go.Figure(data=[edge_trace, node_trace],
|
| 105 |
+
# layout=go.Layout(
|
| 106 |
+
# title='<br>Integrated Network Graph Visualization',
|
| 107 |
+
# titlefont_size=16,
|
| 108 |
+
# dragmode='pan',
|
| 109 |
+
# showlegend=False,
|
| 110 |
+
# hovermode='closest',
|
| 111 |
+
# margin=dict(b=20, l=5, r=5, t=40),
|
| 112 |
+
# width=1000,
|
| 113 |
+
# height=800,
|
| 114 |
+
# xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
|
| 115 |
+
# yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)
|
| 116 |
+
# ))
|
| 117 |
+
# return fig
|
| 118 |
+
|
| 119 |
+
def filter_network(data, include_types, include_fields):
|
| 120 |
+
"""
|
| 121 |
+
Filter the data to only include records of the specified types
|
| 122 |
+
and remove specified fields.
|
| 123 |
+
|
| 124 |
+
Parameters:
|
| 125 |
+
data (list): List of JSON records.
|
| 126 |
+
include_types (set): Asset types to keep.
|
| 127 |
+
include_fields (set): Fields to remove from records.
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
list: Filtered data.
|
| 131 |
+
"""
|
| 132 |
+
filtered_data = []
|
| 133 |
+
|
| 134 |
+
for record in data:
|
| 135 |
+
if record.get("asset_type") in include_types:
|
| 136 |
+
# Create a copy to avoid modifying original data
|
| 137 |
+
filtered_record = {key: value for key, value in record.items() if key in include_fields}
|
| 138 |
+
filtered_data.append(filtered_record)
|
| 139 |
+
|
| 140 |
+
return filtered_data
|
| 141 |
+
|
| 142 |
+
def visualize_network_pyvis(data, include_types, type_to_position, output_html = "graph.html"):
|
| 143 |
+
|
| 144 |
+
width="100%"
|
| 145 |
+
height="1200px"
|
| 146 |
+
layer_spacing=2.0
|
| 147 |
+
node_spacing=2.0
|
| 148 |
+
|
| 149 |
+
# import tempfile
|
| 150 |
+
# output_html = tempfile.NamedTemporaryFile(delete=False)
|
| 151 |
+
|
| 152 |
+
G = create_network(data, include_types, type_to_position) # Create the network graph
|
| 153 |
+
# 1. Assign hierarchy and determine types
|
| 154 |
+
nx.set_node_attributes(
|
| 155 |
+
G,
|
| 156 |
+
{n: type_to_position.get(attrs["type"], 0) for n, attrs in G.nodes(data=True)},
|
| 157 |
+
name="layer"
|
| 158 |
+
)
|
| 159 |
+
types = sorted({attrs["type"] for _, attrs in G.nodes(data=True)})
|
| 160 |
+
|
| 161 |
+
# 2. Layout
|
| 162 |
+
pos = nx.multipartite_layout(G, subset_key="layer", align="horizontal")
|
| 163 |
+
pos = {n: (x * layer_spacing * 1000, y * node_spacing * 1000) for n, (x, y) in pos.items()}
|
| 164 |
+
|
| 165 |
+
# 3. Assign colors
|
| 166 |
+
base_colors = ["#e6194B", "#3cb44b", "#ffe119", "#4363d8", "#f58231",
|
| 167 |
+
"#911eb4", "#46f0f0", "#f032e6", "#bcf60c", "#fabebe"]
|
| 168 |
+
color_map = {t: base_colors[i % len(base_colors)] for i, t in enumerate(types)}
|
| 169 |
+
|
| 170 |
+
# 4. Build the graph
|
| 171 |
+
net = Network(width=width, height=height, directed=True)
|
| 172 |
+
net.toggle_physics(False)
|
| 173 |
+
net.toggle_drag_nodes(True)
|
| 174 |
+
net.show_buttons(filter_=["physics", "interaction", "clustering"])
|
| 175 |
+
|
| 176 |
+
for node_id, attrs in G.nodes(data=True):
|
| 177 |
+
x, y = pos[node_id]
|
| 178 |
+
t = attrs["type"]
|
| 179 |
+
c = color_map[t]
|
| 180 |
+
net.add_node(node_id, label=attrs.get("label", str(node_id)), title=f"{attrs.get('label')}<br>Type: {t}<br>{attrs.get('uri','')}",
|
| 181 |
+
x=x, y=y, physics=False, group=t,
|
| 182 |
+
color={"background": c, "border": c, "highlight": {"background": c, "border": c}, "hover": {"background": c, "border": c}})
|
| 183 |
+
for u, v in G.edges():
|
| 184 |
+
net.add_edge(u, v)
|
| 185 |
+
|
| 186 |
+
# 5. Inject clustering + double-click expand
|
| 187 |
+
cluster_js = f"""
|
| 188 |
+
<script type="text/javascript">
|
| 189 |
+
window.addEventListener('load', () => {{
|
| 190 |
+
const types = {types};
|
| 191 |
+
const colors = {color_map};
|
| 192 |
+
types.forEach(t => {{
|
| 193 |
+
network.cluster({{
|
| 194 |
+
joinCondition: opts => opts.group === t,
|
| 195 |
+
clusterNodeProperties: {{
|
| 196 |
+
id: 'cluster:' + t,
|
| 197 |
+
label: 'Cluster: ' + t,
|
| 198 |
+
shape: 'box',
|
| 199 |
+
color: {{
|
| 200 |
+
background: colors[t],
|
| 201 |
+
border: colors[t],
|
| 202 |
+
highlight: {{background: colors[t], border: colors[t]}},
|
| 203 |
+
hover: {{background: colors[t], border: colors[t]}}
|
| 204 |
+
}}
|
| 205 |
+
}}
|
| 206 |
+
}});
|
| 207 |
+
}});
|
| 208 |
+
network.on('doubleClick', params => {{
|
| 209 |
+
if (params.nodes.length === 1) {{
|
| 210 |
+
const id = params.nodes[0];
|
| 211 |
+
if (network.isCluster(id)) {{
|
| 212 |
+
network.openCluster(id);
|
| 213 |
+
}}
|
| 214 |
+
}}
|
| 215 |
+
}});
|
| 216 |
+
}});
|
| 217 |
+
</script>
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
# 6. Inject a floating HTML legend panel
|
| 221 |
+
legend_html = "<div id='legend' style='position:fixed; top:10px; right:10px; background:white; border:1px solid #ccc; padding:10px; font-family:Arial;'><strong>Legend</strong><br>"
|
| 222 |
+
for t in types:
|
| 223 |
+
c = color_map[t]
|
| 224 |
+
legend_html += f"<div style='display:flex; align-items:center; margin-top:5px;'><span style='width:15px; height:15px; background:{c}; border:1px solid #000; display:inline-block; margin-right:5px;'></span>{t}</div>"
|
| 225 |
+
legend_html += "</div>"
|
| 226 |
+
|
| 227 |
+
# net.toggle_physics(True)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# Combine HTML parts
|
| 231 |
+
net.save_graph(output_html)
|
| 232 |
+
with open(output_html, "r+", encoding="utf-8") as f:
|
| 233 |
+
html = f.read().replace("</body>", cluster_js + legend_html + "\n</body>")
|
| 234 |
+
f.seek(0); f.write(html); f.truncate()
|
| 235 |
+
|
| 236 |
+
return output_html
|
| 237 |
+
|
| 238 |
+
def create_lineage_graph(lineage_data, type="pyvis", output_file="graph.html"):
|
| 239 |
+
|
| 240 |
+
all_types = {record.get("asset_type") for record in lineage_data if record.get("asset_type")}
|
| 241 |
+
# Exclude unwanted types.
|
| 242 |
+
exclude_types = {"user", "secret", "org_secret", "commit", "actor", "build_machine"}
|
| 243 |
+
types_to_position = {
|
| 244 |
+
"organization": 1,
|
| 245 |
+
"repo": 2,
|
| 246 |
+
"branch": 3,
|
| 247 |
+
"workflow": 4,
|
| 248 |
+
"workflow_run": 5,
|
| 249 |
+
"image": 6,
|
| 250 |
+
"pod": 7,
|
| 251 |
+
"namespace": 8
|
| 252 |
+
|
| 253 |
+
}
|
| 254 |
+
include_types = all_types - exclude_types
|
| 255 |
+
# Generate and display the network visualization.
|
| 256 |
+
if type == "plotly":
|
| 257 |
+
# fig = visualize_network_plotly(lineage_data, include_types, types_to_position)
|
| 258 |
+
return None
|
| 259 |
+
else:
|
| 260 |
+
output_file = Path(output_file)
|
| 261 |
+
output_file.touch(exist_ok=True)
|
| 262 |
+
output_file = output_file.resolve()
|
| 263 |
+
output_file = str(output_file)
|
| 264 |
+
file = visualize_network_pyvis(lineage_data, include_types, types_to_position, output_html=output_file)
|
| 265 |
+
return file
|
| 266 |
+
|
| 267 |
+
if __name__ == "__main__":
|
| 268 |
+
# Open the JSON file and load data.
|
| 269 |
+
filepath = "tmp/lineage.json"
|
| 270 |
+
with open(filepath, "r") as f:
|
| 271 |
+
data = json.load(f)
|
| 272 |
+
|
| 273 |
+
# Determine allowed asset types from the data.
|
| 274 |
+
all_types = {record.get("asset_type") for record in data if record.get("asset_type")}
|
| 275 |
+
# Exclude unwanted types.
|
| 276 |
+
exclude_types = {"user", "secret", "org_secret", "commit", "actor", "build_machine"}
|
| 277 |
+
include_types = all_types - exclude_types
|
| 278 |
+
|
| 279 |
+
# Define the mapping for layering.
|
| 280 |
+
type_to_position = {
|
| 281 |
+
"organization": 1,
|
| 282 |
+
"repo": 2,
|
| 283 |
+
"branch": 3,
|
| 284 |
+
"workflow": 4,
|
| 285 |
+
"workflow_run": 5,
|
| 286 |
+
"image": 6,
|
| 287 |
+
"pod": 7,
|
| 288 |
+
"namespace": 8
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
include_fields = [
|
| 292 |
+
"platform_name", "platform_type",
|
| 293 |
+
"asset_name", "asset_type","parent_name", "parent_type"
|
| 294 |
+
]
|
| 295 |
+
# Generate and display the network visualization.
|
| 296 |
+
# filetered = filter_network(data, include_types, include_fields)
|
| 297 |
+
# Touch file and get its full path:
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
filename = create_lineage_graph(data, output_file="tmp/lineage_graph.html")
|
| 301 |
+
print(f"Network graph saved to {filename}")
|
| 302 |
+
print(f"Open by browsing file:///{filename}")
|
scribe_python_client/version.py
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
__version__ = "0.1.
|
|
|
|
| 1 |
+
__version__ = "0.1.5"
|