-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn8n-timings.py
More file actions
718 lines (592 loc) Β· 29.9 KB
/
n8n-timings.py
File metadata and controls
718 lines (592 loc) Β· 29.9 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
#!/usr/bin/env python3
"""
n8n Looped Node Analyzer with Interactive Navigation
This application analyzes a single execution where nodes are executed multiple times (looped)
and creates an interactive plot viewer with proper navigation.
"""
import os
import json
import requests
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from datetime import datetime, timedelta, timezone
from typing import Dict, List, Optional, Any
import argparse
from dotenv import load_dotenv
from collections import defaultdict
# Load environment variables
load_dotenv()
class InteractivePlotViewer:
"""Interactive plot viewer with navigation."""
def __init__(self, node_summary: Dict[str, Any], execution_info: Dict[str, Any]):
self.node_summary = node_summary
self.execution_info = execution_info
self.current_plot = 0
self.plots = ['total_time', 'avg_time', 'execution_count', 'success_rate', 'hierarchical_timeline']
self.plot_titles = {
'total_time': 'Total Execution Time by Node (Summed)',
'avg_time': 'Average Execution Time by Node',
'execution_count': 'Execution Count by Node',
'success_rate': 'Success Rate by Node',
'hierarchical_timeline': 'Hierarchical Timeline View'
}
self.plot_colors = {
'total_time': 'skyblue',
'avg_time': 'lightcoral',
'execution_count': 'lightgreen',
'success_rate': 'gold',
'hierarchical_timeline': 'lightsteelblue'
}
self.plot_units = {
'total_time': 'seconds',
'avg_time': 'seconds',
'execution_count': 'count',
'success_rate': '%',
'hierarchical_timeline': 'timeline'
}
# Prepare data
self.node_names = list(node_summary.keys())
self.data = {
'total_time': [stats['total_time'] for stats in node_summary.values()],
'avg_time': [stats['average_time'] for stats in node_summary.values()],
'execution_count': [stats['total_executions'] for stats in node_summary.values()],
'success_rate': [stats['success_rate'] for stats in node_summary.values()],
'hierarchical_timeline': [] # Special case - will be handled separately
}
# Extract workflow structure for hierarchical view
self.workflow_structure = self.extract_workflow_structure()
# Calculate optimal figure size
num_nodes = len(self.node_names)
if num_nodes <= 5:
self.fig_width = 12
self.fig_height = 8
elif num_nodes <= 10:
self.fig_width = 14
self.fig_height = 10
elif num_nodes <= 20:
self.fig_width = 16
self.fig_height = 12
else:
self.fig_width = 18
self.fig_height = 14
def extract_workflow_structure(self) -> Dict[str, Any]:
"""Extract workflow structure from execution data."""
workflow_data = self.execution_info.get('workflow_data', {})
nodes = workflow_data.get('nodes', [])
connections = workflow_data.get('connections', {})
# Build node structure
node_structure = {}
for node in nodes:
node_structure[node['id']] = {
'name': node.get('name', node['id']),
'type': node.get('type', 'unknown'),
'position': node.get('position', {'x': 0, 'y': 0}),
'connections': []
}
# Build connections
for source_id, targets in connections.items():
if source_id in node_structure:
for target_id in targets:
if target_id in node_structure:
node_structure[source_id]['connections'].append(target_id)
return node_structure
def create_plot(self):
"""Create the current plot."""
plt.clf() # Clear the current figure
plot_type = self.plots[self.current_plot]
if plot_type == 'hierarchical_timeline':
self.create_hierarchical_timeline()
else:
self.create_bar_chart(plot_type)
plt.tight_layout()
def create_bar_chart(self, plot_type: str):
"""Create a bar chart for the given plot type."""
plot_data = self.data[plot_type]
# Create the main plot
ax = plt.subplot(111)
bars = ax.bar(range(len(self.node_names)), plot_data,
color=self.plot_colors[plot_type], alpha=0.8)
# Set title and labels
ax.set_title(f'{self.plot_titles[plot_type]} (Plot {self.current_plot + 1}/{len(self.plots)})',
fontsize=16, fontweight='bold')
ax.set_xlabel('Nodes', fontsize=12)
ax.set_ylabel(f'{self.plot_titles[plot_type].split(" by ")[0]} ({self.plot_units[plot_type]})', fontsize=12)
# Set x-axis labels
ax.set_xticks(range(len(self.node_names)))
ax.set_xticklabels(self.node_names, rotation=45, ha='right')
ax.grid(True, alpha=0.3)
# Add value labels on bars
max_val = max(plot_data) if plot_data else 1
for i, (bar, value) in enumerate(zip(bars, plot_data)):
if self.plot_units[plot_type] == '%':
label = f'{value:.1f}%'
elif self.plot_units[plot_type] == 'seconds':
label = f'{value:.2f}s'
else:
label = f'{value}'
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + max_val*0.01,
label, ha='center', va='bottom', fontsize=10)
# Add execution info
info_text = f"Execution {self.execution_info['execution_id']} | {self.execution_info['workflow_name']} | {self.execution_info['total_nodes']} nodes"
ax.text(0.02, 0.98, info_text, transform=ax.transAxes, fontsize=10,
verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))
def create_hierarchical_timeline(self):
"""Create hierarchical timeline visualization."""
ax = plt.subplot(111)
# Set up the plot
ax.set_title(f'{self.plot_titles["hierarchical_timeline"]} (Plot {self.current_plot + 1}/{len(self.plots)})',
fontsize=16, fontweight='bold')
ax.set_xlabel('Time', fontsize=12)
ax.set_ylabel('Node Hierarchy', fontsize=12)
# Get execution timeline data
timeline_data = self.build_execution_timeline()
if not timeline_data:
ax.text(0.5, 0.5, 'No timeline data available', ha='center', va='center',
transform=ax.transAxes, fontsize=14)
return
# Plot timeline bars
y_positions = {}
y_pos = 0
for node_name, executions in timeline_data.items():
y_positions[node_name] = y_pos
for execution in executions:
start_time = execution['start_time']
duration = execution['duration']
status = execution['status']
# Convert to relative time (seconds from start)
if start_time and self.execution_info.get('start_time'):
# Handle timezone mismatch - make both datetimes timezone-aware
exec_start_time = self.execution_info['start_time']
if start_time.tzinfo is None and exec_start_time.tzinfo is not None:
# Make start_time timezone-aware by assuming UTC
start_time = start_time.replace(tzinfo=exec_start_time.tzinfo)
elif start_time.tzinfo is not None and exec_start_time.tzinfo is None:
# Make exec_start_time timezone-aware by assuming UTC
exec_start_time = exec_start_time.replace(tzinfo=start_time.tzinfo)
relative_start = (start_time - exec_start_time).total_seconds()
else:
relative_start = 0
# Color based on status
color = 'green' if status == 'success' else 'red' if status == 'error' else 'orange'
# Draw execution bar
bar = patches.Rectangle((relative_start, y_pos - 0.4), duration, 0.8,
facecolor=color, alpha=0.7, edgecolor='black', linewidth=0.5)
ax.add_patch(bar)
# Add duration label
if duration > 0.1: # Only show label for longer executions
ax.text(relative_start + duration/2, y_pos, f'{duration:.2f}s',
ha='center', va='center', fontsize=8, fontweight='bold')
y_pos += 1
# Set y-axis labels
ax.set_yticks(range(len(timeline_data)))
ax.set_yticklabels(list(timeline_data.keys()))
# Set x-axis limits
all_start_times = []
for execs in timeline_data.values():
for exec in execs:
if exec['start_time']:
all_start_times.append(exec['start_time'])
if all_start_times and self.execution_info.get('start_time'):
max_time = max(all_start_times)
# Handle timezone mismatch for x-axis limits
exec_start_time = self.execution_info['start_time']
if max_time.tzinfo is None and exec_start_time.tzinfo is not None:
max_time = max_time.replace(tzinfo=exec_start_time.tzinfo)
elif max_time.tzinfo is not None and exec_start_time.tzinfo is None:
exec_start_time = exec_start_time.replace(tzinfo=max_time.tzinfo)
max_relative_time = (max_time - exec_start_time).total_seconds()
ax.set_xlim(0, max_relative_time + 1)
ax.grid(True, alpha=0.3)
# Add legend
legend_elements = [
patches.Patch(color='green', alpha=0.7, label='Success'),
patches.Patch(color='red', alpha=0.7, label='Error'),
patches.Patch(color='orange', alpha=0.7, label='Other')
]
ax.legend(handles=legend_elements, loc='upper right')
# Add execution info
info_text = f"Execution {self.execution_info['execution_id']} | {self.execution_info['workflow_name']} | {self.execution_info['total_nodes']} nodes"
ax.text(0.02, 0.98, info_text, transform=ax.transAxes, fontsize=10,
verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))
def build_execution_timeline(self) -> Dict[str, List[Dict]]:
"""Build timeline data from node executions."""
timeline_data = {}
for node_name, stats in self.node_summary.items():
executions = []
for execution in stats['executions']:
if execution['start_time'] and execution['duration']:
executions.append({
'start_time': execution['start_time'],
'duration': execution['duration'],
'status': execution['status']
})
# Sort by start time
executions.sort(key=lambda x: x['start_time'])
timeline_data[node_name] = executions
return timeline_data
def prev_plot(self, event):
"""Go to previous plot."""
self.current_plot = (self.current_plot - 1) % len(self.plots)
self.create_plot()
plt.draw()
def next_plot(self, event):
"""Go to next plot."""
self.current_plot = (self.current_plot + 1) % len(self.plots)
self.create_plot()
plt.draw()
def on_key(self, event):
"""Handle keyboard events."""
if event.key == 'left' or event.key == 'a':
self.prev_plot(None)
elif event.key == 'right' or event.key == 'd':
self.next_plot(None)
elif event.key == 'q' or event.key == 'escape':
plt.close()
def show(self):
"""Show the interactive plot."""
# Set up the figure
fig = plt.figure(figsize=(self.fig_width, self.fig_height))
fig.canvas.mpl_connect('key_press_event', self.on_key)
# Create initial plot
self.create_plot()
# Show the plot
plt.show()
def save_plot_as_png(self, plot_index: int, plot_name: str, width_pixels: int, height_pixels: int, output_dir: str = ".") -> str:
"""
Save a specific plot as PNG file.
Args:
plot_index: Index of the plot to save (0-based)
plot_name: Name of the plot for filename
width_pixels: Width in pixels
height_pixels: Height in pixels
output_dir: Directory to save the PNG file
Returns:
Path to the saved PNG file
"""
# Set the current plot
self.current_plot = plot_index
# Convert pixels to inches (assuming 100 DPI)
dpi = 100
fig_width = width_pixels / dpi
fig_height = height_pixels / dpi
# Create figure with specified dimensions
fig = plt.figure(figsize=(fig_width, fig_height), dpi=dpi)
# Create the plot
self.create_plot()
# Generate filename using the specified format: $EXECUTIONID_$INDEX_PlotName.png
execution_id = self.execution_info.get('execution_id', 'unknown')
filename = f"{execution_id}_{plot_index}_{plot_name}.png"
filepath = os.path.join(output_dir, filename)
# Save the plot
plt.savefig(filepath, dpi=dpi, bbox_inches='tight', facecolor='white', edgecolor='none')
plt.close(fig) # Close the figure to free memory
return filepath
def export_all_plots_as_png(self, width_pixels: int, height_pixels: int, output_dir: str = ".") -> List[str]:
"""
Export all plots as PNG files.
Args:
width_pixels: Width in pixels
height_pixels: Height in pixels
output_dir: Directory to save the PNG files
Returns:
List of paths to saved PNG files
"""
saved_files = []
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Plot names for filenames
plot_names = {
'total_time': 'TotalTime',
'avg_time': 'AvgTime',
'execution_count': 'ExecutionCount',
'success_rate': 'SuccessRate',
'hierarchical_timeline': 'HierarchicalTimeline'
}
print(f"\nπΈ Exporting {len(self.plots)} plots as PNG files...")
print(f"π Output directory: {output_dir}")
print(f"π Dimensions: {width_pixels}x{height_pixels} pixels")
print("="*60)
for i, plot_type in enumerate(self.plots):
plot_name = plot_names[plot_type]
try:
filepath = self.save_plot_as_png(i, plot_name, width_pixels, height_pixels, output_dir)
saved_files.append(filepath)
print(f"β
Saved: {os.path.basename(filepath)}")
except Exception as e:
print(f"β Failed to save {plot_name}: {e}")
print("="*60)
print(f"π Exported {len(saved_files)} PNG files successfully!")
return saved_files
class N8nLoopedNodeAnalyzer:
"""Analyzes n8n workflow execution data with looped nodes."""
def __init__(self, base_url: str, api_key: str, debug: bool = False):
"""
Initialize the analyzer with API credentials.
Args:
base_url: Base URL of the n8n instance
api_key: API key for authentication
debug: Enable debug mode for detailed output
"""
self.base_url = base_url.rstrip('/')
self.api_key = api_key
self.debug = debug
self.session = requests.Session()
# Correct n8n API authentication
self.session.headers.update({
'X-N8N-API-KEY': api_key,
'Accept': 'application/json',
'Content-Type': 'application/json'
})
def debug_print(self, message: str, data: Any = None):
"""Print debug information if debug mode is enabled."""
if self.debug:
print(f"π DEBUG: {message}")
if data is not None:
if isinstance(data, (dict, list)):
print(json.dumps(data, indent=2, default=str))
else:
print(f"Data: {data}")
print("-" * 50)
def fetch_execution_data(self, execution_id: int) -> Optional[Dict[str, Any]]:
"""
Fetch execution data for a specific execution ID with detailed data.
Args:
execution_id: The execution ID to fetch
Returns:
Dictionary containing execution data or None if failed
"""
# Use includeData=true to get detailed execution data
url = f"{self.base_url}/api/v1/executions/{execution_id}?includeData=true"
try:
response = self.session.get(url)
self.debug_print(f"API Response Status: {response.status_code}")
if response.status_code == 200:
data = response.json()
self.debug_print("Raw API Response", data)
return data
elif response.status_code == 404:
print(f"Execution {execution_id} not found")
return None
else:
print(f"API Error: {response.text}")
return None
except requests.exceptions.RequestException as e:
print(f"Request Error: {e}")
return None
def analyze_looped_execution(self, execution_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Analyze a single execution with looped nodes and sum up execution times.
Args:
execution_data: Execution data dictionary
Returns:
Dictionary containing looped node analysis
"""
if not execution_data:
return {}
# Extract basic execution info
execution_id = execution_data.get('id')
workflow_id = execution_data.get('workflowId')
workflow_name = execution_data.get('workflowData', {}).get('name', 'Unknown')
workflow_data = execution_data.get('workflowData', {})
status = execution_data.get('status', 'unknown')
started_at = execution_data.get('startedAt')
stopped_at = execution_data.get('stoppedAt')
created_at = execution_data.get('createdAt')
# Parse timestamps
start_time = None
end_time = None
duration = None
if started_at:
start_time = datetime.fromisoformat(started_at.replace('Z', '+00:00'))
if stopped_at:
end_time = datetime.fromisoformat(stopped_at.replace('Z', '+00:00'))
if start_time:
duration = (end_time - start_time).total_seconds()
# Analyze looped node executions
node_executions = []
node_summary = defaultdict(list) # Group by node name
if 'data' in execution_data and execution_data['data']:
data_field = execution_data['data']
self.debug_print("Processing data field", data_field)
if 'resultData' in data_field and 'runData' in data_field['resultData']:
run_data = data_field['resultData']['runData']
self.debug_print("Found runData", run_data)
for node_name, node_executions_list in run_data.items():
self.debug_print(f"Processing node: {node_name}", node_executions_list)
for execution in node_executions_list:
# Convert timestamp from milliseconds to datetime
start_timestamp = execution.get('startTime')
execution_time = execution.get('executionTime', 0)
execution_status = execution.get('executionStatus', 'unknown')
node_start_time = None
node_duration = None
if start_timestamp:
# Convert from milliseconds to datetime (UTC)
node_start_time = datetime.fromtimestamp(start_timestamp / 1000, tz=timezone.utc)
node_duration = execution_time / 1000.0 # Convert to seconds
node_execution = {
'execution_id': execution_id,
'workflow_name': workflow_name,
'node_name': node_name,
'start_time': node_start_time,
'duration': node_duration,
'status': execution_status,
'execution_index': execution.get('executionIndex', 0)
}
self.debug_print(f"Node execution: {node_name}", node_execution)
node_executions.append(node_execution)
# Group by node name for summary
node_summary[node_name].append(node_execution)
# Calculate summary statistics for each node
node_summary_stats = {}
for node_name, executions in node_summary.items():
durations = [ex['duration'] for ex in executions if ex['duration'] is not None]
statuses = [ex['status'] for ex in executions]
node_summary_stats[node_name] = {
'total_executions': len(executions),
'total_time': sum(durations),
'average_time': sum(durations) / len(durations) if durations else 0,
'min_time': min(durations) if durations else 0,
'max_time': max(durations) if durations else 0,
'successful_executions': len([s for s in statuses if s == 'success']),
'failed_executions': len([s for s in statuses if s == 'error']),
'success_rate': len([s for s in statuses if s == 'success']) / len(statuses) * 100 if statuses else 0,
'executions': executions
}
return {
'execution_id': execution_id,
'workflow_id': workflow_id,
'workflow_name': workflow_name,
'workflow_data': workflow_data,
'status': status,
'start_time': start_time,
'end_time': end_time,
'duration': duration,
'created_at': created_at,
'has_detailed_data': len(node_executions) > 0,
'node_executions': node_executions,
'node_summary': node_summary_stats,
'total_nodes': len(node_summary_stats),
'total_node_executions': len(node_executions)
}
def create_looped_summary_report(self, analysis_data: Dict[str, Any]):
"""
Create a summary report for looped node execution.
Args:
analysis_data: Analysis data from analyze_looped_execution
"""
if not analysis_data:
print("No analysis data available")
return
print("\n" + "="*80)
print("LOOPED NODE EXECUTION SUMMARY")
print("="*80)
print(f"Execution ID: {analysis_data['execution_id']}")
print(f"Workflow: {analysis_data['workflow_name']}")
print(f"Workflow ID: {analysis_data['workflow_id']}")
print(f"Status: {analysis_data['status']}")
print(f"Start Time: {analysis_data['start_time']}")
print(f"End Time: {analysis_data['end_time']}")
print(f"Total Duration: {analysis_data['duration']:.2f} seconds" if analysis_data['duration'] else "Duration: N/A")
print(f"Total Node Executions: {analysis_data['total_node_executions']}")
print(f"Unique Nodes: {analysis_data['total_nodes']}")
print("="*80)
# Summary by node (summed up)
print(f"\n{'Node Name':<30} | {'Executions':<10} | {'Total Time':<12} | {'Avg Time':<10} | {'Min':<8} | {'Max':<8} | {'Success Rate':<12}")
print("-" * 80)
node_summary = analysis_data['node_summary']
for node_name, stats in node_summary.items():
print(f"{node_name:<30} | {stats['total_executions']:<10} | {stats['total_time']:<12.2f}s | {stats['average_time']:<10.2f}s | {stats['min_time']:<8.2f}s | {stats['max_time']:<8.2f}s | {stats['success_rate']:<12.1f}%")
print("="*80)
# Detailed breakdown for each node
for node_name, stats in node_summary.items():
print(f"\nπ {node_name}")
print("-" * 50)
print(f"Total Executions: {stats['total_executions']}")
print(f"Total Time (summed): {stats['total_time']:.2f} seconds")
print(f"Average Time: {stats['average_time']:.2f} seconds")
print(f"Min Time: {stats['min_time']:.2f} seconds")
print(f"Max Time: {stats['max_time']:.2f} seconds")
print(f"Success Rate: {stats['success_rate']:.1f}%")
# Show individual executions
print(f"\nIndividual Executions:")
for i, exec_data in enumerate(stats['executions']):
start_time_str = exec_data['start_time'].strftime('%H:%M:%S.%f')[:-3] if exec_data['start_time'] else "N/A"
print(f" {i+1}. Duration: {exec_data['duration']:.3f}s at {start_time_str} (Status: {exec_data['status']})")
def create_interactive_visualization(self, analysis_data: Dict[str, Any], export_png: bool = False, png_width: int = 1920, png_height: int = 1080):
"""
Create interactive visualization for looped node execution.
Args:
analysis_data: Analysis data from analyze_looped_execution
export_png: If True, export plots as PNG files instead of showing interactive viewer
png_width: Width in pixels for PNG export
png_height: Height in pixels for PNG export
"""
if not analysis_data or not analysis_data.get('node_summary'):
print("No node summary data available for plotting")
return
# Create interactive viewer
viewer = InteractivePlotViewer(analysis_data['node_summary'], analysis_data)
if export_png:
print("\nπΈ PNG Export Mode")
print("="*60)
print(f"π Dimensions: {png_width}x{png_height} pixels")
print(f"π Output directory: ./plots/")
print("="*60)
# Export all plots as PNG files
saved_files = viewer.export_all_plots_as_png(png_width, png_height, "./plots")
if saved_files:
print(f"\nπ Generated files:")
for filepath in saved_files:
print(f" β’ {filepath}")
else:
print("\nπ― Starting Interactive Plot Viewer...")
print("="*60)
print("NAVIGATION CONTROLS:")
print("β’ Use β β arrow keys (or A/D keys) to navigate")
print("β’ Press Q or Escape to close")
print("β’ All plots in one window with smooth navigation")
print("β’ Includes: Bar charts + Hierarchical Timeline View")
print("="*60)
viewer.show()
def main():
"""Main function to run the analyzer."""
parser = argparse.ArgumentParser(description='Analyze n8n looped node execution with interactive navigation')
parser.add_argument('--execution-id', type=int, required=True, help='Execution ID to analyze')
parser.add_argument('--debug', action='store_true', help='Enable debug mode to see raw API responses')
parser.add_argument('--export-png', action='store_true', help='Export plots as PNG files instead of showing interactive viewer')
parser.add_argument('--png-width', type=int, default=1920, help='PNG width in pixels (default: 1920)')
parser.add_argument('--png-height', type=int, default=1080, help='PNG height in pixels (default: 1080)')
args = parser.parse_args()
# Get configuration from environment
base_url = os.getenv('N8N_BASE_URL')
api_key = os.getenv('N8N_API_KEY')
if not base_url or not api_key:
print("Error: Please set N8N_BASE_URL and N8N_API_KEY in your .env file")
return
print("="*60)
print("n8n LOOPED NODE ANALYZER (INTERACTIVE)")
print("="*60)
print(f"Base URL: {base_url}")
print(f"β
API Authentication: Working!")
print(f"β
Detailed Data: Enabled (includeData=true)")
print(f"Analyzing Execution ID: {args.execution_id}")
print("="*60)
# Initialize analyzer
analyzer = N8nLoopedNodeAnalyzer(base_url, api_key, debug=args.debug)
# Analyze specific execution
print(f"Fetching execution data for ID: {args.execution_id}")
execution_data = analyzer.fetch_execution_data(args.execution_id)
if execution_data:
print("β
Execution data fetched successfully!")
analysis = analyzer.analyze_looped_execution(execution_data)
analyzer.create_looped_summary_report(analysis)
analyzer.create_interactive_visualization(analysis,
export_png=args.export_png,
png_width=args.png_width,
png_height=args.png_height)
else:
print("β Failed to fetch execution data")
if __name__ == "__main__":
main()