-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizations.py
More file actions
2517 lines (2131 loc) · 108 KB
/
visualizations.py
File metadata and controls
2517 lines (2131 loc) · 108 KB
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Visualization module for creating interactive charts and graphs.
This module creates professional, interactive visualizations using Plotly
with Radware branding and styling for both technical and sales audiences.
EXPANDABLE STAT CARDS:
This module includes functionality for creating expandable stat cards that
show detailed information when clicked. Use cases include:
- Longest Attack Duration (shows full attack details)
- Top Source IP (shows attack breakdown)
- Highest Volume Attack (shows attack characteristics)
To create custom expandable cards:
custom_fields = [
('Field Name', 'Field Value'),
('Source IP', '192.168.1.100'),
('Volume (MB)', '1,250.5')
]
html = visualizer.create_expandable_stat_card_for_custom_data(
"Card Title", "Main Value", custom_fields, "unique-id"
)
"""
import logging
from typing import Dict, List, Any, Optional, Tuple
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import pandas as pd
from datetime import datetime, timedelta
from config import (
CHART_COLOR_ASSIGNMENTS, CHART_PREFERENCES, CHART_CONFIG, CHART_LAYOUT,
VOLUME_UNIT, VOLUME_UNIT_CONFIGS, PACKET_UNIT, PACKET_UNIT_CONFIGS,
CHART_PLOTLYJS_MODE
)
from utils import (
format_number, calculate_percentage, get_active_color_palette,
get_chart_colors, get_bandwidth_unit_config
)
logger = logging.getLogger(__name__)
class ForensicsVisualizer:
"""
Creates interactive visualizations for forensics data analysis.
"""
def __init__(self):
"""Initialize the visualizer with user-configurable styling."""
self.active_palette = get_active_color_palette()
self.chart_colors = self.active_palette # Default to active palette
self.base_layout = CHART_LAYOUT.copy()
self.chart_preferences = CHART_PREFERENCES
self.color_assignments = CHART_COLOR_ASSIGNMENTS
logger.info("Initialized ForensicsVisualizer with configurable styling")
def _get_chart_color(self, chart_name: str, color_key: str = 'primary', fallback_index: int = 0):
"""
Get color for a specific chart element.
Args:
chart_name: Name of the chart (e.g., 'monthly_trends', 'attack_type')
color_key: Specific color key (e.g., 'primary', 'volume', 'packets') or index for list format
fallback_index: Index in palette to use as fallback
Returns:
Color string (hex code)
"""
# Check for specific color assignment
color_assignment_key = f'{chart_name}_colors'
if color_assignment_key in self.color_assignments:
chart_colors = self.color_assignments[color_assignment_key]
# Handle list format (new approach)
if isinstance(chart_colors, list):
if isinstance(fallback_index, int) and 0 <= fallback_index < len(chart_colors):
return chart_colors[fallback_index]
elif len(chart_colors) > 0:
return chart_colors[0] # Default to first color
# Handle dict format (backward compatibility)
elif isinstance(chart_colors, dict) and color_key in chart_colors:
return chart_colors[color_key]
# Fall back to active palette
return self.active_palette[fallback_index % len(self.active_palette)]
def _get_chart_colors_list(self, chart_name: str):
"""
Get list of colors for a chart that needs multiple colors.
Args:
chart_name: Name of the chart
Returns:
List of color strings
"""
# Check for specific color assignment
color_assignment_key = f'{chart_name}_colors'
if color_assignment_key in self.color_assignments:
chart_colors = self.color_assignments[color_assignment_key]
# Handle list format (new approach) - return the list directly
if isinstance(chart_colors, list):
return chart_colors
# Handle dict format (backward compatibility) - extract color values
elif isinstance(chart_colors, dict) and len(chart_colors) > 1:
# Return the values if they're colors
color_values = [v for v in chart_colors.values() if isinstance(v, str) and v.startswith('#')]
if color_values:
return color_values
# Fall back to active palette
return self.active_palette
def _get_chart_type(self, chart_name: str) -> str:
"""
Get configured chart type for a specific chart.
Args:
chart_name: Name of chart in CHART_PREFERENCES
Returns:
Chart type string
"""
# Check for runtime preference override first
if chart_name in self.chart_preferences and 'type' in self.chart_preferences[chart_name]:
return self.chart_preferences[chart_name]['type']
# Get default type from CHART_PREFERENCES
if chart_name in self.chart_preferences and 'default_type' in self.chart_preferences[chart_name]:
return self.chart_preferences[chart_name]['default_type']
# Final fallback
return 'bar'
def _convert_to_html(self, fig, custom_config=None):
"""
Convert Plotly figure to HTML with optimized Plotly inclusion.
Args:
fig: Plotly figure object
custom_config: Optional custom configuration to override CHART_CONFIG
Returns:
HTML string of the chart
"""
config = custom_config if custom_config is not None else CHART_CONFIG
return fig.to_html(config=config, include_plotlyjs=CHART_PLOTLYJS_MODE)
def _create_trace_by_type(self, chart_type: str, chart_name: str, x_data, y_data,
color_key: str = 'primary', name: str = None,
hovertemplate: str = None, **kwargs):
"""
Create a trace based on chart type configuration.
Args:
chart_type: Type of chart ('line', 'bar', etc.)
chart_name: Name of chart config in CHART_PREFERENCES
x_data: X-axis data
y_data: Y-axis data
color_key: Key for color in chart preferences
name: Trace name
hovertemplate: Hover template
**kwargs: Additional trace parameters
Returns:
Plotly trace object
"""
# Get color using new system
color = self._get_chart_color(chart_name, color_key, 0)
# Get chart style configuration
chart_style = self.get_chart_style(chart_name, chart_type)
if chart_type == 'line':
# Get line-specific styling from configuration
line_width = chart_style.get('line_width', 3)
marker_size = chart_style.get('marker_size', 8)
mode = chart_style.get('mode', 'lines+markers')
return go.Scatter(
x=x_data,
y=y_data,
mode=mode,
line=dict(color=color, width=line_width),
marker=dict(size=marker_size, color=color),
name=name,
hovertemplate=hovertemplate,
**kwargs
)
elif chart_type == 'bar':
# Get bar-specific styling from configuration
bar_width = chart_style.get('bar_width', None)
show_values = chart_style.get('show_values', False)
values_text_size = chart_style.get('values_text_size', 10) # Default to 10 if not specified
# Build bar trace
bar_trace = go.Bar(
x=x_data,
y=y_data,
marker=dict(color=color),
name=name,
hovertemplate=hovertemplate,
width=bar_width, # Will be None if not specified, which is fine
**kwargs
)
# Add text on bars if show_values is enabled
if show_values:
bar_trace.text = [f'{val:,.0f}' if isinstance(val, (int, float)) else str(val) for val in y_data]
bar_trace.textposition = 'outside'
bar_trace.textfont = dict(size=values_text_size) # Use configured text size
return bar_trace
elif chart_type == 'area':
# Get area-specific styling from configuration
line_width = chart_style.get('line_width', 2)
# Convert hex color to rgba for fill
if color.startswith('#'):
# Convert hex to rgb
hex_color = color.lstrip('#')
rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
fill_color = f'rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, 0.3)'
else:
fill_color = color
return go.Scatter(
x=x_data,
y=y_data,
mode='lines',
line=dict(color=color, width=line_width),
fill='tonexty',
fillcolor=fill_color,
name=name,
hovertemplate=hovertemplate,
**kwargs
)
else:
# Default to bar chart
return go.Bar(
x=x_data,
y=y_data,
marker=dict(color=color),
name=name,
hovertemplate=hovertemplate,
**kwargs
)
def _add_bar_chart_margin(self, fig, y_data, chart_type: str = 'bar', show_values: bool = False):
"""
Add top margin to y-axis for bar charts with outside text to prevent cutoff.
Args:
fig: Plotly figure object
y_data: Y-axis data (list or single value)
chart_type: Type of chart
show_values: Whether values are shown outside bars
"""
# Only add margin for bar charts with outside text
if chart_type == 'bar' and show_values:
# Handle both list and single value
if isinstance(y_data, (list, tuple)):
max_val = max(y_data) if y_data else 0
else:
max_val = y_data
# Add 15% margin at the top
if max_val > 0:
fig.update_yaxes(range=[0, max_val * 1.15])
def _get_chart_type(self, chart_name: str) -> str:
"""
Get configured chart type for a specific chart.
Args:
chart_name: Name of chart in CHART_PREFERENCES
Returns:
Chart type string
"""
# Get default type from CHART_PREFERENCES
if chart_name in self.chart_preferences and 'default_type' in self.chart_preferences[chart_name]:
return self.chart_preferences[chart_name]['default_type']
return 'bar'
def create_monthly_events_trend(self, monthly_data: Dict[str, Any]) -> str:
"""
Create a line chart showing total events per month.
Args:
monthly_data: Dictionary with monthly statistics
Returns:
HTML string of the chart
"""
try:
if not monthly_data.get('has_trends', False):
return self._create_no_data_chart("Month-to-Month Trends", monthly_data.get('reason', 'No data available'))
months = list(monthly_data['months'].keys())
events = [monthly_data['months'][month]['total_events'] for month in months]
# Create formatted month labels
month_labels = [monthly_data['months'][month]['month_name'] for month in months]
fig = go.Figure()
# Get chart type from configuration
chart_type = self._get_chart_type('monthly_events_trend')
# Get chart style configuration
chart_style = self.get_chart_style('monthly_events_trend', chart_type)
# Create trace based on configuration
trace = self._create_trace_by_type(
chart_type=chart_type,
chart_name='monthly_events_trend',
x_data=month_labels,
y_data=events,
color_key='primary',
name='Total Events',
hovertemplate='<b>%{x}</b><br>Events: %{y:,}<extra></extra>'
)
fig.add_trace(trace)
# Add trend line if enabled in chart style
if chart_style.get('show_trend', False) and len(events) > 1:
# Calculate linear trend
x_numeric = list(range(len(events)))
try:
# Simple linear regression
import numpy as np
z = np.polyfit(x_numeric, events, 1)
trend_line = np.poly1d(z)
trend_values = [trend_line(x) for x in x_numeric]
# Add trend line trace
trend_trace = go.Scatter(
x=month_labels,
y=trend_values,
mode='lines',
name='Trend',
line=dict(
color='rgba(255, 107, 53, 0.8)', # Orange trend line
width=2,
dash='dash'
),
hovertemplate='<b>%{x}</b><br>Trend: %{y:,.0f}<extra></extra>'
)
fig.add_trace(trend_trace)
except ImportError:
# Fallback if numpy is not available - simple moving average
if len(events) >= 2:
# Calculate simple moving average as trend
trend_values = []
for i in range(len(events)):
if i == 0:
trend_values.append(events[0])
else:
trend_values.append(sum(events[:i+1]) / (i+1))
trend_trace = go.Scatter(
x=month_labels,
y=trend_values,
mode='lines',
name='Moving Average',
line=dict(
color='rgba(255, 107, 53, 0.8)',
width=2,
dash='dash'
),
hovertemplate='<b>%{x}</b><br>Avg: %{y:,.0f}<extra></extra>'
)
fig.add_trace(trend_trace)
# Add margin for bar charts with outside text
show_values = chart_style.get('show_values', False)
self._add_bar_chart_margin(fig, events, chart_type, show_values)
layout = self.base_layout.copy()
layout.update({
'title': {
'text': 'Security Events Per Month',
'font': {'size': 18, 'color': '#000000'},
'x': 0.5
},
'xaxis': {
'title': 'Month',
'showgrid': True,
'gridcolor': '#f0f0f0'
},
'yaxis': {
'title': 'Number of Events',
'showgrid': True,
'gridcolor': '#f0f0f0'
},
'hovermode': 'x unified',
'height': 500
})
fig.update_layout(layout)
# Disable zoom on axes for bar charts
fig.update_xaxes(fixedrange=True)
fig.update_yaxes(fixedrange=True)
# Bar chart config - disable all zoom
bar_config = {
'displayModeBar': False,
'responsive': True,
'scrollZoom': False,
'doubleClick': False
}
return self._convert_to_html(fig, bar_config)
except Exception as e:
logger.error(f"Failed to create monthly events trend: {e}")
return self._create_error_chart("Monthly Events Trend", str(e))
def create_attack_types_stacked_bar(self, monthly_data: Dict[str, Any], top_n: int = None) -> str:
"""
Create a chart showing top attack types per month.
Supports multiple visualization types: stacked bar, stacked area, or lines.
Args:
monthly_data: Dictionary with monthly statistics
top_n: Number of top attack types to show (None = use config default)
Returns:
HTML string of the chart
"""
try:
# Get chart configuration
chart_type = self.get_chart_type('attack_types_monthly')
chart_style = self.get_chart_style('attack_types_monthly', chart_type)
# Get top_n from config if not specified
if top_n is None:
top_n = self.chart_preferences.get('attack_types_monthly', {}).get('top_n', 5)
if not monthly_data.get('has_trends', False):
return self._create_no_data_chart("Top Attack Types Per Month", monthly_data.get('reason', 'No data available'))
months = list(monthly_data['months'].keys())
month_labels = [monthly_data['months'][month]['month_name'] for month in months]
# Get top attack types across all months
all_attacks = {}
for month in months:
attacks = monthly_data['months'][month]['attack_types']
for attack, attack_info in attacks.items():
if isinstance(attack_info, dict):
count = attack_info.get('count', 0)
else:
# Handle old format (just count)
count = attack_info
all_attacks[attack] = all_attacks.get(attack, 0) + count
top_attacks = sorted(all_attacks.items(), key=lambda x: x[1], reverse=True)[:top_n]
top_attack_names = [attack[0] for attack in top_attacks]
# Get colors for attack types
colors = self._get_chart_colors_list('attack_types_stacked_bar')
fig = go.Figure()
# Create traces based on chart type
for i, attack_name in enumerate(top_attack_names):
values = []
for month in months:
attacks = monthly_data['months'][month]['attack_types']
attack_info = attacks.get(attack_name, 0)
if isinstance(attack_info, dict):
count = attack_info.get('count', 0)
else:
# Handle old format (just count)
count = attack_info
values.append(count)
color = colors[i % len(colors)]
if chart_type == 'stacked_area':
# Stacked area chart
line_width = chart_style.get('line_width', 1)
opacity = chart_style.get('opacity', 0.7)
# Convert hex color to rgba for fill
if color.startswith('#'):
hex_color = color.lstrip('#')
rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
fill_color = f'rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {opacity})'
else:
fill_color = color
fig.add_trace(go.Scatter(
x=month_labels,
y=values,
name=attack_name,
mode='lines',
line=dict(color=color, width=line_width),
fill='tonexty',
fillcolor=fill_color,
stackgroup='one', # Enable stacking
hovertemplate=f'<b>{attack_name}</b><br>%{{x}}<br>Events: %{{y:,}}<extra></extra>'
))
elif chart_type == 'line':
# Line chart - individual trends
mode = chart_style.get('mode', 'lines+markers')
line_width = chart_style.get('line_width', 2)
marker_size = chart_style.get('marker_size', 6)
fig.add_trace(go.Scatter(
x=month_labels,
y=values,
name=attack_name,
mode=mode,
line=dict(color=color, width=line_width),
marker=dict(size=marker_size, color=color),
hovertemplate=f'<b>{attack_name}</b><br>%{{x}}<br>Events: %{{y:,}}<extra></extra>'
))
else: # Default to stacked_bar
# Stacked bar chart
bar_width = chart_style.get('bar_width', 0.8)
show_values = chart_style.get('show_values', False)
bar_trace = go.Bar(
x=month_labels,
y=values,
name=attack_name,
marker_color=color,
width=bar_width,
hovertemplate=f'<b>{attack_name}</b><br>%{{x}}<br>Events: %{{y:,}}<extra></extra>'
)
# Add text on bars if show_values is enabled
if show_values:
values_text_size = chart_style.get('values_text_size', 10)
# Only show value if segment is large enough (more than 5% of max value or > 50)
max_value = max(values) if values else 0
threshold = max(max_value * 0.05, 50) # 5% of max or 50, whichever is larger
bar_trace.text = [f'{val:,}' if val >= threshold else '' for val in values]
bar_trace.textposition = 'inside' # Position in the middle of the bar segment
bar_trace.textfont = dict(size=values_text_size, color='white')
bar_trace.insidetextanchor = 'middle' # Center text within bar segment
bar_trace.textangle = 0 # Prevent text rotation - keep horizontal or hide if no room
bar_trace.constraintext = 'none' # Don't constrain or rotate text, hide if no room
fig.add_trace(bar_trace)
layout = self.base_layout.copy()
# Determine chart title based on type
if chart_type == 'stacked_area':
chart_title = f'Top {top_n} Attack Types Per Month (Stacked Area)'
elif chart_type == 'line':
chart_title = f'Top {top_n} Attack Types Per Month (Trends)'
else:
chart_title = f'Top {top_n} Attack Types Per Month'
layout.update({
'title': {
'text': chart_title,
'font': {'size': 18, 'color': '#000000'},
'x': 0.5
},
'xaxis': {'title': 'Month'},
'yaxis': {'title': 'Number of Events'},
'hovermode': 'x unified',
'height': 500
})
# Set barmode for bar charts
if chart_type == 'stacked_bar':
layout['barmode'] = 'stack'
fig.update_layout(layout)
# Disable zoom on axes
fig.update_xaxes(fixedrange=True)
fig.update_yaxes(fixedrange=True)
# Chart config - disable all zoom
chart_config = {
'displayModeBar': False,
'responsive': True,
'scrollZoom': False,
'doubleClick': False
}
return self._convert_to_html(fig, chart_config)
except Exception as e:
logger.error(f"Failed to create attack types chart: {e}")
return self._create_error_chart("Attack Types Per Month", str(e))
def create_attack_volume_trends(self, monthly_data: Dict[str, Any]) -> str:
"""
Create line charts for attack volume metrics over time.
Args:
monthly_data: Dictionary containing monthly statistics
Returns:
HTML string of the chart
"""
try:
if not monthly_data.get('has_trends', False):
return self._create_no_data_chart("Attack Volume Trends", monthly_data.get('reason', 'No data available'))
months = list(monthly_data['months'].keys())
month_labels = [monthly_data['months'][month]['month_name'] for month in months]
# Extract volume and packet metrics
total_mbits = [monthly_data['months'][month]['total_mbits'] for month in months]
total_packets = [monthly_data['months'][month]['total_packets'] for month in months]
max_pps = [monthly_data['months'][month]['max_pps'] for month in months]
max_bps = [monthly_data['months'][month]['max_bps'] for month in months]
# Convert volume to configured unit
volume_config = VOLUME_UNIT_CONFIGS[VOLUME_UNIT]
# Convert Mbits to bytes first (divide by 8), then to target unit
total_volume = [mbits / 8 / volume_config['divider'] for mbits in total_mbits]
# Convert packets to configured unit
packet_config = PACKET_UNIT_CONFIGS[PACKET_UNIT]
converted_packets = [packets / packet_config['divider'] for packets in total_packets]
# Convert max_bps to configured bandwidth unit
bandwidth_config = get_bandwidth_unit_config()
max_bandwidth_values = [bps / bandwidth_config['divider'] for bps in max_bps]
# Create subplots with 4 rows now
fig = make_subplots(
rows=4, cols=1,
subplot_titles=(
volume_config['chart_title'],
packet_config['chart_title'],
'Attack Max PPS',
bandwidth_config['chart_title']
),
vertical_spacing=0.10,
row_heights=[0.25, 0.25, 0.25, 0.25]
)
# Get chart type and style from configuration
chart_type = self._get_chart_type('attack_volume_trends')
chart_style = self.get_chart_style('attack_volume_trends')
# Check if trend lines should be shown
show_trend = chart_style.get('show_trend', False)
# Create numeric x values for trend calculations
x_numeric = list(range(len(month_labels)))
# Total Volume in configured unit (Row 1)
volume_trace = self._create_trace_by_type(
chart_type=chart_type,
chart_name='attack_volume_trends',
x_data=month_labels,
y_data=total_volume,
color_key='volume',
name=f'Total {volume_config["display_name"]}',
hovertemplate=f'<b>%{{x}}</b><br>Total {volume_config["display_name"]}: %{{y:,.2f}}<extra></extra>'
)
fig.add_trace(volume_trace, row=1, col=1)
# Add trend line for volume if enabled
if show_trend and len(month_labels) > 1:
try:
import numpy as np
# Linear regression
z = np.polyfit(x_numeric, total_volume, 1)
trend_line = np.poly1d(z)
trend_values = [trend_line(x) for x in x_numeric]
trend_trace = go.Scatter(
x=month_labels,
y=trend_values,
mode='lines',
name='Trend',
line=dict(color='rgba(255, 107, 53, 0.8)', width=2, dash='dash'),
hovertemplate='<b>%{x}</b><br>Trend: %{y:,.2f}<extra></extra>'
)
fig.add_trace(trend_trace, row=1, col=1)
except ImportError:
# Fallback to simple moving average
if len(total_volume) >= 3:
trend_values = [sum(total_volume[max(0, i-1):min(len(total_volume), i+2)]) /
len(total_volume[max(0, i-1):min(len(total_volume), i+2)])
for i in range(len(total_volume))]
trend_trace = go.Scatter(
x=month_labels,
y=trend_values,
mode='lines',
name='Trend',
line=dict(color='rgba(255, 107, 53, 0.8)', width=2, dash='dash'),
hovertemplate='<b>%{x}</b><br>Trend: %{y:,.2f}<extra></extra>'
)
fig.add_trace(trend_trace, row=1, col=1)
# Total Packets in configured unit (Row 2)
packets_trace = self._create_trace_by_type(
chart_type=chart_type,
chart_name='attack_volume_trends',
x_data=month_labels,
y_data=converted_packets,
color_key='packets',
name=f'Total Packets {packet_config["display_name"]}',
hovertemplate=f'<b>%{{x}}</b><br>Packets {packet_config["display_name"]}: %{{y:,.2f}}<extra></extra>'
)
fig.add_trace(packets_trace, row=2, col=1)
# Add trend line for packets if enabled
if show_trend and len(month_labels) > 1:
try:
import numpy as np
z = np.polyfit(x_numeric, converted_packets, 1)
trend_line = np.poly1d(z)
trend_values = [trend_line(x) for x in x_numeric]
trend_trace = go.Scatter(
x=month_labels,
y=trend_values,
mode='lines',
name='Trend',
line=dict(color='rgba(255, 107, 53, 0.8)', width=2, dash='dash'),
hovertemplate=f'<b>%{{x}}</b><br>Trend: %{{y:,.2f}}<extra></extra>'
)
fig.add_trace(trend_trace, row=2, col=1)
except ImportError:
if len(converted_packets) >= 3:
trend_values = [sum(converted_packets[max(0, i-1):min(len(converted_packets), i+2)]) /
len(converted_packets[max(0, i-1):min(len(converted_packets), i+2)])
for i in range(len(converted_packets))]
trend_trace = go.Scatter(
x=month_labels,
y=trend_values,
mode='lines',
name='Trend',
line=dict(color='rgba(255, 107, 53, 0.8)', width=2, dash='dash'),
hovertemplate=f'<b>%{{x}}</b><br>Trend: %{{y:,.2f}}<extra></extra>'
)
fig.add_trace(trend_trace, row=2, col=1)
# Max PPS (Row 3)
pps_trace = self._create_trace_by_type(
chart_type=chart_type,
chart_name='attack_volume_trends',
x_data=month_labels,
y_data=max_pps,
color_key='pps',
name='Max PPS',
hovertemplate='<b>%{x}</b><br>Max PPS: %{y:,.0f}<extra></extra>'
)
fig.add_trace(pps_trace, row=3, col=1)
# Add trend line for PPS if enabled
if show_trend and len(month_labels) > 1:
try:
import numpy as np
z = np.polyfit(x_numeric, max_pps, 1)
trend_line = np.poly1d(z)
trend_values = [trend_line(x) for x in x_numeric]
trend_trace = go.Scatter(
x=month_labels,
y=trend_values,
mode='lines',
name='Trend',
line=dict(color='rgba(255, 107, 53, 0.8)', width=2, dash='dash'),
hovertemplate='<b>%{x}</b><br>Trend: %{y:,.0f}<extra></extra>'
)
fig.add_trace(trend_trace, row=3, col=1)
except ImportError:
if len(max_pps) >= 3:
trend_values = [sum(max_pps[max(0, i-1):min(len(max_pps), i+2)]) /
len(max_pps[max(0, i-1):min(len(max_pps), i+2)])
for i in range(len(max_pps))]
trend_trace = go.Scatter(
x=month_labels,
y=trend_values,
mode='lines',
name='Trend',
line=dict(color='rgba(255, 107, 53, 0.8)', width=2, dash='dash'),
hovertemplate='<b>%{x}</b><br>Trend: %{y:,.0f}<extra></extra>'
)
fig.add_trace(trend_trace, row=3, col=1)
# Max bandwidth (Row 4)
bandwidth_trace = self._create_trace_by_type(
chart_type=chart_type,
chart_name='attack_volume_trends',
x_data=month_labels,
y_data=max_bandwidth_values,
color_key='bandwidth',
name=bandwidth_config['chart_name'],
hovertemplate=bandwidth_config['hover_template']
)
fig.add_trace(bandwidth_trace, row=4, col=1)
# Add trend line for bandwidth if enabled
if show_trend and len(month_labels) > 1:
try:
import numpy as np
z = np.polyfit(x_numeric, max_bandwidth_values, 1)
trend_line = np.poly1d(z)
trend_values = [trend_line(x) for x in x_numeric]
trend_trace = go.Scatter(
x=month_labels,
y=trend_values,
mode='lines',
name='Trend',
line=dict(color='rgba(255, 107, 53, 0.8)', width=2, dash='dash'),
hovertemplate=bandwidth_config['hover_template'].replace('Max ', 'Trend: ')
)
fig.add_trace(trend_trace, row=4, col=1)
except ImportError:
if len(max_bandwidth_values) >= 3:
trend_values = [sum(max_bandwidth_values[max(0, i-1):min(len(max_bandwidth_values), i+2)]) /
len(max_bandwidth_values[max(0, i-1):min(len(max_bandwidth_values), i+2)])
for i in range(len(max_bandwidth_values))]
trend_trace = go.Scatter(
x=month_labels,
y=trend_values,
mode='lines',
name='Trend',
line=dict(color='rgba(255, 107, 53, 0.8)', width=2, dash='dash'),
hovertemplate=bandwidth_config['hover_template'].replace('Max ', 'Trend: ')
)
fig.add_trace(trend_trace, row=4, col=1)
# Add margin for bar charts with outside text positioning
show_values = chart_style.get('show_values', False)
if chart_type == 'bar' and show_values:
# Calculate max values for each subplot and add 15% margin
max_volume = max(total_volume) if total_volume else 0
max_packets = max(converted_packets) if converted_packets else 0
max_pps_val = max(max_pps) if max_pps else 0
max_bandwidth = max(max_bandwidth_values) if max_bandwidth_values else 0
# Update each subplot's y-axis range with margin
if max_volume > 0:
fig.update_yaxes(range=[0, max_volume * 1.15], row=1, col=1)
if max_packets > 0:
fig.update_yaxes(range=[0, max_packets * 1.15], row=2, col=1)
if max_pps_val > 0:
fig.update_yaxes(range=[0, max_pps_val * 1.15], row=3, col=1)
if max_bandwidth > 0:
fig.update_yaxes(range=[0, max_bandwidth * 1.15], row=4, col=1)
# Update layout to match monthly events styling
layout = self.base_layout.copy()
layout.update({
'title': {
'text': 'Attack Volume Trends Over Time',
'font': {'size': 18, 'color': '#000000'},
'x': 0.5
},
'height': 1700, # Increased height for 4 subplots
'showlegend': False,
'legend': {
'orientation': 'h',
'yanchor': 'bottom',
'y': -0.08,
'xanchor': 'center',
'x': 0.5,
'font': {'size': 11}
},
'hovermode': 'x unified'
})
fig.update_layout(layout)
# Update axes to match monthly events styling
fig.update_xaxes(showgrid=True, gridcolor='#f0f0f0', fixedrange=True)
fig.update_yaxes(showgrid=True, gridcolor='#f0f0f0', fixedrange=True)
# Bar chart config - disable all zoom
bar_config = {
'displayModeBar': False,
'responsive': True,
'scrollZoom': False,
'doubleClick': False
}
return self._convert_to_html(fig, bar_config)
except Exception as e:
logger.error(f"Failed to create attack volume trends: {e}")
return self._create_error_chart("Attack Volume Trends", str(e))
def create_hourly_heatmap(self, monthly_data: Dict[str, Any]) -> str:
"""
Create a heatmap showing attack intensity by month and hour of day.
Args:
monthly_data: Dictionary with monthly statistics
Returns:
HTML string of the chart
"""
try:
if not monthly_data.get('has_trends', False):
return self._create_no_data_chart("Attack Intensity Heatmap", monthly_data.get('reason', 'No data available'))
months = list(monthly_data['months'].keys())
month_labels = [monthly_data['months'][month]['month_name'] for month in months]
# Create matrix for heatmap (months x hours)
heatmap_data = []
for month in months:
hourly_dist = monthly_data['months'][month]['hourly_distribution']
heatmap_data.append(hourly_dist)
hours = list(range(24))
# Get colorscale from color assignments configuration
color_assignment_key = 'hourly_heatmap_colors'
colorscale = 'Blues' # Default
if color_assignment_key in self.color_assignments:
chart_colors = self.color_assignments[color_assignment_key]
if isinstance(chart_colors, dict) and 'colorscale' in chart_colors:
colorscale = chart_colors['colorscale']
fig = go.Figure(data=go.Heatmap(
z=heatmap_data,
x=hours,
y=month_labels,
colorscale=colorscale, # Use configured colorscale
hovertemplate='<b>%{y}</b><br>Hour: %{x}:00<br>Events: %{z:,}<extra></extra>',
colorbar=dict(title='Number of Events')
))
layout = self.base_layout.copy()
layout.update({
'title': {
'text': 'Attack Intensity by Month and Hour of Day',
'font': {'size': 18, 'color': '#000000'},
'x': 0.5
},
'xaxis': {
'title': 'Hour of Day',
'tickvals': list(range(0, 24, 2)),
'ticktext': [f'{h:02d}:00' for h in range(0, 24, 2)]
},
'yaxis': {'title': 'Month'},
'height': 400
})
fig.update_layout(layout)
return self._convert_to_html(fig)
except Exception as e:
logger.error(f"Failed to create hourly heatmap: {e}")
return self._create_error_chart("Hourly Attack Heatmap", str(e))
def create_attack_type_pie_chart(self, holistic_data: Dict[str, Any], top_n: int = 10) -> str:
"""
Create a chart showing attack type distribution (pie, donut, bar, or horizontal bar).
Args:
holistic_data: Dictionary with holistic analysis data
top_n: Number of top attack types to show
Returns:
HTML string of the chart
"""
try:
attack_types = holistic_data.get('attack_types', {})
if not attack_types:
return self._create_no_data_chart("Attack Type Distribution", "No attack data available")
# Get top attack types
attack_counts = {}
for attack, attack_info in attack_types.items():
if isinstance(attack_info, dict):
count = attack_info.get('count', 0)
else:
# Handle old format (just count)
count = attack_info
attack_counts[attack] = count
# Get chart type and style configuration first to check sort order
chart_type = self._get_chart_type('attack_type_distribution')
chart_style = self.get_chart_style('attack_type_distribution', chart_type)