219 lines
7.6 KiB
Python
Executable File
219 lines
7.6 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""COROS-style GPX visualizer: dark background, elevation-colored track, clean stats."""
|
|
|
|
import argparse
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import gpxpy
|
|
import matplotlib.pyplot as plt
|
|
import numpy as np
|
|
from matplotlib.colors import Normalize
|
|
from matplotlib.lines import Line2D
|
|
from matplotlib.offsetbox import AnchoredOffsetbox, HPacker, TextArea
|
|
|
|
|
|
def parse_gpx(filepath):
|
|
with open(filepath) as f:
|
|
gpx = gpxpy.parse(f)
|
|
return [
|
|
(p.latitude, p.longitude, p.time, p.elevation if p.elevation else 0)
|
|
for track in gpx.tracks
|
|
for segment in track.segments
|
|
for p in segment.points
|
|
]
|
|
|
|
|
|
def haversine_km(lat1, lon1, lat2, lon2):
|
|
R = 6371.0
|
|
dlat = np.radians(lat2 - lat1)
|
|
dlon = np.radians(lon2 - lon1)
|
|
a = (
|
|
np.sin(dlat / 2) ** 2
|
|
+ np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.sin(dlon / 2) ** 2
|
|
)
|
|
return R * 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
|
|
|
|
|
|
def total_distance_km(points):
|
|
return sum(
|
|
haversine_km(points[i][0], points[i][1], points[i + 1][0], points[i + 1][1])
|
|
for i in range(len(points) - 1)
|
|
)
|
|
|
|
|
|
def format_pace(seconds, dist_km):
|
|
if dist_km <= 0:
|
|
return "--:--"
|
|
pace = seconds / dist_km
|
|
return f"{int(pace // 60)}:{int(pace % 60):02d}"
|
|
|
|
|
|
def format_elapsed(seconds):
|
|
hours = seconds / 3600
|
|
return f"{hours:.2f}"
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="COROS-style GPX visualizer")
|
|
parser.add_argument("gpx", help="GPX file")
|
|
parser.add_argument("-o", "--output", help="Save to file")
|
|
parser.add_argument("--max-height", type=float, help="Override max elevation (m)")
|
|
parser.add_argument("--min-height", type=float, help="Override min elevation (m)")
|
|
parser.add_argument("--avg-speed", type=float, help="Average speed (km/h)")
|
|
parser.add_argument("--total-energy", type=float, help="Total energy (kcal)")
|
|
parser.add_argument("--energy-cons", type=float, help="Energy consumption (kcal/km)")
|
|
args = parser.parse_args()
|
|
|
|
points = parse_gpx(args.gpx)
|
|
if not points:
|
|
print("No track points found.")
|
|
return
|
|
|
|
lats = np.array([p[0] for p in points])
|
|
lons = np.array([p[1] for p in points])
|
|
elevations = np.array([p[3] for p in points])
|
|
|
|
dist = total_distance_km(points)
|
|
|
|
if points[0][2] and points[-1][2]:
|
|
elapsed = (points[-1][2] - points[0][2]).total_seconds()
|
|
time_str = format_elapsed(elapsed)
|
|
pace_str = format_pace(elapsed, dist)
|
|
|
|
utc_start = points[0][2].replace(tzinfo=timezone.utc)
|
|
utc_end = points[-1][2].replace(tzinfo=timezone.utc)
|
|
local_start = utc_start.astimezone()
|
|
local_end = utc_end.astimezone()
|
|
start_str = local_start.strftime("%H:%M")
|
|
end_str = local_end.strftime("%H:%M")
|
|
date_str = local_start.strftime("%d.%m.%Y")
|
|
else:
|
|
time_str = pace_str = start_str = end_str = date_str = "N/A"
|
|
|
|
max_ht = args.max_height if args.max_height is not None else elevations.max()
|
|
min_ht = args.min_height if args.min_height is not None else elevations.min()
|
|
max_ht_str = f"{int(round(max_ht))}"
|
|
min_ht_str = f"{int(round(min_ht))}"
|
|
|
|
avg_speed_str = f"{args.avg_speed:.1f}" if args.avg_speed is not None else "\u2014"
|
|
avg_speed_unit = " km/h" if args.avg_speed is not None else ""
|
|
energy_str = f"{args.total_energy:.0f}" if args.total_energy is not None else "\u2014"
|
|
energy_unit = " kcal" if args.total_energy is not None else ""
|
|
energy_cons_str = f"{args.energy_cons:.1f}" if args.energy_cons is not None else "\u2014"
|
|
energy_cons_unit = " kcal/km" if args.energy_cons is not None else ""
|
|
|
|
# Colors
|
|
BG = "#0a0a0f"
|
|
FG = "#ffffff"
|
|
LABEL = "#b39ddb"
|
|
PURPLE_LOW = "#ce93d8"
|
|
PURPLE_HIGH = "#4a148c"
|
|
|
|
fig = plt.figure(figsize=(9, 16), dpi=120)
|
|
fig.patch.set_facecolor(BG)
|
|
|
|
# --- Track map ---
|
|
frame_left, frame_bottom, frame_width, frame_height = 0.02, 0.50, 0.96, 0.46
|
|
|
|
pad_x = frame_width * 0.05
|
|
pad_y = frame_height * 0.05
|
|
ax_map = fig.add_axes(
|
|
[frame_left + pad_x, frame_bottom + pad_y,
|
|
frame_width - 2 * pad_x, frame_height - 2 * pad_y],
|
|
facecolor=BG,
|
|
)
|
|
ax_map.set_axis_off()
|
|
|
|
mid_lat = np.mean(lats)
|
|
ax_map.set_aspect(1.0 / np.cos(np.radians(mid_lat)))
|
|
lat_range = lats.max() - lats.min()
|
|
lon_range = lons.max() - lons.min()
|
|
padding = max(lat_range, lon_range) * 0.10
|
|
ax_map.set_xlim(lons.min() - padding, lons.max() + padding)
|
|
ax_map.set_ylim(lats.min() - padding, lats.max() + padding)
|
|
|
|
# Draw elevation-colored segments
|
|
elev_range = max_ht - min_ht
|
|
if elev_range > 1:
|
|
elev_norm = (elevations - min_ht) / elev_range
|
|
else:
|
|
elev_norm = np.zeros_like(elevations)
|
|
|
|
cmap = plt.cm.Purples
|
|
norm = Normalize(vmin=0, vmax=1)
|
|
|
|
for i in range(len(lons) - 1):
|
|
e = (elev_norm[i] + elev_norm[i + 1]) / 2
|
|
color = cmap(0.3 + 0.7 * e)
|
|
ax_map.plot(lons[i:i + 2], lats[i:i + 2], color=color, linewidth=2.5, zorder=3)
|
|
|
|
ax_map.scatter(lons[0], lats[0],
|
|
c=PURPLE_LOW, s=90, edgecolors=BG, linewidth=2.5, zorder=4)
|
|
ax_map.scatter(lons[-1], lats[-1],
|
|
c=PURPLE_HIGH, s=90, edgecolors=BG, linewidth=2.5, zorder=4)
|
|
|
|
# --- COROS-style stats --------------------------------------------------
|
|
|
|
def hero_text(fig, x, y, value, unit):
|
|
packed = HPacker(children=[
|
|
TextArea(value, textprops=dict(color=FG, fontsize=64, fontweight="bold")),
|
|
TextArea(" " + unit, textprops=dict(color=FG, fontsize=24)),
|
|
], align="baseline", pad=0, sep=2)
|
|
fig.add_artist(AnchoredOffsetbox(
|
|
loc="lower left", child=packed, frameon=False,
|
|
bbox_to_anchor=(x, y), bbox_transform=fig.transFigure,
|
|
borderpad=0, pad=0,
|
|
))
|
|
fig.text(x, y - 0.035, "Distance", fontsize=14, color=LABEL, ha="left")
|
|
|
|
def tile_text(fig, x, y, value, unit, label):
|
|
children = [TextArea(value, textprops=dict(color=FG, fontsize=25, fontweight="bold"))]
|
|
if unit:
|
|
children.append(TextArea(unit, textprops=dict(color=LABEL, fontsize=13)))
|
|
packed = HPacker(children=children, align="baseline", pad=0, sep=2)
|
|
fig.add_artist(AnchoredOffsetbox(
|
|
loc="lower left", child=packed, frameon=False,
|
|
bbox_to_anchor=(x, y), bbox_transform=fig.transFigure,
|
|
borderpad=0, pad=0,
|
|
))
|
|
fig.text(x, y - 0.022, label, fontsize=11, color=LABEL, ha="left")
|
|
|
|
hero_text(fig, 0.07, 0.45, f"{dist:.2f}", "km")
|
|
|
|
# Separator line
|
|
fig.add_artist(Line2D(
|
|
[0.04, 0.96], [0.395, 0.395],
|
|
color=LABEL, linewidth=0.8, alpha=0.5,
|
|
transform=fig.transFigure,
|
|
))
|
|
|
|
tiles = [
|
|
("PACE", pace_str, " /km"),
|
|
("DURATION", time_str, " h"),
|
|
("AVG SPEED", avg_speed_str, avg_speed_unit),
|
|
("MAX HEIGHT", max_ht_str, " m"),
|
|
("MIN HEIGHT", min_ht_str, " m"),
|
|
("ENERGY", energy_str, energy_unit),
|
|
("START", start_str, ""),
|
|
("END", end_str, ""),
|
|
("ENERGY CONS", energy_cons_str, energy_cons_unit),
|
|
]
|
|
|
|
cols = [0.07, 0.38, 0.69]
|
|
rows_y = [0.34, 0.23, 0.12]
|
|
|
|
for i, (label, value, unit) in enumerate(tiles):
|
|
row = i // 3
|
|
col = i % 3
|
|
tile_text(fig, cols[col], rows_y[row], value, unit, label)
|
|
|
|
if args.output:
|
|
plt.savefig(args.output, dpi=300, facecolor=BG)
|
|
print(f"Saved: {args.output}")
|
|
else:
|
|
plt.show()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|