Commits

Thomas Bilk ن committed 0abb858

Initial commit. Running version.

Comments (0)

Files changed (1)

+#!/usr/bin/env python
+# coding: utf8
+
+import os, sys
+from datetime import datetime, timedelta
+from xml.etree import ElementTree
+from xml.etree.ElementTree import Element, SubElement, Comment, parse
+from xml.dom import minidom
+
+def prettify(elem):
+    """Return a pretty-printed XML string for the Element."""
+    rough_string = ElementTree.tostring(elem, 'utf-8')
+    reparsed = minidom.parseString(rough_string)
+    return reparsed.toprettyxml(indent="  ")
+
+
+def writexml(elem, filename):
+    """Write the etree element to the file"""
+    rough_string = ElementTree.tostring(elem, 'utf-8')
+    reparsed = minidom.parseString(rough_string)
+    with open(filename, 'w') as writer:
+        reparsed.writexml(writer, #indent='  ', addindent='  ', newl='\n',
+                          encoding='UTF-8')
+
+
+def create_tcdb(name, coords):
+    """Converts a name and a list of coordinates into an etree doc in the
+    tcx format."""
+    tcdb = Element('TrainingCenterDatabase', {
+        'xmlns': 'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2',
+        'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
+        'xsi:schemaLocation': 'http://www.garmin.com/xmlschemas/' +
+                              'TrainingCenterDatabase/v2 ' +
+                              'http://www.garmin.com/xmlschemas/' +
+                              'TrainingCenterDatabasev2.xsd',
+    })
+    courses = SubElement(tcdb, 'Courses')
+    course = SubElement(courses, 'Course')
+    SubElement(course, 'Name').text = name
+    lap = SubElement(course, 'Lap')
+    SubElement(lap, 'TotalTimeSeconds').text = '0'
+    SubElement(lap, 'DistanceMeters').text = '0'
+    begin = SubElement(lap, 'BeginPosition')
+    SubElement(begin, 'LatitudeDegrees').text = coords[0][1][:11]
+    SubElement(begin, 'LongitudeDegrees').text = coords[0][0][:11]
+    end = SubElement(lap, 'EndPosition')
+    SubElement(end, 'LatitudeDegrees').text = coords[-1][1][:11]
+    SubElement(end, 'LongitudeDegrees').text = coords[-1][0][:11]
+    SubElement(lap, 'Intensity').text = 'Active'
+    track = SubElement(course, 'Track')
+    now = datetime.now()
+    for coord in coords:
+        tp = SubElement(track, 'Trackpoint')
+        SubElement(tp, 'Time').text = now.strftime('%Y-%m-%dT%H:%M:%SZ')
+        pos = SubElement(tp, 'Position')
+        SubElement(pos, 'LatitudeDegrees').text = coord[1][:11]
+        SubElement(pos, 'LongitudeDegrees').text = coord[0][:11]
+        now += timedelta(0, 10)
+    return tcdb
+
+
+def create_gpx(name, coords):
+    now = datetime.now()
+    gpx = Element('gpx', {
+        'xmlns': 'http://www.topografix.com/GPX/1/1',
+        'creator': 'Python',
+        'version': '1.1',
+        'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
+        'xsi:schemaLocation': 'http://www.topografix.com/GPX/1/1 ' +
+                              'http://www.topografix.com/GPX/1/1/gpx.xsd'
+    })
+    meta = SubElement(gpx, 'metadata')
+    SubElement(meta, 'name').text = name
+    # link = SubElement(meta, 'link', {'href': 'http://python.org/'})
+    # SubElement(link, 'text').text = name
+    SubElement(meta, 'time').text = now.strftime('%Y-%m-%dT%H:%M:%SZ')
+    rte = SubElement(gpx, 'rte')
+    SubElement(rte, 'name').text = name
+    for coord in coords:
+        rtept = SubElement(rte, 'rtept', {
+            'lat': coord[1][:12],
+            'lon':coord[0][:12]
+        })
+        SubElement(rtept, 'ele').text = '0.000000'
+    return gpx
+
+
+def parse_kml(kml_file):
+    """Extracts the track name and coordinates from a kml file"""
+    NS = 'http://www.opengis.net/kml/2.2'
+    with open(kml_file, 'rt') as f:
+        tree = parse(f)
+    placemark = tree.find('*//{%s}Placemark' % NS)
+    if placemark is not None:
+        coords = [
+            c.split(',') for c in 
+            placemark.findtext('.//{%s}coordinates' % NS, '').strip().split(' ')
+        ]
+        name = placemark.findtext('./{%s}name' % NS, '')
+        return name, coords
+    return None, None
+
+
+def main():
+    if len(sys.argv) != 3:
+        print 'please supply a format and filename'
+    else:
+        format = sys.argv[1]
+        kml_file = sys.argv[2]
+        name, coords = parse_kml(kml_file)
+        if name and coords:
+            if format == 'gpx':
+                tree = create_gpx(name, coords)
+            else:
+                tree = create_tcdb(name, coords)
+            out_file = '%s.%s' % (
+                os.path.splitext(os.path.split(kml_file)[1])[0],
+                format
+            )
+            writexml(tree, out_file)
+
+
+if __name__ == '__main__':
+    main()