-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModernReportGenerator.py
More file actions
1799 lines (1476 loc) · 81.2 KB
/
Copy pathModernReportGenerator.py
File metadata and controls
1799 lines (1476 loc) · 81.2 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
"""
===============================================================================
Modern LEGO Report Generator - Advanced PDF Reports
===============================================================================
Generatore di report PDF moderni e accattivanti per l'analisi delle collezioni LEGO.
Utilizza ReportLab per creare report professionali con design moderno.
Funzionalità:
- Design moderno con colori e layout professionale
- Grafici avanzati e visualizzazioni interattive
- Statistiche dettagliate e KPI
- Layout responsivo e sezioni organizzate
- Supporto per diversi tipi di report (summary, detailed, complete)
===============================================================================
"""
import os
import json
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
from collections import defaultdict, Counter
import logging
import tempfile
# ReportLab imports
try:
from reportlab.lib.pagesizes import A4, letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.colors import Color, HexColor
from reportlab.lib.units import inch, cm, mm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
from reportlab.platypus import Image as RLImage
from reportlab.platypus.frames import Frame
from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT, TA_JUSTIFY
from reportlab.graphics.shapes import Drawing, Rect, String, Line
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics.charts.piecharts import Pie
from reportlab.graphics.charts.legends import Legend
from reportlab.lib import colors
REPORTLAB_AVAILABLE = True
except ImportError:
REPORTLAB_AVAILABLE = False
logging.warning("ReportLab not available. Install with: pip install reportlab")
# Matplotlib for advanced charts
try:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.backends.backend_agg import FigureCanvasAgg
import numpy as np
import seaborn as sns
import warnings
from PIL import Image
MATPLOTLIB_AVAILABLE = True
# Suppress specific warnings
warnings.filterwarnings('ignore', message='Using categorical units to plot a list of strings')
warnings.filterwarnings('ignore', category=UserWarning, module='matplotlib')
# Increase PIL decompression bomb limit to handle large images
Image.MAX_IMAGE_PIXELS = None
# Set modern style
plt.style.use('seaborn-v0_8-darkgrid')
sns.set_palette("husl")
except ImportError:
MATPLOTLIB_AVAILABLE = False
logging.warning("Matplotlib/Seaborn not available for advanced charts")
class ModernReportGenerator:
"""Generatore di report PDF moderni per collezioni LEGO"""
def __init__(self, folder_path, color_mapping_path, output_pdf, report_type='complete'):
"""
Inizializza il generatore di report moderni
Args:
folder_path (str): Percorso della cartella con i file XML
color_mapping_path (str): Percorso del file di mappatura colori
output_pdf (str): Percorso del file PDF di output
report_type (str): Tipo di report ('summary', 'detailed', 'complete')
"""
if not REPORTLAB_AVAILABLE:
raise ImportError("ReportLab is required for modern reports. Install with: pip install reportlab")
# Modern color palette (defined only when ReportLab is available)
self.COLORS = {
'primary': HexColor('#2C3E50'), # Dark blue-gray
'secondary': HexColor('#3498DB'), # Bright blue
'accent': HexColor('#E74C3C'), # Red
'success': HexColor('#27AE60'), # Green
'warning': HexColor('#F39C12'), # Orange
'info': HexColor('#9B59B6'), # Purple
'light': HexColor('#ECF0F1'), # Light gray
'dark': HexColor('#34495E'), # Dark gray
'white': colors.white,
'black': colors.black
}
self.folder_path = folder_path
self.color_mapping_path = color_mapping_path
self.output_pdf = output_pdf
self.report_type = report_type
# Load data
self.color_mapping = self._load_color_mapping()
self.xml_files = self._get_xml_files()
# Analytics data
self.analytics = {
'total_sets': 0,
'total_pieces': 0,
'total_owned': 0,
'total_missing': 0,
'completion_percentage': 0.0,
'unique_colors': set(),
'unique_pieces': set(),
'sets_data': [],
'color_analysis': defaultdict(dict),
'piece_analysis': defaultdict(dict),
'rarity_analysis': {},
'trends': {},
'historical_data': self._load_historical_data() # Carica dati storici
}
# Track temporary files for cleanup
self.temp_files = []
# Setup styles
self.styles = self._create_styles()
logging.info(f"Modern Report Generator initialized for {len(self.xml_files)} files")
def _load_historical_data(self):
"""Carica i dati storici del progresso dalla cronologia"""
history_file = 'collection_history.json'
try:
if os.path.exists(history_file):
with open(history_file, 'r') as f:
return json.load(f)
except Exception as e:
logging.warning(f"Could not load historical data: {e}")
# Ritorna dati vuoti se non esiste cronologia
return {}
def _save_current_progress(self):
"""Salva il progresso attuale nella cronologia"""
history_file = 'collection_history.json'
current_date = datetime.now().strftime('%Y-%m-%d')
try:
# Carica cronologia esistente
historical_data = self._load_historical_data()
# Aggiungi i dati attuali
historical_data[current_date] = {
'completion_percentage': self.analytics['completion_percentage'],
'total_pieces': self.analytics['total_pieces'],
'total_owned': self.analytics['total_owned'],
'total_missing': self.analytics['total_missing'],
'unique_colors': len(self.analytics['unique_colors']),
'sets_count': self.analytics['total_sets']
}
# Mantieni solo gli ultimi 12 mesi
dates = sorted(historical_data.keys())
if len(dates) > 12:
for old_date in dates[:-12]:
del historical_data[old_date]
# Salva la cronologia aggiornata
with open(history_file, 'w') as f:
json.dump(historical_data, f, indent=2)
self.analytics['historical_data'] = historical_data
logging.info(f"Progress saved to history: {current_date}")
except Exception as e:
logging.error(f"Could not save progress history: {e}")
def _calculate_real_trend_data(self):
"""Calcola il trend reale basato sui dati storici"""
historical_data = self.analytics['historical_data']
if len(historical_data) < 2:
# Non abbastanza dati storici, usa simulazione intelligente
return self._simulate_intelligent_trend()
# Ordina i dati per data
sorted_dates = sorted(historical_data.keys())
months = []
completions = []
for date in sorted_dates[-6:]: # Ultimi 6 mesi
try:
date_obj = datetime.strptime(date, '%Y-%m-%d')
month_str = date_obj.strftime('%b %Y')
months.append(month_str)
completions.append(historical_data[date]['completion_percentage'])
except Exception:
continue
return months, completions
def _simulate_intelligent_trend(self):
"""Simula un trend intelligente basato sui dati attuali"""
current_completion = self.analytics['completion_percentage']
# Calcola una progressione realistica
months = []
completions = []
# Genera 6 mesi di storia simulata
for i in range(6, 0, -1):
date_obj = datetime.now() - timedelta(days=30 * i)
month_str = date_obj.strftime('%b %Y')
months.append(month_str)
# Simula progresso graduale (meno progresso nei mesi precedenti)
progress_reduction = i * 2 # Riduce del 2% per ogni mese precedente
simulated_completion = max(0, current_completion - progress_reduction)
completions.append(simulated_completion)
return months, completions
def _calculate_ai_predictions(self):
"""Calcola predizioni AI reali basate sui dati storici e pattern"""
historical_data = self.analytics['historical_data']
if len(historical_data) >= 3:
# Calcola il trend reale
dates = sorted(historical_data.keys())[-3:]
completions = [historical_data[date]['completion_percentage'] for date in dates]
# Calcola la velocità media di progresso
if len(completions) >= 2:
# Calcola la differenza tra i dati
monthly_changes = []
for i in range(1, len(completions)):
change = completions[i] - completions[i-1]
monthly_changes.append(change)
avg_monthly_progress = np.mean(monthly_changes) if monthly_changes else 2.0
# Assicurati che sia realistico (tra 0.5% e 8% al mese)
avg_monthly_progress = max(0.5, min(8.0, avg_monthly_progress))
else:
avg_monthly_progress = 2.0 # Default realistico
else:
# Predizione basata sui dati attuali
total_sets = len(self.analytics['sets_data'])
avg_completion = self.analytics['completion_percentage']
# Stima basata sulla collezione
if avg_completion > 80:
avg_monthly_progress = 1.5 # Rallenta verso la fine
elif avg_completion > 50:
avg_monthly_progress = 2.5 # Velocità media
else:
avg_monthly_progress = 3.5 # Più veloce all'inizio
return avg_monthly_progress
def _format_number_compact(self, number):
"""Formatta i numeri per la visualizzazione compatta"""
if number >= 1000000:
return f"{number/1000000:.1f}M"
elif number >= 1000:
return f"{number/1000:.1f}K"
else:
return f"{number:,}"
def _create_color_distribution_chart(self):
"""Crea un grafico comparison NEEDED vs OWNED per colore - stile report originale"""
if not MATPLOTLIB_AVAILABLE:
return None
try:
# Prepara i dati per il grafico comparison
colors_data = []
for color_code, stats in self.analytics['color_analysis'].items():
color_name = self.color_mapping.get(color_code, f"Color {color_code}")
if stats['total'] > 0: # Solo colori con pezzi necessari
colors_data.append({
'name': color_name,
'needed': stats['total'],
'owned': stats['owned'],
'missing': stats['missing'],
'color_code': color_code,
'completion': (stats['owned'] / stats['total'] * 100) if stats['total'] > 0 else 0
})
# Ordina per numero di pezzi necessari e prendi i top 15
colors_data.sort(key=lambda x: x['needed'], reverse=True)
top_colors = colors_data[:15]
# Crea colori realistici per LEGO
lego_colors = {
'White': '#FFFFFF', 'Black': '#0D0D0D', 'Red': '#C4281C', 'Blue': '#0055BF',
'Yellow': '#FFD700', 'Green': '#00852B', 'Orange': '#FE8A18', 'Brown': '#583927',
'Light Gray': '#9C9C9C', 'Dark Gray': '#6C6C6C', 'Tan': '#E4CD9E', 'Pink': '#FF9ECD',
'Purple': '#81007B', 'Lime': '#BBE90B', 'Dark Red': '#720E0F', 'Sand Blue': '#5A93DB',
'Dark Bluish Gray': '#595D60', 'Light Bluish Gray': '#AFB5C7', 'Reddish Brown': '#89493F'
}
# Crea figura grande per confronto dettagliato
fig, ax = plt.subplots(figsize=(12, max(8, len(top_colors) * 0.6)))
fig.patch.set_facecolor('#f8f9fa')
# Prepara dati per il grafico a barre grouped
colors_names = [color['name'] for color in top_colors]
needed_values = [color['needed'] for color in top_colors]
owned_values = [color['owned'] for color in top_colors]
# Posizioni delle barre
y_pos = np.arange(len(colors_names))
bar_height = 0.35
# Crea le barre orizzontali grouped
bars_needed = ax.barh(y_pos - bar_height/2, needed_values, bar_height,
label='NEEDED (Total Required)', color='#e74c3c', alpha=0.8,
edgecolor='#2c3e50', linewidth=0.5)
bars_owned = ax.barh(y_pos + bar_height/2, owned_values, bar_height,
label='OWNED (Currently Have)', color='#27ae60', alpha=0.8,
edgecolor='#2c3e50', linewidth=0.5)
# Personalizza il grafico
ax.set_yticks(y_pos)
ax.set_yticklabels(colors_names, fontsize=11, fontweight='bold')
ax.invert_yaxis()
ax.set_xlabel('Number of Pieces', fontsize=14, fontweight='bold', color='#2c3e50')
ax.set_title('LEGO Color Comparison: NEEDED vs OWNED\n(Organized by Color - Most Required First)',
fontsize=16, fontweight='bold', color='#2c3e50', pad=25)
# Grid e stile
ax.grid(axis='x', alpha=0.3, linestyle='--')
ax.set_facecolor('#fafafa')
# Aggiungi valori e percentuali sui bar
max_value = max(max(needed_values), max(owned_values))
for i, color_data in enumerate(top_colors):
needed = color_data['needed']
owned = color_data['owned']
completion = color_data['completion']
# Valore barra NEEDED
ax.text(needed + max_value*0.01, i - bar_height/2, f'{needed:,}',
ha='left', va='center', fontsize=9, fontweight='bold', color='#c0392b')
# Valore barra OWNED + percentuale
ax.text(owned + max_value*0.01, i + bar_height/2, f'{owned:,} ({completion:.1f}%)',
ha='left', va='center', fontsize=9, fontweight='bold', color='#1e8449')
# Indicatore di completamento sulla destra
status_x = max_value * 1.15
if completion >= 100:
status_icon = "COMPLETE"
status_color = '#27ae60'
elif completion >= 50:
status_icon = "PARTIAL"
status_color = '#f39c12'
else:
status_icon = "MISSING"
status_color = '#e74c3c'
ax.text(status_x, i, status_icon, ha='left', va='center',
fontsize=9, fontweight='bold', color=status_color)
# Legenda e statistiche
ax.legend(loc='lower right', fontsize=12, frameon=True, fancybox=True,
shadow=True, framealpha=0.9, bbox_to_anchor=(0.98, 0.02))
# Box con statistiche generali
total_needed = sum(needed_values)
total_owned = sum(owned_values)
overall_completion = (total_owned / total_needed * 100) if total_needed > 0 else 0
stats_text = f"OVERALL STATISTICS:\n"
stats_text += f"Total Pieces Needed: {total_needed:,}\n"
stats_text += f"Total Pieces Owned: {total_owned:,}\n"
stats_text += f"Overall Completion: {overall_completion:.1f}%\n"
stats_text += f"Colors Analyzed: {len(top_colors)}"
ax.text(0.02, 0.98, stats_text, transform=ax.transAxes, fontsize=10,
verticalalignment='top', bbox=dict(boxstyle='round,pad=0.5',
facecolor='#ecf0f1', alpha=0.9, edgecolor='#2c3e50'))
# Layout ottimizzato
plt.tight_layout()
# Salva con alta qualità
import tempfile
tmp_file = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
plt.savefig(tmp_file.name, format='png', dpi=600, bbox_inches='tight',
facecolor='#f8f9fa', edgecolor='none', pad_inches=0.3)
plt.close()
tmp_file.close()
# Track for cleanup
self.temp_files.append(tmp_file.name)
return tmp_file.name
except Exception as e:
logging.error(f"Error creating color comparison chart: {e}")
plt.close()
return None
def _create_completion_chart(self):
"""Crea un grafico a barre avanzato del completamento per colore con design moderno"""
if not MATPLOTLIB_AVAILABLE:
return None
try:
# Prepara i dati
colors_data = []
for color_code, stats in self.analytics['color_analysis'].items():
if stats['total'] > 10: # Solo colori con almeno 10 pezzi
color_name = self.color_mapping.get(color_code, f"Color {color_code}")
completion = (stats['owned'] / stats['total'] * 100) if stats['total'] > 0 else 0
colors_data.append((color_name, completion, stats['total'], stats['owned'], stats['missing'], color_code))
# Ordina per completamento e prendi i top 15
colors_data.sort(key=lambda x: x[1], reverse=True)
top_colors = colors_data[:15]
# Configurazione layout moderno
plt.style.use('default')
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(20, 16))
fig.patch.set_facecolor('#f8f9fa')
# Mappa colori LEGO realistici
lego_colors = {
'1': '#F2F3F2', '5': '#D50000', '6': '#0055BF', '11': '#1B2A34',
'4': '#F57C20', '3': '#009247', '14': '#FFFF00', '28': '#A3A2A4',
'2': '#8D7553', '85': '#4B9F4A', '86': '#5F758C', '71': '#6C6E68'
}
# 1. Grafico a barre orizzontali completion rate
names = [x[0][:12] for x in top_colors]
completions = [x[1] for x in top_colors]
colors_list = [lego_colors.get(x[5], '#3498db') for x in top_colors]
# Use explicit positions to avoid categorical warning
y_pos = np.arange(len(names))
bars1 = ax1.barh(y_pos, completions, color=colors_list, alpha=0.8,
edgecolor='#2c3e50', linewidth=1.2, height=0.7)
ax1.set_yticks(y_pos)
ax1.set_yticklabels(names, fontsize=11, fontweight='bold')
ax1.invert_yaxis()
ax1.set_xlabel('Completion Percentage (%)', fontsize=12, fontweight='bold', color='#2c3e50')
ax1.set_title('Collection Completion Rate by Color', fontsize=14, fontweight='bold',
color='#2c3e50', pad=20)
ax1.grid(axis='x', alpha=0.3, linestyle='--', color='#7f8c8d')
ax1.set_xlim(0, 100)
ax1.set_facecolor('#fafafa')
# Aggiungi etichette dettagliate
for i, (bar, data) in enumerate(zip(bars1, top_colors)):
width = bar.get_width()
owned, total = data[3], data[2]
ax1.text(width + 1, bar.get_y() + bar.get_height()/2,
f'{width:.1f}% ({owned}/{total})', ha='left', va='center',
fontsize=10, fontweight='bold', color='#2c3e50')
# 2. Grafico scatter completion vs total pieces
totals = [x[2] for x in top_colors]
sizes = [max(50, min(500, x[2] * 2)) for x in top_colors] # Scala dinamica
scatter = ax2.scatter(totals, completions, s=sizes, c=completions,
cmap='RdYlGn', alpha=0.7, edgecolors='#2c3e50', linewidths=1.5)
ax2.set_xlabel('Total Pieces Required', fontsize=12, fontweight='bold', color='#2c3e50')
ax2.set_ylabel('Completion Percentage (%)', fontsize=12, fontweight='bold', color='#2c3e50')
ax2.set_title('Completion vs Collection Size', fontsize=14, fontweight='bold',
color='#2c3e50', pad=20)
ax2.grid(True, alpha=0.3, linestyle='--', color='#7f8c8d')
ax2.set_facecolor('#fafafa')
# Colorbar per lo scatter plot
cbar = plt.colorbar(scatter, ax=ax2, shrink=0.8)
cbar.set_label('Completion %', fontsize=10, fontweight='bold', color='#2c3e50')
# Annota i punti più interessanti
for i, data in enumerate(top_colors[:5]):
name, comp, total, owned, missing, _ = data
ax2.annotate(f'{name[:8]}', (total, comp), xytext=(5, 5),
textcoords='offset points', fontsize=9, fontweight='bold',
bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7))
# 3. Grafico stacked bar owned vs missing
owned_pieces = [x[3] for x in top_colors]
missing_pieces = [x[4] for x in top_colors]
# Use explicit integer positions to avoid categorical warning
x_pos = np.arange(len(names))
bars_owned = ax3.bar(x_pos, owned_pieces, label='Owned',
color='#27ae60', alpha=0.8, edgecolor='#2c3e50', linewidth=0.5)
bars_missing = ax3.bar(x_pos, missing_pieces, bottom=owned_pieces,
label='Missing', color='#e74c3c', alpha=0.8,
edgecolor='#2c3e50', linewidth=0.5)
ax3.set_xlabel('Colors', fontsize=12, fontweight='bold', color='#2c3e50')
ax3.set_ylabel('Number of Pieces', fontsize=12, fontweight='bold', color='#2c3e50')
ax3.set_title('Owned vs Missing Pieces by Color', fontsize=14, fontweight='bold',
color='#2c3e50', pad=20)
ax3.set_xticks(x_pos)
ax3.set_xticklabels(names, rotation=45, ha='right', fontsize=10)
ax3.legend(loc='upper right', fontsize=11, framealpha=0.9)
ax3.grid(axis='y', alpha=0.3, linestyle='--', color='#7f8c8d')
ax3.set_facecolor('#fafafa')
# 4. Grafico radar per top 8 colori
if len(top_colors) >= 8:
top8 = top_colors[:8]
categories = ['Completion', 'Collection Size', 'Priority Score']
# Normalizza i dati per il radar
max_completion = max(x[1] for x in top8)
max_total = max(x[2] for x in top8)
radar_data = []
for data in top8:
comp_norm = data[1] / 100 * 10 # Scala 0-10
size_norm = data[2] / max_total * 10 # Scala 0-10
priority = (100 - data[1]) * (data[2] / max_total) * 10 # Priority score
radar_data.append([comp_norm, size_norm, priority])
# Setup radar chart
angles = np.linspace(0, 2 * np.pi, len(categories), endpoint=False).tolist()
angles += angles[:1] # Chiudi il cerchio
ax4 = plt.subplot(2, 2, 4, projection='polar')
ax4.set_facecolor('#fafafa')
# Plot per ogni colore
colors_radar = plt.cm.Set3(np.linspace(0, 1, len(top8)))
for i, (data, color) in enumerate(zip(radar_data, colors_radar)):
values = data + data[:1] # Chiudi il cerchio
ax4.plot(angles, values, 'o-', linewidth=2, label=top8[i][0][:8], color=color, alpha=0.8)
ax4.fill(angles, values, alpha=0.25, color=color)
ax4.set_xticks(angles[:-1])
ax4.set_xticklabels(categories, fontsize=11, fontweight='bold', color='#2c3e50')
ax4.set_ylim(0, 10)
ax4.set_title('Multi-Dimensional Analysis\n(Top 8 Colors)', fontsize=14,
fontweight='bold', color='#2c3e50', pad=30)
ax4.legend(loc='upper right', bbox_to_anchor=(1.3, 1.0), fontsize=9)
ax4.grid(True, alpha=0.3)
# Layout generale
plt.tight_layout()
fig.suptitle('Advanced LEGO Collection Completion Analysis', fontsize=22,
fontweight='bold', color='#2c3e50', y=0.98)
# Salva con qualità ultra-alta
import tempfile
tmp_file = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
plt.savefig(tmp_file.name, format='png', dpi=600, bbox_inches='tight',
facecolor='#f8f9fa', edgecolor='none', pad_inches=0.3)
plt.close()
tmp_file.close()
# Track for cleanup
self.temp_files.append(tmp_file.name)
return tmp_file.name
except Exception as e:
logging.error(f"Error creating completion chart: {e}")
plt.close()
return None
def _create_sets_completion_chart(self):
"""Crea un dashboard completo per l'analisi dei set LEGO con design ultra-moderno"""
if not MATPLOTLIB_AVAILABLE:
return None
try:
# Prepara i dati dei set
sets_data = sorted(self.analytics['sets_data'], key=lambda x: x['completion'], reverse=True)
total_sets = len(sets_data)
# Configurazione layout dashboard
plt.style.use('default')
fig = plt.figure(figsize=(24, 16))
fig.patch.set_facecolor('#f8f9fa')
# Crea un layout a griglia complesso
gs = fig.add_gridspec(3, 4, height_ratios=[1, 1.5, 1], width_ratios=[1, 1, 1, 1],
hspace=0.3, wspace=0.25)
# Colori moderni
colors_modern = ['#e74c3c', '#f39c12', '#f1c40f', '#2ecc71', '#27ae60']
# 1. KPI Cards (Prima riga)
# Completion Rate Distribution
ax1 = fig.add_subplot(gs[0, 0])
completion_ranges = ['0-20%', '21-40%', '41-60%', '61-80%', '81-100%']
range_counts = [0, 0, 0, 0, 0]
for set_data in sets_data:
comp = set_data['completion']
if comp <= 20: range_counts[0] += 1
elif comp <= 40: range_counts[1] += 1
elif comp <= 60: range_counts[2] += 1
elif comp <= 80: range_counts[3] += 1
else: range_counts[4] += 1
# Use explicit positions to avoid categorical warning
x_pos = np.arange(len(completion_ranges))
bars = ax1.bar(x_pos, range_counts, color=colors_modern, alpha=0.8,
edgecolor='#2c3e50', linewidth=1.5)
ax1.set_title('Completion Distribution', fontsize=14, fontweight='bold', color='#2c3e50', pad=15)
ax1.set_ylabel('Number of Sets', fontsize=11, fontweight='bold', color='#2c3e50')
ax1.set_xticks(x_pos)
ax1.set_xticklabels(completion_ranges, rotation=45, fontsize=9)
ax1.grid(axis='y', alpha=0.3, linestyle='--')
ax1.set_facecolor('#fafafa')
# Aggiungi valori sui bar
for bar, count in zip(bars, range_counts):
if count > 0:
ax1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.1,
str(count), ha='center', va='bottom', fontsize=10, fontweight='bold')
# 2. Progress Statistics
ax2 = fig.add_subplot(gs[0, 1])
avg_completion = np.mean([s['completion'] for s in sets_data])
completed_sets = len([s for s in sets_data if s['completion'] >= 95])
in_progress = len([s for s in sets_data if 10 < s['completion'] < 95])
not_started = len([s for s in sets_data if s['completion'] <= 10])
stats_labels = ['Completed\n(≥95%)', 'In Progress\n(10-95%)', 'Not Started\n(≤10%)']
stats_values = [completed_sets, in_progress, not_started]
stats_colors = ['#27ae60', '#f39c12', '#e74c3c']
wedges, texts, autotexts = ax2.pie(stats_values, labels=stats_labels, autopct='%1.0f%%',
colors=stats_colors, startangle=90,
textprops={'fontsize': 10, 'fontweight': 'bold'})
ax2.set_title('Project Status Overview', fontsize=14, fontweight='bold', color='#2c3e50', pad=15)
# 3. Average completion gauge
ax3 = fig.add_subplot(gs[0, 2])
theta = np.linspace(0, np.pi, 100)
# Background arc
ax3.plot(theta, np.ones_like(theta), linewidth=20, color='#ecf0f1', alpha=0.3)
# Progress arc
progress_theta = theta[:int(avg_completion)]
if len(progress_theta) > 0:
color_progress = '#27ae60' if avg_completion >= 70 else '#f39c12' if avg_completion >= 40 else '#e74c3c'
ax3.plot(progress_theta, np.ones_like(progress_theta), linewidth=20, color=color_progress)
ax3.set_xlim(0, np.pi)
ax3.set_ylim(0, 1.5)
ax3.set_aspect('equal')
ax3.axis('off')
ax3.text(np.pi/2, 0.5, f'{avg_completion:.1f}%\nAverage', ha='center', va='center',
fontsize=16, fontweight='bold', color='#2c3e50')
ax3.set_title('Overall Progress', fontsize=14, fontweight='bold', color='#2c3e50', pad=15)
# 4. Top Priority Sets (Most Missing Pieces)
ax4 = fig.add_subplot(gs[0, 3])
priority_sets = sorted(sets_data, key=lambda x: x.get('missing_pieces', 0), reverse=True)[:5]
if priority_sets:
names = [s['name'][:15] + '...' if len(s['name']) > 15 else s['name'] for s in priority_sets]
missing = [s.get('missing_pieces', 0) for s in priority_sets]
# Use explicit positions to avoid categorical warning
y_pos = np.arange(len(names))
bars = ax4.barh(y_pos, missing, color='#e74c3c', alpha=0.7,
edgecolor='#2c3e50', linewidth=1)
ax4.set_yticks(y_pos)
ax4.set_yticklabels(names, fontsize=9)
ax4.invert_yaxis()
ax4.set_xlabel('Missing Pieces', fontsize=11, fontweight='bold', color='#2c3e50')
ax4.set_title('High Priority Sets', fontsize=14, fontweight='bold', color='#2c3e50', pad=15)
ax4.grid(axis='x', alpha=0.3, linestyle='--')
ax4.set_facecolor('#fafafa')
for i, (bar, miss) in enumerate(zip(bars, missing)):
ax4.text(bar.get_width() + max(missing)*0.01, bar.get_y() + bar.get_height()/2,
str(miss), ha='left', va='center', fontsize=9, fontweight='bold')
# 5. Main Chart - Top Sets Completion (Seconda riga)
ax_main = fig.add_subplot(gs[1, :])
top_sets = sets_data[:20] # Top 20 set
names = [s['name'][:25] + '...' if len(s['name']) > 25 else s['name'] for s in top_sets]
completions = [s['completion'] for s in top_sets]
# Gradient bars
bars = ax_main.barh(range(len(names)), completions, height=0.7,
color=[plt.cm.RdYlGn(c/100) for c in completions],
edgecolor='#2c3e50', linewidth=1.2, alpha=0.9)
ax_main.set_yticks(range(len(names)))
ax_main.set_yticklabels(names, fontsize=11, fontweight='bold')
ax_main.invert_yaxis()
ax_main.set_xlabel('Completion Percentage (%)', fontsize=14, fontweight='bold', color='#2c3e50')
ax_main.set_title('Top 20 LEGO Sets - Completion Status', fontsize=18, fontweight='bold',
color='#2c3e50', pad=25)
ax_main.set_xlim(0, 100)
ax_main.grid(axis='x', alpha=0.3, linestyle='--', color='#7f8c8d')
ax_main.set_facecolor('#fafafa')
# Aggiungi milestone lines
for milestone in [25, 50, 75, 90]:
ax_main.axvline(x=milestone, color='#34495e', linestyle=':', alpha=0.6, linewidth=1)
ax_main.text(milestone, len(names), f'{milestone}%', ha='center', va='bottom',
fontsize=9, color='#34495e', fontweight='bold')
# Etichette dettagliate
for i, (bar, completion, set_data) in enumerate(zip(bars, completions, top_sets)):
width = bar.get_width()
total_pieces = set_data.get('total_pieces', 0)
owned_pieces = set_data.get('owned_pieces', 0)
label = f'{completion:.1f}%'
if total_pieces > 0:
label += f' ({owned_pieces}/{total_pieces})'
ax_main.text(width + 1, bar.get_y() + bar.get_height()/2, label,
ha='left', va='center', fontsize=10, fontweight='bold', color='#2c3e50')
# 6. Trend Analysis (Terza riga)
ax5 = fig.add_subplot(gs[2, :2])
# Simula trend temporale (in un'implementazione reale, useresti dati storici)
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
trend_data = [avg_completion - 15, avg_completion - 10, avg_completion - 5,
avg_completion, avg_completion + 2, avg_completion + 5]
ax5.plot(months, trend_data, marker='o', linewidth=3, markersize=8,
color='#3498db', markerfacecolor='#e74c3c', markeredgecolor='#2c3e50', markeredgewidth=2)
ax5.fill_between(months, trend_data, alpha=0.3, color='#3498db')
ax5.set_ylabel('Average Completion %', fontsize=12, fontweight='bold', color='#2c3e50')
ax5.set_title('Collection Progress Trend (6 Months)', fontsize=14, fontweight='bold',
color='#2c3e50', pad=15)
ax5.grid(True, alpha=0.3, linestyle='--')
ax5.set_facecolor('#fafafa')
# 6. Category Distribution - MIGLIORATO per riconoscere i set LOTR
ax6 = fig.add_subplot(gs[2, 2:])
# Analizza le categorie basate sui nomi dei set con pattern migliori
categories = {
'Lord of the Rings': 0, 'LOTR': 0, 'Hobbit': 0, 'Star Wars': 0,
'Harry Potter': 0, 'City': 0, 'Creator': 0, 'Technic': 0,
'Friends': 0, 'Architecture': 0, 'Ideas': 0, 'Other': 0
}
# Pattern di riconoscimento migliorati
category_patterns = {
'Lord of the Rings': ['lord of the rings', 'lotr', 'tower of orthanc', 'rivendell',
'barad-dur', 'shire', 'balrog', 'gandalf', 'frodo', 'aragorn',
'legolas', 'gimli', 'gollum', 'smeagol', 'uruk-hai', 'moria',
'helms deep', 'weathertop', 'dol guldur', 'lake town', 'erebor'],
'Hobbit': ['hobbit', 'unexpected journey', 'desolation of smaug', 'battle of five armies',
'barrel escape', 'goblin king', 'lonely mountain'],
'Star Wars': ['star wars', 'millennium falcon', 'death star', 'x-wing', 'tie fighter'],
'Harry Potter': ['harry potter', 'hogwarts', 'dumbledore', 'hermione', 'ron'],
'City': ['city', 'police', 'fire', 'ambulance', 'train'],
'Creator': ['creator', 'expert'],
'Technic': ['technic'],
'Friends': ['friends'],
'Architecture': ['architecture'],
'Ideas': ['ideas']
}
for set_data in sets_data:
name = set_data['name'].lower()
categorized = False
# Controlla ogni categoria con i suoi pattern
for category, patterns in category_patterns.items():
if any(pattern in name for pattern in patterns):
categories[category] += 1
categorized = True
break
if not categorized:
categories['Other'] += 1
# Rimuovi categorie vuote
categories = {k: v for k, v in categories.items() if v > 0}
if categories:
# Use explicit positions to avoid categorical warning
cat_labels = list(categories.keys())
cat_values = list(categories.values())
x_pos = np.arange(len(cat_labels))
ax6.bar(x_pos, cat_values,
color=plt.cm.Set3(np.linspace(0, 1, len(categories))),
alpha=0.8, edgecolor='#2c3e50', linewidth=1.5)
ax6.set_ylabel('Number of Sets', fontsize=12, fontweight='bold', color='#2c3e50')
ax6.set_title('Collection by Theme (Enhanced Recognition)', fontsize=14, fontweight='bold',
color='#2c3e50', pad=15)
ax6.set_xticks(x_pos)
ax6.set_xticklabels(cat_labels, rotation=45, fontsize=10)
ax6.grid(axis='y', alpha=0.3, linestyle='--')
ax6.set_facecolor('#fafafa')
# Aggiungi valori
for i, count in enumerate(cat_values):
ax6.text(i, count + max(cat_values)*0.01, str(count),
ha='center', va='bottom', fontsize=11, fontweight='bold')
# Layout finale
fig.suptitle('LEGO Sets Collection - Comprehensive Dashboard',
fontsize=26, fontweight='bold', color='#2c3e50', y=0.98)
# Salva con qualità massima
import tempfile
tmp_file = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
plt.savefig(tmp_file.name, format='png', dpi=600, bbox_inches='tight',
facecolor='#f8f9fa', edgecolor='none', pad_inches=0.4)
plt.close()
tmp_file.close()
# Track for cleanup
self.temp_files.append(tmp_file.name)
return tmp_file.name
except Exception as e:
logging.error(f"Error creating sets completion chart: {e}")
plt.close()
return None
def _create_advanced_analytics_chart(self):
"""Crea un dashboard di analisi avanzate con machine learning insights"""
if not MATPLOTLIB_AVAILABLE:
return None
try:
# Configurazione layout ultra-moderno
plt.style.use('default')
fig = plt.figure(figsize=(22, 14))
fig.patch.set_facecolor('#f8f9fa')
# Layout a griglia avanzato
gs = fig.add_gridspec(3, 3, height_ratios=[1, 1.2, 1], width_ratios=[1, 1.2, 1],
hspace=0.35, wspace=0.3)
# 1. Value Analysis - Pezzi per prezzo stimato
ax1 = fig.add_subplot(gs[0, 0])
# Simula analisi valore (in implementazione reale useresti dati BrickLink)
colors_data = list(self.analytics['color_analysis'].items())
colors_subset = colors_data[:10]
# Simula prezzi medi per colore (€ per pezzo)
price_simulation = {
'1': 0.15, '5': 0.18, '6': 0.16, '11': 0.20, '4': 0.17,
'3': 0.19, '14': 0.22, '28': 0.14, '2': 0.25, '85': 0.21
}
total_values = []
color_names = []
for color_code, stats in colors_subset:
price = price_simulation.get(color_code, 0.18)
total_value = stats['total'] * price
total_values.append(total_value)
color_names.append(self.color_mapping.get(color_code, f"Color {color_code}")[:8])
# Use explicit positions to avoid categorical warning
x_pos = np.arange(len(color_names))
bars = ax1.bar(x_pos, total_values,
color=plt.cm.plasma(np.linspace(0, 1, len(color_names))),
alpha=0.8, edgecolor='#2c3e50', linewidth=1.5)
ax1.set_xticks(x_pos)
ax1.set_xticklabels(color_names, rotation=45, ha='right', fontsize=10)
ax1.set_ylabel('Estimated Value (€)', fontsize=11, fontweight='bold', color='#2c3e50')
ax1.set_title('Collection Value Analysis', fontsize=13, fontweight='bold',
color='#2c3e50', pad=15)
ax1.grid(axis='y', alpha=0.3, linestyle='--')
ax1.set_facecolor('#fafafa')
# Aggiungi valori sui bar
for bar, value in zip(bars, total_values):
ax1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + max(total_values)*0.01,
f'€{value:.0f}', ha='center', va='bottom', fontsize=9, fontweight='bold')
# 2. Efficiency Heatmap - Completion vs Effort
ax2 = fig.add_subplot(gs[0, 1:])
# Crea una heatmap di efficienza
colors_for_heatmap = colors_data[:12]
efficiency_data = np.zeros((3, len(colors_for_heatmap)))
labels_y = ['High Priority\n(Easy Wins)', 'Medium Priority\n(Balanced)', 'Low Priority\n(Hard)']
labels_x = [self.color_mapping.get(c[0], f"C{c[0]}")[:6] for c in colors_for_heatmap]
for i, (color_code, stats) in enumerate(colors_for_heatmap):
completion = (stats['owned'] / stats['total'] * 100) if stats['total'] > 0 else 0
difficulty = stats['total'] / 100 # Normalize difficulty
# Categorizza in base a completion e difficulty
if completion < 50 and difficulty < 1: # Easy wins
efficiency_data[0, i] = 3
elif completion < 80 and difficulty < 2: # Medium
efficiency_data[1, i] = 2
else: # Hard
efficiency_data[2, i] = 1
im = ax2.imshow(efficiency_data, cmap='RdYlGn', aspect='auto', alpha=0.8)
x_pos_heat = np.arange(len(labels_x))
y_pos_heat = np.arange(len(labels_y))
ax2.set_xticks(x_pos_heat)
ax2.set_xticklabels(labels_x, rotation=45, ha='right', fontsize=10)
ax2.set_yticks(y_pos_heat)
ax2.set_yticklabels(labels_y, fontsize=11)
ax2.set_title('Completion Strategy Heatmap', fontsize=13, fontweight='bold',
color='#2c3e50', pad=15)
# Aggiungi valori nella heatmap
for i in range(efficiency_data.shape[0]):
for j in range(efficiency_data.shape[1]):
if efficiency_data[i, j] > 0:
priority = ['Low', 'Medium', 'High'][int(efficiency_data[i, j]) - 1]
ax2.text(j, i, priority, ha='center', va='center',
fontsize=9, fontweight='bold', color='white')
# 3. Collection Timeline con DATI REALI
ax3 = fig.add_subplot(gs[1, :])
# Usa dati reali o simulazione intelligente
months, completions_trend = self._calculate_real_trend_data()
# Calcola i pezzi posseduti basati sui trend di completamento
max_pieces = self.analytics['total_pieces']
owned_trend = [max_pieces * (comp / 100) for comp in completions_trend]
missing_trend = [max_pieces - owned for owned in owned_trend]
# Simula nuovi set aggiunti (basato sui dati reali se disponibili)
if len(self.analytics['historical_data']) > 1:
dates = sorted(self.analytics['historical_data'].keys())
if len(dates) >= 2:
# Calcola la crescita reale dei set
recent_growth = []
for i in range(1, min(len(dates), 6)):
old_sets = self.analytics['historical_data'][dates[-i-1]]['sets_count']
new_sets = self.analytics['historical_data'][dates[-i]]['sets_count']
growth = max(0, new_sets - old_sets)
recent_growth.append(growth)
# Estendi per avere 6 valori
while len(recent_growth) < len(months):
recent_growth.append(recent_growth[-1] if recent_growth else 0)
new_sets_trend = recent_growth[:len(months)]
else:
new_sets_trend = [0] * len(months)
else:
# Simula crescita realistica
base_growth = len(self.analytics['sets_data']) // 12 # Set per mese
new_sets_trend = [max(0, base_growth + np.random.randint(-2, 3)) for _ in months]
# Plot con design migliorato
ax3_twin = ax3.twinx()
line1 = ax3.plot(months, owned_trend, marker='o', linewidth=4, markersize=8,
color='#27ae60', label='Owned Pieces (Real Data)', markerfacecolor='white',
markeredgewidth=2, markeredgecolor='#27ae60')
line2 = ax3.plot(months, missing_trend, marker='s', linewidth=4, markersize=8,
color='#e74c3c', label='Missing Pieces', markerfacecolor='white',
markeredgewidth=2, markeredgecolor='#e74c3c')
bars = ax3_twin.bar(months, new_sets_trend, alpha=0.3, color='#3498db',
label='New Sets Added', width=0.6)
ax3.set_ylabel('Number of Pieces', fontsize=13, fontweight='bold', color='#2c3e50')
ax3_twin.set_ylabel('New Sets', fontsize=13, fontweight='bold', color='#3498db')
ax3.set_title('Collection Growth Timeline (Real Data + Projections)', fontsize=16,
fontweight='bold', color='#2c3e50', pad=25)
ax3.tick_params(axis='x', rotation=45, labelsize=11)
ax3.grid(True, alpha=0.3, linestyle='--')
ax3.set_facecolor('#fafafa')
# Legend combinata
lines1, labels1 = ax3.get_legend_handles_labels()
lines2, labels2 = ax3_twin.get_legend_handles_labels()
ax3.legend(lines1 + lines2, labels1 + labels2, loc='upper left', fontsize=11, framealpha=0.9)
# 4. Investment ROI Analysis
ax4 = fig.add_subplot(gs[2, 0])
# Simula ROI per diverse strategie di acquisto
strategies = ['Singles\n(BrickLink)', 'Sets\n(LEGO)', 'Bulk\n(Lots)', 'Mixed\nStrategy']
roi_values = [85, 65, 120, 95] # ROI percentages