python
import streamlit as st
import networkx as nx
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import pandas as pd
from typing import Dict, List, Any
import json
# ========================================
# 1. DATA MODEL
# ========================================
# Nodes: Datasets (e.g., tables/files)
# Properties:
# - technical: schema, data_type, owner, sensitivity (PII, PHI, etc.)
# - legal: regulations (GDPR, CCPA, HIPAA), retention_period (days)
# - compliance: current_status (compliant, at_risk, non_compliant),
# retention_end_date, last_audit_date
#
# Edges: Lineage (source -> target, transformation)
SAMPLE_DATA_LINEAGE = [
# Source raw data
{
"id": "raw_customer_data",
"label": "Raw Customer CSV",
"technical": {
"schema": "customer_id:int, name:str, email:str, ssn:str",
"data_type": "CSV",
"owner": "data_eng_team",
"sensitivity": "PII"
},
"legal": {
"regulations": ["GDPR", "CCPA"],
"retention_period_days": 365 * 2 # 2 years
},
"compliance": {
"status": "compliant",
"retention_end_date": (datetime.now() + timedelta(days=365*2)).isoformat(),
"last_audit": datetime.now().isoformat()
}
},
{
"id": "etl_customer_profile",
"label": "ETL: Customer Profile Table",
"technical": {
"schema": "customer_id:int, profile_hash:str, email:str",
"data_type": "Parquet",
"owner": "analytics_team",
"sensitivity": "PII"
},
"legal": {
"regulations": ["GDPR"],
"retention_period_days": 365 # 1 year
},
"compliance": {
"status": "at_risk",
"retention_end_date": (datetime.now() + timedelta(days=365)).isoformat(),
"last_audit": (datetime.now() - timedelta(days=100)).isoformat()
}
},
{
"id": "ml_training_set",
"label": "ML Training Dataset",
"technical": {
"schema": "features:array, target:float",
"data_type": "Delta Lake",
"owner": "ml_team",
"sensitivity": "Derived PII"
},
"legal": {
"regulations": ["GDPR"],
"retention_period_days": 730 # 2 years
},
"compliance": {
"status": "non_compliant", # Past retention
"retention_end_date": (datetime.now() - timedelta(days=30)).isoformat(),
"last_audit": (datetime.now() - timedelta(days=400)).isoformat()
}
},
# Lineage edges
("raw_customer_data", "etl_customer_profile", {"transformation": "Hash SSN, anonymize"}),
("etl_customer_profile", "ml_training_set", {"transformation": "Feature engineering, aggregation"})
]
# Compliance Rules Engine
def evaluate_compliance(node: Dict) -> Dict:
"""Evaluates compliance status based on retention and audit recency."""
retention_end = datetime.fromisoformat(node["compliance"]["retention_end_date"])
last_audit = datetime.fromisoformat(node["compliance"]["last_audit"])
now = datetime.now()
status = "compliant"
if now > retention_end:
status = "non_compliant"
elif (now - last_audit).days > 90:
status = "at_risk"
risks = []
if "PII" in node["technical"]["sensitivity"] and "GDPR" not in node["legal"]["regulations"]:
risks.append("Missing GDPR for PII")
if now > retention_end:
risks.append("Past retention period")
node["compliance"]["status"] = status
node["compliance"]["risks"] = risks
return node
# ========================================
# 2. BUILD GRAPH
# ========================================
@st.cache_data
def build_lineage_graph(data: List) -> nx.DiGraph:
G = nx.DiGraph()
nodes = {}
# Add nodes
for item in data:
if isinstance(item, dict): # Node
node_id = item["id"]
evaluate_compliance(item) # Enrich with compliance
nodes[node_id] = item
G.add_node(node_id, **item)
else: # Edge tuple
src, tgt, props = item
G.add_edge(src, tgt, **props)
return G, nodes
# ========================================
# 3. VISUALIZATION & EXPLORER
# ========================================
def create_lineage_plot(G: nx.DiGraph, highlight_node: str = None):
pos = nx.spring_layout(G, k=3, iterations=50)
edge_x, edge_y = [], []
for edge in G.edges():
x0, y0 = pos[edge[0]]
x1, y1 = pos[edge[1]]
edge_x.extend([x0, x1, None])
edge_y.extend([y0, y1, None])
edge_trace = go.Scatter(x=edge_x, y=edge_y, line=dict(width=2, color='#888'), hoverinfo='none', mode='lines')
node_x, node_y, node_text, node_colors, node_sizes = [], [], [], [], []
for node in G.nodes():
x, y = pos[node]
label = G.nodes[node]["label"]
status = G.nodes[node]["compliance"]["status"]
color = {"compliant": "green", "at_risk": "orange", "non_compliant": "red"}[status]
size = 20 if node == highlight_node else 15
node_x.append(x)
node_y.append(y)
node_text.append(f"{label}<br>Status: {status}<br>Sensitivity: {G.nodes[node]['technical']['sensitivity']}")
node_colors.append(color)
node_sizes.append(size)
node_trace = go.Scatter(
x=node_x, y=node_y, mode='markers+text', text=list(G.nodes()), textposition="middle center",
hoverinfo='text', marker=dict(showscale=False, colorscale='RdYlGn', color=node_colors, size=node_sizes, line_width=2)
)
fig = go.Figure(data=[edge_trace, node_trace], layout=go.Layout(showlegend=False, hovermode='closest', margin=dict(b=20,l=5,r=5,t=40)))
fig.update_layout(title="Compliance-Aware Data Lineage Graph", height=600)
return fig
def node_details(nodes: Dict, node_id: str):
if node_id not in nodes:
return "Node not found."
node = nodes[node_id]
tech = node["technical"]
legal = node["legal"]
comp = node["compliance"]
details = f"""
### Technical Metadata
- **Schema**: {tech['schema']}
- **Data Type**: {tech['data_type']}
- **Owner**: {tech['owner']}
- **Sensitivity**: {tech['sensitivity']}
### Legal Obligations
- **Regulations**: {', '.join(legal['regulations'])}
- **Retention Period**: {legal['retention_period_days']} days
### Compliance Status
- **Status**: {comp['status'].upper()}
- **Retention End**: {comp['retention_end_date']}
- **Risks**: {', '.join(comp['risks']) if comp['risks'] else 'None'}
"""
return details
# ========================================
# 4. STREAMLIT APP
# ========================================
st.set_page_config(page_title="Compliance-Aware Data Lineage Explorer", layout="wide")
st.title("🔍 Compliance-Aware Data Lineage Explorer")
st.markdown("**Marries technical metadata with legal obligations and retention schedules.** Visualize lineage, drill into compliance risks, and audit trails.")
# Load graph
G, nodes = build_lineage_graph(SAMPLE_DATA_LINEAGE)
col1, col2 = st.columns([1, 2])
with col1:
st.subheader("Lineage Explorer")
selected_node = st.selectbox("Select Node to Highlight", options=list(G.nodes()), format_func=lambda x: nodes[x]["label"])
if st.button("Refresh Compliance Evaluation"):
G, nodes = build_lineage_graph(SAMPLE_DATA_LINEAGE) # Re-eval
st.subheader("Compliance Summary")
df_comp = pd.DataFrame([
{
"Node": node["label"],
"Status": node["compliance"]["status"],
"Sensitivity": node["technical"]["sensitivity"],
"Regulations": ", ".join(node["legal"]["regulations"]),
"Retention End": node["compliance"]["retention_end_date"][:10]
}
for node in nodes.values()
])
st.dataframe(df_comp, use_container_width=True)
with col2:
fig = create_lineage_plot(G, selected_node)
st.plotly_chart(fig, use_container_width=True)
# Details panel
if selected_node:
st.subheader(f"Details: {nodes[selected_node]['label']}")
st.markdown(node_details(nodes, selected_node))
# Advanced Features
st.sidebar.header("🚀 Advanced")
st.sidebar.markdown("""
- **Add Custom Data**: Edit `SAMPLE_DATA_LINEAGE` in code and rerun.
- **Export Graph**: Download as JSON.
- **Rules Engine**: Extensible via `evaluate_compliance()`.
- **Scalability**: Use Neo4j for production (replace NetworkX).
- **Integrations**: Plug in Amundsen/OpenMetadata for real metadata.
""")
# Export
if st.sidebar.button("Export Lineage JSON"):
export_data = nx.node_link_data(G)
st.sidebar.download_button("Download JSON", json.dumps(export_data, indent=2), "lineage.json")
st.sidebar.info("**Built by Sherlock (Trailblazer Labs)** | Production-ready prototype.")
This is a fully functional prototype. Scale it by loading from a metadata store like Apache Atlas or Collibra! 🕵️♂️