python-ballchasing 0.5.4__py3-none-any.whl → 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
scripts/make_types.py DELETED
@@ -1,194 +0,0 @@
1
- import os
2
- import random
3
- from dataclasses import make_dataclass, fields
4
- from typing import List, Any
5
-
6
- from requests import HTTPError
7
-
8
- import ballchasing as bc
9
-
10
- api = bc.Api(os.environ.get("BALLCHASING_API_KEY"))
11
-
12
-
13
- # Creates a starting point for dataclasses that contain response data
14
-
15
- def get_diverse_replays(limit=1000, deep=False):
16
- remaining = limit
17
- while True:
18
- rank = random.choice(bc.Rank.ALL)
19
- season = random.choice(bc.Season.ALL)
20
- playlist = random.choice(bc.Playlist.ALL)
21
- map_id = random.choice(bc.Map.ALL)
22
- try:
23
- replays = api.get_replays(
24
- playlist=playlist,
25
- season=season,
26
- max_rank=rank,
27
- map_id=map_id,
28
- count=10,
29
- deep=deep,
30
- )
31
-
32
- for replay in replays:
33
- yield replay
34
- remaining -= 1
35
- if remaining <= 0:
36
- return
37
- except HTTPError:
38
- continue
39
-
40
-
41
- def get_diverse_groups(deep=False):
42
- if deep:
43
- for group in get_diverse_groups(deep=False):
44
- yield api.get_group(group["id"])
45
- else:
46
- groups = api.get_groups(count=10)
47
- yield from groups
48
- groups = api.get_groups(creator="76561199225615730")
49
- yield from groups
50
-
51
-
52
- classes = {}
53
-
54
-
55
- def get_structure(name, item):
56
- if isinstance(item, (str, int, float, bool)):
57
- return type(item)
58
- elif isinstance(item, list):
59
- sub_name = name.title().replace("_", "")
60
- if sub_name[-1] == "s":
61
- sub_name = sub_name[:-1] # Remove plural 's' for lists
62
- sub_structures = [get_structure(sub_name, item) for item in item]
63
- if len(sub_structures) == 0:
64
- return List[Any]
65
- else:
66
- return List[sub_structures.pop()]
67
- elif isinstance(item, dict):
68
- s = {}
69
- for key, value in item.items():
70
- sub_name = name + "|" + key.title().replace("_", "")
71
- s[key] = get_structure(sub_name, value)
72
- name = name.replace("|", "_")
73
- if name in classes:
74
- # Update with new fields if there are any
75
- existing_dc = classes[name]
76
- for field in fields(existing_dc):
77
- if field.name not in s:
78
- t = field.type
79
- if t == int and s.get(field.name) == float:
80
- t = float
81
- s[field.name] = t
82
- dc = make_dataclass(name, s.items())
83
- classes[name] = dc
84
- return dc
85
- else:
86
- return Any
87
-
88
-
89
- def print_class(cls):
90
- print("@dataclass")
91
- print(f"class {cls.__name__}:")
92
- for field in fields(cls):
93
- if type(field.type) == type(List):
94
- default = "field(default_factory=list)"
95
- print(f" {field.name}: List[{field.type.__args__[0].__name__}] = {default}")
96
- else:
97
- if field.type == str:
98
- default = '""'
99
- print(f" {field.name}: {field.type.__name__} = {default}")
100
- elif field.type in {int, float, bool}:
101
- default = field.type()
102
- print(f" {field.name}: {field.type.__name__} = {default}")
103
- else:
104
- default = None
105
- print(f" {field.name}: Optional[{field.type.__name__}] = {default}")
106
- print()
107
-
108
-
109
- def main():
110
- global classes
111
-
112
- classes_per_category = {}
113
- for deep in (False, True):
114
- name = "DeepReplay" if deep else "ShallowReplay"
115
- it = get_diverse_replays(deep=deep)
116
- # it = tqdm(it)
117
- for replay in it:
118
- structure = get_structure(name, replay)
119
- # break
120
-
121
- for cls in classes.values():
122
- print_class(cls)
123
- print("=" * 80)
124
- classes_per_category[name] = classes
125
- classes = {}
126
-
127
- for deep in (False, True):
128
- name = "DeepGroup" if deep else "ShallowGroup"
129
- for group in get_diverse_groups(deep=deep):
130
- structure = get_structure(name, group)
131
- # break
132
-
133
- for cls in classes.values():
134
- print_class(cls)
135
- print("=" * 80)
136
-
137
- classes_per_category[name] = classes
138
- classes = {}
139
-
140
- # Print all classes without duplicates
141
-
142
- all_classes = {}
143
- for category, cls_dict in classes_per_category.items():
144
- for cls_name, cls in cls_dict.items():
145
- # for cls_name2, cls2 in all_classes.items():
146
- # share_all = True
147
- # if len(fields(cls2)) != len(fields(cls)):
148
- # share_all = False
149
- # elif set(f.name for f in fields(cls2)) != set(f.name for f in fields(cls)):
150
- # share_all = False
151
- # else:
152
- # for f in fields(cls2):
153
- # if f.type != next((f2.type for f2 in fields(cls) if f2.name == f.name), None):
154
- # share_all = False
155
- # break
156
- # if share_all and cls_name != cls_name2:
157
- # new_name = f"shared_{cls_name}_{cls_name2}"
158
- # new_cls = make_dataclass(new_name, [(f.name, f.type) for f in fields(cls)])
159
- # all_classes[new_name] = new_cls
160
- # break
161
- # else: # No break
162
- # all_classes[cls_name] = cls
163
- if cls_name not in all_classes:
164
- all_classes[cls_name] = cls
165
- else:
166
- # Check that they share all fields (name and type)
167
- existing_cls = all_classes[cls_name]
168
- share_all = True
169
- if len(fields(existing_cls)) != len(fields(cls)):
170
- share_all = False
171
- elif set(f.name for f in fields(existing_cls)) != set(f.name for f in fields(cls)):
172
- share_all = False
173
- else:
174
- for f in fields(existing_cls):
175
- if f.type != next((f2.type for f2 in fields(cls) if f2.name == f.name), None):
176
- share_all = False
177
- break
178
- if not share_all:
179
- all_classes[f"{cls_name}_{category}"] = cls
180
- for cls in all_classes.values():
181
- print_class(cls)
182
-
183
- print("=" * 80)
184
- # Find unique classes (by fields)
185
- groups = {}
186
- for cls_name, cls in all_classes.items():
187
- fields_set = frozenset((f.name, f.type) for f in fields(cls))
188
- if fields_set not in groups:
189
- groups[fields_set] = []
190
- groups[fields_set].append(cls_name)
191
-
192
-
193
- if __name__ == '__main__':
194
- main()
scripts/test.py DELETED
@@ -1,52 +0,0 @@
1
- import os
2
- import time
3
-
4
- import ballchasing as bc
5
- from ballchasing import ShallowReplay, DeepReplay, ShallowGroup, DeepGroup
6
-
7
- if __name__ == '__main__':
8
- # Basic tests
9
- token = os.environ.get("BALLCHASING_API_KEY")
10
- api = bc.Api(token)
11
- print(api)
12
- # api.get_replays(season="123")
13
-
14
- replays_response = list(api.get_replays(uploader=api.steam_id, season="f14", count=1000))
15
- print(f"Successfully fetched {len(replays_response)} replays")
16
- typed_replays_response = [ShallowReplay(**replay) for replay in replays_response]
17
- print(f"Succcessfully converted {len(typed_replays_response)} replays to typed objects")
18
- replay_response = api.get_replay(replays_response[0]["id"])
19
- print(f"Successfully fetched deep replay {replay_response['id']}")
20
- typed_replay_response = DeepReplay(**replay_response)
21
- print(f"Succcessfully converted replay {replay_response['id']} to typed object")
22
-
23
- api.download_replay(replay_response["id"], "./")
24
- print(f"Successfully downloaded replay {replay_response['id']} to current directory")
25
- api.delete_replay(replay_response["id"])
26
- print(f"Successfully deleted replay {replay_response['id']}")
27
- upload_response = api.upload_replay("./" + replay_response["id"] + ".replay")
28
- print(f"Successfully uploaded replay {upload_response['id']}")
29
-
30
- groups_response = list(api.get_groups())
31
- print(f"Successfully fetched {len(groups_response)} groups")
32
- typed_groups_response = [ShallowGroup(**group) for group in groups_response]
33
- print(f"Succcessfully converted {len(typed_groups_response)} groups to typed objects")
34
- group_response = api.get_group(groups_response[0]["id"])
35
- print(f"Successfully fetched group {group_response['id']}")
36
- typed_group_response = DeepGroup(**group_response)
37
- print(f"Succcessfully converted deep group {group_response['id']} to typed object")
38
-
39
- create_group_response = api.create_group(name=f"test-{time.time()}",
40
- player_identification=bc.PlayerIdentification.BY_ID,
41
- team_identification=bc.TeamIdentification.BY_DISTINCT_PLAYERS)
42
- print(f"Successfully created group {create_group_response['id']}")
43
- api.patch_group(create_group_response["id"],
44
- team_identification=bc.TeamIdentification.BY_PLAYER_CLUSTERS)
45
- print(f"Successfully patched group {create_group_response['id']}")
46
-
47
- api.patch_replay(upload_response["id"], group=create_group_response["id"])
48
- print(f"Successfully patched replay {upload_response['id']} with group {create_group_response['id']}")
49
-
50
- api.delete_group(create_group_response["id"])
51
- print(f"Successfully deleted group {create_group_response['id']}")
52
- print("Nice")
scripts/test_typed.py DELETED
@@ -1,88 +0,0 @@
1
- import os
2
- import random
3
- from datetime import datetime, timedelta
4
-
5
- import ballchasing as bc
6
- from ballchasing.typed.deep_group import DeepGroup
7
- from ballchasing.typed.deep_replay import DeepReplay
8
- from ballchasing.typed.shallow_replay import ShallowReplay
9
-
10
- # from ballchasing.typed import Replay, Group
11
-
12
- key = os.environ.get("BALLCHASING_API_KEY")
13
-
14
- api = bc.Api(key)
15
-
16
- playlists = bc.Playlist.ALL
17
-
18
- min_date = datetime(2015, 7, 7)
19
- max_date = datetime.now()
20
-
21
-
22
- def deep_equals(d1, d2) -> tuple[bool, str]:
23
- """Recursively compare two dicts, returning (True, "") if they match or (False, "reason") if not."""
24
- if type(d1) != type(d2):
25
- return False, f"Type mismatch: {type(d1)} vs {type(d2)}"
26
-
27
- if isinstance(d1, dict):
28
- keys1 = set(d1.keys())
29
- keys2 = set(d2.keys())
30
- if keys1 != keys2:
31
- return False, f"Key mismatch: {keys1.symmetric_difference(keys2)}"
32
- for k in keys1:
33
- eq, msg = deep_equals(d1[k], d2[k])
34
- if not eq:
35
- return False, f"Key '{k}': {msg}"
36
- return True, ""
37
-
38
- if isinstance(d1, list):
39
- if len(d1) != len(d2):
40
- return False, f"List length mismatch: {len(d1)} vs {len(d2)}"
41
- for i in range(len(d1)):
42
- eq, msg = deep_equals(d1[i], d2[i])
43
- if not eq:
44
- return False, f"Index {i}: {msg}"
45
- return True, ""
46
-
47
- # For other types (int, str, etc.), use equality
48
- if d1 != d2:
49
- return False, f"Value mismatch: {d1} vs {d2}"
50
- return True, ""
51
-
52
-
53
- while True:
54
- playlist = random.choice(playlists)
55
- date = datetime.fromtimestamp(random.randint(int(min_date.timestamp()), int(max_date.timestamp())))
56
-
57
- for replay in api.get_replays(replay_after=date,
58
- replay_before=date + timedelta(days=1),
59
- playlist=playlists,
60
- count=10):
61
- deep_replay = api.get_replay(replay["id"])
62
- typed_replay = ShallowReplay(**replay)
63
- reconstructed_replay = typed_replay.to_dict()
64
- typed_deep_replay = DeepReplay(**deep_replay)
65
- reconstructed_deep_replay = typed_deep_replay.to_dict()
66
-
67
- de, msg = deep_equals(replay, reconstructed_replay)
68
- if not de:
69
- print(f"Shallow replay mismatch: {msg}")
70
- print("Original:", replay)
71
- print("Reconstructed:", reconstructed_replay)
72
-
73
- de, msg = deep_equals(deep_replay, reconstructed_deep_replay)
74
- if not de:
75
- print(f"Deep replay mismatch: {msg}")
76
- print("Original:", deep_replay)
77
- print("Reconstructed:", reconstructed_deep_replay)
78
-
79
- for group in typed_deep_replay.groups:
80
- deep_group = api.get_group(group.id)
81
- deep_typed_group = DeepGroup(**deep_group)
82
- reconstructed_group = deep_typed_group.to_dict()
83
-
84
- de, msg = deep_equals(deep_group, reconstructed_group)
85
- if not de:
86
- print(f"Group mismatch: {msg}")
87
- print("Original:", deep_group)
88
- print("Reconstructed:", reconstructed_group)