-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualization.py
More file actions
262 lines (222 loc) · 9.88 KB
/
Copy pathvisualization.py
File metadata and controls
262 lines (222 loc) · 9.88 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Visualisierungsfunktionen für das Datei-Sortierungsprogramm
"""
import tkinter as tk
from tkinter import ttk, messagebox
from config import POSSIBLE_YEARS, PERMANENT_CATEGORY
from util import center_window
try:
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
VISUALIZATION_AVAILABLE = True
except ImportError:
VISUALIZATION_AVAILABLE = False
def visualize_categories_mindmap(parent, config, files_by_category=None):
"""
Visualisiert die Kategorien und Dateien als Mindmap
Args:
parent: Elternfenster
config: Die Konfiguration mit Kategorien
files_by_category: Optional, Dict mit {Kategorie: [Dateien]} für zusätzliche Darstellung
"""
if not VISUALIZATION_AVAILABLE:
messagebox.showwarning(
"Fehlende Bibliotheken",
"Für die Mindmap-Visualisierung werden die Bibliotheken 'networkx' und 'matplotlib' benötigt.\n\n"
"Installiere sie mit:\npip install networkx matplotlib"
)
return
# Dialog erstellen
dialog = tk.Toplevel(parent)
dialog.title("Kategorie-Mindmap")
dialog.geometry("900x700")
# Kategorien aus der Konfiguration extrahieren
categories = config.get("categories", [])
# Erstellen eines gerichteten Graphen
G = nx.DiGraph()
# Root-Knoten
G.add_node("Kategorien", type="root")
# Sammle alle Kategorien und erstelle eine flache Liste
flat_categories = []
def collect_categories(categories, parent=""):
for category in categories:
cat_name = category.get("name", "")
if cat_name:
flat_categories.append(cat_name)
if category.get("children"):
collect_categories(category["children"], cat_name)
collect_categories(categories)
# Farbgenerator für Kategorien
colors = ['#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6', '#1abc9c', '#d35400', '#34495e']
category_colors = {}
color_index = 0
# Füge Hauptkategorien hinzu
main_categories = set()
for cat in flat_categories:
# Versuche, die Hauptkategorie zu extrahieren (ohne Jahr)
parts = cat.split()
main_category = parts[0] if len(parts) > 0 else ""
# Prüfe, ob das erste Wort ein Jahr ist
if main_category in POSSIBLE_YEARS and len(parts) > 1:
main_category = " ".join(parts[1:])
if main_category and main_category not in main_categories:
main_categories.add(main_category)
# Kategorie und Verbindung zum Root hinzufügen
G.add_node(main_category, type="main_category")
G.add_edge("Kategorien", main_category)
# Farbe zuweisen
category_colors[main_category] = colors[color_index % len(colors)]
color_index += 1
# Füge alle Kategorien als Unterknoten hinzu
for cat in flat_categories:
if cat == PERMANENT_CATEGORY:
# Spezialfall für die permanente Kategorie
G.add_node(cat, type="special_category")
G.add_edge("Kategorien", cat)
continue
# Versuche, die Hauptkategorie zu extrahieren
parts = cat.split()
if not parts:
continue
# Jahr als Prefix entfernen wenn vorhanden
year_prefix = ""
if parts[0] in POSSIBLE_YEARS:
year_prefix = parts[0]
main_category = " ".join(parts[1:])
else:
main_category = " ".join(parts)
# Wenn ein Jahr vorhanden ist, gruppiere Kategorien nach Jahr
if year_prefix:
year_node = f"Jahr {year_prefix}"
# Prüfe, ob der Jahr-Knoten bereits existiert
if not G.has_node(year_node):
G.add_node(year_node, type="year")
G.add_edge("Kategorien", year_node)
# Verbinde Kategorie mit dem Jahrknoten
G.add_node(cat, type="category")
G.add_edge(year_node, cat)
# Zusätzlich mit der Hauptkategorie verbinden für bessere Visualisierung
if G.has_node(main_category):
G.add_edge(main_category, cat, style="dashed")
else:
# Wenn kein Jahr, direkt mit Hauptkategorie verbinden
if main_category in main_categories:
G.add_node(cat, type="category")
G.add_edge(main_category, cat)
else:
# Fallback: Mit Root verbinden
G.add_node(cat, type="category")
G.add_edge("Kategorien", cat)
# Wenn Dateien pro Kategorie vorhanden sind, als weitere Ebene hinzufügen
if files_by_category:
for category, files in files_by_category.items():
if G.has_node(category):
# Reduziere die Anzahl der angezeigten Dateien
max_files = min(5, len(files))
for i in range(max_files):
file_name = os.path.basename(files[i])
G.add_node(file_name, type="file")
G.add_edge(category, file_name)
# Zeige an, wenn es mehr Dateien gibt
if len(files) > max_files:
more_label = f"+ {len(files) - max_files} weitere"
G.add_node(more_label, type="more")
G.add_edge(category, more_label)
# Plot erstellen
fig = Figure(figsize=(12, 8), dpi=100)
ax = fig.add_subplot(111)
try:
# Layout berechnen - hierarchisches Layout für bessere Mindmap-Visualisierung
pos = nx.nx_agraph.graphviz_layout(G, prog='dot')
except:
# Fallback wenn graphviz nicht verfügbar ist
pos = nx.spring_layout(G, seed=42)
# Knotenfarben basierend auf Typ
node_colors = []
for node in G.nodes():
if G.nodes[node]['type'] == 'root':
node_colors.append('#3498db') # Blau für Root
elif G.nodes[node]['type'] == 'main_category':
# Benutze die zugewiesene Kategoriefarbe
node_colors.append(category_colors.get(node, '#95a5a6'))
elif G.nodes[node]['type'] == 'year':
node_colors.append('#f39c12') # Orange für Jahre
elif G.nodes[node]['type'] == 'special_category':
node_colors.append('#e74c3c') # Rot für spezielle Kategorien
elif G.nodes[node]['type'] == 'file':
node_colors.append('#2ecc71') # Grün für Dateien
elif G.nodes[node]['type'] == 'more':
node_colors.append('#95a5a6') # Grau für "+X weitere"
else:
node_colors.append('#95a5a6') # Grau für sonstige
# Knotengrößen basierend auf Typ
node_sizes = []
for node in G.nodes():
if G.nodes[node]['type'] == 'root':
node_sizes.append(2000)
elif G.nodes[node]['type'] == 'main_category':
node_sizes.append(1500)
elif G.nodes[node]['type'] == 'year':
node_sizes.append(1200)
elif G.nodes[node]['type'] == 'category':
node_sizes.append(1000)
elif G.nodes[node]['type'] == 'file':
node_sizes.append(500)
else:
node_sizes.append(700)
# Kantenfarben und -stile
edge_colors = []
edge_styles = []
for u, v, data in G.edges(data=True):
if 'style' in data and data['style'] == 'dashed':
edge_styles.append('dashed')
edge_colors.append('#95a5a6') # Grau für gestrichelte Verbindungen
else:
edge_styles.append('solid')
# Übernehme Farbe vom Zielknoten
if G.nodes[v]['type'] == 'main_category':
edge_colors.append(category_colors.get(v, '#95a5a6'))
elif G.nodes[v]['type'] == 'year':
edge_colors.append('#f39c12')
else:
edge_colors.append('#95a5a6')
# Zeichne Knoten
nx.draw_networkx_nodes(G, pos, ax=ax, node_color=node_colors, node_size=node_sizes, alpha=0.8,
node_shape='o', linewidths=2, edgecolors='white')
# Zeichne Kanten mit unterschiedlichen Stilen
solid_edges = [(u, v) for i, (u, v, d) in enumerate(G.edges(data=True))
if 'style' not in d or d['style'] != 'dashed']
dashed_edges = [(u, v) for i, (u, v, d) in enumerate(G.edges(data=True))
if 'style' in d and d['style'] == 'dashed']
# Zeichne normale Kanten
if solid_edges:
nx.draw_networkx_edges(G, pos, ax=ax, edgelist=solid_edges,
width=2, alpha=0.7, arrows=True, arrowsize=20)
# Zeichne gestrichelte Kanten
if dashed_edges:
nx.draw_networkx_edges(G, pos, ax=ax, edgelist=dashed_edges,
width=1.5, alpha=0.5, style='dashed', arrows=True, arrowsize=15)
# Beschriftungen hinzufügen
nx.draw_networkx_labels(G, pos, ax=ax, font_size=10, font_family='sans-serif',
font_weight='bold', verticalalignment='center')
# Layout anpassen
ax.set_title("Kategorie-Mindmap", fontsize=16, fontweight='bold')
ax.axis('off')
fig.tight_layout()
# Canvas erstellen und anzeigen
canvas = FigureCanvasTkAgg(fig, master=dialog)
canvas_widget = canvas.get_tk_widget()
canvas_widget.pack(fill=tk.BOTH, expand=True)
# Schaltflächen hinzufügen
button_frame = ttk.Frame(dialog)
button_frame.pack(fill=tk.X, padx=10, pady=10)
ttk.Button(button_frame, text="Speichern",
command=lambda: fig.savefig("kategorie_mindmap.png", dpi=300)).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Schließen",
command=dialog.destroy).pack(side=tk.RIGHT, padx=5)
canvas.draw()
center_window(dialog)