-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvprune-replit.py
1355 lines (1113 loc) · 55.2 KB
/
vprune-replit.py
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""VPRUNE.EXE/VPRUNE.PY HELP FILE
VPrune prunes and splits .tcx files to make them more compatible with Lezyne and other GPS devices that are unable to handle large and complex files.
To run on REPL.IT:
0. FORK this repl (button at the top of the repl.it screen). Unfortunately, only one person at a time can use a given repl.it project. But if you fork it, making your own copy, you can save that URL and come back to use the forked version as often as you wish.
=====> After forking, you will have to re-load the "fork" web page (otherwise the web browser pane is still stuck on the original version.)
1. On your forked copy of the repl, Click on "input.tcx" and copy/paste the contents of your .tcx file in place of what is there. (Alternatively: Click "add file" and upload your .tcx, or drag & drop it onto the "Files" pane.)
2. Click repl.it's "Start" button.
3. In the Browser screen, choose your options and the filename of the document to process (input.tcx by default). Click "Process File". (You can click "Open in a new window" to see the screen better.)
4. "Confirm document" - check your options and click confirm. If the white part of the browser screen remains blank, you might need to click the refresh button.
5. "Processing file" screen - Again, click the refresh button as needed. When complete, the button at the bottom will read "Finished"
6. Click "Finish", the program will exit.
7. As soon as the program exits (but not before!) your files should/will appear on the left of REPL.IT in folder "TCXResults"
8. You can copy & paste the resulting files into a text edit OR download all files as a zip in the files pane (look for the 'three dots' - you may have to widen the pane - then "download as zip")
9. Both the tools used to run the program are a bit persnickety (PySimpleGUIWeb persnickety about running consistently; repl.it persnickety about putting the files into your directory). You may need to run it a few times to get satisfactory results.
GENERAL VPRUNE DIRECTIONS (not repl.it specific)
VPrune can be run from the command line OR as a windows program (Windows) OR via web interface (Android)
- If you simply start (or double click on) vprune.py/vprune.exe, a window will pop up - you can choose the file to process and other options
--> If using the web version, a web window should open; if not open a browser on your device and navigate to localhost:8081 or 127.0.0.1:8081
- If you start vprune.exe from the command line with arguments as described below, it will run as a command line program
- The text below describes command line operation but you can choose all the same options via the window
WHAT VPRUNE DOES AND WHY
A .tcx file consists of a long list of Trackpoints and CoursePoints. The files are plain text--open one up in a text editor and take a look.
Trackpoints are the most numerous. They are used to draw the detailed route. There are many fewer CoursePoints, because they are only the places where you get the "turn-by-turn" instructions.
With too few Trackpoints the route becomes "jaggy" and doesn't follow roads or trails exactly. With too many Trackpoints the file may be too large to upload to your GPS device.
In remove Trackpoints, vprune simply deletes points randomly. It does not attempt to use an optimizing algorithm. This seems to work well enough with RideWithGPS style .tcx files--as long as you don't remove too many points.
Every CoursePoint (ie, point with turn-by-turn direction) must have an corresponding Trackpoint. So Trackpoints that correspond to spots with a turn-by-turn direction are never removed.
Via the entrt screen or command line, you can specify --percent to remove a percentage of Trackpoints. So, for example, --percent 100 will leave all Trackpoints in place, while --percent 0 will remove all Trackpoints except those corresponding to a turn (remember, those can't be removed or the file won't work any more).
VPrune can also, optionally, split the file into several segments. This allows the resulting files to be smaller and have better fidelity on the map.
Splitting the route also splits CoursePoints (with turn-by-turn directions) appropriately among the files, meaning that each of these files has far fewer CoursePoints than the original. Many GPS devices have trouble processing .tcx files with too many CoursePoints, so splitting the file into several smaller files is the best way to preserve the turn-by-turn instructions while still allowing these files to work correctly with these devices.
When the file is split into several files, each file overlaps the other at exactly one CoursePoint/turn-by-turn direction point. So when you reach the end of one file, you can simply load the next file to continue from that same point.
By default, output files are named vp_INPUTFILE (if one outputfile) or vp_1_INPUTFILE, vp_2_INPUTFILE, etc, if more than one. You can change the file prefix as desired.
VPrune can also, optionally, clean CoursePoint Notes and/or Generic CoursePoints. This reduces file size, and these features may cause problems with some GPS devices or simply be useless (never displayed) in others.
VPrune is specifically designed process .tcx files created with RideWithGPS and create .tcx files that will work with Lezyne GPS devices, which have problems when .tcx files are too large or have too many turns. It may be useful for .tcx files created by other sources and for other GPS devices as well.
VPrune INPUTFILE - ie, run with default settings, will clean Notes from entries, split the files, and eliminate Trackpoints as needed to create a series of files that should upload/run OK with a Lezyne GPS device.
INSTALLING PYTHON AND VPRUNE.PY UNDER PYTHON
VPrune will run on most any platform that Python can run on. That includes Windows, Linux/Unix, MacOS, and some others (maybe iOS with Pythonista--at least as a command line app). Installation steps:
1. Install Python 3 (3.7+ preferred) from https://www.python.org/downloads/
2. After a fresh Python install, you need to install a few needed libraries. At the command line or console enter these commands in sequence:
pip install docopt
pip install lxml
pip install pysimplegui
pip install pysimpleguiweb
The first two libraries are needed for all versions. The second two are needed to run the windowed GUI and web GUI versions.
3. Depending on your operating system, you may be able to double-click vprune.py to run it (windows mode). Otherwise at the command line or console type:
python vprune.py
Depending on your system setup, you may need to use one of these commands instead:
python 3 vprune.py
py3 vprune.py
py vprune.py
4. With those commands, VPrune will run in the windowed version. If you would rather use the command line/console version, just add the command line parameters described below. Example:
vprune.py mygpsfile.tcx
vprune.py --help
Depending on your system, you may need to add 'python' to the start of the commands, like this:
python vprune.py mygpsfile.tcx
python vprune.py --help
COMMAND LINE USAGE EXAMPLES:
vprune routefile.tcx
vprune --maxturns 100 --maxpoints 1000 --cleancourse --nocleannotes routefile.tcx
vprune --maxturns 60 --maxpoints 400 --prefix new_ routefile.tcx
vprune --split 6 --maxpoints 750 routefile.tcx
vprune --percent 50 routefile.tcx
Usage:
vprune [options] [INPUTFILE]
vprune -h
vprune --help
Options:
INPUTFILE .TCX input filename. If none supplied on command line a GUI window will pop up to ask you to find the file.
-h --help Show this.
--maxturns <max # of turns/CoursePoints before file is split> [Default: --maxturns 80]
--split <# of files to split into> [Specify --maxturns OR --split, not both]
--maxpoints <# of Trackpoints in each output file> [Default: --maxpoints 500]
--percent <pct 0-100 of Trackpoints to retain> [Specify --maxpoints OR --percent, not both]
--cleancourse Strip all Generic CoursePoints. [Default: No cleancourse]
--nocleannotes Do not eliminate all Notes in CoursePoints. [Default: Eliminate all Notes]
--trimnotes Trim notes to 32 characters and remove any potentially troublesome characters (also forces --nocleannotes)
--prefix <string> Prefix output files with this string [Default: vp_]
"""
#vprune.py [--maxturns=<num_turns per file, will split if greater, <= 0, default 150 >][--maxpoints=<num_points <0, default 2000 >] [--percent=<pct 0-100>] [--clean=<BOOL>] INPUTFILE
#from __future__ import print_function
import re, sys, os, glob, random, datetime, math, copy, html, time, platform #, pytz
from docopt import docopt
from io import StringIO
try:
import tkinter
#print("tkinter available, can run windowed GUI")
weborgui='gui'
except ImportError:
#print("tkinter not available, can run web GUI but not windowed GUI")
weborgui='web'
#will run as gui on Windows or other platforms and web on android
#will run as command line prg on either one
#weborgui = 'gui'
#platform=platform.system()
#if platform=='android':
# weborgui = 'web'
weborgui = 'web' #use to force web or gui for testing purposes or if desired on your system
#print(platform, weborgui)
#print("%x" % sys.maxsize, sys.maxsize > 2**32)
#repl.it
print()
print ("*******************************************")
print()
print ("Remember to FORK this repl before running.")
print()
print ("Then *reload* the browser page with the fork, then run the fork.")
print()
print("Detailed instructions @ the top of main.py")
print()
print ("*******************************************")
print()
if (sys.maxsize > 2**32):
print ("64 bit Python")
else:
print ("32 bit Python")
if weborgui=='web':
import PySimpleGUIWeb as sg
else:
import PySimpleGUI as sg
try:
from lxml import etree
#print("running with lxml.etree")
except ImportError:
print("couldn't import lxml, exiting")
exit()
ns1 = 'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'
ns2 = 'http://www.garmin.com/xmlschemas/ActivityExtension/v2'
prefix = 'vp_'
savedir = 'TCXResults'
gui = False
#This is an attempt to get various vprunes running in the same machine to use different web ports, so that different people
#could connect to each one
#However, it doesn't work on repl.it as repl.it intercepts the port and always sends to port 80 regardless of what you do.
webport = random.randint(49152, 65535) #replit
#webport = 8081 #replit
print ("Running on HTTP port", webport) #replit
VPweb_multiple_instance = False
num_courses = 0
num_tracks = 0
num_trackpoints = 0
num_coursepoints = 0
orig_total_courses = 0
orig_total_tracks = 0
orig_total_trackpoints = 0
orig_total_coursepoints = 0
progress_window = []
progress_bar = []
progress = 0
#with open('test.txt','w') as f: # this is how you write to files
# f.write('Hello')
# f.close()
def initVals():
global num_courses,num_tracks, num_trackpoints, num_coursepoints, orig_total_courses, orig_total_tracks, orig_total_trackpoints, orig_total_coursepoints, progress_window, progress_bar, progress
num_courses = 0
num_tracks = 0
num_trackpoints = 0
num_coursepoints = 0
orig_total_courses = 0
orig_total_tracks = 0
orig_total_trackpoints = 0
orig_total_coursepoints = 0
progress_window = []
progress_bar = []
progress = 0
initVals()
def isInt(s):
try:
return float(str(s)).is_integer()
except:
return False
def checkbox_to_radio(window, event, values, delimiter='_'):
"""
Make a sequence of checkboxes act like linked radio buttons, in PySimpleGUI
You include a unique portion at the beginning of the key for the linked checkboxes, ending with a delimiter
So keys 1_checkup 1_checkdown 1_checkacross 1_checkover are all linked, as are 2_checkin 2_checkout
They are like radio buttons, so only one can be on at a time and you can't turn one off by clicking it, but by another choice
make sure one choice is clicked to start for best results.
This is necessary because radio buttons are not working in PySimpleGUIWeb, for now
"""
if event is None:
return
#Little kludge here
if event=='percent':
window.FindElement('2_usepercent').Update(True)
window.FindElement('2_usemaxpoints').Update(False)
return
if event=='maxpoints':
window.FindElement('2_usepercent').Update(False)
window.FindElement('2_usemaxpoints').Update(True)
return
if event=='maxturns':
window.FindElement('1_usemaxturns').Update(True)
window.FindElement('1_usesplit').Update(False)
return
if event=='split':
window.FindElement('1_usemaxturns').Update(False)
window.FindElement('1_usesplit').Update(True)
return
del_pos = (event.find('_'))
if del_pos == -1:
return
if (values[event] == False):
window.FindElement(event).Update(True) # can't turn an element off by clicking it (they're radios)
return
for value in values:
if event == value:
continue
vdel_pos = (event.find('_'))
if vdel_pos < 0:
continue
#print (event[:del_pos+1], value[:vdel_pos+1])
if event[:del_pos+1] == value[:vdel_pos+1]:
try:
window.FindElement(value).Update(False)
except:
print (value, "couldn't find or update element")
# from https://stackoverflow.com/questions/26523929/add-update-elements-at-position-using-lxml-python
def upsert_entry(parent, index, insertdict, begindict, enddict):
entry_template = """
<Lap>
<TotalTimeSeconds>{0}</TotalTimeSeconds>
<DistanceMeters>{1}</DistanceMeters>
<BeginPosition>
<LatitudeDegrees>{2}</LatitudeDegrees>
<LongitudeDegrees>{3}</LongitudeDegrees>
</BeginPosition>
<EndPosition>
<LatitudeDegrees>{4}</LatitudeDegrees>
<LongitudeDegrees>{5}</LongitudeDegrees>
</EndPosition>
<Intensity>Active</Intensity>
</Lap>
"""
entries = parent.findall('./{%s}Lap'%ns1)
#entries = parent.findall('./Lap')
# update if entry already exists.
#print(entries)
if index <= len(entries):
entry = entries[index - 1]
#for child in entry.iter():
#print (type(child))
#print(child.tag, child.text, child.tail)
#print(entry.text)
#print(entry.tag)
for key in insertdict:
#print (key)
if (entry.find(key) is not None):
entry.find(key).text = insertdict[key]
#print ("Inserted into Lap: Key", key, "Value", insertdict[key])
#else:
#print ("Key", key, "not found")
# insert at the end (only if the index is exactly after the last entry)
#elif index == len(entries) + 1:
#entry = etree.fromstring(entry_template.format(insertdict['TotalTimeSeconds'], insertdict['DistanceMeters'],begindict['LatitudeDegrees'],begindict['LongitudeDegrees'],enddict['LatitudeDegrees'],enddict['LongitudeDegrees']))
#parent.append(entry)
#print ("no match found")
def s2p(speed, lever=5):
assert (lever > 0 and lever < 11)
# The array factor contains power at 60km/h at lever positions 1 to 10
factor1 = [200.0,281.0,366.0,447.0,532.0,614.0,702.0,787.0,868.0,953.0]
# The array factor contains power at 29.9km/h at lever positions 1 to 10
factor2 = [85.0,121.0,162.0,196.0,236.0,272.0,307.0,347.0,382.0,417.0]
w = int(round(factor2[lever-1]+(speed-29.9)/30.1*(factor1[lever-1]-factor2[lever-1])))
return w if w > 0 else 0
def check_time(track, time, times):
#print (time)
#print ('\n')
#print (times)
#print ('\n')
if (time in times):
#print ('must keep \n')
return 'must keep'
return 'may eliminate'
def process_trackpoint(track, trackpoint, percent, times, startT, endT, first_distance, first):
global num_trackpoints
returndict={}
for child in trackpoint:
#print ("child")
for elem in child.iter():
#print ("elem")
#print (elem.tag)
if (elem.tag == '{%s}Time'%ns1):
time=elem.text
returndict['{%s}Time'%ns1] = time
#print (time)
courseT = datetime.datetime.strptime(time, "%Y-%m-%dT%H:%M:%SZ")
if (courseT < startT or courseT > endT):
trackpoint.getparent().remove(trackpoint)
return {} # return empty dictionary if we're deleting this point
elif ((random.randint(1,100) > percent) and (check_time(track, time, times) == "may eliminate")):
trackpoint.getparent().remove(trackpoint)
return {} # return empty dictionary if we're deleting this point
else:
num_trackpoints += 1
#if ( elem.tag == '{%s}AltitudeMeters'%ns1 or elem.tag == '{%s}DistanceMeters'%ns1 ):
if (elem.tag == '{%s}DistanceMeters'%ns1):
returndict['{%s}DistanceMeters'%ns1] = elem.text
if (first):
elem.text = "0"
else:
elem.text = str(round(float(elem.text)-float(first_distance),2))
#print (elem.text)
#trackpoint.remove(elem)
if (elem.tag == '{%s}LatitudeDegrees'%ns1):
returndict['{%s}LatitudeDegrees'%ns1] = elem.text
#print (elem.text)
if (elem.tag == '{%s}LongitudeDegrees'%ns1):
returndict['{%s}LongitudeDegrees'%ns1] = elem.text
#print (elem.text)
if ( elem.tag == '{%s}AltitudeMeters'%ns1):
trackpoint.remove(elem)
"""
#elem.attrib['xmlns'] = ns2
for node in elem.iter():
if node.tag == '{%s}Speed'%ns2:
speed_in_m_per_sec = float(node.text)
speed_km_per_h = speed_in_m_per_sec /1000.0 * 60 *60
power = s2p(speed_km_per_h, lever)
# add power to trackpoint
w = etree.SubElement(elem, '{%s}Watts'%ns2)
w.text = str(power)
w.tail = '\n'
"""
return returndict
def update_lap(course, start_returndict, end_returndict):
startT = datetime.datetime.strptime(start_returndict["{%s}Time"%ns1], "%Y-%m-%dT%H:%M:%SZ")
endT = datetime.datetime.strptime(end_returndict["{%s}Time"%ns1], "%Y-%m-%dT%H:%M:%SZ")
deltaT = endT-startT
#As a rule we're chopping existing files into parts, and they have a running total of distance in each trackpoint
#So we can just subtract end-finish distance totals to get the total for our segmented file
#More accurate perhaps would be to calculate it via lat&long for each point
deltaD = str(round(float(end_returndict['{%s}DistanceMeters'%ns1]) - float(start_returndict['{%s}DistanceMeters'%ns1])))
insertdict={} #start_returndict
insertdict[("{%s}TotalTimeSeconds"%ns1)] = str(deltaT.total_seconds()) #str(int(differenceT.total_seconds()))
insertdict["{%s}DistanceMeters"%ns1] = deltaD
insertdict["{%s}BeginPosition/{%s}LatitudeDegrees"%(ns1,ns1)] = start_returndict["{%s}LatitudeDegrees"%ns1]
insertdict["{%s}BeginPosition/{%s}LongitudeDegrees"%(ns1,ns1)] = start_returndict["{%s}LongitudeDegrees"%ns1]
insertdict["{%s}EndPosition/{%s}LatitudeDegrees"%(ns1,ns1)] = end_returndict["{%s}LatitudeDegrees"%ns1]
insertdict["{%s}EndPosition/{%s}LongitudeDegrees"%(ns1,ns1)] = end_returndict["{%s}LongitudeDegrees"%ns1]
#insertdict = [("{%s}TotalTimeSeconds"%ns1) : '232', "{%s}TotalTimeSeconds"%ns1: '232', "{%s}BeginPosition/{%s}LatitudeDegrees"%(ns1,ns1): '232', "{%s}BeginPosition/{%s}LongitudeDegrees"%(ns1,ns1): '232',
# "{%s}EndPosition/{%s}LatitudeDegrees"%(ns1,ns1): '232', "{%s}EndPosition/{%s}LongitudeDegrees"%(ns1,ns1): '232']
upsert_entry(course,1,insertdict,start_returndict, end_returndict)
return
def cleanup_course(course, cleancourse, cleannotes, trimnotes):
#print ("Course cleanup . . . ")
bad_chars = ["\n", "\p", "--"]
for child in course:
if child.tag == '{%s}CoursePoint'%ns1:
for elem in child.iter():
#remove all notes (for now, testing)
if cleannotes and elem.tag == '{%s}Notes'%ns1 and isinstance(elem.text, str):
#print ("Removing:", elem.text)
elem.text=""
child.remove(elem) #remove it entirely
if trimnotes and elem.tag == '{%s}Notes'%ns1 and isinstance(elem.text, str):
#print ("Trimming:", elem.text)
elem.text=elem.text.strip()
elem.text = (elem.text[:30] + '..') if len(elem.text) > 32 else elem.text
#elem.text = filter(lambda i: i not in bad_chars, elem_text)
for i in bad_chars :
elem.text = elem.text.replace(i, ' ')
#print ("Trimmed:", elem.text)
#remove any generic CoursePoints, may cause problems
if cleancourse and elem.tag == '{%s}PointType'%ns1 and elem.text == "Generic":
#print ("Deleting:", elem.text)
child.getparent().remove(child)
def process_track(course, track, percent, times, start_time, end_time):
"""
Process a TCX file track element.
"""
'''
<Lap>
<TotalTimeSeconds>9449</TotalTimeSeconds>
<DistanceMeters>197862.0</DistanceMeters>
<BeginPosition>
<LatitudeDegrees>39.13473</LatitudeDegrees>
<LongitudeDegrees>-94.42453</LongitudeDegrees>
</BeginPosition>
<EndPosition>
<LatitudeDegrees>39.13536</LatitudeDegrees>
<LongitudeDegrees>-94.42447</LongitudeDegrees>
</EndPosition>
<Intensity>Active</Intensity>
</Lap>
'''
first = True
start_returndict = {}
end_returndict = {}
#make sure we have something at least reasonably sensible in these dictionaries as there is a chance they won't ever be updated if the file is corrupted or something
start_returndict[("{%s}TotalTimeSeconds"%ns1)] = "0"
start_returndict["{%s}DistanceMeters"%ns1] = "0"
start_returndict["{%s}BeginPosition/{%s}LatitudeDegrees"%(ns1,ns1)] = "0"
start_returndict["{%s}BeginPosition/{%s}LongitudeDegrees"%(ns1,ns1)] = "0"
start_returndict["{%s}EndPosition/{%s}LatitudeDegrees"%(ns1,ns1)] = "0"
start_returndict["{%s}EndPosition/{%s}LongitudeDegrees"%(ns1,ns1)] = "0"
end_returndict = start_returndict
startT = datetime.datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%SZ")
endT = datetime.datetime.strptime(end_time, "%Y-%m-%dT%H:%M:%SZ")
for child in track:
#print (child.tag)
if child.tag == '{%s}Trackpoint'%ns1:
#print ('working')
returndict = process_trackpoint(track, child, percent, times, startT, endT, start_returndict["{%s}DistanceMeters"%ns1], first )
#print (returndict)
if (returndict != {} and first):
start_returndict = returndict
first = False
if (returndict != {}):end_returndict = returndict
update_lap(course, start_returndict, end_returndict)
def process_file(tree, root, tcxfile, num_parts, percent, first, last, cleancourse, cleannotes, trimnotes, prnt):
"""
Process the whole TCX file.
"""
global num_coursepoints, num_trackpoints, num_tracks, num_courses, prefix, savedir, gui, progress_window, mystdout
for element in root.iter():
if element.tag == '{%s}Course'%ns1:
num_courses += 1
#print (element)
#print (element.tag)
#print ('\n')
times = []
times_elem = element.findall('{%s}CoursePoint/{%s}Time'% (ns1,ns1))
times_count=0
times_included_count = 0
start_time = ""
end_time = ""
times_first = True
for elem in times_elem:
#print(elem.text)
times_count += 1
if (times_count >= first and times_count <= last):
if (times_first):
start_time = elem.text
times.append(elem.text)
end_time = elem.text
times_included_count += 1
times_first = False
else:
#remove all course points not within the given range
elem.getparent().getparent().remove(elem.getparent())
#print (times)
num_coursepoints += times_included_count
tracks = []
for element2 in element.iter():
#print (element2.tag)
#print ('element2 \n')
if element2.tag == '{%s}Track'%ns1:
tracks.append(element2)
#print ('appended track \n')
num_tracks += len(tracks)
for track in tracks:
#print ('processing track \n')
process_track(element, track, percent, times, start_time, end_time)
#update_lap(track)
if cleancourse or cleannotes or trimnotes:
cleanup_course(element, cleancourse, cleannotes, trimnotes)
#new_name = prefix + tcxfile
new_name = os.path.join (os.path.dirname(tcxfile), savedir, prefix + os.path.basename(tcxfile))
try:
os.mkdir(savedir)
#print ('Made', savedir)
except:
pass
#print (savedir, 'already exists, not created')
#tree.write(new_name, encoding='utf-8', xml_declaration=True)
#outputStream = io.BytesIO()
#tree.write(outputStream , encoding='utf-8', xml_declaration=True)
#f = open(new_name, 'w')
#f.write(e.tree.tostring(root))
#f.close()
#old_stdout2 = sys.stdout
#sys.stdout = mystdout2 = StringIO()
#tree.write(sys.stdout, encoding='utf-8', xml_declaration=True)
#sys.stdout = old_stdout2
#print (etree.tostring(root, method='xml'))
#f = open('zzzzzjunk', 'w')
#f.write('for some reason this file is necessary to make the others work')
#f.close()
f = open(new_name, 'wb')
f.write(etree.tostring(root, method='xml'))
f.close()
#f = open('test', 'w')
#f.write('test')
#f.close()
#with open('test.txt','w') as f: # this is how you write to files
# f.write('Hello')
# f.close()
#with open(new_name,'w') as f:
# tree.write(f, encoding='utf-8', xml_declaration=True)
print ("Result written to " + new_name)
if prnt:
print ('\n')
if num_parts>1:
print ("Trimmed to: %s files, %s courses, %s tracks, %s trackpoints (%s per output file), %s coursepoints (%s per output file)"%(num_parts, num_courses, num_tracks, num_trackpoints, round(num_trackpoints/num_parts), num_coursepoints, round(num_coursepoints/num_parts)))
else:
print ("Trimmed to: %s files, %s courses, %s tracks, %s trackpoints, %s coursepoints"%(num_parts, num_courses, num_tracks, num_trackpoints, num_coursepoints))
print('\n')
if gui:
result_string = mystdout.getvalue()
progress_window.FindElement('progresstext').Update(result_string)
progress_window.Refresh()
#sys.stderr.flush()
def count_file(root, percent, maxpoints, num_parts=1, maxturns=500, split=0, prnt=False, whole=False):
"""
Count # of Trackpoints & Coursepoints in the whole TCX file.
"""
global num_coursepoints, num_trackpoints, num_tracks, num_courses, orig_total_coursepoints, orig_total_courses,orig_total_trackpoints,orig_total_tracks, gui, progress_window, mystdout
orig_total_courses = 0
orig_total_tracks = 0
orig_total_trackpoints = 0
orig_total_coursepoints = 0
for element in root.iter():
if element.tag == '{%s}Course'%ns1:
orig_total_courses += 1
#print (element)
#print (element.tag)
#print ('\n')
times = []
#print ('{%s}CoursePoint/{%s}Time'% (ns1,ns1))
times_elem = element.findall('{%s}CoursePoint/{%s}Time'% (ns1,ns1))
for elem in times_elem:
#print(elem.text)
times.append(elem.text)
#print (times)
orig_total_coursepoints += len(times_elem) #slightly wonky way of counting course points, could be updated to just count <coursepoint> elements
tracks = []
for element2 in element.iter():
#print (element2.tag)
#print ('element2 \n')
if element2.tag == '{%s}Track'%ns1:
tracks.append(element2)
#print ('appended track \n')
'''
expr = "count(//{%s}Track/{%s}Trackpoint)"%(ns1,ns1)
expr = "count(//TrainingCenterDatabase/Courses/Course/Track/Trackpoint)"
expr = "count(//Trackpoint)"
print (expr)
#orig_total_trackpoints = root.xpath(expr)
#print (orig_total_trackpoints)
'''
orig_total_tracks += len(tracks)
for track in tracks:
'''
#NOT SURE why none of these counting methods work!
track_elem = element.findall('{%s}Trackpoint/{%s}Time'%(ns1,ns1))
orig_total_trackpoints += len(track_elem)
print (orig_total_trackpoints)
print (len(track_elem))
#print (root.xpath('count(/{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}Trackpoint)'))
#orig_total_trackpoints += track.xpath('count(//Trackpoint)')
'''
for child in track:
#print (child.tag)
if child.tag == '{%s}Trackpoint'%ns1:
#print ('working')
orig_total_trackpoints += 1
temp_num_parts = num_parts
if whole:
if maxturns>0:
temp_num_parts = math.ceil(orig_total_coursepoints/maxturns)
elif split>0:
temp_num_parts = split
maxturns = math.ceil(orig_total_coursepoints/split)
else:
print ("ERROR! Neither split nor maxturns was properly specified. Using default value %s"%maxturns)
maxturns = 80
print ("ERROR! Neither split nor maxturns was properly specified. Using default value %s\n"%maxturns)
temp_num_parts = math.ceil(orig_total_coursepoints/maxturns)
if prnt:
print ("Original file: %s courses, %s tracks, %s trackpoints, %s coursepoints"%(orig_total_courses, orig_total_tracks, orig_total_trackpoints, orig_total_coursepoints))
print ("Minimum trackpoints possible: %s trackpoints (%s per output files)"%(orig_total_coursepoints, round(orig_total_coursepoints/temp_num_parts)))
if (maxpoints > 0):
#print ('B')
if (maxpoints < orig_total_coursepoints/temp_num_parts):
maxpoints = orig_total_coursepoints/temp_num_parts
#assert (orig_total_coursepoints != 0, "Number of course)
if ((orig_total_trackpoints - orig_total_coursepoints ) == 0 ):
percent = 0
else:
percent = (maxpoints-orig_total_coursepoints/temp_num_parts)*100/(orig_total_trackpoints/temp_num_parts-orig_total_coursepoints/temp_num_parts)
if whole:
#print ("Whole")
percent = (maxpoints*temp_num_parts-orig_total_coursepoints)*100/(orig_total_trackpoints-orig_total_coursepoints)
if prnt:
print ("Aiming for: %s files, retain %s%% of trackpoints, retain %s total trackpoints in each file"%(temp_num_parts, round(percent), round(maxpoints)))
print ('\n')
else:
maxpoints = orig_total_coursepoints/temp_num_parts + orig_total_trackpoints/temp_num_parts*percent/100
#maxpoints = orig_total_trackpoints/temp_num_parts*percent/100
#print ('A')
if whole:
maxpoints = orig_total_coursepoints + (orig_total_trackpoints - orig_total_coursepoints)*percent/100
if prnt:
print ("Aiming for: %s files, retain %s%% of trackpoints, retain %s total trackpoints in each file"%(temp_num_parts, round(percent), round(maxpoints/temp_num_parts)))
print ('\n')
if gui:
result_string = mystdout.getvalue()
progress_window.FindElement('progresstext').Update(result_string)
progress_window.Refresh()
return {'percent':percent,'maxturns':maxturns}
#Return a tree with course elements x to y and all others, including corresponding track elements, removed
"""
def tree_prune(tree, root, first, last):
for element in root.iter():
if element.tag == '{%s}Course'%ns1:
times = []
times_elem = element.findall('{%s}CoursePoint/{%s}Time'% (ns1,ns1))
for elem in times_elem:
#print(elem.text)
times.append(elem.text)
#print (times)
tracks = []
for element2 in element.iter():
#print (element2.tag)
#print ('element2 \n')
if element2.tag == '{%s}Track'%ns1:
tracks.append(element2)
#print ('appended track \n')
num_tracks += len(tracks)
for track in tracks:
#print ('processing track \n')
process_track(element, track, percent, times)
#update_lap(track)
new_name = "vprune_" + tcxfile
tree.write(new_name, encoding='utf-8', xml_declaration=True)
print ("Result written to " + new_name)
print ("Trimmed to: %s courses, %s tracks, %s trackpoints, %s coursepoints"%(num_courses, num_tracks, num_trackpoints, num_coursepoints))
"""
def process_file_segments (tree, root, inputfilename, maxturns, split, maxpoints, percent, cleancourse, cleannotes, trimnotes):
global gui, progress_window, progress_bar, progress, mystdout
#num_parts = math.ceil(orig_total_coursepoints/maxturns)
ret = count_file(root, percent, maxpoints, 1, maxturns, split, True, True)
maxturns = ret['maxturns']
num_parts = math.ceil(orig_total_coursepoints/maxturns)
turns_per_part = math.floor(orig_total_coursepoints/num_parts)
total_coursepoints = orig_total_coursepoints
for i in range(num_parts):
start_turn = i * turns_per_part
end_turn = (i+1) * turns_per_part
prnt=False
if (i+1==num_parts):
end_turn = total_coursepoints
prnt=True
newtree = copy.deepcopy(tree)
newroot = newtree.getroot()
ret = count_file(newroot, percent, maxpoints, num_parts, maxturns, False)
segmentpercent = ret ['percent']
segment_filename = os.path.join(os.path.dirname(inputfilename), "%i_%s"%(i+1,os.path.basename(inputfilename)))
process_file(newtree, newroot, segment_filename, num_parts, segmentpercent, start_turn, end_turn, cleancourse, cleannotes, trimnotes, prnt)
if gui:
result_string = mystdout.getvalue()
progress_window.FindElement('progresstext').Update(result_string)
progress_window.Refresh()
progress= 100/num_parts*(i+1)
if weborgui != 'web':
progress_bar.UpdateBar(progress)
#sys.stderr.flush()
def delete_current_tcx_in_directory(inputfilename, prefix):
return # eliminating this now since it doesn't work in repl.it anyway
dir =os.path.dirname(inputfilename)
extension = ".tcx"
#fileList = glob.glob(dir + '\*' + extension)
if not prefix.endswith("_") or len(prefix)<3:
print ("File prefix does not end with '_' or is too short - NOT deleted all files with this prefix:", prefix,'\n')
fileList = glob.glob(os.path.join (dir, prefix+"*"+ extension))
#print (fileList)
if len(fileList)>0:
print ('Removing files', end = '')
if len(dir)>0:
print (' in directory', dir+": ", end = '')
else:
print (': ', end = '')
for filePath in fileList:
try:
print (os.path.basename(filePath) + ' ', end = '')
#So, Repl.it doesn't really honor file deletions. Instead, we're going to clear the files so they have nothing inside.
f = open(filePath, 'w')
f.write('')
f.close()
os.remove(filePath)
except:
print("Error while deleting file : ", filePath, "\n")
print()
print()
def main(argv=None):
global prefix, progress_window, progress_bar, progress, gui, mystdout, weborgui
arguments = docopt(__doc__)
inputfilename = arguments["INPUTFILE"]
saveprint = print
percent = 25
maxpoints = 500
maxturns= 80
split=4
cleancourse=False
cleannotes=False
trimnotes=False
gui=False
progress_debug=False
window_bcolor='lightgray'
multiline_bcolor='white'
sg.SetOptions(
background_color=window_bcolor, text_element_background_color=window_bcolor,
element_background_color=window_bcolor, scrollbar_color=None,
input_elements_background_color=multiline_bcolor
)
turn_split = [sg.Text(' Max Turns per output file'), sg.InputText(key='maxturns', enable_events=True, size=[5,1], default_text="80"), sg.Text(' OR Split original file into '), sg.InputText('4', key='split', enable_events=True, size=[4,1]), sg.Text('new files ') ]
track_percent = [sg.Text(' Max number of Trackpoints in each output file'), sg.InputText('500',key='maxpoints', enable_events=True, size=[5,1]), sg.Text(' OR Percent of Trackpoints to retain '), sg.InputText('25',key='percent', size=[3,1], enable_events=True), sg.Text('(0-100)') ]
if weborgui == 'web':
#Can't have enable_events=True for InputText elements in PySimpleGUIWeb because of a bug, for now. 2019/08
turn_split = [sg.Text(' Max Turns per output file'), sg.InputText(key='maxturns', size=[5,1], default_text="80"), sg.Text(' OR Split original file into '), sg.InputText('4', key='split', size=[4,1]), sg.Text('new files ') ]
track_percent = [sg.Text(' Max number of Trackpoints in each output file'), sg.InputText('500', key='maxpoints', size=[5,1]), sg.Text(' OR Percent of Trackpoints to retain '), sg.InputText('25',key='percent', size=[3,1]), sg.Text('(0-100)') ]
layout = [[sg.Text(' VPrune will simplify your .tcx files by trimming points and splitting the file into several smaller files')],
[sg.Text(' With default options it will produce files suitable for use with Lezyne GPS units and perhaps other GPS units as well')],
[sg.Text('')],
[sg.Frame('',[
[sg.Text(' SPLIT THE FILE',font=('default',19,'italic'), justification='center')],
[sg.Text(' '),sg.Checkbox('Use Max Turns ', default=True,enable_events=True,key='1_usemaxturns'), sg.Checkbox('Use File Split # ', enable_events=True,key='1_usesplit')],
turn_split,
[sg.Text('')],
], background_color=window_bcolor)],
[sg.Frame('',[
[sg.Text(' REDUCE TRACKPOINTS',font=('default',18,'italic'),justification='center')],
[sg.Text(' '),sg.Checkbox('Use Max Trackpoints ', enable_events=True, default=True,key='2_usemaxpoints'), sg.Checkbox('Use Percentage of Trackpoints ', enable_events=True, key='2_usepercent')],
track_percent,
[sg.Text('')],
[sg.Text('File prefix for processed files'), sg.InputText('"vp_"',key='prefix', size=[15,1]), sg.Text('If more than one file, names will be, ie, vp_1_yourfilename.tcx, vp_2_yourfilename.tcx, ...') ],
#[sg.Text('WARNING!!! Files matching prefix_*.tcx in the current repl.it directory will be deleted!')], #repl.it
[sg.Text('')],
], background_color=window_bcolor)],
[sg.Frame('',[
[sg.Text(' CLEAN THE OUTPUT FILES',font=('default',18,'italic'),justification='center')],
[sg.Text(' '),sg.Checkbox('Strip all "Generic" CoursePoints', key='cleancourse')],
[sg.Text(' '),sg.Checkbox('Remove all Notes ', default=True,enable_events=True, key='3_cleannotes'), sg.Checkbox('Trim/clean Notes', enable_events=True, key='3_trimnotes'), sg.Checkbox('Leave Notes alone ', enable_events=True, key='3_nocleannotes')],
#[sg.Checkbox('Show progress Debug Window', key='progress_debug')],
[sg.Text('')],
], background_color=window_bcolor)],
[sg.Frame('',[
[sg.Text(' CHOOSE THE DOCUMENT',font=('default',18,'italic'))],
#[sg.In(key='inputfile', size=[50,1], focus=True)],
[sg.Text(' '),sg.In('input.tcx',key='inputfile', size=[70,1], focus=True), sg.FileBrowse(), sg.Text(' ')],
#Can try sg.FileBrowse OR sg.FilesBrowse
], background_color=window_bcolor)],
[sg.Text('')],
[sg.Text(' '),sg.Open('Process File'),sg.Text(' '), sg.Exit(), sg.Text(' '), sg.Help("Help")],
[sg.Text('')],
[sg.Multiline('', visible=False, key='webnotes', size=(700,200))],
]
main_window = []
if weborgui=='web':
main_window = sg.Window('VPrune', layout, text_justification='center', use_default_focus=False, background_color=window_bcolor, web_port=webport, web_multiple_instance = VPweb_multiple_instance)
else:
main_window = sg.Window('VPrune', layout, text_justification='center', use_default_focus=False, background_color=window_bcolor)
if not isinstance(inputfilename, str) or len(inputfilename)==0:
gui = True
if gui:
main_window.Finalize()
if weborgui == 'web':
webnotes = '''VPrune - Special Notes for Web Edition:
* The BROWSE button will not work - you will have to manually type the filename in the input field
* To avoid typing directory names (needed as part of the filename, if you are not in the
correct directory), run VPrune in the same directory as your .tcx files
* To avoid typing long filenames, rename your .tcx to a short, simple name
'''
main_window.FindElement('webnotes').Update(webnotes, visible=True)
main_window.FindElement('maxturns').Update(str(maxturns))
main_window.FindElement('split').Update(str(split))
main_window.FindElement('maxpoints').Update(str(maxpoints))
main_window.FindElement('percent').Update(str(percent))
main_window.FindElement('prefix').Update(prefix)
main_window.FindElement('inputfile').Update('input.tcx')
main_window_disabled=False
while True:
initVals()
if not isinstance(inputfilename, str) or len(inputfilename)==0 or gui==True:
if main_window_disabled:
if weborgui != 'web':
main_window.Enable()
main_window_disabled=False
while True:
event, values = main_window.Read()
#print (event, values)
checkbox_to_radio(main_window, event, values, "_")
if event in (None, 'Exit', 'Process File', 'Help'):
break
#print(event, values)
#sys.stderr.flush()
if (event=="Exit") or event is None:
#main_window.Close()
os._exit(1) #repl.it
sys.exit()
break
elif event == "Help":
#sg.PopupScrolled(__doc__,title='VPrune - Help',non_blocking=True)
#sg.PopupScrolled(__doc__,size=(600,400))
#continue
if weborgui=='web':
sx=600
sy=600
else:
sx=80
sy=40
layout = [[sg.Text('VPrune Help')],
[sg.Multiline('', size=(sx,sy), key='helptext', background_color=multiline_bcolor)],
[sg.Submit('Close')]
]
help_window=[]
if weborgui=='web':
help_window = sg.Window('VPrune - Help', layout, keep_on_top=True, disable_minimize=True, background_color = window_bcolor, web_port=webport, web_multiple_instance=VPweb_multiple_instance)
else:
help_window = sg.Window('VPrune - Help', layout, keep_on_top=True, disable_minimize=True)
#help_window = sg.Window('VPrune - Help', layout, keep_on_top=True, disable_minimize=True, web_port=webport)