# -*- coding: utf-8 -*-
"""
Hugging Face Spaces Dashboard for NSN Integration
Multi-panel interactive dashboard for contributor challenges
"""
import gradio as gr
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from typing import Dict, List, Tuple
import json
from backend_telemetry_rank_adapter import BackendTelemetryRankAdapter
from edit_propagation_engine import EditPropagationEngine
from rank_feedback_generator import RankFeedbackGenerator
from ensemble_inference_manager import EnsembleInferenceManager
class NSNDashboard:
"""Hugging Face Spaces Dashboard for NSN Integration"""
def __init__(self):
self.telemetry_adapter = BackendTelemetryRankAdapter()
self.propagation_engine = EditPropagationEngine()
self.feedback_generator = RankFeedbackGenerator()
self.ensemble_manager = EnsembleInferenceManager()
# Panel 1: FLOPs vs Reliability (per backend)
def create_flops_reliability_chart(self, backend_id: str) -> go.Figure:
"""Line chart of rank vs reliability across backend states"""
ranks = [8, 16, 32, 64, 128, 256]
# Simulate different backend states
states = {
'Optimal': {'error_rate': 0.01, 'coherence_time': 150.0, 'gate_fidelity': 0.99},
'Good': {'error_rate': 0.03, 'coherence_time': 100.0, 'gate_fidelity': 0.96},
'Degraded': {'error_rate': 0.06, 'coherence_time': 60.0, 'gate_fidelity': 0.92},
'Poor': {'error_rate': 0.10, 'coherence_time': 30.0, 'gate_fidelity': 0.88}
}
fig = go.Figure()
for state_name, telemetry in states.items():
reliabilities = []
flops = []
for rank in ranks:
result = self.telemetry_adapter.adapt_rank(
backend_id=backend_id,
telemetry=telemetry,
current_rank=rank
)
reliabilities.append(result.reliability_score)
flops.append(rank * 1e6) # Approximate FLOPs
fig.add_trace(go.Scatter(
x=flops,
y=reliabilities,
mode='lines+markers',
name=state_name,
line=dict(width=2),
marker=dict(size=8)
))
fig.update_layout(
title=f'FLOPs vs Reliability - {backend_id}',
xaxis_title='FLOPs',
yaxis_title='Reliability Score',
xaxis_type='log',
template='plotly_white',
height=400
)
return fig
# Panel 2: Multilingual Heatmap (accuracy across ranks)
def create_multilingual_heatmap(self, languages: List[str]) -> go.Figure:
"""Heatmap of accuracy across languages and ranks"""
ranks = [8, 16, 32, 64, 128, 256]
# Simulate accuracy data
accuracy_matrix = []
for lang in languages:
lang_accuracies = []
base_accuracy = 0.95 if lang in ['english', 'chinese', 'spanish'] else 0.75
for rank in ranks:
# Higher ranks = higher accuracy
accuracy = base_accuracy + (rank / 256.0) * 0.1
accuracy = min(accuracy, 0.99)
lang_accuracies.append(accuracy)
accuracy_matrix.append(lang_accuracies)
fig = go.Figure(data=go.Heatmap(
z=accuracy_matrix,
x=[f'Rank {r}' for r in ranks],
y=languages,
colorscale='RdYlGn',
text=[[f'{val:.3f}' for val in row] for row in accuracy_matrix],
texttemplate='%{text}',
textfont={"size": 10},
colorbar=dict(title='Accuracy')
))
fig.update_layout(
title='Multilingual Edit Accuracy Across Ranks',
xaxis_title='NSN Rank',
yaxis_title='Language',
template='plotly_white',
height=400
)
return fig
# Panel 3: Subspace Containment Graphs
def create_containment_heatmap(self, languages: List[str], rank: int) -> go.Figure:
"""Heatmap of containment scores with flow arrows"""
heatmap_data = self.propagation_engine.compute_containment_heatmap(languages, rank)
fig = go.Figure(data=go.Heatmap(
z=heatmap_data,
x=languages,
y=languages,
colorscale='Blues',
text=[[f'{val:.2f}' for val in row] for row in heatmap_data],
texttemplate='%{text}',
textfont={"size": 10},
colorbar=dict(title='Containment Score')
))
# Add flow arrows for high containment
annotations = []
for i, source in enumerate(languages):
for j, target in enumerate(languages):
if i != j and heatmap_data[i][j] > 0.75:
annotations.append(dict(
x=j,
y=i,
text='→',
showarrow=False,
font=dict(size=20, color='red')
))
fig.update_layout(
title=f'Subspace Containment Matrix (Rank {rank})',
xaxis_title='Target Language',
yaxis_title='Source Language',
annotations=annotations,
template='plotly_white',
height=500
)
return fig
# Panel 4: Pareto Frontier (efficiency vs expressiveness)
def create_pareto_frontier(self, contributor_data: List[Dict]) -> go.Figure:
"""Scatter plot showing efficiency vs accuracy trade-off"""
fig = go.Figure()
# Group by contributor
contributors = {}
for data in contributor_data:
cid = data['contributor_id']
if cid not in contributors:
contributors[cid] = {'efficiency': [], 'accuracy': [], 'ranks': []}
contributors[cid]['efficiency'].append(data['efficiency'])
contributors[cid]['accuracy'].append(data['accuracy'])
contributors[cid]['ranks'].append(data['rank'])
# Plot each contributor
for cid, data in contributors.items():
fig.add_trace(go.Scatter(
x=data['efficiency'],
y=data['accuracy'],
mode='markers+lines',
name=cid,
marker=dict(size=10),
text=[f'Rank {r}' for r in data['ranks']],
hovertemplate='%{text}
Efficiency: %{x:.2e}
Accuracy: %{y:.3f}'
))
# Add Pareto frontier
all_efficiency = [e for d in contributors.values() for e in d['efficiency']]
all_accuracy = [a for d in contributors.values() for a in d['accuracy']]
# Find Pareto optimal points
pareto_x, pareto_y = self._compute_pareto_frontier(all_efficiency, all_accuracy)
fig.add_trace(go.Scatter(
x=pareto_x,
y=pareto_y,
mode='lines',
name='Pareto Frontier',
line=dict(color='red', width=3, dash='dash')
))
fig.update_layout(
title='Efficiency vs Accuracy Pareto Frontier',
xaxis_title='Efficiency (Accuracy/FLOPs)',
yaxis_title='Accuracy',
xaxis_type='log',
template='plotly_white',
height=400
)
return fig
def _compute_pareto_frontier(self, x: List[float], y: List[float]) -> Tuple[List, List]:
"""Compute Pareto frontier points"""
points = sorted(zip(x, y), key=lambda p: (-p[0], -p[1]))
pareto_x, pareto_y = [], []
max_y = -float('inf')
for px, py in points:
if py > max_y:
pareto_x.append(px)
pareto_y.append(py)
max_y = py
return pareto_x, pareto_y
# Panel 5: Contributor Leaderboard + Feedback
def create_leaderboard_table(self, leaderboard_data: List[Dict]) -> pd.DataFrame:
"""Create leaderboard DataFrame"""
df = pd.DataFrame(leaderboard_data)
df = df.sort_values('total_score', ascending=False)
df['rank'] = range(1, len(df) + 1)
return df[['rank', 'contributor_id', 'badge', 'total_score',
'avg_accuracy', 'avg_efficiency', 'num_submissions']]
def create_feedback_panel(self, contributor_id: str) -> Dict:
"""Generate personalized feedback panel"""
panel = self.feedback_generator.generate_feedback_panel(contributor_id)
feedback_html = f"""
Badge: {panel['recommendation'].personalized_badge}
Recommended Rank: {panel['recommendation'].recommended_rank}
Confidence: {panel['recommendation'].confidence:.2%}