From 179b2429cf3ef3a24c337deb09d37c823845a29e Mon Sep 17 00:00:00 2001 From: sheepfreak221 Date: Sun, 22 Nov 2026 19:34:02 +0100 Subject: [PATCH] initial release --- LICENSE | 0 README.md | 182 +++++++++++- gpx_visualizer_v8.py | 266 +++++++++++++++++ gpx_visualizer_v9.py | 291 ++++++++++++++++++ historisch/gpx_visualizer.py | 159 ++++++++++ historisch/gpx_visualizer_2.py | 292 +++++++++++++++++++ historisch/gpx_visualizer_3.py | 202 +++++++++++++ historisch/gpx_visualizer_3_coros.py | 245 ++++++++++++++++ historisch/gpx_visualizer_3_coros_darkmap.py | 218 ++++++++++++++ historisch/gpx_visualizer_3_coros_fixed.py | 213 ++++++++++++++ historisch/gpx_visualizer_3_coros_folium.py | 234 +++++++++++++++ historisch/gpx_visualizer_v4.py | 221 ++++++++++++++ historisch/gpx_visualizer_v5.py | 218 ++++++++++++++ historisch/gpx_visualizer_v6.py | 257 ++++++++++++++++ historisch/gpx_visualizer_v7.py | 260 +++++++++++++++++ requirements.txt | 4 + 16 files changed, 3261 insertions(+), 1 deletion(-) mode change 100644 => 100755 LICENSE mode change 100644 => 100755 README.md create mode 100755 gpx_visualizer_v8.py create mode 100755 gpx_visualizer_v9.py create mode 100755 historisch/gpx_visualizer.py create mode 100755 historisch/gpx_visualizer_2.py create mode 100755 historisch/gpx_visualizer_3.py create mode 100755 historisch/gpx_visualizer_3_coros.py create mode 100755 historisch/gpx_visualizer_3_coros_darkmap.py create mode 100755 historisch/gpx_visualizer_3_coros_fixed.py create mode 100755 historisch/gpx_visualizer_3_coros_folium.py create mode 100755 historisch/gpx_visualizer_v4.py create mode 100755 historisch/gpx_visualizer_v5.py create mode 100755 historisch/gpx_visualizer_v6.py create mode 100755 historisch/gpx_visualizer_v7.py create mode 100755 requirements.txt diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 1d46e20..831da60 --- a/README.md +++ b/README.md @@ -1,2 +1,182 @@ -# GPX-Run-Dashboard +# GPX Run Dashboard +Turn a GPX file and a background photo into a finished running dashboard in +9:16 story format: a map with an elevation-colored track, a large distance +readout and a grid of key metrics. + +The design borrows from the dashboards of **Strava**, **COROS** and **Garmin**, +taking whatever works best from each of them. + +--- + +## What it does + +1. Reads the track points (latitude, longitude, time, elevation) from the GPX file. +2. Computes distance, duration, pace and start/end times directly from the data. +3. Crops the background photo to 9:16 and puts a dark gradient on top. The + strength of the gradient adapts automatically to the brightness of the photo, + so the text stays readable. +4. Draws the track as a map. The line is colored by elevation (light purple for + low, dark purple for high) and start and finish are marked. +5. Renders the dashboard below it, with distance as the hero value and nine + metric tiles. + +The result is a PNG in 9:16 (2700 x 4800 px at 300 dpi), ready for +Instagram and Strava stories or as a cover image. + +--- + +## Version 8 vs. version 9 + +The only difference is the **elevation profile**: + +| | v8 | v9 | +|---|---|---| +| Map with elevation coloring | yes | yes | +| Dashboard and metrics | yes | yes | +| Elevation profile at the bottom | no | yes | + +`gpx_visualizer_v8.py` is the compact version. `gpx_visualizer_v9.py` adds an +elevation profile over cumulative distance at the bottom (line plus area fill) +and moves the metric tiles up a bit to make room for it. + +Everything else is identical in both scripts: same parameters, same logic. + +--- + +## Installation + +Requires Python 3.9 or newer. + +```bash +pip install -r requirements.txt +``` + +Or individually: + +```bash +pip install gpxpy matplotlib numpy pillow +``` + +| Package | Used for | +|---|---| +| `gpxpy` | Parsing GPX files | +| `matplotlib` | Map, typography and layout | +| `numpy` | Distance calculation, elevation normalization | +| `Pillow` | Photo cropping, EXIF rotation, gradient overlay | + +--- + +## Usage + +```bash +# Version 9 (with elevation profile) +python gpx_visualizer_v9.py \ + --gpx run.gpx \ + --photo sunrise.jpg \ + -o dashboard.png +``` + +```bash +# Version 8 (without elevation profile), with extra metrics +python gpx_visualizer_v8.py \ + --gpx run.gpx \ + --photo sunrise.jpg \ + --ascent 312 \ + --avg-speed 11.4 \ + --total-energy 742 \ + --energy-cons 9.8 \ + -o dashboard.png +``` + +Without `-o` the result is only shown in a window (`plt.show()`). + +### Parameters + +| Parameter | Description | +|---|---| +| `--gpx` | **Required.** Path to the GPX file | +| `--photo` | **Required.** Path to the background photo | +| `-o`, `--output` | Output file (PNG). Without it, a preview window opens | +| `--distance` | Override the distance in km instead of computing it from the GPX | +| `--max-height` | Override the highest point in m | +| `--ascent` | Total ascent in m (not computed from the GPX) | +| `--pace` | Pace as text, for example `4:52` (otherwise derived from duration and distance) | +| `--start` | Start time as text, for example `18:04` | +| `--end` | End time as text, for example `18:52` | +| `--avg-speed` | Average speed in km/h | +| `--total-energy` | Total energy in kcal | +| `--energy-cons` | Energy consumption in kcal/min | + +--- + +## What comes from the GPX, what you have to pass in + +Computed automatically from the GPX: + +- Distance (haversine over all track points) +- Duration, and from that the pace +- Start and end time, converted to the local time zone +- Minimum and maximum elevation for the track coloring +- Elevation profile (v9 only) + +Not part of standard GPX files, so they are passed as parameters: + +- Total ascent (`--ascent`) +- Average speed (`--avg-speed`) +- Energy and energy consumption (`--total-energy`, `--energy-cons`) + +If a value is missing, the tile shows a placeholder dash. The tiles do not +disappear, they stay in the layout as placeholders. + +--- + +## Design + +- **Background:** Photo, center-cropped to 9:16, honoring EXIF rotation. The + dark gradient at the top and bottom is calculated from the average brightness + of the photo, so bright photos get more dimming. +- **Map:** At the top, without axes or frame. The track sits on top of a soft + black shadow line so it stays readable on busy photos. The aspect ratio is + corrected for the mean latitude, so the map is not distorted. +- **Colors:** A purple ramp for elevation (`Purples`), light start marker + (`#ce93d8`), dark finish marker (`#4a148c`), labels in `#b39ddb`. +- **Distance:** The hero value at the top of the lower block, followed by a thin + divider and a 3x3 grid of metrics. +- **v9:** Elevation profile at the very bottom, as a line with an area fill, + showing only the left and bottom axis, kept subtle and transparent. + +--- + +## Notes + +- **Time zones:** GPX timestamps are treated as UTC and converted to local time + for display. If your device writes local times without a timezone offset into + the GPX, start and end can be shifted. In that case just set `--start` and + `--end` manually. +- **Missing elevation data:** Points without elevation are treated as `0`. That + distorts the track coloring, but not distance or time. +- **Photos:** A portrait photo that roughly fits the format works best. It will + be cropped, and the crop is always centered. +- **Multiple tracks or segments:** All points are concatenated. Jumps between + segments count as distance. + +--- + +## Project structure + +``` +. +├── gpx_visualizer_v8.py # Dashboard without elevation profile +├── gpx_visualizer_v9.py # Dashboard with elevation profile +├── requirements.txt +├── README.md # English +└── README.de.md # German +``` + +--- + +## The short version + +GPX in, photo in, finished running dashboard out. No server, no upload, no API: +everything runs locally in a single Python script. diff --git a/gpx_visualizer_v8.py b/gpx_visualizer_v8.py new file mode 100755 index 0000000..311c97b --- /dev/null +++ b/gpx_visualizer_v8.py @@ -0,0 +1,266 @@ +#!/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() diff --git a/gpx_visualizer_v9.py b/gpx_visualizer_v9.py new file mode 100755 index 0000000..711479c --- /dev/null +++ b/gpx_visualizer_v9.py @@ -0,0 +1,291 @@ +#!/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 + + cum_dist = [0.0] + for i in range(1, len(points)): + d = haversine_km(points[i - 1][0], points[i - 1][1], points[i][0], points[i][1]) + cum_dist.append(cum_dist[-1] + d) + cum_dist = np.array(cum_dist) + + 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.32, 0.245, 0.17] + + 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) + + # --- Elevation profile --- + ax_elev = fig.add_axes([0.04, 0.035, 0.92, 0.09], facecolor="none") + ax_elev.plot(cum_dist, elevations, color=LABEL, linewidth=1.5, alpha=0.8) + ax_elev.fill_between(cum_dist, elevations.min(), elevations, color=LABEL, alpha=0.15) + + ax_elev.tick_params(left=False, right=False, top=False, bottom=False, + labelleft=False, labelbottom=False) + ax_elev.set_frame_on(False) + ax_elev.spines["bottom"].set_visible(True) + ax_elev.spines["left"].set_visible(True) + ax_elev.spines["top"].set_visible(False) + ax_elev.spines["right"].set_visible(False) + ax_elev.spines["bottom"].set_color(LABEL) + ax_elev.spines["left"].set_color(LABEL) + ax_elev.spines["bottom"].set_alpha(0.4) + ax_elev.spines["left"].set_alpha(0.4) + ax_elev.spines["bottom"].set_linewidth(0.8) + ax_elev.spines["left"].set_linewidth(0.8) + + if args.output: + plt.savefig(args.output, dpi=300, facecolor="none") + print(f"Saved: {args.output}") + else: + plt.show() + + +if __name__ == "__main__": + main() diff --git a/historisch/gpx_visualizer.py b/historisch/gpx_visualizer.py new file mode 100755 index 0000000..91baa0e --- /dev/null +++ b/historisch/gpx_visualizer.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Visualize a GPX track: route in upper half, stats in lower half, photo as background.""" + +import argparse +from datetime import timedelta + +import gpxpy +import matplotlib.pyplot as plt +from matplotlib.patches import Rectangle +import numpy as np +from PIL import Image, ImageFilter, ImageOps + + +def parse_gpx(filepath): + with open(filepath) as f: + gpx = gpxpy.parse(f) + return [ + (p.latitude, p.longitude, p.time) + 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 "\u2014" + pace = seconds / dist_km + return f"{int(pace // 60)}:{int(pace % 60):02d} min/km" + + +def main(): + parser = argparse.ArgumentParser(description="GPX track visualizer with photo background") + parser.add_argument("gpx", help="GPX file") + parser.add_argument("photo", help="Background photo") + parser.add_argument("-o", "--output", help="Save to file") + 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]) + + dist = total_distance_km(points) + + if points[0][2] and points[-1][2]: + elapsed = (points[-1][2] - points[0][2]).total_seconds() + time_str = f"{str(timedelta(seconds=int(elapsed)))} h" + pace_str = format_pace(elapsed, dist) + else: + time_str = pace_str = "N/A" + + img = Image.open(args.photo) + transposed = ImageOps.exif_transpose(img) + if transposed is not None: + img = transposed + + img_w, img_h = img.size + + # --- Blurred version for track box background --- + img_blur = img.filter(ImageFilter.GaussianBlur(radius=40)) + + fig = plt.figure(figsize=(9, 16)) + fig.patch.set_facecolor("black") + + # --- Background photo (full figure) --- + ax_bg = fig.add_axes([0, 0, 1, 1], zorder=0) + ax_bg.imshow(img, aspect="auto") + ax_bg.set_axis_off() + + # --- Blurred box behind the track --- + left_fig, bottom_fig, w_fig, h_fig = 0.06, 0.47, 0.88, 0.50 + + # Map figure coords -> image pixel coords + # imshow with origin='upper': figure_y=0 → img row = img_h (bottom) + # figure_y=1 → img row = 0 (top) + col_start = int(left_fig * img_w) + col_end = int((left_fig + w_fig) * img_w) + row_start = int((1 - bottom_fig - h_fig) * img_h) + row_end = int((1 - bottom_fig) * img_h) + + img_blur_arr = np.array(img_blur) + crop_blur = img_blur_arr[row_start:row_end, col_start:col_end] + + ax_blur = fig.add_axes([left_fig, bottom_fig, w_fig, h_fig], zorder=1, facecolor="none") + ax_blur.imshow(crop_blur, aspect="auto") + ax_blur.set_axis_off() + ax_blur.add_patch(Rectangle( + (0, 0), 1, 1, transform=ax_blur.transAxes, + fill=False, edgecolor="white", linewidth=1.5, + )) + + # --- Track with padding inside the box --- + pad_x = w_fig * 0.05 + pad_y = h_fig * 0.05 + ax1 = fig.add_axes( + [left_fig + pad_x, bottom_fig + pad_y, w_fig - 2 * pad_x, h_fig - 2 * pad_y], + zorder=2, facecolor="none", + ) + ax1.set_axis_off() + + ax1.plot(lons, lats, color="#f0e8d8", linewidth=2.5, zorder=5) + ax1.scatter(lons[0], lats[0], c="#90d090", s=50, zorder=6) + ax1.scatter(lons[-1], lats[-1], c="#d09090", s=50, zorder=6) + + mid_lat = np.mean(lats) + ax1.set_aspect(1.0 / np.cos(np.radians(mid_lat))) + + # --- Lower half: stats --- + ax2 = fig.add_axes([0, 0, 1, 1], zorder=3, facecolor="none") + ax2.set_axis_off() + + ax2.text( + 0.5, 0.26, f"{dist:.2f} km", + fontsize=56, fontweight="bold", color="white", + ha="center", va="center", transform=fig.transFigure, + ) + + ax2.text( + 0.5, 0.155, time_str, + fontsize=36, fontweight="bold", color="white", + ha="center", va="center", transform=fig.transFigure, + ) + + ax2.text( + 0.5, 0.06, pace_str, + fontsize=30, fontweight="bold", color="white", + ha="center", va="center", transform=fig.transFigure, + ) + + if args.output: + plt.savefig(args.output, dpi=300, bbox_inches="tight", facecolor="black", pad_inches=0) + else: + plt.show() + + +if __name__ == "__main__": + main() diff --git a/historisch/gpx_visualizer_2.py b/historisch/gpx_visualizer_2.py new file mode 100755 index 0000000..742e29e --- /dev/null +++ b/historisch/gpx_visualizer_2.py @@ -0,0 +1,292 @@ +#!/usr/bin/env python3 +"""Strava-style GPX visualizer: Blur inside frame only, sharp outside.""" + +import argparse +from datetime import datetime, timedelta, timezone +import numpy as np +import matplotlib.pyplot as plt +from PIL import Image, ImageFilter, ImageOps, ImageDraw +import gpxpy + + +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 + mins = int(pace // 60) + secs = int(pace % 60) + return f"{mins}:{secs: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 blur_inside_frame(img, frame_rect, blur_radius=30): + """ + Blur the image inside the frame rectangle only. + frame_rect: (x, y, width, height) in pixel coordinates + """ + x, y, w, h = frame_rect + + # Create mask: white inside frame, black outside + mask = Image.new('L', img.size, 0) + draw = ImageDraw.Draw(mask) + draw.rectangle([x, y, x + w, y + h], fill=255) + + # Blur the entire image + img_blur = img.filter(ImageFilter.GaussianBlur(radius=blur_radius)) + + # Composite: blurred inside frame, sharp outside + img_blur = img_blur.convert('RGBA') + img_sharp = img.convert('RGBA') + + result = Image.composite(img_blur, img_sharp, mask) + + return result + + +def main(): + parser = argparse.ArgumentParser(description="GPX visualizer with frame blur") + parser.add_argument("gpx", help="GPX file") + parser.add_argument("photo", help="Background photo") + parser.add_argument("-o", "--output", help="Save to file") + parser.add_argument("-t", "--title", help="Activity title", default="Morning Run") + parser.add_argument("--max-elev", type=float, help="Override max elevation (meters)") + parser.add_argument("--min-elev", type=float, help="Override min elevation (meters)") + parser.add_argument("--blur", type=float, default=20, help="Blur strength inside frame (default: 20)") + parser.add_argument("--date", help="Date (default: from GPX start time)") + parser.add_argument("--avg-speed", help="Average speed (e.g. 10.5 km/h)") + parser.add_argument("--total-energy", help="Total energy (e.g. 450 kcal)") + parser.add_argument("--energy-cons", help="Energy consumption (e.g. 35 kcal/km)") + args = parser.parse_args() + + # --- Parse GPX --- + 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]) + + # --- Calculate stats --- + 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 = args.date or local_start.strftime("%d.%m.%Y") + else: + elapsed = time_str = pace_str = start_str = end_str = date_str = "N/A" + + # --- Elevation with manual override --- + if args.max_elev is not None: + max_elev = args.max_elev + else: + max_elev = elevations.max() + + if args.min_elev is not None: + min_elev = args.min_elev + else: + min_elev = elevations.min() + + max_str = f"{int(round(max_elev))}m" + min_str = f"{int(round(min_elev))}m" + + print(f"📍 Highest point: {max_str}") + print(f"📍 Lowest point: {min_str}") + + # --- Load and prepare photo --- + img = Image.open(args.photo) + img = ImageOps.exif_transpose(img) or img + + # Resize to 9:16 (Instagram portrait) + target_w, target_h = 1080, 1920 + img_ratio = img.width / img.height + target_ratio = target_w / target_h + + if img_ratio > target_ratio: + new_w = int(img.height * target_ratio) + offset = (img.width - new_w) // 2 + img = img.crop((offset, 0, offset + new_w, img.height)) + else: + new_h = int(img.width / target_ratio) + offset = (img.height - new_h) // 2 + img = img.crop((0, offset, img.width, offset + new_h)) + img = img.resize((target_w, target_h), Image.Resampling.LANCZOS) + + # --- Define frame rectangle (same as matplotlib frame) --- + # Frame in relative coordinates: 0.05, 0.55, 0.90, 0.40 + frame_left = 0.05 + frame_bottom = 0.55 + frame_width = 0.90 + frame_height = 0.40 + + # Convert to pixel coordinates + px_left = int(frame_left * target_w) + px_bottom = int(frame_bottom * target_h) + px_width = int(frame_width * target_w) + px_height = int(frame_height * target_h) + px_top = target_h - px_bottom - px_height + + # --- Apply blur only inside frame --- + img_blurred = blur_inside_frame( + img, + (px_left, px_top, px_width, px_height), + blur_radius=args.blur + ) + + # --- Add dark gradient overlay (Strava style) --- + overlay = Image.new('RGBA', (target_w, target_h), (0, 0, 0, 0)) + draw = ImageDraw.Draw(overlay) + for y in range(int(target_h * 0.4), target_h): + alpha = int(255 * (y - target_h * 0.4) / (target_h * 0.6)) + draw.rectangle([(0, y), (target_w, y+1)], fill=(0, 0, 0, alpha)) + img_blurred = Image.alpha_composite(img_blurred.convert('RGBA'), overlay).convert('RGB') + + # --- Convert PIL image to numpy array for matplotlib --- + img_array = np.array(img_blurred) + + # --- Create matplotlib figure --- + fig = plt.figure(figsize=(9, 16), dpi=120) + + # --- Background photo --- + 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 with frame --- + # Frame with white border + ax_frame = fig.add_axes([frame_left, frame_bottom, frame_width, frame_height], zorder=1) + ax_frame.set_facecolor('none') + ax_frame.set_axis_off() + + # Draw white frame border + from matplotlib.patches import Rectangle + rect = Rectangle( + (0, 0), 1, 1, + transform=ax_frame.transAxes, + fill=False, + edgecolor='white', + linewidth=2.5, + alpha=0.9 + ) + ax_frame.add_patch(rect) + + # Inner track area (with padding inside frame) + pad_x = frame_width * 0.06 + pad_y = frame_height * 0.06 + ax_map = fig.add_axes( + [frame_left + pad_x, frame_bottom + pad_y, + frame_width - 2*pad_x, frame_height - 2*pad_y], + zorder=2 + ) + ax_map.set_facecolor('none') + ax_map.set_axis_off() + + # Plot track with glow effect + ax_map.plot(lons, lats, color='#ff6b35', linewidth=8, alpha=0.2, zorder=1) + ax_map.plot(lons, lats, color='#ff6b35', linewidth=4, alpha=0.5, zorder=2) + ax_map.plot(lons, lats, color='#ff6b35', linewidth=2.5, zorder=3) + + # Start/end markers + ax_map.scatter(lons[0], lats[0], c='#4ade80', s=100, edgecolors='white', linewidth=2.5, zorder=4) + ax_map.scatter(lons[-1], lats[-1], c='#f87171', s=100, edgecolors='white', linewidth=2.5, zorder=4) + + # Aspect ratio for map + mid_lat = np.mean(lats) + ax_map.set_aspect(1.0 / np.cos(np.radians(mid_lat))) + + # Auto-zoom with padding + lat_range = lats.max() - lats.min() + lon_range = lons.max() - lons.min() + padding = max(lat_range, lon_range) * 0.12 + ax_map.set_xlim(lons.min() - padding, lons.max() + padding) + ax_map.set_ylim(lats.min() - padding, lats.max() + padding) + + # --- Stats (lower 55%) --- + avg_speed = args.avg_speed or "\u2014" + energy = args.total_energy or "\u2014" + energy_cons = args.energy_cons or "\u2014" + + stats = [ + ("DATE", date_str), + ("START", start_str), + ("ENDE", end_str), + ("DURATION", time_str), + ("DISTANCE", f"{dist:.2f} km"), + ("PACE", f"{pace_str} min/km"), + ("AVG SPEED", avg_speed), + ("ENERGY", energy), + ("MAX ELEV", max_str), + ("MIN ELEV", min_str), + ("ENERGY CONS", energy_cons), + ] + + cols = [0.125, 0.375, 0.625, 0.875] + rows_y = [0.43, 0.28, 0.13] + + for i, (label, value) in enumerate(stats): + row = i // 4 + col = i % 4 + fig.text(cols[col], rows_y[row] + 0.035, label, + fontsize=10, color='#9ca3af', ha='center', + va='bottom', family='sans-serif', weight='600') + fig.text(cols[col], rows_y[row], value, + fontsize=19, fontweight='bold', color='white', + ha='center', va='bottom', family='sans-serif') + + # --- Save or show --- + if args.output: + plt.savefig(args.output, dpi=300, bbox_inches='tight', + facecolor='black', pad_inches=0) + print(f"✅ Saved: {args.output}") + else: + plt.show() + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/historisch/gpx_visualizer_3.py b/historisch/gpx_visualizer_3.py new file mode 100755 index 0000000..cc7eb6c --- /dev/null +++ b/historisch/gpx_visualizer_3.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""COROS-style GPX visualizer: black background, clean typography, track map + stats.""" + +import argparse +from datetime import datetime, timedelta, timezone + +import gpxpy +import matplotlib.pyplot as plt +import numpy as np +from matplotlib.patches import Rectangle + + +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="COROS-style GPX visualizer") + parser.add_argument("gpx", help="GPX file") + parser.add_argument("-o", "--output", help="Save to file") + parser.add_argument("--max-elev", type=float, help="Override max elevation (m)") + parser.add_argument("--min-elev", 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_elev = args.max_elev if args.max_elev is not None else elevations.max() + min_elev = args.min_elev if args.min_elev is not None else elevations.min() + max_elev_str = f"{int(round(max_elev))}" + min_elev_str = f"{int(round(min_elev))}" + + 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 "" + + BG = "#090909" + FG = "#ffffff" + MUTED = "#A0A0A0" + TRACK_COLOR = "#ff6b35" + + fig = plt.figure(figsize=(9, 16), dpi=120) + fig.patch.set_facecolor(BG) + + # --- Track map --- + frame_left, frame_bottom, frame_width, frame_height = 0.05, 0.55, 0.90, 0.40 + + ax_frame = fig.add_axes([frame_left, frame_bottom, frame_width, frame_height], zorder=1) + ax_frame.set_facecolor(BG) + ax_frame.set_axis_off() + ax_frame.add_patch(Rectangle( + (0, 0), 1, 1, transform=ax_frame.transAxes, + fill=False, edgecolor=MUTED, linewidth=1.5, + )) + + pad_x = frame_width * 0.06 + pad_y = frame_height * 0.06 + ax_map = fig.add_axes( + [frame_left + pad_x, frame_bottom + pad_y, + frame_width - 2 * pad_x, frame_height - 2 * pad_y], + zorder=2, facecolor=BG, + ) + ax_map.set_axis_off() + + ax_map.plot(lons, lats, color=TRACK_COLOR, linewidth=8, alpha=0.15, zorder=1) + ax_map.plot(lons, lats, color=TRACK_COLOR, linewidth=4, alpha=0.4, zorder=2) + ax_map.plot(lons, lats, color=TRACK_COLOR, linewidth=2.5, zorder=3) + ax_map.scatter(lons[0], lats[0], c="#4ade80", s=100, edgecolors=BG, linewidth=2.5, zorder=4) + ax_map.scatter(lons[-1], lats[-1], c="#f87171", s=100, edgecolors=BG, linewidth=2.5, zorder=4) + + 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.12 + ax_map.set_xlim(lons.min() - padding, lons.max() + padding) + ax_map.set_ylim(lats.min() - padding, lats.max() + padding) + + # --- COROS-style stats -------------------------------------------------- + + def hero_text(fig, x, y, value, unit, size_val, size_unit): + fig.text(x, y, value, fontsize=size_val, fontweight="bold", color=FG, + ha="left", va="bottom", family="sans-serif") + fig.text( + x + len(value) * size_val * 0.0068, y + size_val * 0.006, + unit, fontsize=size_unit, color=MUTED, + ha="left", va="bottom", family="sans-serif", + ) + + def tile_text(fig, x, y, value, unit, label): + fig.text(x, y, value, fontsize=22, fontweight="bold", color=FG, + ha="center", va="bottom", family="sans-serif") + if unit: + fig.text(x + len(value) * 0.016, y + 0.003, + unit, fontsize=13, color=MUTED, + ha="left", va="bottom", family="sans-serif") + fig.text(x, y - 0.030, label, fontsize=9, color=MUTED, + ha="center", va="bottom", family="sans-serif", weight="600") + + hero_text(fig, 0.08, 0.48, f"{dist:.2f}", "km", 72, 22) + fig.text(0.08, 0.445, "Distanz", fontsize=13, color=MUTED, + ha="left", va="bottom", family="sans-serif", weight="600") + + tiles = [ + ("PACE", pace_str, " /km"), + ("DURATION", time_str, ""), + ("AVG SPEED", avg_speed_str, avg_speed_unit), + ("MAX ELEV", max_elev_str, " m"), + ("MIN ELEV", min_elev_str, " m"), + ("ENERGY", energy_str, energy_unit), + ("START", start_str, ""), + ("ENDE", end_str, ""), + ("ENERGY CONS", energy_cons_str, energy_cons_unit), + ] + + cols = [0.17, 0.50, 0.83] + rows_y = [0.36, 0.23, 0.10] + + 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, bbox_inches="tight", + facecolor=BG, pad_inches=0) + print(f"Saved: {args.output}") + else: + plt.show() + + +if __name__ == "__main__": + main() diff --git a/historisch/gpx_visualizer_3_coros.py b/historisch/gpx_visualizer_3_coros.py new file mode 100755 index 0000000..7aa760b --- /dev/null +++ b/historisch/gpx_visualizer_3_coros.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +"""COROS-style GPX visualizer: black background, clean typography, track map + stats.""" + +import argparse +from datetime import datetime, timedelta, timezone + +import gpxpy +import matplotlib.pyplot as plt +import numpy as np +from matplotlib.patches import Rectangle +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 = 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="COROS-style GPX visualizer") + parser.add_argument("gpx", help="GPX file") + parser.add_argument("-o", "--output", help="Save to file") + parser.add_argument("--max-elev", type=float, help="Override max elevation (m)") + parser.add_argument("--min-elev", 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_elev = args.max_elev if args.max_elev is not None else elevations.max() + min_elev = args.min_elev if args.min_elev is not None else elevations.min() + max_elev_str = f"{int(round(max_elev))}" + min_elev_str = f"{int(round(min_elev))}" + + 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 "" + + BG = "#090909" + FG = "#ffffff" + MUTED = "#A0A0A0" + TRACK_COLOR = "#ff6b35" + + fig = plt.figure(figsize=(9, 16), dpi=120) + fig.patch.set_facecolor(BG) + + # --- Track map --- + frame_left, frame_bottom, frame_width, frame_height = 0.05, 0.55, 0.90, 0.40 + + ax_frame = fig.add_axes([frame_left, frame_bottom, frame_width, frame_height], zorder=1) + ax_frame.set_facecolor(BG) + ax_frame.set_axis_off() + ax_frame.add_patch(Rectangle( + (0, 0), 1, 1, transform=ax_frame.transAxes, + fill=False, edgecolor=MUTED, linewidth=1.5, + )) + + pad_x = frame_width * 0.06 + pad_y = frame_height * 0.06 + ax_map = fig.add_axes( + [frame_left + pad_x, frame_bottom + pad_y, + frame_width - 2 * pad_x, frame_height - 2 * pad_y], + zorder=2, facecolor=BG, + ) + ax_map.set_axis_off() + + ax_map.plot(lons, lats, color=TRACK_COLOR, linewidth=8, alpha=0.15, zorder=1) + ax_map.plot(lons, lats, color=TRACK_COLOR, linewidth=4, alpha=0.4, zorder=2) + ax_map.plot(lons, lats, color=TRACK_COLOR, linewidth=2.5, zorder=3) + ax_map.scatter(lons[0], lats[0], c="#4ade80", s=100, edgecolors=BG, linewidth=2.5, zorder=4) + ax_map.scatter(lons[-1], lats[-1], c="#f87171", s=100, edgecolors=BG, linewidth=2.5, zorder=4) + + 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.12 + ax_map.set_xlim(lons.min() - padding, lons.max() + padding) + ax_map.set_ylim(lats.min() - padding, lats.max() + padding) + + # --- COROS-style stats -------------------------------------------------- + + from matplotlib.offsetbox import AnchoredOffsetbox, HPacker, TextArea + + def hero_text(fig, x, y, value, unit): + num=TextArea(value,textprops=dict(color=FG,fontsize=64,fontweight='bold')) + unt=TextArea(" "+unit,textprops=dict(color=FG,fontsize=24)) + pack=HPacker(children=[num,unt],align='baseline',pad=0,sep=2) + box=AnchoredOffsetbox(loc='lower left',child=pack,frameon=False, + bbox_to_anchor=(x,y),bbox_transform=fig.transFigure,borderpad=0,pad=0) + fig.add_artist(box) + fig.text(x,y-0.035,"Distanz",fontsize=14,color=MUTED,ha='left') + +def tile_text(fig, x, y, value, unit, label): + + value_box = TextArea( + value, + textprops=dict( + color=FG, + fontsize=25, + fontweight="bold", + family="sans-serif", + ), + ) + + if unit: + unit_box = TextArea( + unit, + textprops=dict( + color=MUTED, + fontsize=13, + family="sans-serif", + ), + ) + + packed = HPacker( + children=[value_box, unit_box], + align="baseline", + sep=2, + pad=0, + ) + else: + packed = value_box + + box = AnchoredOffsetbox( + loc="lower left", + child=packed, + frameon=False, + bbox_to_anchor=(x, y), + bbox_transform=fig.transFigure, + borderpad=0, + pad=0, + ) + + fig.add_artist(box) + + fig.text( + x, + y - 0.022, + label, + fontsize=11, + color=MUTED, + ha="left", + ) + + hero_text(fig,0.07,0.47,f"{dist:.2f}","km") + + tiles = [ + ("PACE", pace_str, " /km"), + ("DURATION", time_str, ""), + ("AVG SPEED", avg_speed_str, avg_speed_unit), + ("MAX ELEV", max_elev_str, " m"), + ("MIN ELEV", min_elev_str, " m"), + ("ENERGY", energy_str, energy_unit), + ("START", start_str, ""), + ("ENDE", end_str, ""), + ("ENERGY CONS", energy_cons_str, energy_cons_unit), + ] + + cols = [0.07, 0.38, 0.69] + rows_y = [0.34, 0.22, 0.10] + + 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, bbox_inches="tight", + facecolor=BG, pad_inches=0) + print(f"Saved: {args.output}") + else: + plt.show() + + +if __name__ == "__main__": + main() diff --git a/historisch/gpx_visualizer_3_coros_darkmap.py b/historisch/gpx_visualizer_3_coros_darkmap.py new file mode 100755 index 0000000..4b70742 --- /dev/null +++ b/historisch/gpx_visualizer_3_coros_darkmap.py @@ -0,0 +1,218 @@ +#!/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 +import contextily as ctx +from matplotlib.colors import Normalize +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 = 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="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" + MUTED = "#A0A0A0" + 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() + try: + ctx.add_basemap(ax_map, crs="EPSG:4326", source=ctx.providers.CartoDB.DarkMatterNoLabels, attribution=False) + except Exception: + pass + + # 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) + + 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) + + # --- 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=MUTED, 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=MUTED, 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=MUTED, ha="left") + + hero_text(fig, 0.07, 0.465, f"{dist:.2f}", "km") + + tiles = [ + ("PACE", pace_str, " /km"), + ("DURATION", time_str, ""), + ("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() diff --git a/historisch/gpx_visualizer_3_coros_fixed.py b/historisch/gpx_visualizer_3_coros_fixed.py new file mode 100755 index 0000000..7b0ba29 --- /dev/null +++ b/historisch/gpx_visualizer_3_coros_fixed.py @@ -0,0 +1,213 @@ +#!/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.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 = 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="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" + MUTED = "#A0A0A0" + 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=MUTED, 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=MUTED, 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=MUTED, ha="left") + + hero_text(fig, 0.07, 0.465, f"{dist:.2f}", "km") + + tiles = [ + ("PACE", pace_str, " /km"), + ("DURATION", time_str, ""), + ("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() diff --git a/historisch/gpx_visualizer_3_coros_folium.py b/historisch/gpx_visualizer_3_coros_folium.py new file mode 100755 index 0000000..4618e00 --- /dev/null +++ b/historisch/gpx_visualizer_3_coros_folium.py @@ -0,0 +1,234 @@ +#!/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 folium +from folium import PolyLine +from PIL import Image +import io, os +import numpy as np +from matplotlib.colors import Normalize +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 = 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="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" + MUTED = "#A0A0A0" + 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() + + # 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) + + 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) + + + # Render dark folium map (optional) + try: + m=folium.Map(location=[float(np.mean(lats)),float(np.mean(lons))], + zoom_start=13,tiles=None,control_scale=False) + folium.TileLayer( + tiles="https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png", + attr="CartoDB").add_to(m) + PolyLine(list(zip(lats,lons)),color="#bb86fc",weight=5).add_to(m) + folium.CircleMarker((lats[0],lons[0]),radius=6,color="#ce93d8",fill=True).add_to(m) + folium.CircleMarker((lats[-1],lons[-1]),radius=6,color="#4a148c",fill=True).add_to(m) + html=args.output+"_map.html" if args.output else "map.html" + m.save(html) + print("Interactive map saved:",html) + except Exception as e: + print("Folium map failed:",e) + + # --- 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=MUTED, 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=MUTED, 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=MUTED, ha="left") + + hero_text(fig, 0.07, 0.465, f"{dist:.2f}", "km") + + tiles = [ + ("PACE", pace_str, " /km"), + ("DURATION", time_str, ""), + ("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() diff --git a/historisch/gpx_visualizer_v4.py b/historisch/gpx_visualizer_v4.py new file mode 100755 index 0000000..0338b1d --- /dev/null +++ b/historisch/gpx_visualizer_v4.py @@ -0,0 +1,221 @@ +#!/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 = 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="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" + MUTED = "#A0A0A0" + 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=MUTED, 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=MUTED, 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=MUTED, ha="left") + + hero_text(fig, 0.07, 0.45, f"{dist:.2f}", "km") + + # Separator line (spanning width of the 3 tile columns) + fig.add_artist(Line2D( + [0.04, 0.96], [0.395, 0.395], + color=MUTED, 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), + ("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() diff --git a/historisch/gpx_visualizer_v5.py b/historisch/gpx_visualizer_v5.py new file mode 100755 index 0000000..6b7f377 --- /dev/null +++ b/historisch/gpx_visualizer_v5.py @@ -0,0 +1,218 @@ +#!/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() diff --git a/historisch/gpx_visualizer_v6.py b/historisch/gpx_visualizer_v6.py new file mode 100755 index 0000000..1ad0f6a --- /dev/null +++ b/historisch/gpx_visualizer_v6.py @@ -0,0 +1,257 @@ +#!/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", help="GPX file") + parser.add_argument("photo", 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("--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/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_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 = 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" + + 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/km" 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 + 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((38 + 77 * 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.25, 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", 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() diff --git a/historisch/gpx_visualizer_v7.py b/historisch/gpx_visualizer_v7.py new file mode 100755 index 0000000..9904802 --- /dev/null +++ b/historisch/gpx_visualizer_v7.py @@ -0,0 +1,260 @@ +#!/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", help="GPX file") + parser.add_argument("photo", 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/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_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/km" 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 + 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((102 + 153 * 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() diff --git a/requirements.txt b/requirements.txt new file mode 100755 index 0000000..ae6d2de --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +gpxpy>=1.5 +matplotlib>=3.6 +numpy>=1.23 +pillow>=9.1