initial release
This commit is contained in:
1 parent
7fce668291
commit
179b2429cf
16 files changed
+3261
-1
No files matched your search
Executable
+159
@@ -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()
|
||||
Executable
+292
@@ -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()
|
||||
Executable
+202
@@ -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()
|
||||
Executable
+245
@@ -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()
|
||||
Executable
+218
@@ -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()
|
||||
Executable
+213
@@ -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()
|
||||
Executable
+234
@@ -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()
|
||||
Executable
+221
@@ -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()
|
||||
Executable
+218
@@ -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()
|
||||
Executable
+257
@@ -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()
|
||||
Executable
+260
@@ -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()
|
||||
Reference in new issue
Block a user