267 lines
9.6 KiB
Python
Executable File
267 lines
9.6 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""GPX visualizer: photo 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
|
|
from PIL import Image, ImageDraw, ImageOps
|
|
|
|
|
|
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 = int(seconds // 3600)
|
|
mins = int((seconds % 3600) // 60)
|
|
if hours > 0:
|
|
return f"{hours}h {mins}m"
|
|
return f"{mins}m"
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="GPX visualizer with photo background")
|
|
parser.add_argument("--gpx", required=True, help="GPX file")
|
|
parser.add_argument("--photo", required=True, help="Background photo")
|
|
parser.add_argument("-o", "--output", help="Save to file")
|
|
parser.add_argument("--distance", type=float, help="Override distance (km)")
|
|
parser.add_argument("--max-height", type=float, help="Override max elevation (m)")
|
|
parser.add_argument("--ascent", type=float, help="Total ascent (m)")
|
|
parser.add_argument("--pace", help="Pace (e.g. 4:52)")
|
|
parser.add_argument("--start", help="Start time (HH:MM)")
|
|
parser.add_argument("--end", help="End time (HH:MM)")
|
|
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/min)")
|
|
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_calc = total_distance_km(points)
|
|
dist = args.distance if args.distance is not None else dist_calc
|
|
|
|
if points[0][2] and points[-1][2]:
|
|
elapsed = (points[-1][2] - points[0][2]).total_seconds()
|
|
time_str = format_elapsed(elapsed)
|
|
pace_str = args.pace if args.pace else 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 = args.start if args.start else local_start.strftime("%H:%M")
|
|
end_str = args.end if args.end else 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"
|
|
if args.pace:
|
|
pace_str = args.pace
|
|
|
|
max_ht = args.max_height if args.max_height is not None else elevations.max()
|
|
min_ht = elevations.min()
|
|
max_ht_str = f"{int(round(max_ht))}"
|
|
|
|
ascent_str = f"{int(round(args.ascent))}" if args.ascent is not None else "\u2014"
|
|
|
|
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/min" if args.energy_cons is not None else ""
|
|
|
|
FG = "#ffffff"
|
|
LABEL = "#b39ddb"
|
|
PURPLE_LOW = "#ce93d8"
|
|
PURPLE_HIGH = "#4a148c"
|
|
|
|
target_w, target_h = 1080, 1920
|
|
|
|
img = Image.open(args.photo)
|
|
img = ImageOps.exif_transpose(img) or img
|
|
|
|
img_ratio = img.width / img.height
|
|
target_ratio = target_w / target_h
|
|
if img_ratio > target_ratio:
|
|
new_w = int(img.height * target_ratio)
|
|
off = (img.width - new_w) // 2
|
|
img = img.crop((off, 0, off + new_w, img.height))
|
|
else:
|
|
new_h = int(img.width / target_ratio)
|
|
off = (img.height - new_h) // 2
|
|
img = img.crop((0, off, img.width, off + new_h))
|
|
img = img.resize((target_w, target_h), Image.Resampling.LANCZOS)
|
|
|
|
# Dark gradient overlay
|
|
img_gray = img.convert("L")
|
|
avg_brightness = np.mean(np.array(img_gray)) / 255.0
|
|
|
|
top_base = 0.50 - avg_brightness * 0.35
|
|
bot_base = 0.95 - avg_brightness * 0.50
|
|
|
|
overlay = Image.new("RGBA", (target_w, target_h), (0, 0, 0, 0))
|
|
draw = ImageDraw.Draw(overlay)
|
|
for y in range(target_h):
|
|
t = y / target_h
|
|
alpha = int(255 * (top_base + (bot_base - top_base) * t))
|
|
draw.rectangle([(0, y), (target_w, y + 1)], fill=(0, 0, 0, alpha))
|
|
img = Image.alpha_composite(img.convert("RGBA"), overlay).convert("RGB")
|
|
|
|
img_array = np.array(img)
|
|
|
|
fig = plt.figure(figsize=(9, 16), dpi=120)
|
|
fig.patch.set_facecolor("none")
|
|
|
|
ax_bg = fig.add_axes([0, 0, 1, 1], zorder=0)
|
|
ax_bg.imshow(img_array, aspect="auto")
|
|
ax_bg.set_axis_off()
|
|
|
|
# --- 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="none",
|
|
)
|
|
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)
|
|
|
|
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)
|
|
|
|
ax_map.plot(lons, lats, color="black", linewidth=5, alpha=0.35, zorder=2)
|
|
|
|
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="none", linewidth=0, zorder=4)
|
|
ax_map.scatter(lons[-1], lats[-1],
|
|
c=PURPLE_HIGH, s=90, edgecolors="none", linewidth=0, 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.022, "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.425, f"{dist:.2f}", "km")
|
|
|
|
fig.add_artist(Line2D(
|
|
[0.04, 0.96], [0.385, 0.385],
|
|
color=LABEL, linewidth=0.8, alpha=0.5,
|
|
transform=fig.transFigure,
|
|
))
|
|
|
|
tiles = [
|
|
("PACE", pace_str, " /km"),
|
|
("DURATION", time_str, ""),
|
|
("AVG SPEED", avg_speed_str, avg_speed_unit),
|
|
("HIGHEST POINT", max_ht_str, " m"),
|
|
("ASCENT", ascent_str, " m"),
|
|
("ENERGY (EST.)", 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.33, 0.22, 0.11]
|
|
|
|
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="none")
|
|
print(f"Saved: {args.output}")
|
|
else:
|
|
plt.show()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|