python-ballchasing 0.5.3__py3-none-any.whl → 0.6.0__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.
ballchasing/rate_limit.py CHANGED
@@ -13,6 +13,7 @@ class RateLimitCategory(str, Enum):
13
13
  CORE = "core" # GET/PATCH/DELETE /replays/{id}, /groups/{id}, POST /groups, upload, maps
14
14
  DOWNLOAD = "download" # GET /replays/{id}/file
15
15
  PING = "ping" # GET /
16
+ UPLOAD = "upload" # POST /v2/upload: limited by the account's upload quota, not per second
16
17
 
17
18
 
18
19
  # Hourly rate limit backoff times per category (seconds to wait between requests)
@@ -20,7 +21,8 @@ class RateLimitCategory(str, Enum):
20
21
  # - gold: list 1000/hr (3.6s), core 2000/hr (1.8s), download 400/hr (9.0s)
21
22
  # - diamond: list 2000/hr (1.8s), core 5000/hr (0.72s), download 1000/hr (3.6s)
22
23
  # - champion: list 8/s, core 8/s, download 2000/hr (1.8s)
23
- # - gc: list 16/s, core 16/s, download 2/s (0.5s)
24
+ # - gc, legend, org, bot: list 16/s, core 16/s, download 2/s (0.5s)
25
+ # Source: the x-rate-limits extension of each operation in https://ballchasing.com/doc/api/openapi.json
24
26
  CATEGORY_HOURLY_SLEEP_TIMES: dict[str, dict[RateLimitCategory, float]] = {
25
27
  "regular": {
26
28
  RateLimitCategory.LIST: 3600 / 500, # 7.2s
@@ -53,6 +55,10 @@ CATEGORY_HOURLY_SLEEP_TIMES: dict[str, dict[RateLimitCategory, float]] = {
53
55
  RateLimitCategory.PING: 0.0,
54
56
  },
55
57
  }
58
+ for _tier in ("legend", "org", "bot"): # Same limits as GC patrons
59
+ CATEGORY_HOURLY_SLEEP_TIMES[_tier] = CATEGORY_HOURLY_SLEEP_TIMES["gc"]
60
+ for _times in CATEGORY_HOURLY_SLEEP_TIMES.values():
61
+ _times.setdefault(RateLimitCategory.UPLOAD, 0.0)
56
62
 
57
63
  # Maximum calls per second (burst rates)
58
64
  CATEGORY_BURST_RATES: dict[str, dict[RateLimitCategory, float]] = {
@@ -62,6 +68,10 @@ CATEGORY_BURST_RATES: dict[str, dict[RateLimitCategory, float]] = {
62
68
  "champion": {RateLimitCategory.LIST: 8.0, RateLimitCategory.CORE: 8.0, RateLimitCategory.DOWNLOAD: 2.0, RateLimitCategory.PING: 10.0},
63
69
  "gc": {RateLimitCategory.LIST: 16.0, RateLimitCategory.CORE: 16.0, RateLimitCategory.DOWNLOAD: 2.0, RateLimitCategory.PING: 10.0},
64
70
  }
71
+ for _tier in ("legend", "org", "bot"): # Same limits as GC patrons
72
+ CATEGORY_BURST_RATES[_tier] = CATEGORY_BURST_RATES["gc"]
73
+ for _rates in CATEGORY_BURST_RATES.values():
74
+ _rates.setdefault(RateLimitCategory.UPLOAD, 10.0)
65
75
 
66
76
 
67
77
  def resolve_category(url_or_endpoint: str) -> RateLimitCategory:
@@ -69,6 +79,8 @@ def resolve_category(url_or_endpoint: str) -> RateLimitCategory:
69
79
  path = url_or_endpoint.split("?")[0].rstrip("/")
70
80
  if path.endswith("/file"):
71
81
  return RateLimitCategory.DOWNLOAD
82
+ if path.endswith("/v2/upload"):
83
+ return RateLimitCategory.UPLOAD
72
84
  if path.endswith("/replays") or path.endswith("/groups"):
73
85
  return RateLimitCategory.LIST
74
86
  if path == "" or path.endswith("/api") or path.endswith("/api/"):
@@ -29,6 +29,15 @@ saves {}.stats.core.saves FALSE TRUE FALSE normalizable TRUE int
29
29
  assists {}.stats.core.assists FALSE TRUE FALSE normalizable TRUE int
30
30
  score {}.stats.core.score FALSE TRUE FALSE normalizable TRUE int
31
31
  shooting_percentage {}.stats.core.shooting_percentage FALSE TRUE FALSE average TRUE int
32
+ epic_saves {}.stats.core.epic_saves FALSE TRUE FALSE normalizable TRUE int
33
+ clears {}.stats.core.clears FALSE TRUE FALSE normalizable TRUE int
34
+ centers {}.stats.core.centers FALSE TRUE FALSE normalizable TRUE int
35
+ aerial_hits {}.stats.core.aerial_hits FALSE TRUE FALSE normalizable TRUE int
36
+ first_touches {}.stats.core.first_touches FALSE TRUE FALSE normalizable TRUE int
37
+ flip_resets {}.stats.core.flip_resets FALSE TRUE FALSE normalizable TRUE int
38
+ crossbar_hits {}.stats.core.crossbar_hits FALSE TRUE FALSE normalizable TRUE int
39
+ bicycle_hits {}.stats.core.bicycle_hits FALSE TRUE FALSE normalizable TRUE int
40
+ juggle_hits {}.stats.core.juggle_hits FALSE TRUE FALSE normalizable TRUE int
32
41
  bpm {}.stats.boost.bpm FALSE TRUE FALSE average TRUE float
33
42
  bcpm {}.stats.boost.bcpm FALSE TRUE FALSE average TRUE float
34
43
  avg_boost_amount {}.stats.boost.avg_amount FALSE TRUE FALSE average TRUE float
@@ -57,6 +66,7 @@ time_slow_speed {}.stats.movement.time_slow_speed FALSE TRUE FALSE time TRUE flo
57
66
  time_ground {}.stats.movement.time_ground FALSE TRUE FALSE time TRUE float
58
67
  time_low_air {}.stats.movement.time_low_air FALSE TRUE FALSE time TRUE float
59
68
  time_high_air {}.stats.movement.time_high_air FALSE TRUE FALSE time TRUE float
69
+ time_wall {}.stats.movement.time_wall FALSE TRUE FALSE time TRUE float
60
70
  time_powerslide {}.stats.movement.time_powerslide FALSE TRUE FALSE time TRUE float
61
71
  count_powerslide {}.stats.movement.count_powerslide FALSE TRUE FALSE normalizable TRUE int
62
72
  time_defensive_third {}.stats.positioning.time_defensive_third FALSE TRUE FALSE time TRUE float
@@ -68,6 +78,10 @@ time_behind_ball {}.stats.positioning.time_behind_ball FALSE TRUE FALSE time TRU
68
78
  time_infront_ball {}.stats.positioning.time_infront_ball FALSE TRUE FALSE time TRUE float
69
79
  demos_inflicted {}.stats.demo.inflicted FALSE TRUE FALSE normalizable TRUE int
70
80
  demos_taken {}.stats.demo.taken FALSE TRUE FALSE normalizable TRUE int
81
+ demos_inflicted_in_offensive_half {}.stats.demo.inflicted_in_offensive_half FALSE TRUE FALSE normalizable TRUE int
82
+ demos_inflicted_in_defensive_half {}.stats.demo.inflicted_in_defensive_half FALSE TRUE FALSE normalizable TRUE int
83
+ demos_taken_in_offensive_half {}.stats.demo.taken_in_offensive_half FALSE TRUE FALSE normalizable TRUE int
84
+ demos_taken_in_defensive_half {}.stats.demo.taken_in_defensive_half FALSE TRUE FALSE normalizable TRUE int
71
85
  start_time {}.players.{}.start_time FALSE FALSE TRUE info FALSE float
72
86
  end_time {}.players.{}.end_time FALSE FALSE TRUE info FALSE float
73
87
  player_name {}.players.{}.name FALSE FALSE TRUE info FALSE str
@@ -92,6 +106,15 @@ assists {}.players.{}.stats.core.assists FALSE FALSE TRUE normalizable FALSE int
92
106
  score {}.players.{}.stats.core.score FALSE FALSE TRUE normalizable FALSE int
93
107
  mvp {}.players.{}.stats.core.mvp FALSE FALSE TRUE info FALSE bool
94
108
  shooting_percentage {}.players.{}.stats.core.shooting_percentage FALSE FALSE TRUE average FALSE float
109
+ epic_saves {}.players.{}.stats.core.epic_saves FALSE FALSE TRUE normalizable FALSE int
110
+ clears {}.players.{}.stats.core.clears FALSE FALSE TRUE normalizable FALSE int
111
+ centers {}.players.{}.stats.core.centers FALSE FALSE TRUE normalizable FALSE int
112
+ aerial_hits {}.players.{}.stats.core.aerial_hits FALSE FALSE TRUE normalizable FALSE int
113
+ first_touches {}.players.{}.stats.core.first_touches FALSE FALSE TRUE normalizable FALSE int
114
+ flip_resets {}.players.{}.stats.core.flip_resets FALSE FALSE TRUE normalizable FALSE int
115
+ crossbar_hits {}.players.{}.stats.core.crossbar_hits FALSE FALSE TRUE normalizable FALSE int
116
+ bicycle_hits {}.players.{}.stats.core.bicycle_hits FALSE FALSE TRUE normalizable FALSE int
117
+ juggle_hits {}.players.{}.stats.core.juggle_hits FALSE FALSE TRUE normalizable FALSE int
95
118
  bpm {}.players.{}.stats.boost.bpm FALSE FALSE TRUE average FALSE float
96
119
  bcpm {}.players.{}.stats.boost.bcpm FALSE FALSE TRUE average FALSE float
97
120
  avg_amount {}.players.{}.stats.boost.avg_amount FALSE FALSE TRUE average FALSE float
@@ -123,6 +146,7 @@ percent_supersonic_speed {}.players.{}.stats.movement.percent_supersonic_speed F
123
146
  percent_ground {}.players.{}.stats.movement.percent_ground FALSE FALSE TRUE average FALSE float
124
147
  percent_low_air {}.players.{}.stats.movement.percent_low_air FALSE FALSE TRUE average FALSE float
125
148
  percent_high_air {}.players.{}.stats.movement.percent_high_air FALSE FALSE TRUE average FALSE float
149
+ percent_wall {}.players.{}.stats.movement.percent_wall FALSE FALSE TRUE average FALSE float
126
150
  avg_distance_to_ball {}.players.{}.stats.positioning.avg_distance_to_ball FALSE FALSE TRUE average FALSE float
127
151
  avg_distance_to_ball_possession {}.players.{}.stats.positioning.avg_distance_to_ball_possession FALSE FALSE TRUE average FALSE float
128
152
  avg_distance_to_ball_no_possession {}.players.{}.stats.positioning.avg_distance_to_ball_no_possession FALSE FALSE TRUE average FALSE float
@@ -140,4 +164,8 @@ percent_most_forward {}.players.{}.stats.positioning.percent_most_forward FALSE
140
164
  percent_closest_to_ball {}.players.{}.stats.positioning.percent_closest_to_ball FALSE FALSE TRUE average FALSE float
141
165
  percent_farthest_from_ball {}.players.{}.stats.positioning.percent_farthest_from_ball FALSE FALSE TRUE average FALSE float
142
166
  demos_inflicted {}.players.{}.stats.demo.inflicted FALSE FALSE TRUE normalizable FALSE int
143
- demos_taken {}.players.{}.stats.demo.taken FALSE FALSE TRUE normalizable FALSE int
167
+ demos_taken {}.players.{}.stats.demo.taken FALSE FALSE TRUE normalizable FALSE int
168
+ demos_inflicted_in_offensive_half {}.players.{}.stats.demo.inflicted_in_offensive_half FALSE FALSE TRUE normalizable FALSE int
169
+ demos_inflicted_in_defensive_half {}.players.{}.stats.demo.inflicted_in_defensive_half FALSE FALSE TRUE normalizable FALSE int
170
+ demos_taken_in_offensive_half {}.players.{}.stats.demo.taken_in_offensive_half FALSE FALSE TRUE normalizable FALSE int
171
+ demos_taken_in_defensive_half {}.players.{}.stats.demo.taken_in_defensive_half FALSE FALSE TRUE normalizable FALSE int
@@ -1,5 +1,2 @@
1
- # Imports for the objects meant to be initialized directly
2
- from ballchasing.typed.deep_group import DeepGroup
3
- from ballchasing.typed.deep_replay import DeepReplay
4
- from ballchasing.typed.shallow_group import ShallowGroup
5
- from ballchasing.typed.shallow_replay import ShallowReplay
1
+ # Imports for the objects meant to be initialized directly. All the classes are in ballchasing.typed.models.
2
+ from ballchasing.typed.models import DeepGroup, DeepReplay, ShallowGroup, ShallowReplay
@@ -0,0 +1,106 @@
1
+ """Base classes and the @model decorator for the typed response objects (see models.py)."""
2
+ import functools
3
+ import logging
4
+ from dataclasses import dataclass, field, fields, is_dataclass
5
+ from datetime import datetime
6
+ from typing import get_args
7
+
8
+ try:
9
+ from typing import dataclass_transform
10
+ except ImportError: # Python 3.10
11
+ def dataclass_transform(**kwargs):
12
+ return lambda fn: fn
13
+
14
+ from ballchasing.util.dates import from_rfc3339, to_rfc3339
15
+
16
+ logger = logging.getLogger("ballchasing")
17
+
18
+ _reported_unknown_fields: set[tuple[str, str]] = set()
19
+
20
+
21
+ @dataclass_transform(field_specifiers=(field,))
22
+ def model(cls=None, /, **dataclass_kwargs):
23
+ """
24
+ Like ``@dataclass`` (and taking the same arguments), but the generated ``__init__`` accepts keyword arguments
25
+ that are not fields.
26
+
27
+ The API adds response fields over time; a plain dataclass would raise a ``TypeError`` on the first unknown one.
28
+ Unknown fields are kept (unconverted) in the instance's ``_extra`` dict instead, and included by ``to_dict``.
29
+ """
30
+ if cls is None:
31
+ return functools.partial(model, **dataclass_kwargs)
32
+ cls = dataclass(cls, **dataclass_kwargs)
33
+ dataclass_init = cls.__init__
34
+ known = frozenset(f.name for f in fields(cls))
35
+
36
+ @functools.wraps(dataclass_init)
37
+ def __init__(self, *args, **kwargs):
38
+ extra = {k: kwargs.pop(k) for k in [k for k in kwargs if k not in known]}
39
+ for k in extra:
40
+ if (cls.__name__, k) not in _reported_unknown_fields:
41
+ _reported_unknown_fields.add((cls.__name__, k))
42
+ logger.debug(f"Unknown field '{k}' for {cls.__name__}, stored in _extra")
43
+ self._extra = extra
44
+ dataclass_init(self, *args, **kwargs)
45
+
46
+ cls.__init__ = __init__
47
+ return cls
48
+
49
+
50
+ class _BaseModel:
51
+ """
52
+ Base model class for all dataclasses in this module.
53
+ """
54
+ _extra: dict # Response fields without a dataclass field (set by @model), not a dataclass field itself
55
+
56
+ def to_dict(self):
57
+ """
58
+ Convert (back) to a dict. Not a perfect recreation.
59
+ """
60
+ result = dict(getattr(self, "_extra", {}))
61
+ for field in fields(self):
62
+ value = getattr(self, field.name)
63
+ if isinstance(value, _BaseModel):
64
+ result[field.name] = value.to_dict()
65
+ elif isinstance(value, list):
66
+ if len(value) > 0:
67
+ result[field.name] = [item.to_dict() if isinstance(item, _BaseModel) else item for item in value]
68
+ elif isinstance(value, datetime):
69
+ # Convert datetime objects to rfc3339 formatted strings
70
+ result[field.name] = to_rfc3339(value)
71
+ elif value is not None:
72
+ # Include non-None values, preserving valid 0 and False values
73
+ result[field.name] = value
74
+ return result
75
+
76
+
77
+ class _DictToTypeMixin:
78
+ """
79
+ Mixin class to convert dicts to their respective types in dataclasses.
80
+ """
81
+
82
+ def __post_init__(self):
83
+ for field in fields(self):
84
+ value = getattr(self, field.name)
85
+ actual_type = field.type
86
+ if args := get_args(field.type):
87
+ actual_type = args[0]
88
+ # Into models and other dataclasses (e.g. in a user's subclass), not e.g. Any or dict
89
+ is_model = isinstance(actual_type, type) and (issubclass(actual_type, _BaseModel) or is_dataclass(actual_type))
90
+ if isinstance(value, dict) and is_model:
91
+ new_value = actual_type(**value)
92
+ setattr(self, field.name, new_value)
93
+ elif isinstance(value, list) and is_model:
94
+ new_value = [actual_type(**item) if isinstance(item, dict) else item for item in value]
95
+ setattr(self, field.name, new_value)
96
+ elif isinstance(value, str) and actual_type is datetime:
97
+ # Load rfc3339 formatted strings as datetime objects
98
+ new_value = from_rfc3339(value)
99
+ setattr(self, field.name, new_value)
100
+ # else: # For testing
101
+ # # Check that the value has the type specified in the dataclass field
102
+ # if value is not None and not isinstance(value, actual_type):
103
+ # if isinstance(value, int) and actual_type is float:
104
+ # pass # ints can be converted losslessly to floats
105
+ # else:
106
+ # raise TypeError(f"Expected {field.name} to be of type {actual_type}, got {type(value)}")