5247c27d7ff7382966f67bbf2df36b8e3c41356c
[pyrungps.git] / parsegpx.py
1 #!/usr/bin/env python
2 # coding: UTF-8
3
4 import sys
5 import os
6 from lxml import etree
7 from urllib2 import unquote
8 import pygpx
9 import pyosmname
10 import sqlite3
11 import datetime
12
13 def write_parsed_to_db(db,gpx,filename):
14
15   conn = sqlite3.connect(db)
16   cur = conn.cursor()
17
18   cur.execute ("delete from tracks where filename=?" , (filename.decode('UTF-8'),))
19   
20   tracks = gpx.tracks
21   
22   for track in tracks:
23
24       try:
25         author = gpx.author
26       except:
27         author = None 
28         
29       try:
30         name = gpx.name
31       except:
32         name = None
33         
34       if author:
35         try:
36           cur.execute("insert into authors(name,description) values(?,?)", (author,''))         
37           print "created author %s" % (author)
38         except:
39           print "failed to create author %s" % (author)
40           pass
41
42       try:
43
44         print "processing..."
45         start = track.start()
46         if start:
47           printable = pyosmname.GeoName(start.lat,start.lon).printable
48           start_time = track.start_time()
49           full_duration = track.full_duration().total_seconds()
50           distance = track.distance()
51           filtered_distance = track.filtered_distance(max_speed=50)
52           ascent = track.elevation_gain()
53           descent = track.elevation_loss()
54           ((minlat,minlon),(maxlat,maxlon)) = track.bound_box()
55           params = ( 
56             gpx.author,name,filename.decode('UTF-8'),
57             track.sport,start_time,full_duration,
58             distance,filtered_distance,ascent,descent,
59             start.lat,start.lon,
60             printable,
61             minlat,minlon,maxlat,maxlon
62              )
63           cur.execute("""
64             insert into tracks(
65               author,name,filename,sport,
66               start_time,duration,
67               distance,distance_filtered,
68               ascent,descent,
69               lat,lon,printable_location,minlat,minlon,maxlat,maxlon) 
70             values(
71               ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
72               """ 
73               , params )
74           conn.commit()
75           print "created track %s" % (filename)
76
77       except:
78       
79         raise
80
81 def write_tree_to_db(db,tree,filename):
82
83   gpx = pygpx.GPX()
84   gpx.ReadTree(tree)
85
86   write_parsed_to_db(db,gpx,filename)
87
88