-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreports.py
More file actions
513 lines (418 loc) · 19.4 KB
/
reports.py
File metadata and controls
513 lines (418 loc) · 19.4 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
import collections
import datetime
from datetime import date, timedelta
import rich.console
from rich import box
from rich.bar import Bar
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table
from rich.tree import Tree
console = rich.console.Console()
class LibraryCache:
def __init__(self, music):
self.music = music
self._tracks = None
self._albums = None
self._artists = None
def get_tracks(self):
if self._tracks is None:
self._tracks = self.music.searchTracks()
return self._tracks
def get_albums(self):
if self._albums is None:
self._albums = self.music.searchAlbums()
return self._albums
def get_artists(self):
if self._artists is None:
self._artists = self.music.searchArtists()
return self._artists
def clear(self):
self._tracks = None
self._albums = None
self._artists = None
def show_library_coverage(cache, state):
"""Report A: Library Coverage ('The Void')"""
console.clear()
console.rule("[bold blue]Report: Library Coverage")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
transient=True
) as progress:
progress.add_task("Scanning library statistics...", total=None)
# Fetch counts
progress.add_task("Scanning tracks (this is the big one)...", total=None)
total_tracks = len(cache.get_tracks())
progress.add_task("Scanning albums...", total=None)
total_albums = len(cache.get_albums())
progress.add_task("Scanning artists...", total=None)
total_artists = len(cache.get_artists())
count_total = total_tracks + total_albums + total_artists
count_inferred = 0
count_twin = 0
for entry in state.values():
if isinstance(entry, dict):
if not entry.get('m', False):
count_inferred += 1
if entry.get('t', 0) > 0:
count_twin += 1
else:
count_inferred += 1
count_manual = count_total - count_inferred
# Render Table
table = Table(box=box.SIMPLE_HEAD)
table.add_column("Metric", style="cyan")
table.add_column("Count", justify="right")
table.add_column("Percentage", justify="right")
table.add_column("Visual", width=40)
def add_row(label, value, total, color):
pct = (value / total * 100) if total > 0 else 0
bar = Bar(total, 0, value, width=40, color=color)
table.add_row(label, f"{value:,}", f"{pct:.1f}%", bar)
add_row("Total Items", count_total, count_total, "black")
add_row("Total Tracks", total_tracks, count_total, "cyan")
add_row("Total Albums", total_albums, count_total, "blue")
add_row("Total Artists", total_artists, count_total, "purple")
add_row("Manual Ratings", count_manual, count_total, "green")
add_row("Inferred Ratings", count_inferred, count_total, "yellow")
add_row("Twin-Linked", count_twin, count_total, "magenta")
console.print(table)
console.print(f"\n[dim]Total Library Size: {count_total:,} items[/dim]\n")
input("Press Enter to continue...")
def show_rating_histogram(cache, state):
"""Report B: Rating Histogram"""
console.clear()
console.rule("[bold blue]Report B: Rating Histogram")
with Progress(SpinnerColumn(), TextColumn("Analyzing rating distribution..."), transient=True) as progress:
progress.add_task("scan")
rated_tracks = cache.get_tracks()
manual_buckets = collections.Counter()
inferred_buckets = collections.Counter()
for track in rated_tracks:
if not track.userRating: continue
key = str(track.ratingKey)
rating = track.userRating or 0.0
# Snap to nearest 0.5 (Plex uses 0-10 scale, so we divide by 2)
# Actually, let's keep 0-10 scale for internal math but display as stars (0-5)
stars = round((rating / 2.0) * 2) / 2.0 # Round to nearest 0.5
if key in state:
entry = state[key]
if isinstance(entry, dict) and entry.get('m', False):
manual_buckets[stars] += 1
else:
inferred_buckets[stars] += 1
else:
manual_buckets[stars] += 1
# Determine max width for scaling
all_counts = manual_buckets + inferred_buckets
if not all_counts:
console.print("No rated tracks found.")
input("Press Enter...")
return
max_count = max(all_counts.values())
max_bar_width = 50
total_items = sum(all_counts.values())
# Use a table for alignment
table = Table(box=None, padding=(0, 2), show_header=True)
table.add_column("Rating", justify="right", style="cyan")
table.add_column("Distribution", style="white")
table.add_column("Count", justify="right", style="green")
table.add_column("Pct", justify="right", style="yellow")
# Iterate 5.0 down to 0.5
for i in range(10, 0, -1):
stars = i / 2.0
m_count = manual_buckets.get(stars, 0)
i_count = inferred_buckets.get(stars, 0)
total = m_count + i_count
if total == 0: continue
# Calculate bar segments
total_width = int((total / max_count) * max_bar_width)
if total_width == 0 and total > 0: total_width = 1
m_width = int((m_count / total) * total_width)
i_width = total_width - m_width
# Correct for integer truncation issues, ensuring visibility of small segments.
if total_width == 1 and m_count > 0 and i_count > 0:
# For a single-char bar with mixed content, give it to the majority.
if i_count > m_count:
i_width = 1
m_width = 0
# In a tie, the original calculation (m_width=0, i_width=1) is preserved
# unless we explicitly override, so we'll let manual win the tie.
else: # m_count >= i_count
m_width = 1
i_width = 0
elif m_count > 0 and m_width == 0:
m_width = 1
i_width = max(0, total_width - 1)
elif i_count > 0 and i_width == 0:
i_width = 1
m_width = max(0, total_width - 1)
bar_str = f"[green]{'█' * m_width}[/green][yellow]{'░' * i_width}[/yellow]"
pct = (total / total_items) * 100
table.add_row(f"{stars:.1f}", bar_str, f"{total}", f"{pct:.1f}%")
console.print(table)
console.print("\n[green]█ Manual[/green] [yellow]░ Inferred[/yellow]")
input("\nPress Enter to continue...")
def show_twins_inventory(clusters):
"""Report C: Twins Inventory"""
console.clear()
console.rule("[bold blue]Report C: Twins Inventory")
if not clusters:
console.print("No twin clusters found. Run Phase 5 logic first or ensure Twin Logic is enabled.")
input("Press Enter...")
return
# Sort clusters by Artist Name of the first item
clusters.sort(key=lambda c: c[0]['item'].grandparentTitle or "Unknown")
tree = Tree("[bold magenta]Twin Clusters Registry[/bold magenta]")
for cluster in clusters:
if len(cluster) < 2: continue
# Representative info
first = cluster[0]['item']
artist = first.grandparentTitle or "Unknown"
title = first.title
# Calculate cluster rating (average of manual anchors or all)
manuals = [t for t in cluster if t['is_manual']]
if manuals:
rating = sum(t['rating'] for t in manuals) / len(manuals)
source = "Manual Anchor"
else:
rating = sum(t['rating'] for t in cluster) / len(cluster)
source = "Inferred Consensus"
node = tree.add(f"[bold]{artist} - {title}[/bold] [yellow]({rating / 2:.2f}★)[/yellow] [dim]({source})[/dim]")
for t in cluster:
item = t['item']
album = item.parentTitle or "Unknown"
duration = f"{item.duration // 60000}:{(item.duration // 1000) % 60:02d}"
rtype = "[green]Manual[/green]" if t['is_manual'] else "[dim]Inferred[/dim]"
node.add(f"{album} - {duration} {rtype}")
console.print(tree)
# Offer export since this can be huge
if console.input("\nExport to text file? (y/N): ").strip().lower() == 'y':
filename = "report_twins.txt"
with open(filename, "w", encoding="utf-8") as f:
from rich.console import Console
# Use a wide width to prevent wrapping in the text file
file_console = Console(file=f, width=console.width)
file_console.print(tree)
console.print(f"Exported to {filename}")
input("Press Enter to continue...")
def show_dissenter_report(cache):
"""Report D: The Dissenter Report (Outliers)"""
console.clear()
console.rule("[bold blue]Report D: The Dissenter Report")
limit_str = console.input("How many records to show? [dim](default: 50)[/dim]: ").strip()
try:
limit = int(limit_str) if limit_str else 50
except ValueError:
limit = 50
with Progress(SpinnerColumn(), TextColumn("{task.description}"), transient=True) as progress:
# 1. Fetch all rated albums to build a lookup map
progress.add_task("Fetching Album ratings...", total=None)
albums = cache.get_albums()
album_map = {str(a.ratingKey): a.userRating for a in albums if a.userRating}
# 2. Fetch all rated tracks
progress.add_task("Fetching Track ratings...", total=None)
tracks = cache.get_tracks()
dissenters = []
# 3. Calculate deviations
task = progress.add_task("Calculating deviations...", total=len(tracks))
for track in tracks:
progress.advance(task)
if not track.userRating: continue
if not track.parentRatingKey: continue
pkey = str(track.parentRatingKey)
if pkey in album_map:
album_rating = album_map[pkey]
track_rating = track.userRating
delta = track_rating - album_rating # Signed delta to show direction
# We care about magnitude of deviation
if abs(delta) > 0.1:
dissenters.append({
'artist': track.grandparentTitle,
'title': track.title,
'album': track.parentTitle,
'track_rating': track_rating,
'album_rating': album_rating,
'delta': delta,
'abs_delta': abs(delta)
})
# Sort by absolute deviation descending
dissenters.sort(key=lambda x: x['abs_delta'], reverse=True)
top_n = dissenters[:limit]
table = Table(title=f"Top {limit} Dissenters (Tracks vs Album)", box=box.SIMPLE_HEAD)
table.add_column("Artist", style="cyan")
table.add_column("Track Title", style="white")
table.add_column("Album", style="blue")
table.add_column("Track ★", justify="right", style="green")
table.add_column("Album ★", justify="right", style="yellow")
table.add_column("Deviation", justify="right", style="bold red")
for d in top_n:
sign = "+" if d['delta'] > 0 else ""
table.add_row(
d['artist'],
d['title'],
d['album'] or "",
f"{d['track_rating'] / 2:.1f}",
f"{d['album_rating'] / 2:.1f}",
f"{sign}{d['delta'] / 2:.1f}"
)
console.print(table)
if console.input("\nExport to text file? (y/N): ").strip().lower() == 'y':
filename = "report_dissenters.txt"
with open(filename, "w", encoding="utf-8") as f:
from rich.console import Console
# Use the main console's width to ensure consistent table rendering in the file
file_console = Console(file=f, width=console.width)
file_console.print(table)
console.print(f"Exported to {filename}")
input("\nPress Enter to continue...")
def show_manual_rating_history(cache, state):
"""Report E: Manual Rating History"""
console.clear()
console.rule("[bold blue]Report: Manual Rating History")
def parse_date_input(prompt, default_date=None):
while True:
date_str = console.input(prompt).strip()
if not date_str and default_date:
return default_date
if not date_str: # If no default and no input, return None
return None
try:
return datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
except ValueError:
console.print("[red]Invalid date format. Please use YYYY-MM-DD.[/red]")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
transient=True
) as progress:
progress.add_task("Finding date range of rating history...", total=None)
# First pass to find the absolute min_date for defaulting
all_event_dates = set()
def collect_all_dates(items):
for item in items:
if item.lastRatedAt:
all_event_dates.add(item.lastRatedAt.date())
collect_all_dates(cache.get_artists())
collect_all_dates(cache.get_albums())
collect_all_dates(cache.get_tracks())
earliest_available_date = min(all_event_dates) if all_event_dates else date.min
start_date = parse_date_input(
f"Enter start date (YYYY-MM-DD) [dim](default: {earliest_available_date.strftime('%Y-%m-%d')})[/dim]: ",
default_date=earliest_available_date
)
end_date = parse_date_input(
f"Enter end date (YYYY-MM-DD) [dim](default: {date.today().strftime('%Y-%m-%d')})[/dim]: ",
default_date=date.today()
)
if start_date and end_date and start_date > end_date:
console.print("[red]Start date cannot be after end date. Swapping them.[/red]")
start_date, end_date = end_date, start_date
console.print(f"[dim]Showing data from {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}[/dim]\n")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
transient=True
) as progress:
progress.add_task("Harvesting manual rating events...", total=None)
events = collections.defaultdict(lambda: collections.defaultdict(int))
# These min_date/max_date will now track the actual range of events *within* the user's filter
filtered_min_date, filtered_max_date = date.max, date.min
def process_items(items, item_type):
nonlocal filtered_min_date, filtered_max_date
for item in items:
if not item.lastRatedAt:
continue
event_date = item.lastRatedAt.date()
# Filter by user-specified date range
if not (start_date <= event_date <= end_date):
continue
key = str(item.ratingKey)
is_manual = False
if key not in state:
is_manual = True
else:
entry = state[key]
if isinstance(entry, dict):
if entry.get('m', False):
is_manual = True
elif 'lr' in entry and entry['lr']: # Check if 'lr' exists and is not empty
try:
stored_timestamp = datetime.datetime.fromisoformat(entry['lr']).timestamp()
if item.lastRatedAt.timestamp() > stored_timestamp:
is_manual = True
except ValueError:
# Handle cases where 'lr' might be malformed, treat as not hijacked
pass
if is_manual:
events[event_date][item_type] += 1
if event_date < filtered_min_date:
filtered_min_date = event_date
if event_date > filtered_max_date:
filtered_max_date = event_date
process_items(cache.get_artists(), 'artist')
process_items(cache.get_albums(), 'album')
process_items(cache.get_tracks(), 'track')
if not events:
console.print("No manual rating events found within the specified date range.")
input("Press Enter...")
return
# Adaptive Bucketing
# Use filtered_min_date and filtered_max_date for span calculation
span_days = (filtered_max_date - filtered_min_date).days if filtered_min_date != date.max else 0
if span_days < 45:
get_bucket_key = lambda d: d
format_bucket_key = lambda d: d.strftime("%Y-%m-%d")
elif 45 <= span_days <= 182: # approx 6 months
get_bucket_key = lambda d: d - timedelta(days=d.weekday())
format_bucket_key = lambda d: f"{d.strftime('%Y-%m-%d')} (Week)"
else:
get_bucket_key = lambda d: d.replace(day=1)
format_bucket_key = lambda d: d.strftime("%Y-%m")
# Aggregate into buckets
buckets = collections.defaultdict(lambda: collections.defaultdict(int))
for event_date, counts in events.items():
bucket_key = get_bucket_key(event_date)
for item_type, count in counts.items():
buckets[bucket_key][item_type] += count
# Column-Relative Scaling
max_artists = max((b.get('artist', 0) for b in buckets.values()), default=1)
max_albums = max((b.get('album', 0) for b in buckets.values()), default=1)
max_tracks = max((b.get('track', 0) for b in buckets.values()), default=1)
# Visual Representation
table = Table(title="Manual Rating Activity Timeline", box=box.SIMPLE_HEAD)
table.add_column("Time Bucket", style="cyan", no_wrap=True)
table.add_column("Artists", justify="right")
table.add_column("Albums", justify="right")
table.add_column("Tracks", justify="right")
# Sort buckets by date descending and limit to a readable number
sorted_buckets = sorted(buckets.items(), key=lambda item: item[0], reverse=True)
for bucket_key, counts in sorted_buckets[:30]: # Show approx 30 rows
artist_count = counts.get('artist', 0)
album_count = counts.get('album', 0)
track_count = counts.get('track', 0)
artist_bar = Bar(max_artists, 0, artist_count, color="blue")
album_bar = Bar(max_albums, 0, album_count, color="green")
track_bar = Bar(max_tracks, 0, track_count, color="red")
# Create a grid for each cell to hold the count and the bar
artist_cell = Table.grid(expand=True)
artist_cell.add_column(justify="right", no_wrap=True)
artist_cell.add_column()
artist_cell.add_row(f"{artist_count} ", artist_bar)
album_cell = Table.grid(expand=True)
album_cell.add_column(justify="right", no_wrap=True)
album_cell.add_column()
album_cell.add_row(f"{album_count} ", album_bar)
track_cell = Table.grid(expand=True)
track_cell.add_column(justify="right", no_wrap=True)
track_cell.add_column()
track_cell.add_row(f"{track_count} ", track_bar)
table.add_row(
format_bucket_key(bucket_key),
artist_cell,
album_cell,
track_cell
)
table.caption = "\nBars are scaled relative to each column's historical peak."
console.print(table)
input("\nPress Enter to continue...")