Download scripts/lvl_running/fit3.py from lvlmotion/running: direct link, hf CLI and curl.
- Browser
- Download file 5.77 kB
-
https://huggingface.co/datasets/lvlmotion/running/resolve/main/scripts/lvl_running/fit3.py
- Command line
-
hf download hf://datasets/lvlmotion/running/scripts/lvl_running/fit3.py
-
curl -L -o fit3.py https://huggingface.co/datasets/lvlmotion/running/resolve/main/scripts/lvl_running/fit3.py
5.77 kB
| """Samsung Galaxy Fit3 watch loader -- the non-LEVEL reference (heart rate, cadence, speed). | |
| Fit3 data is day-level: data/<subject>/<day>/fit3/. Two on-disk layouts, same Fit3 object out: | |
| released dataset (our own schema): | |
| fit3_live.csv 10 s samples: time(us), heart_rate, cadence, speed | |
| fit3_summary.csv one row: start_time(us), duration_s, hr_mean/max/min, cadence_mean/max, ... | |
| Samsung Health export ("Download personal data"), staged into fit3/: | |
| live_data.json 10 s samples: heart_rate, cadence, distance, power, speed, start_time(ms) | |
| location_data.json 1 s samples: latitude, longitude, altitude, accuracy, start_time(ms) | |
| exercise_summary.csv the summary CSV -- avg/max HR etc. | |
| Times are epoch-us, on the same clock as the IMU and phone streams. | |
| """ | |
| from __future__ import annotations | |
| import csv | |
| import json | |
| import os | |
| from dataclasses import dataclass | |
| import pandas as pd | |
| LIVE_COLS = ["time", "heart_rate", "cadence", "speed"] # Samsung's `power` is always 0 on the Fit3 | |
| class Fit3: | |
| live: pd.DataFrame # time(us), heart_rate, cadence, speed (10 s) | |
| loc: pd.DataFrame # time(us), lat, lon, altitude, accuracy (1 s; Samsung export only) | |
| summary: dict # hr_mean/max/min, cadence_mean/max, mean_speed, duration_min, calorie | |
| def _load_series(fit3_dir: str) -> tuple[pd.DataFrame, pd.DataFrame]: | |
| public = os.path.join(fit3_dir, "fit3_live.csv") | |
| if os.path.exists(public): | |
| live = pd.read_csv(public) | |
| return live[[c for c in LIVE_COLS if c in live]].sort_values("time").reset_index(drop=True), pd.DataFrame() | |
| def js(name): | |
| p = os.path.join(fit3_dir, name) | |
| return json.load(open(p)) if os.path.exists(p) else [] | |
| live = pd.DataFrame(js("live_data.json")) | |
| if not live.empty: | |
| live["time"] = live["start_time"].astype("int64") * 1000 | |
| live = live[[c for c in LIVE_COLS if c in live]].sort_values("time").reset_index(drop=True) | |
| loc = pd.DataFrame(js("location_data.json")) | |
| if not loc.empty: | |
| loc["time"] = loc["start_time"].astype("int64") * 1000 | |
| loc = loc.rename(columns={"latitude": "lat", "longitude": "lon"}) | |
| loc = loc[["time", "lat", "lon", "altitude", "accuracy"]].sort_values("time").reset_index(drop=True) | |
| return live, loc | |
| def _parse_summary(fit3_dir: str, start_us: int | None) -> dict: | |
| """The run's summary: fit3_summary.csv, else the matching row of Samsung's exercise_summary.csv. | |
| Samsung header (line 2) is prefix-labelled (com.samsung.health.exercise.<field>); rows carry one extra | |
| trailing field, but zip(header, row) aligns the leading columns we need. We pick the running | |
| workout (exercise_type 1002) nearest the session start, else the longest running workout. | |
| """ | |
| pub = os.path.join(fit3_dir, "fit3_summary.csv") | |
| if os.path.exists(pub): | |
| rows = pd.read_csv(pub).to_dict("records") | |
| if not rows: | |
| return {} | |
| r = {k: (None if pd.isna(v) else v) for k, v in rows[0].items()} | |
| return {"start_time": r.get("start_time"), "duration_min": (r.get("duration_s") or 0) / 60.0, | |
| "hr_mean": r.get("hr_mean"), "hr_max": r.get("hr_max"), "hr_min": r.get("hr_min"), | |
| "cadence_mean": r.get("cadence_mean"), "cadence_max": r.get("cadence_max"), | |
| "mean_speed": r.get("speed_mean_mps"), "calorie": r.get("calorie_kcal")} | |
| p = os.path.join(fit3_dir, "exercise_summary.csv") | |
| if not os.path.exists(p): | |
| return {} | |
| lines = open(p, encoding="utf-8-sig").read().splitlines() | |
| if len(lines) < 3: | |
| return {} | |
| hdr = next(csv.reader([lines[1]])) | |
| idx = {h.split(".")[-1]: i for i, h in enumerate(hdr)} # last segment: start_time, duration, ... | |
| def g(row, key, cast=str): | |
| j = idx.get(key) | |
| if j is None or j >= len(row) or row[j] == "": | |
| return None | |
| try: | |
| return cast(row[j]) | |
| except ValueError: | |
| return row[j] | |
| best, best_key = None, None | |
| for ln in lines[2:]: | |
| row = next(csv.reader([ln])) | |
| if g(row, "exercise_type") != "1002": # running only | |
| continue | |
| dur = g(row, "duration", float) or 0.0 | |
| st = g(row, "start_time") # "YYYY-MM-DD HH:MM:SS.000" (UTC) | |
| key = dur | |
| if start_us is not None and st: | |
| try: | |
| t = pd.Timestamp(st, tz="UTC").value // 1000 # -> epoch us | |
| key = -abs(t - start_us) # nearest start wins | |
| except Exception: | |
| pass | |
| if best_key is None or key > best_key: | |
| best, best_key = row, key | |
| if best is None: | |
| return {} | |
| return { | |
| "start_time": g(best, "start_time"), | |
| "duration_min": (g(best, "duration", float) or 0) / 60000.0, | |
| "hr_mean": g(best, "mean_heart_rate", float), | |
| "hr_max": g(best, "max_heart_rate", float), | |
| "hr_min": g(best, "min_heart_rate", float), | |
| "cadence_mean": g(best, "mean_cadence", float), | |
| "cadence_max": g(best, "max_cadence", float), | |
| "mean_speed": g(best, "mean_speed", float), | |
| "calorie": g(best, "calorie", float), | |
| } | |
| def load_fit3(day_path: str) -> Fit3 | None: | |
| """Fit3 for one day folder (data/<subject>/<day>), or None if that day has no watch data.""" | |
| fit3_dir = os.path.join(day_path, "fit3") | |
| if not os.path.isdir(fit3_dir): | |
| return None | |
| live, loc = _load_series(fit3_dir) | |
| if live.empty and loc.empty: | |
| return None | |
| start_us = int(live["time"].iloc[0]) if not live.empty else int(loc["time"].iloc[0]) | |
| return Fit3(live=live, loc=loc, summary=_parse_summary(fit3_dir, start_us)) | |