forked from tkrajina/gpxpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpxinfo
executable file
·196 lines (162 loc) · 7.25 KB
/
gpxinfo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/usr/bin/env python
"""
Command line utility to extract basic statistics from gpx file(s)
"""
import pdb
import sys as mod_sys
import logging as mod_logging
import math as mod_math
import argparse as mod_argparse
import gpxpy as mod_gpxpy
import gpxpy.gpx as mod_gpx
from typing import *
import json
KM_TO_MILES = 0.621371
M_TO_FEET = 3.28084
def format_time(time_s: float) -> str:
if not time_s:
return 'n/a'
elif args.seconds:
return str(int(time_s))
else:
mins, secs = divmod(int(time_s), 60)
hrs, mins = divmod(mins, 60)
return f"{hrs:02d}:{mins:02d}:{secs:02d}"
def format_long_length(length: float) -> str:
if args.miles:
return f'{length / 1000. * KM_TO_MILES:.3f}miles'
else:
return f'{length / 1000.:.3f}km'
def format_short_length(length: float) -> str:
if args.miles:
return f'{length * M_TO_FEET:.2f}ft'
else:
return f'{length:.2f}m'
def format_speed(speed: float) -> str:
if not speed:
speed = 0
if args.miles:
return f'{speed * KM_TO_MILES * 3600. / 1000.:.2f}mph'
else:
return f'{speed:.2f}m/s = {speed * 3600. / 1000.:.2f}km/h'
def print_gpx_part_info(gpx_part: Union[mod_gpx.GPX, mod_gpx.GPXTrack, mod_gpx.GPXTrackSegment],
indentation: str=' ', direct_print=False) :
"""
gpx_part may be a track or segment.
"""
length_2d = gpx_part.length_2d()
length_3d = gpx_part.length_3d()
out_object = {}
out_object["Length 2D"] = format_long_length(length_2d or 0)
out_object["Length 3D"] = format_long_length(length_3d)
if direct_print:
print(f'{indentation}Length 2D: {format_long_length(length_2d or 0)}')
print(f'{indentation}Length 3D: {format_long_length(length_3d)}')
moving_data = gpx_part.get_moving_data()
raw_moving_data = gpx_part.get_moving_data(raw=True)
if moving_data:
out_object["Moving time"] = format_time(moving_data.moving_time)
out_object["Stopped time"] = format_time(moving_data.stopped_time)
out_object["Max speed"] = f'{format_speed(moving_data.max_speed)} (raw: {format_speed(raw_moving_data.max_speed) if raw_moving_data else "?"})'
out_object["Avg speed"] = format_speed(moving_data.moving_distance / moving_data.moving_time) if moving_data.moving_time > 0 else "?"
if direct_print:
print(f'{indentation}Moving time: {format_time(moving_data.moving_time)}')
print(f'{indentation}Stopped time: {format_time(moving_data.stopped_time)}')
print(f'{indentation}Max speed: {format_speed(moving_data.max_speed)} (raw: {format_speed(raw_moving_data.max_speed) if raw_moving_data else "?"})')
print(f'{indentation}Avg speed: {format_speed(moving_data.moving_distance / moving_data.moving_time) if moving_data.moving_time > 0 else "?"}')
uphill, downhill = gpx_part.get_uphill_downhill()
out_object["Total uphill"] = format_short_length(uphill)
out_object["Total downhill"] = format_short_length(downhill)
if direct_print:
print(f'{indentation}Total uphill: {format_short_length(uphill)}')
print(f'{indentation}Total downhill: {format_short_length(downhill)}')
start_time, end_time = gpx_part.get_time_bounds()
if start_time and end_time:
out_object["Started"] = start_time.strftime("%m/%d/%Y, %H:%M:%S")
out_object["Ended"] = end_time.strftime("%m/%d/%Y, %H:%M:%S")
if direct_print:
print(f'{indentation}Started: {start_time}')
print(f'{indentation}Ended: {end_time}')
points_no = len(list(gpx_part.walk(only_points=True)))
out_object["Points"] = points_no
if direct_print:
print(f'{indentation}Points: {points_no}')
if points_no > 0:
distances: List[float] = []
previous_point = None
for point in gpx_part.walk(only_points=True):
if previous_point:
distance = point.distance_2d(previous_point)
distances.append(distance)
previous_point = point
out_object["Avg distance between points"] = format_short_length(sum(distances) / len(list(gpx_part.walk())))
if direct_print:
print(f'{indentation}Avg distance between points: {format_short_length(sum(distances) / len(list(gpx_part.walk())))}')
if direct_print:
print('')
return out_object
def print_gpx_info(gpx: mod_gpx.GPX, gpx_file: str, direct_print=False) -> None:
out_obj = {}
# out_obj["File"] = gpx_file
if direct_print:
print(f'File: {gpx_file}')
out_obj["File Properties"] = {}
out_obj["File Properties"]["name"] = gpx.name
out_obj["File Properties"]["description"] = gpx.description
out_obj["File Properties"]["Author"] = gpx.author_name
out_obj["File Properties"]["Email"] = gpx.author_email
if direct_print:
if gpx.name:
print(f' GPX name: {gpx.name}')
if gpx.description:
print(f' GPX description: {gpx.description}')
if gpx.author_name:
print(f' Author: {gpx.author_name}')
if gpx.author_email:
print(f' Email: {gpx.author_email}')
out_obj['part info'] = print_gpx_part_info(gpx, direct_print=direct_print);
out_obj["tracks_segments"] = []
for track_no, track in enumerate(gpx.tracks):
out_obj["tracks_segments"].append([])
for segment_no, segment in enumerate(track.segments):
part_info = print_gpx_part_info(segment, direct_print=direct_print)
# seg = f'Track #{track_no}, Segment #{segment_no}'
out_obj["tracks_segments"][track_no].append(part_info)
if direct_print:
print(f' Track #{track_no}, Segment #{segment_no}')
print_gpx_part_info(segment, indentation=' ')
return out_obj
def run(gpx_files: List[str], direct_print = False) -> None:
if not gpx_files:
print('No GPX files given')
mod_sys.exit(1)
out_obj = {}
for gpx_file in gpx_files:
try:
gpx = mod_gpxpy.parse(open(gpx_file))
info = print_gpx_info(gpx, gpx_file, direct_print=direct_print)
out_obj[gpx_file] = info
except Exception as e:
mod_logging.exception(e)
out_obj[gpx_file] = 0
continue
direct_print(f'Error processing {gpx_file}')
mod_sys.exit(1)
if not direct_print:
print(json.dumps(out_obj), end='')
def make_parser() -> mod_argparse.ArgumentParser:
parser = mod_argparse.ArgumentParser(usage='%(prog)s [-s] [-m] [-d] [file ...]',
description='Command line utility to extract basic statistics from gpx file(s)')
parser.add_argument('-s', '--seconds', action='store_true',
help='print times as N seconds, rather than HH:MM:SS')
parser.add_argument('-m', '--miles', action='store_true',
help='print distances and speeds using miles and feet')
parser.add_argument('-d', '--debug', action='store_true',
help='show detailed logging')
return parser
if __name__ == '__main__':
args, gpx_files = make_parser().parse_known_args()
if args.debug:
mod_logging.basicConfig(level=mod_logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
run(gpx_files)