Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
harshdeep committed Mar 20, 2016
0 parents commit 99ac2bc
Show file tree
Hide file tree
Showing 5 changed files with 135 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
*.json
*.csv
data
3 changes: 3 additions & 0 deletions config.json.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"google_api_key":"YOUR_API_KEY_HERE"
}
9 changes: 9 additions & 0 deletions input.json.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"inputs": [
{
"name":"sample",
"origin":"Townsend St & 5th St, San Francisco, CA 94107",
"destination":"Levi’s Stadium, 4900 Marie P DeBartolo Way, Santa Clara, CA 95054"
}
]
}
49 changes: 49 additions & 0 deletions plot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import plotly
from plotly.graph_objs import Scatter, Layout
import json
import csv
import argparse
import os
from datetime import datetime

def excel_time_to_datetime(time):
return datetime.strptime(time, '%x %X')

def get_trace(trace_name, data_dir):
filename = data_dir + '/' + trace_name + '.csv'
duration = []
time = []
with open(filename, 'rb') as csvfile:
reader = csv.reader(csvfile)
next(reader)
for row in reader:
duration.append(float(row[2])/60)
time.append(excel_time_to_datetime(row[1].strip()))

return Scatter(
x = time,
y = duration,
mode = 'lines',
name = trace_name
)

parser = argparse.ArgumentParser(description='Upload commute time data to Plotly')
parser.add_argument('input', type=argparse.FileType('r'), help='JSON file listing the start and end destinations. See input.json.sample for example.')
args = parser.parse_args()
inputs = json.loads(args.input.read())['inputs']

data_dir = os.path.dirname(os.path.realpath(__file__)) + '/data'

for path in inputs:
trace_out = get_trace(path['name']+'_out', data_dir)
trace_back = get_trace(path['name']+'_back', data_dir)
plotly.plotly.plot(
{
'data': [trace_out, trace_back],
'layout': {
'title': 'Daily Commute'
}
},
filename=path['name'] + ' commute',
sharing='public'
)
71 changes: 71 additions & 0 deletions traffic_snapshot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import requests
import datetime
import json
import os.path
import pytz
from pytz import timezone
from datetime import datetime
import argparse
import time

API_BASE_URL = "https://maps.googleapis.com/maps/api/directions/json"

def api_call(path, query_params, api_key):
query_params['key'] = api_key
return requests.get(API_BASE_URL + path, params=query_params)

def duration(origin, destination, api_key):
r = api_call('', {
'destination': destination,
'origin': origin,
'traffic_model': 'best_guess',
'mode': 'driving',
'departure_time': 'now'
},
api_key)
if (r.status_code != 200):
raise Exception('API Call Failed. ' + r.text)
r = r.json()
if (r['status'] != 'OK'):
raise Exception('API Call Failed. ' + r['error_message'])
return r['routes'][0]['legs'][0]['duration_in_traffic']['value']

def current_time_in_pst():
date = datetime.now(tz=pytz.utc)
return date.astimezone(timezone('US/Pacific'))

def datetime_to_timestamp(date):
return int(time.mktime(date.timetuple()))

def excel_time(time):
return time.strftime('%x %X')

def append_duration(filepath, origin, destination, api_key):
d = duration(origin, destination, api_key)
f = None
if not os.path.isfile(filepath):
f = open(filepath, 'w+')
f.write('Timestamp, Time, Duration\n')
else:
f = open(filepath, 'a')

time = current_time_in_pst()
f.write('{0}, {1}, {2}\n'.format(datetime_to_timestamp(time), excel_time(time), d))
f.close()

parser = argparse.ArgumentParser(description='Take commute time snapshot')
parser.add_argument('input', type=argparse.FileType('r'), help='JSON file listing the start and end destinations. See input.json.sample for example.')
parser.add_argument('config', type=argparse.FileType('r'), help='JSON file containing your app configuration, particularly Google Maps API key. See config.json.sample for example.')
args = parser.parse_args()
inputs = json.loads(args.input.read())['inputs']
api_key = json.loads(args.config.read())['google_api_key']

data_dir = os.path.dirname(os.path.realpath(__file__)) + '/data'
if not os.path.exists(data_dir):
os.makedirs(data_dir)

for path in inputs:
out_csv = data_dir + '/' + path['name'] + '_out.csv'
append_duration(out_csv, path['origin'], path['destination'], api_key)
back_csv = data_dir + '/' + path['name'] + '_back.csv'
append_duration(back_csv, path['destination'], path['origin'], api_key)

0 comments on commit 99ac2bc

Please sign in to comment.