-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeployment-analyse.py
More file actions
2859 lines (2330 loc) · 126 KB
/
Copy pathdeployment-analyse.py
File metadata and controls
2859 lines (2330 loc) · 126 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
DeploymentAnalyzer.
Simple Image Deployment Analysis Tool
A simplified GUI application for analyzing image deployment delays.
This tool allows importing Excel/CSV files and visualizing processing delays
with options to customize the analysis and dive deeper when needed.
.
(c) 2025 by Axel Schmidt
"""
from version import VERSION, APP_VERSION_DISPLAY, VERSION_DATE
# Debug print to verify version information
print(f"Debug - Version information:")
print(f"VERSION = '{VERSION}'")
print(f"APP_VERSION_DISPLAY = '{APP_VERSION_DISPLAY}'")
print(f"VERSION_DATE = '{VERSION_DATE}'")
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from datetime import datetime, timedelta
import locale
import os
import sys # Added missing sys import
import argparse
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import threading
import time
from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk
import numpy as np
import matplotlib
import csv
import logging
from logging.handlers import RotatingFileHandler
import traceback
import configparser # Added for config file reading
# Check for configuration file
def load_config():
"""Load application configuration from app_config.ini if available"""
config = configparser.ConfigParser()
config_paths = []
if getattr(sys, 'frozen', False):
# Running as compiled exe
app_dir = os.path.dirname(sys.executable)
config_paths.append(os.path.join(app_dir, 'app_config.ini'))
else:
# Running in development
app_dir = os.path.dirname(os.path.abspath(__file__))
config_paths.append(os.path.join(app_dir, 'app_config.ini'))
# Try to load config from possible locations
config_loaded = False
config_file_used = None
for config_path in config_paths:
if os.path.exists(config_path):
try:
config.read(config_path)
config_loaded = True
config_file_used = config_path
print(f"Loaded configuration from: {config_path}")
break
except Exception as e:
print(f"Error loading config from {config_path}: {e}")
if not config_loaded:
print("No configuration file found, using defaults")
return config, config_loaded, config_file_used
# Load configuration
app_config, config_loaded, config_file_used = load_config()
# Print initial startup status - helpful for debugging
print("Application starting...")
print(f"Current working directory: {os.getcwd()}")
print(f"Is frozen (PyInstaller): {'_MEIPASS' in dir(sys)}")
# Helper function for PyInstaller bundled resources
def resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
if getattr(sys, 'frozen', False):
# Running as compiled exe
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
print(f"Using PyInstaller base path: {base_path}")
else:
# Running in normal Python environment
base_path = os.path.dirname(os.path.abspath(__file__))
print(f"Using script directory as base path: {base_path}")
return os.path.join(base_path, relative_path)
except Exception as e:
print(f"Error in resource_path for {relative_path}: {str(e)}")
traceback.print_exc()
return relative_path
# Define log directories based on environment
def get_writable_dir(dirname):
"""Returns a writable directory path that works both in development and when frozen"""
# Check if we have a path override in the config
if config_loaded and 'Paths' in app_config and f"{dirname}Dir" in app_config['Paths']:
# If running as exe, use the directory specified in the config
if getattr(sys, 'frozen', False):
app_dir = os.path.dirname(sys.executable)
config_path = app_config['Paths'][f"{dirname}Dir"]
# If path is relative, make it relative to the executable
if not os.path.isabs(config_path):
target_dir = os.path.join(app_dir, config_path)
else:
target_dir = config_path
print(f"Using configured {dirname} directory: {target_dir}")
return target_dir
# Default behavior if no config or not frozen
if getattr(sys, 'frozen', False):
# If running as exe, use a directory next to the executable
app_dir = os.path.dirname(sys.executable)
target_dir = os.path.join(app_dir, dirname)
else:
# In development, use local directory
target_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), dirname)
print(f"Using default {dirname} directory: {target_dir}")
return target_dir
# Create necessary directories
try:
logs_dir = get_writable_dir('logs')
data_dir = get_writable_dir('data')
output_dir = get_writable_dir('output')
os.makedirs(logs_dir, exist_ok=True)
os.makedirs(data_dir, exist_ok=True)
os.makedirs(output_dir, exist_ok=True)
print(f"Created directories: logs, data, output")
except Exception as e:
print(f"Error creating directories: {str(e)}")
traceback.print_exc()
# Set up logging
try:
log_file = os.path.join(logs_dir, 'deployment_analysis.log')
print(f"Log file path: {log_file}")
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s',
handlers=[
logging.StreamHandler(),
RotatingFileHandler(log_file, maxBytes=5*1024*1024, backupCount=2)
]
)
logger = logging.getLogger(__name__)
logger.info("Logging system initialized")
except Exception as e:
print(f"Error setting up logging: {str(e)}")
traceback.print_exc()
try:
# Set backend to TkAgg for GUI applications
matplotlib.use('TkAgg')
logger.info(f"Using {matplotlib.get_backend()} backend for matplotlib")
except Exception as e:
print(f"Error setting matplotlib backend: {str(e)}")
traceback.print_exc()
# Configure locale for German weekday names
try:
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
except:
try:
locale.setlocale(locale.LC_TIME, 'German')
except:
logger.warning("Could not set German locale. Using system default.")
class DeploymentAnalyzer:
"""
Class for analyzing deployment data from Excel/CSV files.
"""
def __init__(self):
"""Initialize the analyzer with empty data structures."""
self.df = None
self.cleaned_data = None
self.pivot_table = None
self.loaded_files = []
def import_file(self, file_path):
"""
Import data from Excel or CSV file.
Args:
file_path: Path to the Excel or CSV file
Returns:
DataFrame: The imported data
"""
try:
# Check if file is CSV
if file_path.lower().endswith('.csv'):
# Read the first line to detect delimiter
with open(file_path, 'r') as f:
first_line = f.readline()
# Check for delimiter by counting occurrences
semicolons = first_line.count(';')
commas = first_line.count(',')
# Determine the likely delimiter
delimiter = ';' if semicolons > commas else ','
# Read with the detected delimiter
self.df = pd.read_csv(file_path, delimiter=delimiter, parse_dates=True)
else:
# Assume Excel file
self.df = pd.read_excel(file_path, parse_dates=True)
self.loaded_files = [file_path]
return self.df
except Exception as e:
messagebox.showerror("Import Error", f"Error importing file: {str(e)}")
return None
def add_file(self, file_path):
"""
Add data from another file to the existing dataset.
Args:
file_path: Path to the Excel or CSV file
Returns:
DataFrame: The combined data
"""
try:
# Import the new file
if file_path.lower().endswith('.csv'):
# Read the first line to detect delimiter
with open(file_path, 'r') as f:
first_line = f.readline()
# Check for delimiter by counting occurrences
semicolons = first_line.count(';')
commas = first_line.count(',')
# Determine the likely delimiter
delimiter = ';' if semicolons > commas else ','
# Read with the detected delimiter
new_df = pd.read_csv(file_path, delimiter=delimiter, parse_dates=True)
else:
# Assume Excel file
new_df = pd.read_excel(file_path, parse_dates=True)
# Combine with existing data if any
if self.df is not None:
self.df = pd.concat([self.df, new_df], ignore_index=True)
else:
self.df = new_df
# Add to loaded files list
self.loaded_files.append(file_path)
return self.df
except Exception as e:
messagebox.showerror("Import Error", f"Error adding file: {str(e)}")
return None
def process_data(self):
"""
Clean and process the raw data.
Returns:
DataFrame: The cleaned data
"""
if self.df is None:
return None
try:
# Make a copy to avoid modifying the original
df = self.df.copy()
# Check if we have the expected columns
expected_cols = ['IPTC_DE Anweisung', 'IPTC_EN Anweisung',
'Bild Upload Zeitpunkt', 'Bild Veröffentlicht',
'Bild Aktivierungszeitpunkt']
# Check if we have at least some of the expected columns
if not any(col in df.columns for col in expected_cols):
# Try alternative column names
alt_cols = ['Bildankunft', 'Onlinestellung']
if not any(col in df.columns for col in alt_cols):
raise ValueError("Could not identify required columns in the data")
# Extract time from IPTC_DE Anweisung if available
if 'IPTC_DE Anweisung' in df.columns:
df['IPTC_Timestamp'] = df['IPTC_DE Anweisung'].str.extract(r'\[(\d{2}:\d{2}:\d{2})\]').iloc[:, 0]
# Convert date columns to datetime
date_cols = ['Bild Upload Zeitpunkt', 'Bild Aktivierungszeitpunkt', 'Bildankunft', 'Onlinestellung']
for col in date_cols:
if col in df.columns:
df[col] = pd.to_datetime(df[col], dayfirst=True, errors='coerce')
# Combine date and time for Bildankunft if needed
if 'IPTC_Timestamp' in df.columns and 'Bild Aktivierungszeitpunkt' in df.columns:
df['Bildankunft'] = df.apply(self._combine_date_time, axis=1)
# Calculate delay in minutes
if 'Bildankunft' in df.columns and 'Bild Aktivierungszeitpunkt' in df.columns:
df['Verzögerung_Minuten'] = (df['Bild Aktivierungszeitpunkt'] - df['Bildankunft']).dt.total_seconds() / 60
elif 'Bildankunft' in df.columns and 'Onlinestellung' in df.columns:
df['Verzögerung_Minuten'] = (df['Onlinestellung'] - df['Bildankunft']).dt.total_seconds() / 60
# Filter out negative delays and extreme outliers
if 'Verzögerung_Minuten' in df.columns:
df = df[df['Verzögerung_Minuten'] >= 0]
df = df[df['Verzögerung_Minuten'] < 24 * 60] # Less than 24 hours
# Extract day of week and hour
if 'Bildankunft' in df.columns:
df['Wochentag'] = df['Bildankunft'].dt.day_name()
df['Tag'] = df['Bildankunft'].dt.day
df['Stunde'] = df['Bildankunft'].dt.hour
df['Monat'] = df['Bildankunft'].dt.month
df['Jahr'] = df['Bildankunft'].dt.year
self.cleaned_data = df
return df
except Exception as e:
messagebox.showerror("Processing Error", f"Error processing data: {str(e)}")
return None
def _combine_date_time(self, row):
"""
Combine date from activation timestamp with time from IPTC timestamp.
Args:
row: DataFrame row with IPTC_Timestamp and Bild Aktivierungszeitpunkt.
Returns:
datetime: Combined datetime object.
"""
try:
if pd.isna(row['IPTC_Timestamp']) or pd.isna(row['Bild Aktivierungszeitpunkt']):
return pd.NaT
# Get the base date from the activation timestamp
base_date = row['Bild Aktivierungszeitpunkt'].date()
# Parse the IPTC timestamp
iptc_time = datetime.strptime(row['IPTC_Timestamp'], '%H:%M:%S').time()
# Combine date and time
bildankunft = datetime.combine(base_date, iptc_time)
# If the result is later than the activation timestamp, it's likely from the previous day
if bildankunft > row['Bild Aktivierungszeitpunkt']:
bildankunft = bildankunft - timedelta(days=1)
return bildankunft
except:
return pd.NaT
def create_pivot_table(self, max_delay=None, granularity="daily"):
"""
Create a pivot table of processing delays.
Args:
max_delay: Maximum delay to include (in minutes)
granularity: Time granularity ('daily', 'weekly', 'monthly', 'yearly', 'hourly')
Returns:
DataFrame: Pivot table
"""
if self.cleaned_data is None:
return None
# Make a copy to avoid modifying the original
data = self.cleaned_data.copy()
# Apply max delay filter if specified
if max_delay is not None:
data = data[data['Verzögerung_Minuten'] <= max_delay]
# Ensure all hours are represented (0-23)
all_hours = list(range(24))
# Create pivot table based on granularity
if granularity == "daily":
# Pivot by day of month and hour
data['Day'] = data['Bildankunft'].dt.day
data['Hour'] = data['Bildankunft'].dt.hour
pivot = pd.pivot_table(
data,
values='Verzögerung_Minuten',
index='Day',
columns='Hour',
aggfunc='mean',
fill_value=0
)
# Ensure all hours are included
pivot = pivot.reindex(columns=all_hours, fill_value=0)
elif granularity == "weekly":
try:
# Pivot by day of week and hour
try:
# Try with different pandas versions
try:
# Using day_name() method for newer pandas
data['Weekday'] = data['Bildankunft'].dt.day_name().str[:3]
except:
# For older pandas versions
data['Weekday'] = data['Bildankunft'].dt.strftime('%a')
except:
# Last resort fallback
data['Weekday'] = data['Bildankunft'].dt.weekday
weekday_map = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'}
data['Weekday'] = data['Weekday'].map(weekday_map)
data['Hour'] = data['Bildankunft'].dt.hour
# Define weekday order
weekday_order = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
# Create pivot table
pivot = pd.pivot_table(
data,
values='Verzögerung_Minuten',
index='Weekday',
columns='Hour',
aggfunc='mean'
)
# Ensure all weekdays and hours are included by reindexing
pivot = pivot.reindex(index=weekday_order, columns=all_hours)
# Fill NaN values with 0 for values and use None (a different color) for missing data points
pivot = pivot.fillna(value=float('nan'))
except Exception as e:
print(f"Error creating weekly pivot table: {str(e)}")
# Fallback to a simpler weekly view
try:
data['Day'] = data['Bildankunft'].dt.day
data['Hour'] = data['Bildankunft'].dt.hour
pivot = pd.pivot_table(
data,
values='Verzögerung_Minuten',
index='Day',
columns='Hour',
aggfunc='mean'
)
# Ensure all hours are included
pivot = pivot.reindex(columns=all_hours)
pivot = pivot.fillna(value=float('nan'))
except Exception as e2:
print(f"Failed to create fallback pivot: {str(e2)}")
return None
elif granularity == "monthly":
# Pivot by month and hour
data['Month'] = data['Bildankunft'].dt.month
data['Hour'] = data['Bildankunft'].dt.hour
pivot = pd.pivot_table(
data,
values='Verzögerung_Minuten',
index='Month',
columns='Hour',
aggfunc='mean'
)
# Ensure all months (1-12) and hours are included
all_months = list(range(1, 13))
pivot = pivot.reindex(index=all_months, columns=all_hours)
# Fill missing values with NaN to render as white/empty cells
pivot = pivot.fillna(value=float('nan'))
# Map month numbers to month names
month_names = {
1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun',
7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'
}
pivot.index = [month_names.get(m, m) for m in pivot.index]
# Calculate global min and max for monthly averages
self.global_min = pivot.min().min()
self.global_max = pivot.max().max()
elif granularity == "yearly":
# Create a date column combining year, month, and day for each entry
data['Date'] = pd.to_datetime(data['Bildankunft'].dt.date)
data['Hour'] = data['Bildankunft'].dt.hour
# Sort the data by date for a chronological view
data = data.sort_values('Date')
# Create pivot table with date as index and hour as columns
pivot = pd.pivot_table(
data,
values='Verzögerung_Minuten',
index='Date',
columns='Hour',
aggfunc='mean'
)
# Ensure all hours are included
pivot = pivot.reindex(columns=all_hours)
pivot = pivot.fillna(value=float('nan'))
# Format the date index to be more readable
pivot.index = [d.strftime('%b %d') for d in pivot.index]
else: # "hourly" (combined view)
# Pivot by hour only, combining all dates
data['Hour'] = data['Bildankunft'].dt.hour
# Use a dummy index to get a 1-row heatmap
data['All Data'] = 'All Data'
pivot = pd.pivot_table(
data,
values='Verzögerung_Minuten',
index='All Data',
columns='Hour',
aggfunc='mean'
)
# Ensure all hours are included
pivot = pivot.reindex(columns=all_hours)
pivot = pivot.fillna(value=float('nan'))
self.pivot_table = pivot
return pivot
def create_heatmap(self, cmap='YlOrRd', figsize=(10, 6), granularity=None):
"""
Create a heatmap visualization of the pivot table.
Args:
cmap: Colormap for the heatmap
figsize: Figure size tuple (width, height)
granularity: Time granularity ('daily', 'weekly', 'monthly', 'yearly')
Returns:
Figure: Matplotlib figure object
"""
if self.pivot_table is None:
print("No pivot table available. Please run create_pivot_table first.")
return None
try:
# Use non-interactive backend to avoid main thread issues
import matplotlib
default_backend = matplotlib.get_backend()
matplotlib.use('Agg')
# Close any existing figures to prevent thread issues
plt.close('all')
# Get dimensions of the pivot table
rows = len(self.pivot_table.index)
cols = len(self.pivot_table.columns)
# Define standard dimensions for complete datasets to ensure consistent square sizes
standard_rows = {"monthly": 12, "weekly": 7, "yearly": rows, "daily": rows}
standard_cols = 24 # Hours in a day
# Adjust figure size based on standard dimensions for consistent square sizes
if granularity in ['weekly', 'monthly']:
std_rows = standard_rows.get(granularity, rows)
# Calculate figure size based on standard dimensions rather than actual data size
adjusted_height = max(8, min(std_rows * 0.4, 16))
adjusted_width = max(10, min(standard_cols * 0.8, 20))
figsize = (adjusted_width, adjusted_height)
elif granularity == 'yearly':
# For yearly view, use a more balanced approach to sizing
# Aim for rectangles with 2:1 ratio (twice as wide as tall)
row_to_col_ratio = rows / cols
# Calculate width based on number of columns (hours) - increased for better screen usage
adjusted_width = max(16, min(cols * 0.8, 24)) # Increased width for wider rectangles
# Calculate height based on width and row-to-column ratio, but half as tall for 2:1 ratio
adjusted_height = max(6, min(adjusted_width * row_to_col_ratio * 0.35, 18)) # Adjusted ratio for 2:1 rectangles
# Limit height for very large datasets to prevent excessive stretching
if rows > 40:
adjusted_height = min(adjusted_height, 20)
figsize = (adjusted_width, adjusted_height)
# Create new figure
fig, ax = plt.subplots(figsize=figsize)
# Set aspect ratio - for yearly view, use 2:1 rectangles instead of squares
if granularity in ['weekly', 'monthly']:
# Use square cells for weekly and monthly views
ax.set_aspect('equal', adjustable='box', anchor='C')
elif granularity == 'yearly':
# For yearly view, use rectangles twice as wide as tall (2:1 ratio)
# We set aspect to 0.5 to make cells twice as wide as tall
ax.set_aspect(0.5, adjustable='box', anchor='C')
# Create a masked array to handle NaN values properly
mask = np.isnan(self.pivot_table.values) # Using .values to avoid Series truth value ambiguity
# Custom colormap with white for NaN/missing values - using updated method to avoid deprecation warning
try:
# Modern matplotlib approach (3.7+)
cmap_with_white = matplotlib.colormaps[cmap].copy()
except (AttributeError, KeyError):
# Fallback for older versions
try:
cmap_with_white = plt.get_cmap(cmap).copy() # Use plt.get_cmap instead of plt.cm.get_cmap
except:
# Last resort fallback
cmap_with_white = plt.cm.get_cmap(cmap).copy()
cmap_with_white.set_bad('white', 1.0) # Set NaN cells to white
# Determine appropriate linewidth based on view type
if granularity == 'yearly':
linewidth = 0 # No lines for yearly view to remove spacing between rectangles
elif granularity == 'yearly' and rows > 20:
linewidth = 0.2 # Thinner lines for yearly view with many rows
else:
linewidth = 0.5
# Compute vmin and vmax for adaptive color scaling
# If it's yearly view, we want to adapt the color scale to show more variation
vmin, vmax = None, None # Default values
if granularity == 'yearly':
# Calculate quartile-based bounds to emphasize the variation in the middle of the data
# Get the data as numpy array to avoid Series truth value ambiguity
data_values = self.pivot_table.values
if not np.all(mask): # Using numpy's all instead of mask.all()
data_flat = data_values.flatten()
data_flat = data_flat[~np.isnan(data_flat)] # Filter out NaN values
if len(data_flat) > 0:
# For very low variation data, use percentiles closer to median
data_std = np.std(data_flat)
data_range = np.max(data_flat) - np.min(data_flat)
# If data has low variation, use tighter percentiles to enhance contrast
if data_range < 5 or data_std < 2:
vmin = np.percentile(data_flat, 30) # 30th percentile
vmax = np.percentile(data_flat, 90) # 90th percentile
else:
vmin = np.percentile(data_flat, 10) # 10th percentile
vmax = np.percentile(data_flat, 95) # 95th percentile
# Ensure vmin and vmax are not the same to prevent colormap issues
if vmin == vmax:
vmin = 0 if vmin == 0 else vmin * 0.9
vmax = vmax * 1.1
# Create heatmap with masked data - without annotations
heatmap = sns.heatmap(
self.pivot_table,
cmap=cmap_with_white,
annot=False, # No annotations as requested by user
linewidths=linewidth,
ax=ax,
cbar_kws={'label': 'Average Delay (minutes)'},
mask=mask, # Mask NaN values
vmin=vmin, # Custom range for color scaling
vmax=vmax,
robust=True # Use robust quantile-based scaling for color range
)
# Optimize tick labels display based on the view type
if granularity == "yearly":
# Special handling for yearly view to make it more compact and readable
# Reduce font size for tick labels
plt.setp(ax.get_xticklabels(), fontsize=6, rotation=45, ha='right')
# For yearly view with many rows, show fewer y-tick labels
if rows > 25:
# Show approximately 20 tick labels (one every N rows)
tick_step = max(1, rows // 20)
# Create indices that are guaranteed to be within bounds
# This ensures we don't try to access indices beyond the size of the array
visible_ticks = list(range(0, rows, tick_step))
# Always include the first and last tick if not already included
if len(visible_ticks) > 0 and visible_ticks[-1] != rows - 1:
if rows - 1 not in visible_ticks: # Only append if not already there
visible_ticks.append(rows - 1)
# Safety check - ensure all indices are within bounds
visible_ticks = [i for i in visible_ticks if 0 <= i < rows]
if len(visible_ticks) > 0: # Only proceed if we have valid ticks
# Get current ticks
y_ticks = ax.get_yticks()
# Extra safety check to ensure we don't have an index error
valid_indices = [i for i in visible_ticks if i < len(y_ticks)]
if valid_indices: # Only proceed if we have valid indices
# Set visible y-ticks and format them
ax.set_yticks([y_ticks[i] for i in valid_indices])
ax.set_yticklabels([self.pivot_table.index[i] for i in valid_indices],
fontsize=6, rotation=0)
else:
# For smaller datasets, just set the font size
plt.setp(ax.get_yticklabels(), fontsize=6, rotation=0)
# Adjust layout based on view type
if granularity == 'yearly' and rows > 25:
# More compact layout for large yearly views
plt.tight_layout(pad=1.2, h_pad=0.8, w_pad=0.8, rect=[0.03, 0.03, 0.97, 0.97])
else:
plt.tight_layout()
# Switch back to the original backend
matplotlib.use(default_backend)
return fig
except Exception as e:
print(f"Error creating heatmap: {str(e)}")
return None
def get_loaded_files_summary(self):
"""
Get a summary of loaded files.
Returns:
str: Summary of loaded files
"""
if not self.loaded_files:
return "No files loaded"
file_names = [os.path.basename(f) for f in self.loaded_files]
return f"{len(file_names)} file(s): " + ", ".join(file_names)
def get_statistics(self):
"""
Calculate basic statistics of the cleaned data.
Returns:
dict: Statistics dictionary
"""
if self.cleaned_data is None or 'Verzögerung_Minuten' not in self.cleaned_data.columns:
return {
'total_records': 0,
'avg_delay': 0,
'min_delay': 0,
'max_delay': 0
}
stats = {
'total_records': len(self.cleaned_data),
'avg_delay': self.cleaned_data['Verzögerung_Minuten'].mean(),
'min_delay': self.cleaned_data['Verzögerung_Minuten'].min(),
'max_delay': self.cleaned_data['Verzögerung_Minuten'].max()
}
# Get available months and years
if 'Monat' in self.cleaned_data.columns and 'Jahr' in self.cleaned_data.columns:
# Get unique month-year combinations
month_year_df = self.cleaned_data[['Monat', 'Jahr']].drop_duplicates()
# Convert month numbers to names
month_names = {
1: 'January', 2: 'February', 3: 'March', 4: 'April',
5: 'May', 6: 'June', 7: 'July', 8: 'August',
9: 'September', 10: 'October', 11: 'November', 12: 'December'
}
# Create list of available month-year combinations
available_months = []
for _, row in month_year_df.iterrows():
month_name = month_names.get(row['Monat'], str(row['Monat']))
available_months.append((row['Monat'], row['Jahr'], f"{month_name} {row['Jahr']}"))
stats['available_months'] = sorted(available_months)
stats['available_years'] = sorted(self.cleaned_data['Jahr'].unique().tolist())
return stats
def save_heatmap(self, fig, output_path):
"""
Save the heatmap figure to a file.
Args:
fig: Matplotlib figure to save
output_path: Path to save the figure
Returns:
bool: Success status
"""
try:
fig.savefig(output_path, bbox_inches='tight', dpi=300)
return True
except Exception as e:
print(f"Error saving heatmap: {str(e)}")
return False
def export_data(self, output_path):
"""
Export the cleaned data to a CSV or Excel file.
Args:
output_path: Path to save the data
Returns:
bool: Success status
"""
try:
if self.cleaned_data is None:
return False
if output_path.lower().endswith('.csv'):
self.cleaned_data.to_csv(output_path, index=False)
else:
self.cleaned_data.to_excel(output_path, index=False)
return True
except Exception as e:
print(f"Error exporting data: {str(e)}")
return False
class SimpleAnalysisGUI:
"""
A simple GUI for analyzing image deployment delays with optimized layout
focusing on the heatmap visualization.
"""
def __init__(self, root):
"""Initialize the GUI with screen-fitting size."""
self.root = root
# Modified to ensure full version is displayed
self.root.title(f"Deployment Analyzer v{VERSION}") # Explicitly use VERSION
# Set window to fit screen with some margin
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
window_width = int(screen_width * 0.9)
window_height = int(screen_height * 0.9)
self.root.geometry(f"{window_width}x{window_height}")
self.root.minsize(800, 600)
self.analyzer = DeploymentAnalyzer()
self.file_path = None
self.current_figure = None
self.selected_granularity = tk.StringVar(value="yearly")
self.canvas = None
self.selected_month = None
self.selected_year = None
self.selected_week = None
self.running_threads = []
# Track application state
self.is_running = True
# Set up a protocol for window closing
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# Create main frames with weight distribution to make heatmap dominant
self.create_main_frames()
self._create_widgets()
self._setup_layout()
def on_closing(self):
"""Handle window close event properly."""
# Set flag to indicate application is closing
self.is_running = False
# Close any matplotlib figures to prevent memory leaks
plt.close('all')
# Wait for threads to finish (with timeout)
for thread in self.running_threads[:]:
if thread.is_alive():
thread.join(0.1) # Wait for 100ms max
# Destroy the window
self.root.destroy()
def create_main_frames(self):
"""Create main frames with proper weight distribution."""
# Configure root grid to give heatmap more space
self.root.grid_columnconfigure(0, weight=1)
self.root.grid_rowconfigure(1, weight=3) # Give more weight to visualization row
# Create top control panel frame (for file selection, quick stats)
self.control_panel = ttk.Frame(self.root)
self.control_panel.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
# Create center visualization frame (for heatmap and navigation)
self.visualization_frame = ttk.Frame(self.root)
self.visualization_frame.grid(row=1, column=0, sticky="nsew", padx=5, pady=5)
self.visualization_frame.grid_rowconfigure(0, weight=1) # Canvas row
self.visualization_frame.grid_rowconfigure(1, weight=0) # Navigation row
self.visualization_frame.grid_columnconfigure(0, weight=1)
# Create canvas frame for the visualization
self.canvas_frame = ttk.Frame(self.visualization_frame)
self.canvas_frame.grid(row=0, column=0, sticky="nsew", padx=5, pady=5)
# Create navigation frame (for time period buttons) inside visualization frame
self.navigation_frame = ttk.Frame(self.visualization_frame)
self.navigation_frame.grid(row=1, column=0, sticky="ew", padx=5, pady=5)
# Create bottom navigation frame (for time period buttons)
self.navigation_frame = ttk.Frame(self.root)
self.navigation_frame.grid(row=2, column=0, sticky="ew", padx=5, pady=5)
def _create_widgets(self):
"""Create all widgets for the GUI with optimized space usage."""
padding = {"padx": 3, "pady": 3}
# Using regular tk.Button with direct color styling for the import button
# CONTROL PANEL WIDGETS -------------------------
# File selection frame - more compact
self.file_frame = ttk.LabelFrame(self.control_panel, text="File Selection")
# File path entry and browse button
self.path_var = tk.StringVar()
self.path_entry = ttk.Entry(self.file_frame, textvariable=self.path_var, width=50)
self.browse_button = tk.Button(self.file_frame, text="Import", command=self.browse_file,
bg="#90EE90", activebackground="#7CCD7C",
relief=tk.RAISED, padx=10, pady=2,
borderwidth=2, cursor="hand2")
self.add_file_button = ttk.Button(self.file_frame, text="+ Add Data", command=self.add_file)
# Quick stats frame - more compact
self.stats_frame = ttk.LabelFrame(self.control_panel, text="Statistics")
# Statistics labels in a more compact layout
self.files_label = ttk.Label(self.stats_frame, text="No files loaded")
self.total_records_label = ttk.Label(self.stats_frame, text="Total Records: 0")
self.avg_delay_label = ttk.Label(self.stats_frame, text="Avg: 0 min")
self.min_delay_label = ttk.Label(self.stats_frame, text="Min: 0 min")
self.max_delay_label = ttk.Label(self.stats_frame, text="Max: 0 min")
# Run button - commented out to remove from GUI
# self.run_button = ttk.Button(self.control_panel, text="Run Analysis", command=self.run_analysis)
# Create a dummy button object that's not shown in UI but responds to all method calls
self.run_button = ttk.Button(self.root) # Create but don't add to layout
# VISUALIZATION FRAME WIDGETS -------------------------
# Canvas for the heatmap
self.canvas_frame = ttk.Frame(self.visualization_frame)
# Status and progress frame
self.status_frame = ttk.Frame(self.visualization_frame)
self.status_label = ttk.Label(self.status_frame, text="Ready")
self.progress = ttk.Progressbar(self.status_frame, orient="horizontal", mode="determinate")
# Export buttons
self.export_frame = ttk.Frame(self.visualization_frame)
self.export_img_button = ttk.Button(
self.export_frame, text="Export Image", command=self.export_heatmap
)
self.export_data_button = ttk.Button(
self.export_frame, text="Export Data", command=self.export_data
)
# NAVIGATION FRAME WIDGETS -------------------------
# Hierarchical time period buttons
self.periods_frame = ttk.LabelFrame(self.navigation_frame, text="Time Periods")
# Create frames for each level
self.years_frame = ttk.Frame(self.periods_frame)
self.months_frame = ttk.Frame(self.periods_frame)
self.weeks_frame = ttk.Frame(self.periods_frame)
# Labels for each section
self.years_label = ttk.Label(self.years_frame, text="Years:")
self.months_label = ttk.Label(self.months_frame, text="Months:")
self.weeks_label = ttk.Label(self.weeks_frame, text="Weeks:")
# Button containers
self.years_buttons_frame = ttk.Frame(self.years_frame)
self.months_buttons_frame = ttk.Frame(self.months_frame)
# Add a canvas and scrollable frame for weeks to handle many buttons