Files
2026-11-22 19:34:02 +01:00

292 lines
9.6 KiB
Python
Executable File

#!/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()