File size: 11,963 Bytes
223a8c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
from typing import List, Dict, Any, Optional
import json

class DataVisualizationEngine:
    """Generate chart configurations from query results"""
    
    def create_chart(self, data: List[Dict], chart_type: str, config: Dict[str, Any]) -> Dict[str, Any]:
        """
        Create chart configuration from data
        
        Args:
            data: Query results
            chart_type: bar, line, pie, area, scatter, heatmap
            config: {
                "x_column": "date",
                "y_column": "revenue",
                "group_by": "category",
                "title": "Revenue by Date",
                "colors": ["#FFB800", "#00FF88"]
            }
        """
        try:
            if not data:
                return {'ok': False, 'error': 'No data provided'}
            
            x_column = config.get('x_column')
            y_column = config.get('y_column')
            
            if chart_type == 'pie':
                return self._create_pie_chart(data, config)
            elif chart_type == 'bar':
                return self._create_bar_chart(data, x_column, y_column, config)
            elif chart_type == 'line':
                return self._create_line_chart(data, x_column, y_column, config)
            elif chart_type == 'area':
                return self._create_area_chart(data, x_column, y_column, config)
            elif chart_type == 'scatter':
                return self._create_scatter_chart(data, x_column, y_column, config)
            elif chart_type == 'heatmap':
                return self._create_heatmap(data, config)
            else:
                return {'ok': False, 'error': f'Unknown chart type: {chart_type}'}
                
        except Exception as e:
            return {'ok': False, 'error': str(e)}
    
    def _create_pie_chart(self, data: List[Dict], config: Dict) -> Dict:
        """Create pie chart configuration"""
        label_column = config.get('label_column') or list(data[0].keys())[0]
        value_column = config.get('value_column') or list(data[0].keys())[1]
        
        labels = [str(row.get(label_column, '')) for row in data]
        values = [float(row.get(value_column, 0)) for row in data]
        
        return {
            'ok': True,
            'chart_type': 'pie',
            'data': {
                'labels': labels,
                'datasets': [{
                    'data': values,
                    'backgroundColor': config.get('colors', self._get_default_colors(len(labels)))
                }]
            },
            'options': {
                'title': config.get('title', 'Pie Chart'),
                'responsive': True
            }
        }
    
    def _create_bar_chart(self, data: List[Dict], x_column: str, y_column: str, config: Dict) -> Dict:
        """Create bar chart configuration"""
        labels = [str(row.get(x_column, '')) for row in data]
        values = [float(row.get(y_column, 0)) for row in data]
        
        group_by = config.get('group_by')
        
        if group_by:
            # Grouped bar chart
            datasets = self._create_grouped_datasets(data, x_column, y_column, group_by, config)
        else:
            # Simple bar chart
            datasets = [{
                'label': y_column,
                'data': values,
                'backgroundColor': config.get('colors', [self._get_default_colors(1)[0]])[0]
            }]
        
        return {
            'ok': True,
            'chart_type': 'bar',
            'data': {
                'labels': labels if not group_by else list(set(labels)),
                'datasets': datasets
            },
            'options': {
                'title': config.get('title', 'Bar Chart'),
                'responsive': True,
                'scales': {
                    'y': {'beginAtZero': True}
                }
            }
        }
    
    def _create_line_chart(self, data: List[Dict], x_column: str, y_column: str, config: Dict) -> Dict:
        """Create line chart configuration"""
        labels = [str(row.get(x_column, '')) for row in data]
        values = [float(row.get(y_column, 0)) for row in data]
        
        group_by = config.get('group_by')
        
        if group_by:
            datasets = self._create_grouped_datasets(data, x_column, y_column, group_by, config, chart_type='line')
        else:
            datasets = [{
                'label': y_column,
                'data': values,
                'borderColor': config.get('colors', [self._get_default_colors(1)[0]])[0],
                'fill': False,
                'tension': 0.4
            }]
        
        return {
            'ok': True,
            'chart_type': 'line',
            'data': {
                'labels': labels if not group_by else list(set(labels)),
                'datasets': datasets
            },
            'options': {
                'title': config.get('title', 'Line Chart'),
                'responsive': True,
                'scales': {
                    'y': {'beginAtZero': True}
                }
            }
        }
    
    def _create_area_chart(self, data: List[Dict], x_column: str, y_column: str, config: Dict) -> Dict:
        """Create area chart configuration"""
        chart = self._create_line_chart(data, x_column, y_column, config)
        chart['chart_type'] = 'area'
        
        # Enable fill for area chart
        for dataset in chart['data']['datasets']:
            dataset['fill'] = True
            dataset['backgroundColor'] = dataset['borderColor'] + '40'  # Add transparency
        
        return chart
    
    def _create_scatter_chart(self, data: List[Dict], x_column: str, y_column: str, config: Dict) -> Dict:
        """Create scatter chart configuration"""
        points = [{'x': float(row.get(x_column, 0)), 'y': float(row.get(y_column, 0))} for row in data]
        
        return {
            'ok': True,
            'chart_type': 'scatter',
            'data': {
                'datasets': [{
                    'label': f'{y_column} vs {x_column}',
                    'data': points,
                    'backgroundColor': config.get('colors', [self._get_default_colors(1)[0]])[0]
                }]
            },
            'options': {
                'title': config.get('title', 'Scatter Plot'),
                'responsive': True,
                'scales': {
                    'x': {'title': {'display': True, 'text': x_column}},
                    'y': {'title': {'display': True, 'text': y_column}}
                }
            }
        }
    
    def _create_heatmap(self, data: List[Dict], config: Dict) -> Dict:
        """Create heatmap configuration"""
        x_column = config.get('x_column')
        y_column = config.get('y_column')
        value_column = config.get('value_column')
        
        # Build matrix
        x_values = sorted(list(set(str(row.get(x_column, '')) for row in data)))
        y_values = sorted(list(set(str(row.get(y_column, '')) for row in data)))
        
        matrix = []
        for y in y_values:
            row = []
            for x in x_values:
                value = next((float(r.get(value_column, 0)) for r in data 
                             if str(r.get(x_column)) == x and str(r.get(y_column)) == y), 0)
                row.append(value)
            matrix.append(row)
        
        return {
            'ok': True,
            'chart_type': 'heatmap',
            'data': {
                'x_labels': x_values,
                'y_labels': y_values,
                'matrix': matrix
            },
            'options': {
                'title': config.get('title', 'Heatmap'),
                'responsive': True
            }
        }
    
    def _create_grouped_datasets(self, data: List[Dict], x_column: str, y_column: str, 
                                 group_by: str, config: Dict, chart_type: str = 'bar') -> List[Dict]:
        """Create datasets for grouped charts"""
        groups = {}
        for row in data:
            group = str(row.get(group_by, 'Unknown'))
            if group not in groups:
                groups[group] = []
            groups[group].append(row)
        
        colors = config.get('colors', self._get_default_colors(len(groups)))
        datasets = []
        
        for i, (group_name, group_data) in enumerate(groups.items()):
            values = [float(row.get(y_column, 0)) for row in group_data]
            
            dataset = {
                'label': group_name,
                'data': values
            }
            
            if chart_type == 'line':
                dataset['borderColor'] = colors[i]
                dataset['fill'] = False
                dataset['tension'] = 0.4
            else:
                dataset['backgroundColor'] = colors[i]
            
            datasets.append(dataset)
        
        return datasets
    
    def _get_default_colors(self, count: int) -> List[str]:
        """Get default color palette"""
        base_colors = [
            '#FFB800',  # Amber
            '#00FF88',  # Mint
            '#FF3B5C',  # Crimson
            '#0095FF',  # Blue
            '#9D4EDD',  # Purple
            '#06FFA5',  # Cyan
            '#FF006E',  # Pink
            '#FFBE0B',  # Yellow
        ]
        
        # Repeat colors if needed
        return (base_colors * ((count // len(base_colors)) + 1))[:count]
    
    def get_chart_types(self) -> List[Dict[str, str]]:
        """Get available chart types"""
        return [
            {'value': 'bar', 'label': 'Bar Chart', 'icon': 'πŸ“Š'},
            {'value': 'line', 'label': 'Line Chart', 'icon': 'πŸ“ˆ'},
            {'value': 'area', 'label': 'Area Chart', 'icon': 'πŸ“‰'},
            {'value': 'pie', 'label': 'Pie Chart', 'icon': 'πŸ₯§'},
            {'value': 'scatter', 'label': 'Scatter Plot', 'icon': '⚫'},
            {'value': 'heatmap', 'label': 'Heatmap', 'icon': 'πŸ”₯'},
        ]
    
    def analyze_data_for_chart(self, data: List[Dict]) -> Dict[str, Any]:
        """Analyze data and suggest best chart type"""
        if not data:
            return {'ok': False, 'error': 'No data'}
        
        columns = list(data[0].keys())
        numeric_columns = []
        categorical_columns = []
        
        for col in columns:
            sample_value = data[0].get(col)
            try:
                float(sample_value)
                numeric_columns.append(col)
            except:
                categorical_columns.append(col)
        
        suggestions = []
        
        if len(categorical_columns) >= 1 and len(numeric_columns) >= 1:
            suggestions.append({
                'type': 'bar',
                'config': {
                    'x_column': categorical_columns[0],
                    'y_column': numeric_columns[0]
                },
                'reason': 'Good for comparing categories'
            })
        
        if len(numeric_columns) >= 2:
            suggestions.append({
                'type': 'scatter',
                'config': {
                    'x_column': numeric_columns[0],
                    'y_column': numeric_columns[1]
                },
                'reason': 'Good for correlation analysis'
            })
        
        if len(categorical_columns) >= 1 and len(numeric_columns) >= 1:
            suggestions.append({
                'type': 'pie',
                'config': {
                    'label_column': categorical_columns[0],
                    'value_column': numeric_columns[0]
                },
                'reason': 'Good for showing proportions'
            })
        
        return {
            'ok': True,
            'columns': {
                'numeric': numeric_columns,
                'categorical': categorical_columns
            },
            'suggestions': suggestions
        }

data_visualization_engine = DataVisualizationEngine()