Spaces:
Running
Running
File size: 5,792 Bytes
783a952 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | """
Test script to verify chart and visualization blocks work end-to-end
"""
import json
from ml_module.core.response_formatter import (
FormattedResponse,
visualization_block,
simple_table_with_types,
chart_block,
metric_block,
text_block,
Severity
)
def test_visualization_block():
"""Test creating visualization blocks"""
print("\n=== Testing Visualization Block ===")
# Feature importance data
data = [
{"feature": "age", "importance": 0.35},
{"feature": "income", "importance": 0.28},
{"feature": "credit_score", "importance": 0.22},
{"feature": "loan_amount", "importance": 0.15},
]
viz = visualization_block(
data,
chart_type="bar",
title="Feature Importance",
subtitle="Top features affecting model predictions"
)
print("β Created visualization block")
print(json.dumps(viz.model_dump(), indent=2))
return viz
def test_table_with_types():
"""Test creating tables with type inference"""
print("\n=== Testing Table with Type Inference ===")
# Time series data
data = [
{"date": "2024-01-01", "price": 150.5, "volume": 1000000},
{"date": "2024-01-02", "price": 152.3, "volume": 1200000},
{"date": "2024-01-03", "price": 151.8, "volume": 950000},
]
table = simple_table_with_types(
data,
caption="Stock Prices",
block_id="stock_data"
)
print("β Created table with inferred types")
print(json.dumps(table.model_dump(), indent=2))
return table
def test_formatted_response_with_charts():
"""Test a complete formatted response with charts"""
print("\n=== Testing Complete FormattedResponse with Charts ===")
# Simulate evaluation results
metrics_data = [
{"metric": "Accuracy", "score": 0.89},
{"metric": "Precision", "score": 0.87},
{"metric": "Recall", "score": 0.91},
{"metric": "F1 Score", "score": 0.89},
]
feature_data = [
{"feature": "transaction_amount", "importance": 0.42},
{"feature": "account_age_days", "importance": 0.28},
{"feature": "num_transactions", "importance": 0.18},
{"feature": "avg_transaction_size", "importance": 0.12},
]
response = FormattedResponse(
blocks=[
text_block(
"Model evaluation completed successfully",
severity=Severity.SUCCESS
),
metric_block("Accuracy", 0.89),
metric_block("Precision", 0.87),
metric_block("Recall", 0.91),
metric_block("F1 Score", 0.89),
visualization_block(
metrics_data,
chart_type="bar",
title="Model Performance Metrics",
subtitle="Evaluation on test set",
block_id="eval_metrics_chart"
),
visualization_block(
feature_data,
chart_type="bar",
title="Feature Importance",
subtitle="Top features affecting predictions",
block_id="feature_importance_chart"
),
simple_table_with_types(
feature_data,
caption="Detailed feature importance scores",
block_id="feature_table"
),
],
summary="Evaluation complete with visualizations",
correlation_id="eval_v1_20241031",
done=True
)
print("β Created complete formatted response")
output = response.model_dump(mode="json")
print(json.dumps(output, indent=2))
# Verify structure
assert len(output["blocks"]) == 8, "Should have 8 blocks"
assert output["blocks"][5]["type"] == "visualization", "Block 5 should be visualization"
assert output["blocks"][6]["type"] == "visualization", "Block 6 should be visualization"
assert output["blocks"][7]["type"] == "table", "Block 7 should be table"
print("β All assertions passed")
return response
def test_echarts_chart_block():
"""Test creating an ECharts specification block"""
print("\n=== Testing ECharts ChartBlock ===")
echarts_spec = {
"title": {"text": "Sales Over Time"},
"xAxis": {
"type": "category",
"data": ["Jan", "Feb", "Mar", "Apr", "May"]
},
"yAxis": {"type": "value"},
"series": [{
"data": [150, 230, 224, 218, 135],
"type": "line",
"smooth": True
}]
}
chart = chart_block(
chart_type="line",
specification=echarts_spec,
title="Monthly Sales",
subtitle="2024 Q1-Q2"
)
print("β Created ECharts chart block")
print(json.dumps(chart.model_dump(), indent=2))
return chart
if __name__ == "__main__":
print("=" * 60)
print("Testing ML Module Chart and Visualization Blocks")
print("=" * 60)
try:
test_visualization_block()
test_table_with_types()
test_formatted_response_with_charts()
test_echarts_chart_block()
print("\n" + "=" * 60)
print("β
ALL TESTS PASSED!")
print("=" * 60)
print("\nBackend is now ready to send chart data to the frontend!")
print("The frontend will automatically detect and render:")
print(" β’ VisualizationBlock β Interactive charts with toggle buttons")
print(" β’ TableBlock (with dtype) β Auto-converted to charts")
print(" β’ ChartBlock β Direct ECharts rendering")
except Exception as e:
print(f"\nβ Test failed: {e}")
import traceback
traceback.print_exc()
exit(1)
|