mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-24 21:06:23 +01:00
Merge branch 'worktree-agent-aa94bbfa685da1112'
This commit is contained in:
commit
6df7c397ca
@ -52,10 +52,11 @@ Runs and walks are credited by ONE rule, whatever the TCX sport or the
|
|||||||
`_Walking` file-name suffix (RunnerUp's files and the workout app's alike): a
|
`_Walking` file-name suffix (RunnerUp's files and the workout app's alike): a
|
||||||
day's activities are summed, and the day counts once their distance reaches
|
day's activities are summed, and the day counts once their distance reaches
|
||||||
3.5 km (5% GPS tolerance) OR their *moving* time reaches the shared duration
|
3.5 km (5% GPS tolerance) OR their *moving* time reaches the shared duration
|
||||||
bar (30 min minus the hidden leeway). Both are summed over trackpoint pairs
|
bar (30 min minus the hidden leeway). Both are summed over the track cut into
|
||||||
seen within 30 s of each other and travelled at no more than 25 km/h (faster
|
windows of at least 10 s, each judged by its average speed: faster than 25 km/h
|
||||||
is a vehicle or a GPS jump: no time, no distance); moving time also needs
|
(a vehicle or a GPS jump) counts neither time nor distance; moving time needs
|
||||||
0.5 m/s or more. Pauses, standing still, dropouts and files without
|
0.5 m/s or more (1 m/s across a signal dropout longer than 30 s, so a pause
|
||||||
|
earns nothing but a run through a dropout keeps its time). Files without
|
||||||
trackpoints earn nothing (the lap totals are never used). The reward is the usual one
|
trackpoints earn nothing (the lap totals are never used). The reward is the usual one
|
||||||
workout credit per day (`runnerup_verified:<date>`); the log's `activity`
|
workout credit per day (`runnerup_verified:<date>`); the log's `activity`
|
||||||
field is display only. Code: `screen_locker/_walk_tcx.py`.
|
field is display only. Code: `screen_locker/_walk_tcx.py`.
|
||||||
|
|||||||
133
screen_locker/_activity_day.py
Normal file
133
screen_locker/_activity_day.py
Normal file
@ -0,0 +1,133 @@
|
|||||||
|
"""A day's activities summed under the one crediting rule (see ``_walk_tcx``).
|
||||||
|
|
||||||
|
The day counts as the workout once EITHER its summed distance reaches
|
||||||
|
``MIN_RUN_DISTANCE_KM`` (within the GPS tolerance) OR its summed moving time
|
||||||
|
reaches the shared duration bar. The sport only labels messages.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
from screen_locker._constants import (
|
||||||
|
MIN_RUN_DISTANCE_KM,
|
||||||
|
MIN_WORKOUT_DURATION_MINUTES,
|
||||||
|
RUNNERUP_DISTANCE_TOLERANCE,
|
||||||
|
WORKOUT_DURATION_ACCEPT_MINUTES,
|
||||||
|
)
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterable
|
||||||
|
|
||||||
|
# RunnerUp's sport codes, for labels only (the label never decides credit).
|
||||||
|
SPORT_NAMES: dict[int, str] = {
|
||||||
|
0: "Running",
|
||||||
|
1: "Biking",
|
||||||
|
2: "Other",
|
||||||
|
3: "Orienteering",
|
||||||
|
4: "Walking",
|
||||||
|
5: "Treadmill",
|
||||||
|
6: "Gym",
|
||||||
|
7: "Stationary Bike",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def distance_qualifies(distance_km: float) -> bool:
|
||||||
|
"""Whether a distance meets the minimum, with the GPS tolerance."""
|
||||||
|
return distance_km * (1 + RUNNERUP_DISTANCE_TOLERANCE) >= MIN_RUN_DISTANCE_KM
|
||||||
|
|
||||||
|
|
||||||
|
def moving_qualifies(moving_minutes: float) -> bool:
|
||||||
|
"""Whether moving time meets the shared duration bar (leeway included)."""
|
||||||
|
return moving_minutes >= WORKOUT_DURATION_ACCEPT_MINUTES
|
||||||
|
|
||||||
|
|
||||||
|
def _distance_metres(activity: dict[str, Any]) -> float:
|
||||||
|
"""Credited metres; the root-DB path has no trackpoints, so its total stands in."""
|
||||||
|
return float(activity.get("track_distance_m", activity.get("distance_m", 0.0)))
|
||||||
|
|
||||||
|
|
||||||
|
def _moving_seconds(activity: dict[str, Any]) -> float:
|
||||||
|
"""Moving seconds; the root-DB path has no trackpoints, so wall-clock stands in."""
|
||||||
|
return float(activity.get("moving_seconds", activity.get("duration_seconds", 0.0)))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ActivityDay:
|
||||||
|
"""A day's activities, summed.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
legs: Distinct activities (deduplicated by the activity's ``Id``: the
|
||||||
|
WebDAV copy and the phone's copy are the same activity).
|
||||||
|
moving_minutes: Their summed moving time.
|
||||||
|
distance_km: Their summed distance.
|
||||||
|
completed_at: Unix time the activity that took the day over the bar
|
||||||
|
ended -- when the workout was actually done -- or ``None`` if the
|
||||||
|
day never got there (or the activity recorded no end).
|
||||||
|
all_walks: Whether every activity was a walk (label only).
|
||||||
|
sport: The sport code when the day is a single non-walk activity.
|
||||||
|
"""
|
||||||
|
|
||||||
|
legs: int
|
||||||
|
moving_minutes: float
|
||||||
|
distance_km: float
|
||||||
|
completed_at: float | None
|
||||||
|
all_walks: bool = False
|
||||||
|
sport: int = -1
|
||||||
|
|
||||||
|
@property
|
||||||
|
def qualifies(self) -> bool:
|
||||||
|
"""Whether the day counts as its workout: distance OR moving time."""
|
||||||
|
return distance_qualifies(self.distance_km) or moving_qualifies(
|
||||||
|
self.moving_minutes
|
||||||
|
)
|
||||||
|
|
||||||
|
def message(self) -> str:
|
||||||
|
"""The verification line, in the RunnerUp verifier's own style."""
|
||||||
|
if self.all_walks:
|
||||||
|
return (
|
||||||
|
f"Walking: {self.legs} walk(s), {self.distance_km:.1f} km, "
|
||||||
|
f"{self.moving_minutes:.0f} min moving"
|
||||||
|
)
|
||||||
|
if self.legs == 1:
|
||||||
|
name = SPORT_NAMES.get(self.sport, str(self.sport))
|
||||||
|
return f"{name}: {self.distance_km:.1f} km in {self.moving_minutes:.0f} min"
|
||||||
|
return (
|
||||||
|
f"Activity: {self.legs} activities, {self.distance_km:.1f} km, "
|
||||||
|
f"{self.moving_minutes:.0f} min moving"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def activity_shortfall(day: ActivityDay) -> str:
|
||||||
|
"""Why a day's activity did not count yet."""
|
||||||
|
return (
|
||||||
|
f"{day.message()} -- need {MIN_RUN_DISTANCE_KM:g}+ km or "
|
||||||
|
f"{MIN_WORKOUT_DURATION_MINUTES}+ min moving"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def activity_day(activities: Iterable[dict[str, Any]]) -> ActivityDay:
|
||||||
|
"""Sum parsed exports (``parse_tcx_file`` dicts) into one :class:`ActivityDay`."""
|
||||||
|
unique: dict[str, dict[str, Any]] = {}
|
||||||
|
for activity in activities:
|
||||||
|
unique.setdefault(str(activity.get("activity_id") or id(activity)), activity)
|
||||||
|
ordered = sorted(unique.values(), key=lambda a: a.get("ended_at") or 0.0)
|
||||||
|
moving = 0.0
|
||||||
|
metres = 0.0
|
||||||
|
completed_at: float | None = None
|
||||||
|
for activity in ordered:
|
||||||
|
moving += _moving_seconds(activity)
|
||||||
|
metres += _distance_metres(activity)
|
||||||
|
if completed_at is None and (
|
||||||
|
moving_qualifies(moving / 60) or distance_qualifies(metres / 1000)
|
||||||
|
):
|
||||||
|
completed_at = activity.get("ended_at")
|
||||||
|
return ActivityDay(
|
||||||
|
legs=len(ordered),
|
||||||
|
moving_minutes=moving / 60,
|
||||||
|
distance_km=metres / 1000,
|
||||||
|
completed_at=completed_at,
|
||||||
|
all_walks=bool(ordered) and all(a.get("walking") for a in ordered),
|
||||||
|
sport=int(ordered[0].get("sport", -1)) if ordered else -1,
|
||||||
|
)
|
||||||
@ -116,6 +116,11 @@ GRACE_STATE_FILE = Path(__file__).resolve().parent / "grace_floor.json"
|
|||||||
MIN_MOVING_SPEED_MPS = 0.5
|
MIN_MOVING_SPEED_MPS = 0.5
|
||||||
MAX_MOVING_SPEED_MPS = 25 / 3.6
|
MAX_MOVING_SPEED_MPS = 25 / 3.6
|
||||||
WALK_MAX_GAP_SECONDS = 30
|
WALK_MAX_GAP_SECONDS = 30
|
||||||
|
# Speed is judged over windows of at least this long (1 s fixes jitter), and a
|
||||||
|
# window longer than WALK_MAX_GAP_SECONDS (a GPS dropout) only counts as
|
||||||
|
# moving time at this speed or faster, so standing through a gap earns nothing.
|
||||||
|
TRACK_WINDOW_SECONDS = 10
|
||||||
|
MIN_DROPOUT_SPEED_MPS = 1.0
|
||||||
# Workout records this PC must keep deleted in the sync store, pushed as
|
# Workout records this PC must keep deleted in the sync store, pushed as
|
||||||
# tombstones on every tick (see _sync_tombstones for why once is not enough).
|
# tombstones on every tick (see _sync_tombstones for why once is not enough).
|
||||||
SYNC_TOMBSTONES_FILE = Path(__file__).resolve().parent / "sync_tombstones.json"
|
SYNC_TOMBSTONES_FILE = Path(__file__).resolve().parent / "sync_tombstones.json"
|
||||||
|
|||||||
@ -18,40 +18,47 @@ survives only in the file name (``Sport.TapiriikType()``): ``..._Walking.tcx``.
|
|||||||
The Strava export variant writes ``Sport="Walking"``, so that counts too.
|
The Strava export variant writes ``Sport="Walking"``, so that counts too.
|
||||||
|
|
||||||
**Moving time, not elapsed.** A lap's ``TotalTimeSeconds`` is wall-clock: one
|
**Moving time, not elapsed.** A lap's ``TotalTimeSeconds`` is wall-clock: one
|
||||||
real lap reads 101 min for 1 km of standing about. Moving time is summed over
|
real lap reads 101 min for 1 km of standing about. The track is cut into
|
||||||
consecutive trackpoint pairs travelled at least at ``MIN_MOVING_SPEED_MPS``:
|
windows of at least ``TRACK_WINDOW_SECONDS`` (a fix every second jitters, so
|
||||||
standing still is too slow. A pair further apart than ``WALK_MAX_GAP_SECONDS``
|
one raw pair can read 15 m/s inside a 3 m/s run) and each window is judged by
|
||||||
is a GPS dropout whose motion is unknown and earns nothing -- an activity is
|
its average speed. Faster than ``MAX_MOVING_SPEED_MPS`` (25 km/h) is a vehicle
|
||||||
never credited for time nobody saw, so a pause cannot buy a run its duration.
|
or a GPS jump: neither time nor distance counts, so a bus ride earns nothing.
|
||||||
A pair faster than ``MAX_MOVING_SPEED_MPS`` (25 km/h) is a vehicle or a GPS
|
Otherwise its metres count, and its seconds count as moving time at
|
||||||
jump: it counts neither moving time nor distance, so a bus ride earns nothing.
|
``MIN_MOVING_SPEED_MPS`` or faster; standing still is too slow. A window longer
|
||||||
The day's distance is the sum of the surviving pairs (``track_distance_m``),
|
than ``WALK_MAX_GAP_SECONDS`` is a signal dropout (real exports have 2 minute
|
||||||
never the lap's ``DistanceMeters`` total, and an export with no trackpoints
|
ones): the runner may have kept running unseen, so it counts as moving only at
|
||||||
cannot be speed-checked, so it credits nothing. Only the root-DB fallback,
|
``MIN_DROPOUT_SPEED_MPS`` or faster, while a pause (no distance across the
|
||||||
which has no trackpoints at all, is judged by its recorded distance and
|
gap) earns nothing -- a pause cannot buy a run its duration.
|
||||||
duration.
|
The day's distance is the sum of the windows (``track_distance_m``), never the
|
||||||
|
lap's ``DistanceMeters`` total, and an export with no trackpoints cannot be
|
||||||
|
speed-checked, so it credits nothing. Only the root-DB fallback, which has no
|
||||||
|
trackpoints at all, is judged by its recorded distance and duration.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import itertools
|
|
||||||
import logging
|
import logging
|
||||||
from typing import TYPE_CHECKING, Any
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
from screen_locker._activity_day import (
|
||||||
|
SPORT_NAMES,
|
||||||
|
ActivityDay,
|
||||||
|
activity_day,
|
||||||
|
activity_shortfall,
|
||||||
|
distance_qualifies,
|
||||||
|
moving_qualifies,
|
||||||
|
)
|
||||||
from screen_locker._constants import (
|
from screen_locker._constants import (
|
||||||
MAX_MOVING_SPEED_MPS,
|
MAX_MOVING_SPEED_MPS,
|
||||||
|
MIN_DROPOUT_SPEED_MPS,
|
||||||
MIN_MOVING_SPEED_MPS,
|
MIN_MOVING_SPEED_MPS,
|
||||||
MIN_RUN_DISTANCE_KM,
|
TRACK_WINDOW_SECONDS,
|
||||||
MIN_WORKOUT_DURATION_MINUTES,
|
|
||||||
RUNNERUP_DISTANCE_TOLERANCE,
|
|
||||||
WALK_MAX_GAP_SECONDS,
|
WALK_MAX_GAP_SECONDS,
|
||||||
WORKOUT_DURATION_ACCEPT_MINUTES,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Iterable
|
from collections.abc import Iterator
|
||||||
import xml.etree.ElementTree as ET
|
import xml.etree.ElementTree as ET
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
@ -59,18 +66,6 @@ _logger = logging.getLogger(__name__)
|
|||||||
_TCX_NS = "{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}"
|
_TCX_NS = "{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}"
|
||||||
_WALKING = "Walking"
|
_WALKING = "Walking"
|
||||||
|
|
||||||
# RunnerUp's sport codes, for labels only (the label never decides credit).
|
|
||||||
SPORT_NAMES: dict[int, str] = {
|
|
||||||
0: "Running",
|
|
||||||
1: "Biking",
|
|
||||||
2: "Other",
|
|
||||||
3: "Orienteering",
|
|
||||||
4: "Walking",
|
|
||||||
5: "Treadmill",
|
|
||||||
6: "Gym",
|
|
||||||
7: "Stationary Bike",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def is_walking_export(name: str, sport: str) -> bool:
|
def is_walking_export(name: str, sport: str) -> bool:
|
||||||
"""Whether a TCX export is a walk, from its file name or its Sport tag."""
|
"""Whether a TCX export is a walk, from its file name or its Sport tag."""
|
||||||
@ -100,27 +95,55 @@ def _trackpoints(activity: ET.Element) -> list[tuple[float, float]]:
|
|||||||
return points
|
return points
|
||||||
|
|
||||||
|
|
||||||
|
def _segments(
|
||||||
|
points: list[tuple[float, float]],
|
||||||
|
) -> Iterator[tuple[float, float]]:
|
||||||
|
"""``(seconds, metres)`` of the track cut into windows of >= TRACK_WINDOW_SECONDS.
|
||||||
|
|
||||||
|
A fix every second jitters (one pair can read 15 m/s inside a 3 m/s run),
|
||||||
|
so speed is judged over a window, never over a raw 1 s pair. Fixes that
|
||||||
|
are already further apart than the window are their own segment.
|
||||||
|
"""
|
||||||
|
if not points:
|
||||||
|
return
|
||||||
|
anchor = points[0]
|
||||||
|
for point in points[1:]:
|
||||||
|
if point[0] - anchor[0] >= TRACK_WINDOW_SECONDS:
|
||||||
|
yield point[0] - anchor[0], point[1] - anchor[1]
|
||||||
|
anchor = point
|
||||||
|
if points[-1] is not anchor:
|
||||||
|
yield points[-1][0] - anchor[0], points[-1][1] - anchor[1]
|
||||||
|
|
||||||
|
|
||||||
def track_summary(activity: ET.Element) -> dict[str, Any]:
|
def track_summary(activity: ET.Element) -> dict[str, Any]:
|
||||||
"""Moving seconds, credited distance and end time, from the trackpoints.
|
"""Moving seconds, credited distance and end time, from the trackpoints.
|
||||||
|
|
||||||
A pair counts when its points are within ``WALK_MAX_GAP_SECONDS`` and it
|
A segment (see :func:`_segments`) counts unless it was travelled faster
|
||||||
was not travelled faster than ``MAX_MOVING_SPEED_MPS``. It then adds its
|
than ``MAX_MOVING_SPEED_MPS``: it then adds its metres to
|
||||||
metres to ``track_distance_m``, and its seconds to ``moving_seconds`` too
|
``track_distance_m``, and its seconds to ``moving_seconds`` too when it was
|
||||||
when it was travelled at least at ``MIN_MOVING_SPEED_MPS``.
|
travelled at least at ``MIN_MOVING_SPEED_MPS``. A segment longer than
|
||||||
|
``WALK_MAX_GAP_SECONDS`` is a signal dropout whose motion is unknown; it
|
||||||
|
only counts as moving time at ``MIN_DROPOUT_SPEED_MPS``, so a pause (no
|
||||||
|
distance across the gap) earns no time while a runner whose GPS went away
|
||||||
|
for two minutes keeps the time and metres the far side proves.
|
||||||
"""
|
"""
|
||||||
points = _trackpoints(activity)
|
points = _trackpoints(activity)
|
||||||
moving = 0.0
|
moving = 0.0
|
||||||
metres = 0.0
|
metres = 0.0
|
||||||
for (t0, d0), (t1, d1) in itertools.pairwise(points):
|
for seconds, travelled in _segments(points):
|
||||||
gap = t1 - t0
|
if seconds <= 0:
|
||||||
if not 0 < gap <= WALK_MAX_GAP_SECONDS:
|
|
||||||
continue
|
continue
|
||||||
speed = (d1 - d0) / gap
|
speed = travelled / seconds
|
||||||
if speed > MAX_MOVING_SPEED_MPS:
|
if speed > MAX_MOVING_SPEED_MPS:
|
||||||
continue
|
continue
|
||||||
metres += max(d1 - d0, 0.0)
|
metres += max(travelled, 0.0)
|
||||||
if speed >= MIN_MOVING_SPEED_MPS:
|
floor = (
|
||||||
moving += gap
|
MIN_MOVING_SPEED_MPS
|
||||||
|
if seconds <= WALK_MAX_GAP_SECONDS
|
||||||
|
else MIN_DROPOUT_SPEED_MPS
|
||||||
|
)
|
||||||
|
if speed >= floor:
|
||||||
|
moving += seconds
|
||||||
return {
|
return {
|
||||||
"activity_id": activity.findtext(f"{_TCX_NS}Id") or "",
|
"activity_id": activity.findtext(f"{_TCX_NS}Id") or "",
|
||||||
"moving_seconds": moving,
|
"moving_seconds": moving,
|
||||||
@ -129,107 +152,21 @@ def track_summary(activity: ET.Element) -> dict[str, Any]:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def distance_qualifies(distance_km: float) -> bool:
|
# The day aggregate lives in ``_activity_day``; these names stay importable here,
|
||||||
"""Whether a distance meets the minimum, with the GPS tolerance."""
|
# along with the walk-only names they replaced.
|
||||||
return distance_km * (1 + RUNNERUP_DISTANCE_TOLERANCE) >= MIN_RUN_DISTANCE_KM
|
|
||||||
|
|
||||||
|
|
||||||
def moving_qualifies(moving_minutes: float) -> bool:
|
|
||||||
"""Whether moving time meets the shared duration bar (leeway included)."""
|
|
||||||
return moving_minutes >= WORKOUT_DURATION_ACCEPT_MINUTES
|
|
||||||
|
|
||||||
|
|
||||||
def _distance_metres(activity: dict[str, Any]) -> float:
|
|
||||||
"""Credited metres; the root-DB path has no trackpoints, so its total stands in."""
|
|
||||||
return float(activity.get("track_distance_m", activity.get("distance_m", 0.0)))
|
|
||||||
|
|
||||||
|
|
||||||
def _moving_seconds(activity: dict[str, Any]) -> float:
|
|
||||||
"""Moving seconds; the root-DB path has no trackpoints, so wall-clock stands in."""
|
|
||||||
return float(activity.get("moving_seconds", activity.get("duration_seconds", 0.0)))
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class ActivityDay:
|
|
||||||
"""A day's activities, summed.
|
|
||||||
|
|
||||||
Attributes:
|
|
||||||
legs: Distinct activities (deduplicated by the activity's ``Id``: the
|
|
||||||
WebDAV copy and the phone's copy are the same activity).
|
|
||||||
moving_minutes: Their summed moving time.
|
|
||||||
distance_km: Their summed distance.
|
|
||||||
completed_at: Unix time the activity that took the day over the bar
|
|
||||||
ended -- when the workout was actually done -- or ``None`` if the
|
|
||||||
day never got there (or the activity recorded no end).
|
|
||||||
all_walks: Whether every activity was a walk (label only).
|
|
||||||
sport: The sport code when the day is a single non-walk activity.
|
|
||||||
"""
|
|
||||||
|
|
||||||
legs: int
|
|
||||||
moving_minutes: float
|
|
||||||
distance_km: float
|
|
||||||
completed_at: float | None
|
|
||||||
all_walks: bool = False
|
|
||||||
sport: int = -1
|
|
||||||
|
|
||||||
@property
|
|
||||||
def qualifies(self) -> bool:
|
|
||||||
"""Whether the day counts as its workout: distance OR moving time."""
|
|
||||||
return distance_qualifies(self.distance_km) or moving_qualifies(
|
|
||||||
self.moving_minutes
|
|
||||||
)
|
|
||||||
|
|
||||||
def message(self) -> str:
|
|
||||||
"""The verification line, in the RunnerUp verifier's own style."""
|
|
||||||
if self.all_walks:
|
|
||||||
return (
|
|
||||||
f"Walking: {self.legs} walk(s), {self.distance_km:.1f} km, "
|
|
||||||
f"{self.moving_minutes:.0f} min moving"
|
|
||||||
)
|
|
||||||
if self.legs == 1:
|
|
||||||
name = SPORT_NAMES.get(self.sport, str(self.sport))
|
|
||||||
return f"{name}: {self.distance_km:.1f} km in {self.moving_minutes:.0f} min"
|
|
||||||
return (
|
|
||||||
f"Activity: {self.legs} activities, {self.distance_km:.1f} km, "
|
|
||||||
f"{self.moving_minutes:.0f} min moving"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def activity_shortfall(day: ActivityDay) -> str:
|
|
||||||
"""Why a day's activity did not count yet."""
|
|
||||||
return (
|
|
||||||
f"{day.message()} -- need {MIN_RUN_DISTANCE_KM:g}+ km or "
|
|
||||||
f"{MIN_WORKOUT_DURATION_MINUTES}+ min moving"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def activity_day(activities: Iterable[dict[str, Any]]) -> ActivityDay:
|
|
||||||
"""Sum parsed exports (``parse_tcx_file`` dicts) into one :class:`ActivityDay`."""
|
|
||||||
unique: dict[str, dict[str, Any]] = {}
|
|
||||||
for activity in activities:
|
|
||||||
unique.setdefault(str(activity.get("activity_id") or id(activity)), activity)
|
|
||||||
ordered = sorted(unique.values(), key=lambda a: a.get("ended_at") or 0.0)
|
|
||||||
moving = 0.0
|
|
||||||
metres = 0.0
|
|
||||||
completed_at: float | None = None
|
|
||||||
for activity in ordered:
|
|
||||||
moving += _moving_seconds(activity)
|
|
||||||
metres += _distance_metres(activity)
|
|
||||||
if completed_at is None and (
|
|
||||||
moving_qualifies(moving / 60) or distance_qualifies(metres / 1000)
|
|
||||||
):
|
|
||||||
completed_at = activity.get("ended_at")
|
|
||||||
return ActivityDay(
|
|
||||||
legs=len(ordered),
|
|
||||||
moving_minutes=moving / 60,
|
|
||||||
distance_km=metres / 1000,
|
|
||||||
completed_at=completed_at,
|
|
||||||
all_walks=bool(ordered) and all(a.get("walking") for a in ordered),
|
|
||||||
sport=int(ordered[0].get("sport", -1)) if ordered else -1,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# Back-compat names: the walk-only rule these replaced.
|
|
||||||
WalkDay = ActivityDay
|
WalkDay = ActivityDay
|
||||||
walk_day = activity_day
|
walk_day = activity_day
|
||||||
walk_shortfall = activity_shortfall
|
walk_shortfall = activity_shortfall
|
||||||
|
__all__ = [
|
||||||
|
"SPORT_NAMES",
|
||||||
|
"ActivityDay",
|
||||||
|
"WalkDay",
|
||||||
|
"activity_day",
|
||||||
|
"activity_shortfall",
|
||||||
|
"distance_qualifies",
|
||||||
|
"is_walking_export",
|
||||||
|
"moving_qualifies",
|
||||||
|
"track_summary",
|
||||||
|
"walk_day",
|
||||||
|
"walk_shortfall",
|
||||||
|
]
|
||||||
|
|||||||
127
screen_locker/tests/test_tcx_real_shapes.py
Normal file
127
screen_locker/tests/test_tcx_real_shapes.py
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
"""Speed cap, lap-only files and the shapes real exports have (dropouts, jitter)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from screen_locker.tests._activity_helpers import (
|
||||||
|
DAY,
|
||||||
|
Verifier,
|
||||||
|
drop,
|
||||||
|
tcx,
|
||||||
|
tcx_points,
|
||||||
|
verify,
|
||||||
|
)
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(name="verifier")
|
||||||
|
def verifier_fixture(tmp_path: Path) -> Verifier:
|
||||||
|
"""A Verifier reading a temporary drop directory."""
|
||||||
|
return Verifier(tmp_path)
|
||||||
|
|
||||||
|
|
||||||
|
def parsed(verifier: Verifier, sport: str, points: list[tuple[int, float]]) -> dict:
|
||||||
|
"""Drop a track made of exactly ``points`` and return its parsed summary."""
|
||||||
|
drop(verifier.folder, "08-00-00", "_Running", tcx_points(sport, "08:00", points))
|
||||||
|
(path,) = verifier._find_runnerup_exports_for_date(DAY)
|
||||||
|
data = verifier._pull_and_parse_tcx(path)
|
||||||
|
assert data is not None
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
class TestLapOnlyExport:
|
||||||
|
"""An export with laps but no trackpoints has no moving time to credit."""
|
||||||
|
|
||||||
|
def test_wall_clock_alone_credits_nothing(self, verifier: Verifier) -> None:
|
||||||
|
"""40 min on the lap clock, 1 km, no trackpoints: too short."""
|
||||||
|
body = (
|
||||||
|
'<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/'
|
||||||
|
'TrainingCenterDatabase/v2"><Activities><Activity Sport="Running">'
|
||||||
|
"<Id>2026-10-10T08:00</Id><Lap><TotalTimeSeconds>2400</TotalTimeSeconds>"
|
||||||
|
"<DistanceMeters>1000</DistanceMeters></Lap></Activity></Activities>"
|
||||||
|
"</TrainingCenterDatabase>"
|
||||||
|
)
|
||||||
|
drop(verifier.folder, "08-00-00", "_Running", body)
|
||||||
|
result = verify(verifier)
|
||||||
|
assert result is not None
|
||||||
|
assert result[0] == "too_short"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSpeedCap:
|
||||||
|
"""Segments faster than 25 km/h count neither moving time nor distance."""
|
||||||
|
|
||||||
|
def test_a_car_trip_credits_nothing(self, verifier: Verifier) -> None:
|
||||||
|
"""10 km at 40 km/h (15 min) is a vehicle, not a workout."""
|
||||||
|
drop(
|
||||||
|
verifier.folder,
|
||||||
|
"08-00-00",
|
||||||
|
"_Walking",
|
||||||
|
tcx("Walking", "08:00", moving_min=15, metres=10000),
|
||||||
|
)
|
||||||
|
result = verify(verifier)
|
||||||
|
assert result is not None
|
||||||
|
assert result[0] == "too_short"
|
||||||
|
|
||||||
|
def test_one_gps_jump_drops_only_its_window(self, verifier: Verifier) -> None:
|
||||||
|
"""A 60 km/h jump inside a 3 m/s run loses its 10 s window and no more."""
|
||||||
|
points = [(s, s * 3.0 + (83.0 if s > 600 else 0.0)) for s in range(0, 1201, 5)]
|
||||||
|
data = parsed(verifier, "Running", points)
|
||||||
|
assert data["moving_seconds"] == pytest.approx(1190)
|
||||||
|
assert data["track_distance_m"] == pytest.approx(3570)
|
||||||
|
result = verify(verifier)
|
||||||
|
assert result is not None
|
||||||
|
assert result[0] == "verified"
|
||||||
|
|
||||||
|
def test_a_car_with_sparse_fixes_still_credits_nothing(
|
||||||
|
self, verifier: Verifier
|
||||||
|
) -> None:
|
||||||
|
"""40 km/h with a fix every 60 s is dropped as a dropout too."""
|
||||||
|
points = [(s, s * 11.1) for s in range(0, 1500, 60)]
|
||||||
|
drop(
|
||||||
|
verifier.folder,
|
||||||
|
"08-00-00",
|
||||||
|
"_Walking",
|
||||||
|
tcx_points("Walking", "08:00", points),
|
||||||
|
)
|
||||||
|
result = verify(verifier)
|
||||||
|
assert result is not None
|
||||||
|
assert result[0] == "too_short"
|
||||||
|
|
||||||
|
|
||||||
|
class TestRealRunShapes:
|
||||||
|
"""Shapes seen in real exports (checked on 27 days of them) stay whole."""
|
||||||
|
|
||||||
|
def test_sparse_fixes_every_18_seconds_still_count(
|
||||||
|
self, verifier: Verifier
|
||||||
|
) -> None:
|
||||||
|
"""Old RunnerUp files have a fix every 15-60 s: a 4 km run in 42 min."""
|
||||||
|
points = [(s, s * 1.6) for s in range(0, 2520, 18)]
|
||||||
|
data = parsed(verifier, "Running", points)
|
||||||
|
assert data["track_distance_m"] == pytest.approx(points[-1][1])
|
||||||
|
assert data["moving_seconds"] == pytest.approx(points[-1][0])
|
||||||
|
|
||||||
|
def test_a_gps_dropout_at_running_pace_is_kept(self, verifier: Verifier) -> None:
|
||||||
|
"""A 2 minute signal loss with the runner still moving keeps both."""
|
||||||
|
points = [(s, s * 1.7) for s in range(600)]
|
||||||
|
points += [(s, s * 1.7) for s in range(720, 1320)]
|
||||||
|
data = parsed(verifier, "Running", points)
|
||||||
|
assert data["track_distance_m"] == pytest.approx(1319 * 1.7, rel=0.01)
|
||||||
|
assert data["moving_seconds"] == pytest.approx(1319, rel=0.01)
|
||||||
|
|
||||||
|
def test_a_standing_pause_earns_nothing(self, verifier: Verifier) -> None:
|
||||||
|
"""A 5 minute gap with ~no movement adds no time (and ~no metres)."""
|
||||||
|
points = [(s, s * 1.7) for s in range(600)]
|
||||||
|
points += [(s, 600 * 1.7 + 2) for s in range(900, 910)]
|
||||||
|
data = parsed(verifier, "Running", points)
|
||||||
|
assert data["moving_seconds"] == pytest.approx(599, abs=12)
|
||||||
|
|
||||||
|
def test_one_second_jitter_is_smoothed(self, verifier: Verifier) -> None:
|
||||||
|
"""A 1 s fix 12 m ahead (12 m/s alone) is noise inside a 3 m/s run."""
|
||||||
|
points = [(s, s * 3.0 + (12.0 if not s % 50 else 0.0)) for s in range(600)]
|
||||||
|
data = parsed(verifier, "Running", points)
|
||||||
|
assert data["track_distance_m"] > 0.97 * points[-1][1]
|
||||||
@ -20,7 +20,6 @@ from screen_locker.tests._activity_helpers import (
|
|||||||
Verifier,
|
Verifier,
|
||||||
drop,
|
drop,
|
||||||
tcx,
|
tcx,
|
||||||
tcx_points,
|
|
||||||
verify,
|
verify,
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -182,55 +181,3 @@ class TestActivityDay:
|
|||||||
"""The shortfall names both ways to qualify."""
|
"""The shortfall names both ways to qualify."""
|
||||||
day: ActivityDay = activity_day([{"distance_m": 100.0, "moving_seconds": 60.0}])
|
day: ActivityDay = activity_day([{"distance_m": 100.0, "moving_seconds": 60.0}])
|
||||||
assert activity_shortfall(day).endswith("need 3.5+ km or 30+ min moving")
|
assert activity_shortfall(day).endswith("need 3.5+ km or 30+ min moving")
|
||||||
|
|
||||||
|
|
||||||
class TestLapOnlyExport:
|
|
||||||
"""An export with laps but no trackpoints has no moving time to credit."""
|
|
||||||
|
|
||||||
def test_wall_clock_alone_credits_nothing(self, verifier: Verifier) -> None:
|
|
||||||
"""40 min on the lap clock, 1 km, no trackpoints: too short."""
|
|
||||||
body = (
|
|
||||||
'<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/'
|
|
||||||
'TrainingCenterDatabase/v2"><Activities><Activity Sport="Running">'
|
|
||||||
"<Id>2026-10-10T08:00</Id><Lap><TotalTimeSeconds>2400</TotalTimeSeconds>"
|
|
||||||
"<DistanceMeters>1000</DistanceMeters></Lap></Activity></Activities>"
|
|
||||||
"</TrainingCenterDatabase>"
|
|
||||||
)
|
|
||||||
drop(verifier.folder, "08-00-00", "_Running", body)
|
|
||||||
result = verify(verifier)
|
|
||||||
assert result is not None
|
|
||||||
assert result[0] == "too_short"
|
|
||||||
|
|
||||||
|
|
||||||
class TestSpeedCap:
|
|
||||||
"""Pairs faster than 25 km/h count neither moving time nor distance."""
|
|
||||||
|
|
||||||
def test_a_car_trip_credits_nothing(self, verifier: Verifier) -> None:
|
|
||||||
"""10 km at 40 km/h (15 min) is a vehicle, not a workout."""
|
|
||||||
drop(
|
|
||||||
verifier.folder,
|
|
||||||
"08-00-00",
|
|
||||||
"_Walking",
|
|
||||||
tcx("Walking", "08:00", moving_min=15, metres=10000),
|
|
||||||
)
|
|
||||||
result = verify(verifier)
|
|
||||||
assert result is not None
|
|
||||||
assert result[0] == "too_short"
|
|
||||||
|
|
||||||
def test_one_gps_jump_drops_only_its_pair(self, verifier: Verifier) -> None:
|
|
||||||
"""A 60 km/h jump inside a 3 m/s run loses that pair and nothing else."""
|
|
||||||
points = [(s, s * 3.0 + (83.0 if s > 600 else 0.0)) for s in range(0, 1201, 5)]
|
|
||||||
drop(
|
|
||||||
verifier.folder,
|
|
||||||
"08-00-00",
|
|
||||||
"_Running",
|
|
||||||
tcx_points("Running", "08:00", points),
|
|
||||||
)
|
|
||||||
(path,) = verifier._find_runnerup_exports_for_date(DAY)
|
|
||||||
data = verifier._pull_and_parse_tcx(path)
|
|
||||||
assert data is not None
|
|
||||||
assert data["moving_seconds"] == pytest.approx(1195)
|
|
||||||
assert data["track_distance_m"] == pytest.approx(3585)
|
|
||||||
result = verify(verifier)
|
|
||||||
assert result is not None
|
|
||||||
assert result[0] == "verified"
|
|
||||||
|
|||||||
@ -79,11 +79,30 @@ class TestTrackSummary:
|
|||||||
pytest.approx(600)
|
pytest.approx(600)
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_a_gps_dropout_earns_nothing(self) -> None:
|
def test_a_repeated_timestamp_tail_adds_nothing(self) -> None:
|
||||||
"""Two points 100 s apart at walking pace: motion unseen, not counted."""
|
"""A final fix with the same time as the one before it has no duration."""
|
||||||
summary = track_summary(activity([(0, "0.1", None), (100, "130", None)]))
|
summary = track_summary(
|
||||||
|
activity([(0, "0", None), (20, "30", None), (20, "31", None)])
|
||||||
|
)
|
||||||
|
assert summary["moving_seconds"] == pytest.approx(20)
|
||||||
|
|
||||||
|
def test_a_slow_dropout_earns_nothing(self) -> None:
|
||||||
|
"""Two points 100 s apart, 30 m: a pause, not motion. No time."""
|
||||||
|
summary = track_summary(activity([(0, "0.1", None), (100, "30", None)]))
|
||||||
assert not summary["moving_seconds"]
|
assert not summary["moving_seconds"]
|
||||||
|
|
||||||
|
def test_a_dropout_at_walking_pace_keeps_its_time(self) -> None:
|
||||||
|
"""Two points 100 s apart, 130 m: the walker kept walking while unseen."""
|
||||||
|
summary = track_summary(activity([(0, "0.1", None), (100, "130", None)]))
|
||||||
|
assert summary["moving_seconds"] == pytest.approx(100)
|
||||||
|
assert summary["track_distance_m"] == pytest.approx(129.9)
|
||||||
|
|
||||||
|
def test_a_vehicle_across_a_dropout_earns_nothing(self) -> None:
|
||||||
|
"""Two points 100 s apart, 2 km: 72 km/h is not a person."""
|
||||||
|
summary = track_summary(activity([(0, "0", None), (100, "2000", None)]))
|
||||||
|
assert not summary["moving_seconds"]
|
||||||
|
assert not summary["track_distance_m"]
|
||||||
|
|
||||||
def test_unusable_points_are_skipped(
|
def test_unusable_points_are_skipped(
|
||||||
self, caplog: pytest.LogCaptureFixture
|
self, caplog: pytest.LogCaptureFixture
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user