activity-parser 0.9.0__tar.gz

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.
Files changed (28) hide show
  1. activity_parser-0.9.0/.github/workflows/ci.yml +25 -0
  2. activity_parser-0.9.0/.github/workflows/release.yml +17 -0
  3. activity_parser-0.9.0/.gitignore +24 -0
  4. activity_parser-0.9.0/.pre-commit-config.yaml +28 -0
  5. activity_parser-0.9.0/LICENSE +20 -0
  6. activity_parser-0.9.0/PKG-INFO +97 -0
  7. activity_parser-0.9.0/README.md +74 -0
  8. activity_parser-0.9.0/pyproject.toml +57 -0
  9. activity_parser-0.9.0/src/activity_parser/__init__.py +12 -0
  10. activity_parser-0.9.0/src/activity_parser/parse_activity.py +281 -0
  11. activity_parser-0.9.0/src/activity_parser/parse_fit_file.py +105 -0
  12. activity_parser-0.9.0/src/activity_parser/parse_tcx_gpx.py +201 -0
  13. activity_parser-0.9.0/src/activity_parser/py.typed +0 -0
  14. activity_parser-0.9.0/tests/files/README.md +10 -0
  15. activity_parser-0.9.0/tests/files/bad_speed.gpx +41 -0
  16. activity_parser-0.9.0/tests/files/garmin-edge-820-bike.fit +0 -0
  17. activity_parser-0.9.0/tests/files/garmin-fenix-5-bike.fit +0 -0
  18. activity_parser-0.9.0/tests/files/mixed_offset.gpx +33 -0
  19. activity_parser-0.9.0/tests/files/mixed_offset.tcx +45 -0
  20. activity_parser-0.9.0/tests/files/multi_segment.gpx +21 -0
  21. activity_parser-0.9.0/tests/files/no_position.tcx +41 -0
  22. activity_parser-0.9.0/tests/files/no_time.gpx +37 -0
  23. activity_parser-0.9.0/tests/files/no_time.tcx +52 -0
  24. activity_parser-0.9.0/tests/files/sample.gpx +67 -0
  25. activity_parser-0.9.0/tests/files/sample.tcx +139 -0
  26. activity_parser-0.9.0/tests/test_parse_activity.py +60 -0
  27. activity_parser-0.9.0/tests/test_parse_fit.py +99 -0
  28. activity_parser-0.9.0/tests/test_parse_tcx_gpx.py +212 -0
@@ -0,0 +1,25 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ schedule:
8
+ - cron: "0 6 1,15 * *"
9
+ workflow_dispatch:
10
+
11
+ jobs:
12
+ test:
13
+ runs-on: ubuntu-latest
14
+ strategy:
15
+ matrix:
16
+ python-version: ["3.11", "3.12", "3.13", "3.14"]
17
+ steps:
18
+ - uses: actions/checkout@v7
19
+ - uses: astral-sh/setup-uv@v8.2.0
20
+ with:
21
+ enable-cache: true
22
+ cache-suffix: ${{ matrix.python-version }}
23
+ - run: uv sync --python ${{ matrix.python-version }}
24
+ - run: uv run pre-commit run --all-files
25
+ - run: uv build
@@ -0,0 +1,17 @@
1
+ name: Release
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ environment: pypi
11
+ permissions:
12
+ id-token: write
13
+ steps:
14
+ - uses: actions/checkout@v7
15
+ - uses: astral-sh/setup-uv@v8.2.0
16
+ - run: uv build
17
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,24 @@
1
+ # Byte-compiled / optimized files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ .DS_Store
6
+
7
+ # Distribution / packaging
8
+ build/
9
+ dist/
10
+ *.egg-info/
11
+ .eggs/
12
+
13
+ # Environments
14
+ .venv/
15
+ env/
16
+
17
+ # Tooling caches
18
+ .pytest_cache/
19
+ .ruff_cache/
20
+ .pyright/
21
+
22
+ # Editors
23
+ .idea/
24
+ .vscode/
@@ -0,0 +1,28 @@
1
+ repos:
2
+ - repo: local
3
+ hooks:
4
+ - id: ruff-check
5
+ name: ruff check
6
+ entry: uv run ruff check --fix
7
+ language: system
8
+ types: [python]
9
+
10
+ - id: ruff-format
11
+ name: ruff format
12
+ entry: uv run ruff format
13
+ language: system
14
+ types: [python]
15
+
16
+ - id: pyright
17
+ name: pyright
18
+ entry: uv run pyright
19
+ language: system
20
+ types: [python]
21
+ pass_filenames: false
22
+
23
+ - id: pytest
24
+ name: pytest
25
+ entry: uv run pytest -q
26
+ language: system
27
+ pass_filenames: false
28
+ always_run: true
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-2026 Tabish Mustufa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: activity-parser
3
+ Version: 0.9.0
4
+ Summary: Parser for loading FIT, TCX and GPX files into Pandas DataFrames.
5
+ Project-URL: Repository, https://github.com/tabishm52/activity_parser
6
+ Project-URL: Issues, https://github.com/tabishm52/activity_parser/issues
7
+ Author-email: Tabish Mustufa <tabishm@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: fit,fitness,gps,gpx,pandas,parser,tcx
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Topic :: Scientific/Engineering :: GIS
18
+ Requires-Python: >=3.11
19
+ Requires-Dist: fitdecode
20
+ Requires-Dist: lxml
21
+ Requires-Dist: pandas
22
+ Description-Content-Type: text/markdown
23
+
24
+ # activity-parser
25
+
26
+ [![CI](https://github.com/tabishm52/activity_parser/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tabishm52/activity_parser/actions/workflows/ci.yml)
27
+
28
+ Parser for loading FIT, TCX and GPX activity files into Pandas DataFrames.
29
+
30
+ Provides a parser object for reading (optionally gzipped) FIT, TCX, and GPX activity files and converting them into Pandas DataFrames.
31
+ During import, column names extracted from activity files are normalized into a canonical set of output column names.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ pip install activity-parser
37
+ ```
38
+
39
+ ## Usage
40
+
41
+ Create a new instance of the `ActivityParser` class to be reused for subsequent parsing of activity files:
42
+
43
+ ```python
44
+ import activity_parser
45
+ parser = activity_parser.ActivityParser()
46
+ ```
47
+
48
+ Parse FIT, TCX and GPX files into normalized DataFrames:
49
+
50
+ ```python
51
+ records, laps, extra = parser.parse('path/to/fit_file.fit')
52
+ records, laps, extra = parser.parse('path/to/gpx_file.gpx')
53
+ records, laps, extra = parser.parse('path/to/tcx_file.tcx')
54
+ ```
55
+
56
+ Regardless of source format, `records` and `laps` use a canonical set of column names (see [Output columns](#output-columns) below), e.g.:
57
+
58
+ ```
59
+ distance speed cadence heart_rate
60
+ time
61
+ 2026-01-05 08:00:00+00:00 0.00 36.0 80 100
62
+ 2026-01-05 08:00:01+00:00 0.01 36.0 81 101
63
+ ```
64
+
65
+ `extra` is not canonicalized like `records` and `laps`: it's a dict of leftover, format-specific metadata passed through with its native field names, and its shape differs by format.
66
+ For FIT, it's keyed by FIT message name (e.g. `session`, `device_info`).
67
+ For TCX/GPX, it's a single dict of the root element's attributes/fields (e.g. `Creator`, `Id`).
68
+ Treat it as raw metadata to inspect per-format rather than something to consume generically.
69
+
70
+ ## Output columns
71
+
72
+ Units are aligned to FIT's standard units (via `fitdecode.StandardUnitsDataProcessor`), and columns are renamed/converted where needed so the same name means the same unit regardless of source format:
73
+
74
+ | Column | Unit | FIT | TCX | GPX |
75
+ |---|---|:-:|:-:|:-:|
76
+ | `latitude`, `longitude` | degrees | Yes | Yes | Yes |
77
+ | `altitude` | meters | Yes | Yes | Yes |
78
+ | `distance` | km | Yes | Yes | — |
79
+ | `speed` | km/h | Yes | Yes | (\*) |
80
+ | `cadence` | rpm | Yes | Yes | Yes |
81
+ | `heart_rate` | bpm | Yes | Yes | Yes |
82
+ | `power` | watts | Yes | Yes | Yes |
83
+ | `temperature` | °C | Yes | — | Yes |
84
+
85
+ Not every column appears in every file: `parse()` only includes columns actually present in the source.
86
+ Two of these gaps are structural (GPX has no field for cumulative distance, in the base spec or in Garmin's `TrackPointExtension`, and TCX has no field for temperature, in the base spec or in Garmin's `ActivityExtension`), so those will never appear regardless of exporter.
87
+ GPX files also have no lap data, so `laps` will always be an empty DataFrame.
88
+
89
+ (\*) `speed` for GPX is exporter-dependent, not a format limitation: it's defined in Garmin's `TrackPointExtension/v2` schema.
90
+ Any exporter that emits `v2` (or another extension exposing a `speed`-named field) will have it picked up and normalized.
91
+
92
+ `laps` follows the same convention for shared metrics (`total_distance`, `avg_speed`, `max_speed`, `avg_heart_rate`, `avg_power`, `total_calories`, etc.).
93
+ FIT also exposes FIT-specific fields not available from TCX/GPX (e.g. `fractional_cadence`, `left_right_balance`, `accumulated_power`) under their native FIT names.
94
+
95
+ ## License
96
+
97
+ MIT
@@ -0,0 +1,74 @@
1
+ # activity-parser
2
+
3
+ [![CI](https://github.com/tabishm52/activity_parser/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tabishm52/activity_parser/actions/workflows/ci.yml)
4
+
5
+ Parser for loading FIT, TCX and GPX activity files into Pandas DataFrames.
6
+
7
+ Provides a parser object for reading (optionally gzipped) FIT, TCX, and GPX activity files and converting them into Pandas DataFrames.
8
+ During import, column names extracted from activity files are normalized into a canonical set of output column names.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ pip install activity-parser
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ Create a new instance of the `ActivityParser` class to be reused for subsequent parsing of activity files:
19
+
20
+ ```python
21
+ import activity_parser
22
+ parser = activity_parser.ActivityParser()
23
+ ```
24
+
25
+ Parse FIT, TCX and GPX files into normalized DataFrames:
26
+
27
+ ```python
28
+ records, laps, extra = parser.parse('path/to/fit_file.fit')
29
+ records, laps, extra = parser.parse('path/to/gpx_file.gpx')
30
+ records, laps, extra = parser.parse('path/to/tcx_file.tcx')
31
+ ```
32
+
33
+ Regardless of source format, `records` and `laps` use a canonical set of column names (see [Output columns](#output-columns) below), e.g.:
34
+
35
+ ```
36
+ distance speed cadence heart_rate
37
+ time
38
+ 2026-01-05 08:00:00+00:00 0.00 36.0 80 100
39
+ 2026-01-05 08:00:01+00:00 0.01 36.0 81 101
40
+ ```
41
+
42
+ `extra` is not canonicalized like `records` and `laps`: it's a dict of leftover, format-specific metadata passed through with its native field names, and its shape differs by format.
43
+ For FIT, it's keyed by FIT message name (e.g. `session`, `device_info`).
44
+ For TCX/GPX, it's a single dict of the root element's attributes/fields (e.g. `Creator`, `Id`).
45
+ Treat it as raw metadata to inspect per-format rather than something to consume generically.
46
+
47
+ ## Output columns
48
+
49
+ Units are aligned to FIT's standard units (via `fitdecode.StandardUnitsDataProcessor`), and columns are renamed/converted where needed so the same name means the same unit regardless of source format:
50
+
51
+ | Column | Unit | FIT | TCX | GPX |
52
+ |---|---|:-:|:-:|:-:|
53
+ | `latitude`, `longitude` | degrees | Yes | Yes | Yes |
54
+ | `altitude` | meters | Yes | Yes | Yes |
55
+ | `distance` | km | Yes | Yes | — |
56
+ | `speed` | km/h | Yes | Yes | (\*) |
57
+ | `cadence` | rpm | Yes | Yes | Yes |
58
+ | `heart_rate` | bpm | Yes | Yes | Yes |
59
+ | `power` | watts | Yes | Yes | Yes |
60
+ | `temperature` | °C | Yes | — | Yes |
61
+
62
+ Not every column appears in every file: `parse()` only includes columns actually present in the source.
63
+ Two of these gaps are structural (GPX has no field for cumulative distance, in the base spec or in Garmin's `TrackPointExtension`, and TCX has no field for temperature, in the base spec or in Garmin's `ActivityExtension`), so those will never appear regardless of exporter.
64
+ GPX files also have no lap data, so `laps` will always be an empty DataFrame.
65
+
66
+ (\*) `speed` for GPX is exporter-dependent, not a format limitation: it's defined in Garmin's `TrackPointExtension/v2` schema.
67
+ Any exporter that emits `v2` (or another extension exposing a `speed`-named field) will have it picked up and normalized.
68
+
69
+ `laps` follows the same convention for shared metrics (`total_distance`, `avg_speed`, `max_speed`, `avg_heart_rate`, `avg_power`, `total_calories`, etc.).
70
+ FIT also exposes FIT-specific fields not available from TCX/GPX (e.g. `fractional_cadence`, `left_right_balance`, `accumulated_power`) under their native FIT names.
71
+
72
+ ## License
73
+
74
+ MIT
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "activity-parser"
7
+ version = "0.9.0"
8
+ description = "Parser for loading FIT, TCX and GPX files into Pandas DataFrames."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [
13
+ { name = "Tabish Mustufa", email = "tabishm@gmail.com" },
14
+ ]
15
+ keywords = ["fit", "tcx", "gpx", "gps", "fitness", "pandas", "parser"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Scientific/Engineering :: GIS",
24
+ ]
25
+ requires-python = ">=3.11"
26
+ dependencies = [
27
+ "pandas",
28
+ "lxml",
29
+ "fitdecode",
30
+ ]
31
+
32
+ [project.urls]
33
+ Repository = "https://github.com/tabishm52/activity_parser"
34
+ Issues = "https://github.com/tabishm52/activity_parser/issues"
35
+
36
+ [dependency-groups]
37
+ dev = [
38
+ "lxml-stubs",
39
+ "pandas-stubs",
40
+ "pre-commit",
41
+ "pyright",
42
+ "pytest",
43
+ "ruff",
44
+ ]
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
48
+
49
+ [tool.ruff]
50
+ line-length = 100
51
+ target-version = "py311"
52
+
53
+ [tool.ruff.lint]
54
+ select = ["E", "W", "F", "I", "PL", "UP"]
55
+
56
+ [tool.ruff.lint.per-file-ignores]
57
+ "tests/*" = ["PLR2004"]
@@ -0,0 +1,12 @@
1
+ """Parser for loading FIT, TCX and GPX files into Pandas DataFrames."""
2
+
3
+ from .parse_activity import ActivityParser
4
+ from .parse_fit_file import parse_fit
5
+ from .parse_tcx_gpx import parse_gpx, parse_tcx
6
+
7
+ __all__ = [
8
+ "ActivityParser",
9
+ "parse_fit",
10
+ "parse_gpx",
11
+ "parse_tcx",
12
+ ]
@@ -0,0 +1,281 @@
1
+ """Class for parsing FIT, TCX and GPX files into Pandas DataFrames."""
2
+
3
+ from collections.abc import Mapping, Sequence
4
+ from os import PathLike
5
+ from pathlib import Path
6
+ from typing import IO, Any
7
+
8
+ import pandas as pd
9
+
10
+ from .parse_fit_file import parse_fit
11
+ from .parse_tcx_gpx import parse_gpx, parse_tcx
12
+
13
+
14
+ def select_and_rename_cols(
15
+ df: pd.DataFrame,
16
+ selector: Sequence[str],
17
+ mapper: Mapping[str, str],
18
+ ) -> pd.DataFrame:
19
+ """Select and rename columns from a DataFrame."""
20
+ cols = [col for col in selector if col in df.columns]
21
+ return df.loc[:, cols].rename(columns=mapper)
22
+
23
+
24
+ def normalize_extension(ext: str) -> str:
25
+ """Normalize an extension string to one of: fit, tcx, gpx."""
26
+ normalized = ext.lower().lstrip(".")
27
+ if normalized == "gz":
28
+ raise ValueError("Ambiguous extension: .gz without base extension.")
29
+ return normalized
30
+
31
+
32
+ def infer_extension(file: str | PathLike[str]) -> str:
33
+ """Infer normalized extension from a path-like input."""
34
+ p = Path(file)
35
+ ext = p.suffix
36
+ if ext.lower() == ".gz":
37
+ ext = Path(p.stem).suffix
38
+ return normalize_extension(ext)
39
+
40
+
41
+ class ActivityParser:
42
+ """Parser for FIT, GPX and TCX files.
43
+
44
+ Each instance of this class is a parser object that can be used to import FIT, GPX
45
+ and TCX files into DataFrames. During parsing, the column names in the resulting
46
+ DataFrames are normalized to a standard set of names to allow for more
47
+ interchangeable use of DataFrames from the different activity file types.
48
+ """
49
+
50
+ def __init__(self, strict_xml: bool = False) -> None:
51
+ """Initialize parser settings, selectors, and mappers.
52
+
53
+ Args:
54
+ strict_xml: If True, TCX/GPX XML parsing fails on malformed input.
55
+ If False, parser recovery is enabled.
56
+ """
57
+ self.strict_xml = strict_xml
58
+
59
+ # 'Selectors' specify the list and order of columns to be copied from each
60
+ # DataFrame (records and laps for each file type), and 'mappers' translate the
61
+ # imported column names into canonical names
62
+
63
+ self.fit_records_selector = [
64
+ "position_lat",
65
+ "position_long",
66
+ "altitude",
67
+ "distance",
68
+ "speed",
69
+ "cadence",
70
+ "fractional_cadence",
71
+ "heart_rate",
72
+ "power",
73
+ "left_right_balance",
74
+ "accumulated_power",
75
+ "temperature",
76
+ ]
77
+
78
+ self.tcx_records_selector = [
79
+ "LatitudeDegrees",
80
+ "LongitudeDegrees",
81
+ "AltitudeMeters",
82
+ "DistanceKm",
83
+ "Speed",
84
+ "Cadence",
85
+ "HeartRateBpm",
86
+ "Watts",
87
+ ]
88
+
89
+ self.gpx_records_selector = [
90
+ "lat",
91
+ "lon",
92
+ "ele",
93
+ "speed",
94
+ "cad",
95
+ "hr",
96
+ "power",
97
+ "atemp",
98
+ ]
99
+
100
+ self.fit_records_mapper = {
101
+ "position_lat": "latitude",
102
+ "position_long": "longitude",
103
+ "altitude": "altitude",
104
+ "distance": "distance",
105
+ "speed": "speed",
106
+ "cadence": "cadence",
107
+ "fractional_cadence": "fractional_cadence",
108
+ "heart_rate": "heart_rate",
109
+ "power": "power",
110
+ "left_right_balance": "left_right_balance",
111
+ "accumulated_power": "accumulated_power",
112
+ "temperature": "temperature",
113
+ }
114
+
115
+ self.tcx_records_mapper = {
116
+ "LatitudeDegrees": "latitude",
117
+ "LongitudeDegrees": "longitude",
118
+ "AltitudeMeters": "altitude",
119
+ "DistanceKm": "distance",
120
+ "Speed": "speed",
121
+ "Cadence": "cadence",
122
+ "HeartRateBpm": "heart_rate",
123
+ "Watts": "power",
124
+ }
125
+
126
+ self.gpx_records_mapper = {
127
+ "lat": "latitude",
128
+ "lon": "longitude",
129
+ "ele": "altitude",
130
+ "speed": "speed",
131
+ "cad": "cadence",
132
+ "hr": "heart_rate",
133
+ "power": "power",
134
+ "atemp": "temperature",
135
+ }
136
+
137
+ self.fit_laps_selector = [
138
+ "event",
139
+ "event_type",
140
+ "lap_trigger",
141
+ "start_time",
142
+ "total_elapsed_time",
143
+ "total_timer_time",
144
+ "start_position_lat",
145
+ "start_position_long",
146
+ "end_position_lat",
147
+ "end_position_long",
148
+ "total_distance",
149
+ "total_ascent",
150
+ "total_descent",
151
+ "avg_vam",
152
+ "avg_speed",
153
+ "max_speed",
154
+ "avg_cadence",
155
+ "max_cadence",
156
+ "avg_fractional_cadence",
157
+ "max_fractional_cadence",
158
+ "total_strokes",
159
+ "avg_heart_rate",
160
+ "max_heart_rate",
161
+ "time_in_hr_zone",
162
+ "avg_power",
163
+ "max_power",
164
+ "normalized_power",
165
+ "left_right_balance",
166
+ "time_in_power_zone",
167
+ "total_work",
168
+ "avg_temperature",
169
+ "max_temperature",
170
+ "total_calories",
171
+ "total_fat_calories",
172
+ "sport",
173
+ "sub_sport",
174
+ ]
175
+
176
+ self.tcx_laps_selector = [
177
+ "TriggerMethod",
178
+ "StartTime",
179
+ "TotalTimeSeconds",
180
+ "DistanceKm",
181
+ "AvgSpeed",
182
+ "MaximumSpeed",
183
+ "Cadence",
184
+ "MaxBikeCadence",
185
+ "AverageHeartRateBpm",
186
+ "MaximumHeartRateBpm",
187
+ "AvgWatts",
188
+ "MaxWatts",
189
+ "Calories",
190
+ ]
191
+
192
+ # Just use the FIT names for lap data as canonical
193
+ self.fit_laps_mapper = {}
194
+
195
+ self.tcx_laps_mapper = {
196
+ "TriggerMethod": "lap_trigger",
197
+ "StartTime": "start_time",
198
+ "TotalTimeSeconds": "total_elapsed_time",
199
+ "DistanceKm": "total_distance",
200
+ "AvgSpeed": "avg_speed",
201
+ "MaximumSpeed": "max_speed",
202
+ "Cadence": "avg_cadence",
203
+ "MaxBikeCadence": "max_cadence",
204
+ "AverageHeartRateBpm": "avg_heart_rate",
205
+ "MaximumHeartRateBpm": "max_heart_rate",
206
+ "AvgWatts": "avg_power",
207
+ "MaxWatts": "max_power",
208
+ "Calories": "total_calories",
209
+ }
210
+
211
+ def parse(
212
+ self,
213
+ file: str | PathLike[str] | IO[bytes],
214
+ ext: str | None = None,
215
+ ) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
216
+ """Loads a FIT, TCX or GPX activity into Pandas DataFrames.
217
+
218
+ During import, column names in ``records`` and ``laps`` are normalized into a
219
+ canonical set of names. Note this function does not guarantee that all canonical
220
+ columns appear in the output, it only renames the columns that are present in
221
+ the activity file.
222
+
223
+ Args:
224
+ file: Binary file-like or path-like object. A path-like argument ending in
225
+ ``.gz`` will be unzipped before processing.
226
+ ext: File type, case-insensitive: ``fit``, ``tcx``, or ``gpx``. Required for
227
+ a file-like ``file``; optional for a path-like ``file`` (inferred from
228
+ the name).
229
+
230
+ Returns:
231
+ Tuple containing records, laps, and selected extra metadata.
232
+ """
233
+ if ext is not None:
234
+ ext_normalized = normalize_extension(ext)
235
+ elif isinstance(file, (str, PathLike)):
236
+ ext_normalized = infer_extension(file)
237
+ else:
238
+ raise ValueError("ext must be provided when file is a file-like object.")
239
+
240
+ if ext_normalized == "fit":
241
+ records, laps, extra = parse_fit(file)
242
+ records = select_and_rename_cols(
243
+ records,
244
+ self.fit_records_selector,
245
+ self.fit_records_mapper,
246
+ )
247
+ records.rename_axis("time", inplace=True)
248
+ laps = select_and_rename_cols(
249
+ laps,
250
+ self.fit_laps_selector,
251
+ self.fit_laps_mapper,
252
+ )
253
+
254
+ elif ext_normalized == "tcx":
255
+ records, laps, extra = parse_tcx(file, strict_xml=self.strict_xml)
256
+ records = select_and_rename_cols(
257
+ records,
258
+ self.tcx_records_selector,
259
+ self.tcx_records_mapper,
260
+ )
261
+ records.rename_axis("time", inplace=True)
262
+ laps = select_and_rename_cols(
263
+ laps,
264
+ self.tcx_laps_selector,
265
+ self.tcx_laps_mapper,
266
+ )
267
+
268
+ elif ext_normalized == "gpx":
269
+ records, laps, extra = parse_gpx(file, strict_xml=self.strict_xml)
270
+ records = select_and_rename_cols(
271
+ records,
272
+ self.gpx_records_selector,
273
+ self.gpx_records_mapper,
274
+ )
275
+ records.rename_axis("time", inplace=True)
276
+ # Note GPX files have no lap information
277
+
278
+ else:
279
+ raise ValueError(f"File type not supported: {ext_normalized}")
280
+
281
+ return records, laps, extra