25161c8d761517d5d46122d777c71fe8efb022e3
[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 pygeocode
10 import sqlite3
11 import datetime
12
13 def check_db_for_training(db,sport,timestamp):
14
15   conn = sqlite3.connect(db)
16   cur = conn.cursor()
17
18   cur.execute ("select count(*) from tracks where sport=? and start_time=?" , (sport,timestamp))
19   return cur.fetchall()[0][0]
20
21 def write_parsed_to_db(db,gpx,filename):
22
23   conn = sqlite3.connect(db)
24   cur = conn.cursor()
25
26   cur.execute ("delete from tracks where filename=?" , (filename.decode('UTF-8'),))
27   
28   tracks = gpx.tracks
29   
30   for track in tracks:
31
32       try:
33         author = gpx.author
34       except:
35         author = None 
36         
37       try:
38         name = gpx.name
39       except:
40         name = None
41         
42       if author:
43         try:
44           cur.execute("insert into authors(name,description) values(?,?)", (author,''))         
45           print "created author %s" % (author)
46         except:
47           print "failed to create author %s" % (author)
48           pass
49
50       try:
51
52         print "processing..."
53         start = track.start()
54         if start:
55           printable = pygeocode.GeoName(start.lat,start.lon).printable
56           start_time = track.start_time()
57           full_duration = track.full_duration().total_seconds()
58           distance = track.distance()
59           filtered_distance = track.filtered_distance(max_speed=50)
60           ascent = track.elevation_gain()
61           descent = track.elevation_loss()
62           ((minlat,minlon),(maxlat,maxlon)) = track.bound_box()
63           params = ( 
64             gpx.author,name,filename.decode('UTF-8'),
65             track.sport,start_time,full_duration,
66             distance,filtered_distance,ascent,descent,
67             start.lat,start.lon,
68             printable,
69             minlat,minlon,maxlat,maxlon
70              )
71           cur.execute("""
72             insert into tracks(
73               author,name,filename,sport,
74               start_time,duration,
75               distance,distance_filtered,
76               ascent,descent,
77               lat,lon,printable_location,minlat,minlon,maxlat,maxlon) 
78             values(
79               ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
80               """ 
81               , params )
82           conn.commit()
83           print "created track %s" % (filename)
84
85       except:
86       
87         raise
88
89 def write_tree_to_db(db,tree,filename):
90
91   gpx = pygpx.GPX()
92   gpx.ReadTree(tree)
93
94   write_parsed_to_db(db,gpx,filename)
95
96