-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
1636 lines (1533 loc) · 60.7 KB
/
main.py
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
import random, json, os, sys, time, subprocess, webbrowser, math
from howlongtobeatpy import HowLongToBeat
from difflib import SequenceMatcher
from pathlib import Path
from pick import pick
import datetime as dt
import pandas as pd
from rich.console import Console
from rich.prompt import IntPrompt
from rich.progress import track
from rich.table import Table
from rich.theme import Theme
# classes
from classes.setup import Setup
from classes.steam import Steam
from classes.game_skipper import GameSkipper
from classes.utils import Utils, keyboard_interrupt
from classes.logger import Logger
# my package
from easierexcel import Excel, Sheet
class Tracker(Steam, Utils):
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)
# rich console
custom_theme = Theme(
{
"primary": "bold deep_sky_blue1",
"secondary": "bold pale_turquoise1",
"info": "dim cyan",
"warning": "bold light_goldenrod1",
"danger": "bold red",
}
)
console = Console(theme=custom_theme)
title = "Game Library Tracker"
# config init
setup = Setup()
config_path, config_data, ignore_data = setup.run()
# steam_data
steam_key = config_data["steam_data"]["api_key"]
steam_id = str(config_data["steam_data"]["steam_id"])
vanity_url = config_data["steam_data"]["vanity_url"]
# settings
playstation_data_link = config_data["settings"]["playstation_data_link"]
excel_filename = config_data["settings"]["excel_filename"]
logging = config_data["settings"]["logging"]
# misc
name_ignore_list = [string.lower() for string in ignore_data["name_ignore_list"]]
app_id_ignore_list = ignore_data["app_id_ignore_list"]
game_skipper = GameSkipper(name_ignore_list, app_id_ignore_list)
# logging setup
if logging:
Log = Logger()
tracker_log_path = "logs/tracker.log"
tracker = Log.create_log(name="tracker", log_path=tracker_log_path)
error_log = Log.create_log(name="base_error", log_path="logs/error.log")
# class init
options = {
"shrink_to_fit_cell": True,
"header": {"bold": True, "font_size": 16},
"default_align": "center_align",
"left_align": [
"Name",
"Developers",
"Publishers",
"User Tags",
"Notes",
"Genre",
],
# "light_grey_fill": [],
"percent": [
"%",
"Percent",
"Discount",
],
"currency": ["Price", "MSRP", "Cost"],
"integer": ["App ID", "Number", "Release Year"],
"count_days": ["Days Till Release"],
"date": ["Last Updated", "Date"],
"decimal": ["Hours Played", "Linux Hours", "Time To Beat in Hours"],
}
# excel setup
excel = Excel(excel_filename, use_logging=logging)
steam = Sheet(
excel_object=excel,
sheet_name="Steam",
column_name="App ID",
options=options,
)
playstation = Sheet(
excel_object=excel,
sheet_name="Playstation",
column_name="Name",
options=options,
)
sales = Sheet(
excel_object=excel,
sheet_name="Sales",
column_name="Name",
options=options,
)
# sets play status choices for multiple functions
play_status_choices = {
"1": "Played",
"2": "Unplayed",
"3": "Endless",
"4": "Replay",
"5": "Must Play",
"6": "Finished",
"7": "Waiting",
"8": "Quit",
"9": "Ignore",
}
# misc
ps_data = Path("configs/playstation_games.json")
# columns
excel_columns = [
date_added_col := "Date Added",
date_updated_col := "Date Updated",
my_rating_col := "My Rating",
rating_comp_col := "Rating Comparison",
steam_rev_per_col := "Steam Review Percent",
steam_rev_total_col := "Steam Review Total",
price_col := "Price",
discount_col := "Discount",
steam_player_count_col := "Player Count",
name_col := "Name",
play_status_col := "Play Status",
platform_col := "Platform",
dev_col := "Developers",
pub_col := "Publishers",
genre_col := "Genre",
user_tags_col := "User Tags",
ea_col := "Early Access",
time_played_col := "Time Played",
hours_played_col := "Hours Played",
linux_hours_col := "Linux Hours",
last_play_time_col := "Last Play Time",
time_to_beat_col := "Time To Beat in Hours",
store_link_col := "Store Link",
release_col := "Release Year",
app_id_col := "App ID",
]
# not applicable cell values
na_values = [
"NaN",
"Invalid Date",
"No Tags",
"No Year",
"No Score",
"Not Found",
"No Reviews",
"Missing Data",
"Few Reviews",
"Not Enough Reviews",
"No Publisher",
"No Developer",
]
errors = []
def __init__(self, save) -> None:
"""
Game Library Tracking Class.
"""
self.save_to_file = save
if not self.steam_id:
self.update_steam_id()
def update_steam_id(self):
"""
Updates the steam id in the config using the given vanity url if present.
"""
if not self.vanity_url:
raise "Steam ID and Vanity URL is blank. Please enter at one of them"
steam_id = self.get_steam_id(self.vanity_url, self.steam_key)
if steam_id:
self.config_data["settings"]["steam_id"] = steam_id
self.save_json_output(self.config_data, self.config_path)
def get_friends_list_changes(self, check_freq_days: int = 7) -> None:
"""
Checks for changes to your friends list.
Shows a table of new and removed friends Steam ID's and usernames.
"""
# check last run
if self.recently_executed(self.config_data, "friends_sync", check_freq_days):
return
self.update_last_run(self.config_data, "friends_sync")
# get friends
print("\nStarting Steam Friends Sync")
prev_friends_ids = self.config_data["friend_ids"]
friend_data = self.get_steam_friends(self.steam_key, self.steam_id)
cur_friend_ids = [friend["steamid"] for friend in friend_data]
# finds changes
additions = list(set(cur_friend_ids) - set(prev_friends_ids))
removals = list(set(prev_friends_ids) - set(cur_friend_ids))
if not additions and not removals:
self.console.print("No friends added or removed", style="secondary")
return
# view changes
title = "Friends List Updates"
table = Table(
title=title,
show_lines=True,
title_style="bold",
style="deep_sky_blue1",
)
table.add_column("Type", justify="center")
table.add_column("Username", justify="left")
table.add_column("Steam ID", justify="left")
for steam_id in removals:
username = self.get_steam_username(steam_id, self.steam_key)
row = [
"Removed",
username,
steam_id,
]
table.add_row(*row)
# logging
msg = f"Added to Friends List: {username}"
self.tracker.info(msg)
for steam_id in additions:
username = self.get_steam_username(steam_id, self.steam_key)
row = [
"Added",
username,
steam_id,
]
table.add_row(*row)
# logging
msg = f"Removed from Friends List: {username}"
self.tracker.info(msg)
self.console.print(table, new_line_start=True)
# update friend data in config
self.config_data["friend_ids"] = cur_friend_ids
self.save_json_output(self.config_data, self.config_path)
def set_title(self, title=None):
"""
Sets the CLI windows title.
"""
if title:
set_title = title
else:
set_title = self.title
os.system("title " + set_title)
def get_time_to_beat(self, game_name):
"""
Uses howlongtobeatpy to get the time to beat for entered game.
"""
self.api_sleeper("time_to_beat")
try:
results = HowLongToBeat().search(game_name)
except:
for _ in range(3):
time.sleep(10)
results = HowLongToBeat().search(game_name)
return ""
if not results:
self.api_sleeper("time_to_beat")
if game_name.isupper():
results = HowLongToBeat().search(game_name.title())
else:
results = HowLongToBeat().search(game_name.upper())
time_to_beat = "-"
if results is not None and len(results) > 0:
best_element = max(results, key=lambda element: element.similarity)
time_to_beat = best_element.main_extra or best_element.main_story or "-"
return time_to_beat
def create_save_every_nth(self, save_on_nth=20):
counter = 0
def save_every_nth():
nonlocal counter
counter += 1
if counter % save_on_nth == 0:
self.excel.save(use_print=False, backup=False)
counter = 0
return save_every_nth
def set_release_year(self, app_id, release_year):
"""
Sets `app_id`'s release year cell to `release_year` if a year is not
already set.
"""
cur_val = self.steam.get_cell(app_id, self.release_col)
if not self.any_is_num(cur_val):
return self.steam.update_cell(app_id, self.release_col, release_year)
def set_genre(self, app_id, genre):
"""
Sets `app_id`'s genre cell to `genre`.
"""
return self.steam.update_cell(app_id, self.genre_col, genre)
def set_time_to_beat(self, app_id, new_ttb, cur_ttb):
"""
Sets `app_id`'s Time to beat cell to `time_to_beat`.
"""
if not new_ttb:
return
if not self.any_is_num(cur_ttb):
return self.steam.update_cell(app_id, self.time_to_beat_col, new_ttb)
def set_hours_played(self, app_id, hours):
"""
Sets `app_id`'s Hours Played cell to `hours`.
"""
return self.steam.update_cell(app_id, self.hours_played_col, hours)
def set_linux_hours_played(self, app_id, hours):
"""
Sets `app_id`'s Linux Hours cell to `hours`.
"""
return self.steam.update_cell(app_id, self.linux_hours_col, hours)
def set_last_playtime(self, app_id, set_last_playtime):
"""
Sets `app_id`'s last play time to `set_last_playtime`.
"""
column = self.last_play_time_col
return self.steam.update_cell(app_id, column, set_last_playtime)
def set_time_played(self, app_id, time_played):
"""
Sets `app_id`'s time played to `time_played`.
"""
column = self.time_played_col
return self.steam.update_cell(app_id, column, time_played)
def set_play_status(self, app_id, new_status, cur_status=None):
"""
Sets `app_id`'s Play Status cell to `new_status` if it the current status is unplayed.
"""
if cur_status == "Unplayed" and new_status != cur_status:
return self.steam.update_cell(app_id, self.play_status_col, new_status)
def set_date_updated(self, app_id):
"""
Sets `app_id`'s Date Updated cell to the current date.
"""
cur_date = dt.datetime.now()
return self.steam.update_cell(app_id, self.date_updated_col, cur_date)
@staticmethod
def get_price_info(game_info: {}):
"""
Gets price info from `game_info` and returns None if anything is set up
wrong for any or all return values.
"""
if "price_overview" not in game_info.keys():
return None, None, None
price_data = game_info["price_overview"]
# price
price = None
if "final_formatted" in price_data.keys():
price_value = price_data["final_formatted"]
try:
price = float(price_value.replace("$", ""))
except:
price = None
# discount
discount = None
if "discount_percent" in price_data.keys():
discount = float(price_data["discount_percent"])
# on sale
on_sale = None
if "discount_percent" in price_data.keys():
on_sale = price_data["discount_percent"] > 0
return price, discount, on_sale
def get_game_info(self, app_id):
"""
Gets game info with steam api using a `app_id`.
"""
info_dict = {
"game_name": "-",
self.dev_col: "-",
self.pub_col: "-",
self.genre_col: "-",
self.ea_col: "No",
self.steam_rev_per_col: "No Reviews",
self.steam_rev_total_col: "No Reviews",
self.user_tags_col: "No Tags",
self.release_col: "No Year",
"price": "-",
"discount": 0.0,
"on_sale": False,
"drm_notice": "-",
"categories": "-",
}
def get_json_desc(data):
return [item["description"] for item in data]
app_details = self.get_app_details(app_id)
if not app_details:
return info_dict
# gets games store data
store_link = self.get_store_link(app_id)
self.api_sleeper("store_data")
response = self.request_url(store_link)
# steam review data
percent, total = self.get_steam_review(app_id=app_id, response=response)
info_dict[self.steam_rev_per_col] = percent
info_dict[self.steam_rev_total_col] = total
# get user tags
tags = self.get_steam_user_tags(app_id=app_id, response=response)
if tags:
info_dict[self.user_tags_col] = ", ".join(tags)
# info_dict setup
if "data" in app_details[str(app_id)].keys():
game_info = app_details[str(app_id)]["data"]
keys = game_info.keys()
# get game name
if "name" in keys:
info_dict["game_name"] = game_info["name"]
# get developer
if "developers" in keys:
output = self.list_to_sentence(game_info["developers"])
if output != "":
info_dict[self.dev_col] = output
# get publishers
if "publishers" in keys:
output = self.list_to_sentence(game_info["publishers"])
if output != "":
info_dict[self.pub_col] = output
# get genre
if "genres" in keys:
genres = get_json_desc(game_info["genres"])
info_dict[self.genre_col] = ", ".join(genres)
# early access
if self.ea_col in info_dict[self.genre_col]:
info_dict[self.ea_col] = "Yes"
# get release year
if "release_date" in keys:
release_date = game_info["release_date"]["date"]
release_date = self.get_year(release_date)
info_dict[self.release_col] = release_date
# get price_info
if "price_overview" in keys:
price, discount, on_sale = self.get_price_info(game_info)
if price:
info_dict["price"] = price
if discount:
info_dict["discount"] = discount
if on_sale:
info_dict["on_sale"] = on_sale
# get linux compat
if "linux_compat" in keys:
info_dict["linux_compat"] = game_info["platforms"]["linux"]
# categories
if "categories" in keys:
categories = get_json_desc(game_info["categories"])
info_dict["categories"] = self.list_to_sentence(categories)
# drm info
if "drm_notice" in keys:
info_dict["drm_notice"] = game_info["drm_notice"]
# runs unicode remover on all values
return {k: self.unicode_remover(v) for k, v in info_dict.items()}
return info_dict
def find_recent_games(
self,
df: pd.DataFrame,
column: str,
n_days: int = 7,
) -> list[dict]:
"""
Finds recent games by dates in `column` within `n_days`.
"""
df[column] = pd.to_datetime(df[column])
filtered_df = df[abs((df[column] - dt.datetime.now()).dt.days) <= n_days]
return filtered_df.sort_values(
by=self.date_updated_col, ascending=False
).to_dict(orient="records")
def update_extra_steam_info(self, app_ids):
"""
ph
"""
save_every_nth = self.create_save_every_nth()
update_total = len(app_ids)
cur_itr = 0
print()
desc = "Syncing Game Data"
for app_id in track(app_ids, description=desc):
game_data = self.steam.get_row(app_id)
game_name = game_data[self.name_col]
# How long to beat check
cur_ttb = game_data[self.time_to_beat_col]
if not cur_ttb:
new_ttb = self.get_time_to_beat(game_name)
self.set_time_to_beat(app_id, new_ttb, cur_ttb)
steam_info = self.get_game_info(app_id)
# updates sheet with data found in steam_info
special_case_col = [self.release_col]
for key, val in steam_info.items():
if key in self.excel_columns and steam_info[key]:
if key not in special_case_col:
self.steam.update_cell(app_id, key, val)
# release year
if steam_info[self.release_col]:
year = steam_info[self.release_col]
self.set_release_year(app_id, year)
if self.save_to_file:
save_every_nth()
# title progress percentage
cur_itr += 1
progress = cur_itr / update_total * 100
self.set_title(f"{progress:.2f}% - {self.title}")
self.set_title()
def update_all_game_data(self):
"""
ph
"""
app_ids = [int(app_id) for app_id in self.steam.row_idx.keys()]
self.update_extra_steam_info(app_ids)
def get_recently_played_app_ids(self, df: pd.DataFrame, n_days=30) -> list:
"""
ph
"""
# check last run
if self.recently_executed(self.config_data, "updated_recently_played", n_days):
return []
# get recently played games
recently_played = App.find_recent_games(df, self.date_updated_col, n_days)
recently_played_app_ids = [game[self.app_id_col] for game in recently_played]
return recently_played_app_ids
def updated_game_data(self, df, skip_filled=True, skip_by_play_status=False):
"""
Updates game data for games that were played recently and are missing data.
Use `skip_filled` to skip non blank entries.
Use `skip_by_play_status` to only check games with a specific play status.
"""
# starts the update list with recently played games
update_list = self.get_recently_played_app_ids(df, n_days=30)
updated_recent = True if update_list else False
column_list = [
self.genre_col,
self.pub_col,
self.dev_col,
self.steam_rev_per_col,
self.steam_rev_total_col,
self.user_tags_col,
self.time_to_beat_col,
self.release_col,
self.ea_col,
]
# adds games with missing data to update_list
for app_id in self.steam.row_idx:
game_data = self.steam.get_row(app_id)
if skip_by_play_status:
if game_data[self.play_status_col] not in [
"Unplayed",
"Played",
"Finished",
"Quit",
"Replay",
"Must Play",
]:
continue
if skip_filled:
for column in column_list:
cell = game_data[column]
if cell == None and app_id not in update_list:
update_list.append(app_id)
continue
else:
update_list.append(app_id)
# checks if data should be updated
if update_list:
msg = f"\nDo you want to update data for {len(update_list)} games?\n"
if not self.is_response_yes(msg):
return
else:
return
# updates game data
try:
self.update_extra_steam_info(update_list)
if updated_recent:
self.update_last_run(self.config_data, "updated_recently_played")
print(f"\nUpdated Data for {len(update_list)} games")
except KeyboardInterrupt:
print("\nCancelled")
finally:
if self.save_to_file:
self.excel.save(use_print=False)
def output_recently_played_games(self, df, n_days=7):
"""
Creates a table with the recently played Gmes.
"""
recently_played_games = App.find_recent_games(df, "Date Updated", n_days)
# creates table
title = "Recently Played Games"
table = Table(
title=title,
show_lines=True,
title_style="bold",
style="deep_sky_blue1",
)
table.add_column("Days\nSince", justify="center")
table.add_column("Date Updated", justify="center")
table.add_column("Name", justify="left")
table.add_column("Play\nStatus", justify="center")
table.add_column("Hours\nPlayed", justify="right")
table.add_column("Time\nTo Beat", justify="right")
table.add_column("Last\nPlay Time", justify="center")
# add rows
for game in recently_played_games[:10]:
# days since
last_updated_dt = game[self.date_updated_col]
last_updated = (
last_updated_dt.strftime("%a %b %d, %Y") if last_updated_dt else "-"
)
days_since = str(abs(self.days_since(last_updated_dt)))
# last play time
last_play_time = "-"
if type(game[self.last_play_time_col]) is str:
last_play_time = game[self.last_play_time_col]
# hours played
hours_played = (
str(game[self.hours_played_col])
if not math.isnan(game[self.hours_played_col])
else "0"
)
# time to beat
ttb = (
str(game[self.time_to_beat_col])
if type(game[self.time_to_beat_col]) is float
else "-"
)
# row setup
row = [
days_since,
last_updated,
game[self.name_col],
game[self.play_status_col],
hours_played,
ttb,
last_play_time,
]
table.add_row(*row)
# print table
self.console.print(table, new_line_start=True)
def output_play_status_info(self, df):
"""
Creates a table with counts and percentage of each play status.
"""
title = "Play Status Statistics\n(Excludes Ignored)"
table = Table(
title=title,
show_lines=True,
title_style="bold",
style="deep_sky_blue1",
)
play_statuses = df["Play Status"].value_counts()
total_games = df["Name"].count() - play_statuses["Ignore"]
row1, row2 = [], []
for status in self.play_status_choices.values():
if status == "Ignore":
continue
table.add_column(status, justify="center")
row1.append(str(play_statuses[status]))
row2.append(f"{play_statuses[status]/total_games:.1%}")
table.add_row(*row1)
table.add_row(*row2)
self.console.print(table, new_line_start=True)
def output_playtime_info(self, df):
"""
Creates a table with counts and percentage of each play status.
"""
title = "Playtime Statistics"
table = Table(
title=title,
show_lines=True,
title_style="bold",
style="deep_sky_blue1",
)
data = {}
# TODO remove any games with ignore status
total_hours_sum = df["Hours Played"].sum()
linux_hours_sum = df["Linux Hours"].sum()
data["Total\nHours"] = round(total_hours_sum, 1)
data["Total\nDays"] = round(total_hours_sum / 24, 1)
data["Linux\nHours"] = round(linux_hours_sum, 1)
data["% Linux\nHours"] = f"{linux_hours_sum / total_hours_sum:.1%}"
# averages
data["Average\nHours"] = round(df["Hours Played"].mean(), 1)
data["Median\nHours"] = round(df["Hours Played"].median(), 1)
# min max
data["Max\nHours"] = round(df["Hours Played"].max(), 1)
row = []
for name, stat in data.items():
table.add_column(name, justify="center")
row.append(str(stat))
table.add_row(*row)
self.console.print(table, new_line_start=True)
def output_review_info(self, df):
"""
Outputs a table of review stats.
"""
title = "Rating Statistics"
table = Table(
title=title,
show_lines=True,
title_style="bold",
style="deep_sky_blue1",
)
data = {}
# TODO remove any games with ignore status
# my ratings
my_ratings = df["My Rating"]
data["My\nTotal"] = my_ratings.count()
data["My\nAverage"] = round(my_ratings.mean(), 1)
# steam ratings
steam_ratings = df["Steam Review Percent"].astype("float")
data["Steam\nTotal"] = steam_ratings.count()
steam_avg = round(steam_ratings.mean(), 1)
data["Steam\nAverage"] = f"{round(steam_avg*100)}%"
row = []
for name, stat in data.items():
table.add_column(name, justify="center")
row.append(str(stat))
table.add_row(*row)
self.console.print(table, new_line_start=True)
def find_tag_rating_avg(self, df):
"""
Finds the average library owner rating for each game tag.
"""
# Split the comma-separated values in the 'Genres' column into separate rows
df_exploded = df.assign(Tag=df["User Tags"].str.split(",")).explode("Tag")
tag_counts = df_exploded["Tag"].value_counts()
print("\nTag Counts", tag_counts)
min_tags = 2
min_total_ratings = 5
popular_tags = tag_counts[tag_counts >= min_tags].index
print("\nPopular Tags", popular_tags)
df_filtered_tags = df_exploded[df_exploded["Tag"].isin(popular_tags)]
# Group by the 'Genre' column and calculate the average rating for each genre
average_ratings_by_genre = df_filtered_tags.groupby("Tag")["My Rating"].mean()
filtered_tags = average_ratings_by_genre.index[
average_ratings_by_genre.index.isin(
tag_counts[tag_counts > min_total_ratings].index
)
]
# Display the result
top_30_ratings = filtered_tags.sort_values(ascending=False)
print(top_30_ratings)
# for ind in top_30_ratings.index:
# print(df["Name"][ind], df["My Rating"][ind])
def output_statistics(self, dataframe):
"""
Outputs tables of game library statistics.
"""
self.output_play_status_info(dataframe)
self.output_playtime_info(dataframe)
self.output_review_info(dataframe)
@staticmethod
def decide_play_status(play_status: str, minutes_played: int or float):
"""
Using time_played and play_status,
determines what the play_status should change to.
"""
minutes_played_type = type(minutes_played)
if minutes_played_type is not float and minutes_played_type is not int:
return play_status or ""
if play_status not in ["Played", "Unplayed", "Must Play", None]:
return play_status
# play status change
if minutes_played >= 30:
play_status = "Played"
else:
if play_status != "Must Play":
play_status = "Unplayed"
return play_status
def name_change_checker(self, name_changes):
"""
Checks the `name_changes` to see if they contain any
name changes to possibly fufill.
"""
name_change_warning_num = 5
name_changes_total = len(name_changes)
if name_changes_total == 0:
return
elif name_changes_total > name_change_warning_num:
print(f"\nName Change Total {name_changes_total}")
print(f"Over Warning Threshold of {name_change_warning_num}")
return
print("\nName Changes:")
for names_dict in name_changes:
new_name = names_dict["new_name"]
old_name = names_dict["old_name"]
print(f'"{old_name}" to "{new_name}"')
msg = "Do you want to update the above game names?:\n"
if self.is_response_yes(msg):
for names_dict in name_changes:
app_id = names_dict["app_id"]
new_name = names_dict["new_name"]
self.steam.update_cell(app_id, self.name_col, new_name)
return
print("Skipping Name Changes")
def output_played_games_info(self, played_games):
"""
Outputs a table of played game stats.
"""
total_games_played = len(played_games)
title = f"Games Played: {len(played_games)}"
if total_games_played > 1:
title += f"\nLast Session Playtime: {self.total_session_playtime:.1f} Hours"
table = Table(
title=title,
show_lines=True,
title_style="bold",
style="deep_sky_blue1",
)
table.add_column("Name", justify="left")
table.add_column("Time\nPlayed", justify="center")
table.add_column("Total\nPlaytime", justify="center")
for game in played_games:
row = [
game["name"],
game["added_time_played"],
f"{game['total_playtime']} Hours",
]
table.add_row(*row)
self.console.print(table, new_line_start=True)
def output_added_games_info(self, added_games):
"""
Outputs a table of added game stats.
"""
title = f"Games Added: {len(added_games)}"
table = Table(
title=title,
show_lines=True,
title_style="bold",
style="deep_sky_blue1",
)
table.add_column("Name", justify="left")
table.add_column("Total Playtime", justify="center")
for game in added_games:
playtime = "Unplayed"
if game["total_playtime"]:
playtime = f"{game['total_playtime']} Hours"
row = [
game["name"],
playtime,
]
table.add_row(*row)
self.console.print(table, new_line_start=True)
def game_check(self, steam_games, sheet_games):
"""
Checks for new games or game updates from `steam_games` based on `sheet_games`.
"""
self.total_session_playtime = 0
added_games = []
played_games = []
name_changes = []
save_every_nth = self.create_save_every_nth()
# game checking
print()
total_games = len(steam_games)
desc = f"Syncing [bold]{total_games:,}[/bold] Steam Games"
for game in track(steam_games, description=desc):
game_name, app_id = game["name"], game["appid"]
# ignore check
if self.game_skipper.skip_game(game_name, app_id):
continue
# name change check
# TODO below fails if game is added at this time.
cur_game_data = self.steam.get_row(app_id)
if (
cur_game_data[self.name_col]
and cur_game_data[self.name_col] != game_name
):
msg = f'Name Change: "{cur_game_data[self.name_col]}" to "{game_name}"'
self.tracker.info(msg)
name_change_dict = {
"new_name": game_name,
"old_name": cur_game_data[self.name_col],
"app_id": app_id,
}
name_changes.append(name_change_dict)
# sets play time earlier so it only needs to be set up once
minutes_played = game["playtime_forever"]
time_played = self.convert_time_passed(min=minutes_played)
linux_minutes_played = ""
if "playtime_linux_forever" in game.keys():
linux_minutes_played = game["playtime_linux_forever"]
# play status
cur_status = cur_game_data[self.play_status_col]
new_status = self.decide_play_status(cur_status, minutes_played)
# updates or adds game
if app_id in sheet_games:
sheet_games.remove(app_id)
update_info = self.update_steam_game(
app_id,
game_name,
minutes_played,
linux_minutes_played,
new_status,
cur_status,
time_played,
)
if update_info:
played_games.append(update_info)
else:
added_info = self.add_steam_game(
app_id,
game_name,
minutes_played,
linux_minutes_played,
time_played,
new_status,
)
added_games.append(added_info)
# saves each time the checks count is divisible by num
if self.save_to_file:
save_every_nth()
# prints the total games updated and added
if 0 < len(played_games) < 50:
self.output_played_games_info(played_games)
# game names changed
self.name_change_checker(name_changes)
# games added
total_added_games = len(added_games)
if 0 < total_added_games < 50:
if total_added_games > 50:
added_games = added_games[:50]
print("Showing First 50 Games Added")
self.output_added_games_info(added_games)
# checks for removed games
total_removed_games = len(sheet_games)
if total_removed_games:
removed_game_names = [
self.steam.get_cell(app_id, self.name_col) for app_id in sheet_games
]
removed_games_names_str = self.list_to_sentence(removed_game_names)
if self.is_response_yes(
f"\nDo you want to delele all the following games?\n{removed_games_names_str}"
):
for app_id in sheet_games:
self.steam.delete_row(str(app_id))
if self.excel.changes_made and self.save_to_file:
self.excel.save(use_print=False)
else:
print("\nNo Steam games were added or updated")
def sync_steam_games(self, steam_key: int, steam_id: int):
"""
Gets games owned by the entered `steam_id`
and runs excel update/add functions.
"""