Selaa lähdekoodia

initial work towards commute data inclusion

Martin 8 vuotta sitten
vanhempi
commit
2e55042a83
6 muutettua tiedostoa jossa 179 lisäystä ja 7 poistoa
  1. 121 0
      commute.py
  2. 11 1
      config.py
  3. 14 1
      db_schema.py
  4. 28 0
      geo_util.py
  5. 2 2
      init_localities.py
  6. 3 3
      monitor.py

+ 121 - 0
commute.py

@@ -0,0 +1,121 @@
+import hashlib
+import json
+import requests
+
+import config
+import data
+import db
+import geo_util
+
+class TransitMethod:
+    DRIVING = 'driving'
+    WALKING = 'walking'
+    CYCLING = 'bicycling'
+    TRANSIT = 'transit'
+
+def _get_key(*args):
+    k = ','.join([str(x) for x in args]).encode('utf-8')
+    return hashlib.md5(k).hexdigest()[-12:]
+
+def _record_api_response(response):
+
+    stmt = 'replace into transit (id, mode, submode, src_lat, src_lon, dest_lat, dest_lon, distance, duration, raw_json) VALUES'
+    params = []
+
+    for route in response.get('routes', []):
+        for leg in route.get('legs', []):
+            for step in leg.get('steps', []):
+                distance = step['distance']['value']
+                duration = step['duration']['value']
+                source = round(step['start_location']['lat'], 10), round(step['start_location']['lng'], 10)
+                destination = round(step['end_location']['lat'], 10), round(step['end_location']['lng'], 10)
+                mode = step['travel_mode']
+                submode = step.get('transit_details', {}).get('line', {}).get('vehicle', {}).get('type')
+
+                stmt += ' (?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
+                params.extend([
+                    _get_key(source, destination, mode, submode),
+                    mode,
+                    submode,
+                    source[0],
+                    source[1],
+                    destination[0],
+                    destination[1],
+                    distance,
+                    duration,
+                    json.dumps(step),
+                ])
+
+    with db.connect() as conn:
+        conn.execute(stmt[:-1], *params)
+
+
+
+def directions_call(source, destination, mode):
+    # doc: https://developers.google.com/maps/documentation/directions/intro
+
+    url = 'https://maps.googleapis.com/maps/api/directions/json?origin=%s,%s&destination=%s,%s&key=%s&mode=%s&arrival_time=%i&alternatives=true'
+    params = (
+        source[0],
+        source[1],
+        destination[0],
+        destination[1],
+        config.GCLOUD_API_KEY,
+        mode,
+        config.WORKPLACE_TARGET_TIME,
+    )
+
+    #resp = requests.get(url % params)
+    # print(resp.status_code)
+    # print(json.dumps(resp.json()))
+
+    resp_data = data.x
+
+    _record_api_response(resp_data)
+
+
+
+def load_data():
+
+    graph = {
+        config.WORKPLACE: {}
+    }
+
+    with db.connect() as conn:
+        rows = conn.select('select id, mode, dest_lat, dest_lon, src_lat, src_lon, duration from transit')
+
+        for key, mode, src_lat, src_lon, dest_lat, dest_lon, duration in rows:
+            loc = src_lat, src_lon
+
+            if loc not in graph:
+                graph[loc] = {}
+
+                for lat, lon in graph:
+                    if 0 < geo_util.ggcd(lon, lat, src_lon, src_lat) < 200:
+                        k = 'w-' + _get_key(lon, lat, src_lon, src_lat)
+                        graph[loc][k] = {
+                            'mode': TransitMethod.WALKING,
+                            'dest': (lat, lon),
+                            'duration': 0,
+                        }
+                        graph[lat,lon][k] = {
+                            'mode': TransitMethod.WALKING,
+                            'dest': loc,
+                            'duration': 0,
+                        }
+
+            graph[loc][key] = {
+                'mode': mode,
+                'dest': (dest_lat, dest_lon),
+                'duration': duration,
+            }
+            
+    for k, v in graph.items():
+        print((k,v))
+
+    print(graph[config.WORKPLACE])
+
+
+# directions_call((53.388631,-6.071959), config.WORKPLACE, TransitMethod.TRANSIT)
+
+load_data()

+ 11 - 1
config.py

@@ -1,14 +1,24 @@
-API_KEY = '5f4bc74f-8d9a-41cb-ab85-a1b7cfc86622'
+import os
+
+MYHOME_API_KEY = '5f4bc74f-8d9a-41cb-ab85-a1b7cfc86622'
 BASE = 'https://api.myhome.ie'
 
+GCLOUD_API_KEY = os.getenv('IEP_GCLOUD_KEY')
+
 DB_PATH = 'data.db'
 
 MONITORED_LOCALITIES = [
     1265, # Co Dublin
     4011, # Co Wicklow
     3587, # Co Tipp
+    2362, # Co Kildare
+    2535, # Co Louth
+    2712, # Co Meath
 ]
 
+WORKPLACE = (53.353361,-6.247984)
+WORKPLACE_TARGET_TIME = 1540893600 # tue 10:00
+
 SEARCH_PARAMS = {
     'ChannelIds': [1],
     'Destinations': [],

+ 14 - 1
db_schema.py

@@ -71,5 +71,18 @@ SCHEMA_STATEMENTS = [
 
     'alter table search_results add column search_locality_id integer',
     
-    
+    '''
+    create table transit (
+        id varchar(256) not null primary key,
+        mode varchar(128) not null,
+        submode varchar(128),
+        src_lat float not null,
+        src_lon float not null,
+        dest_lat float not null,
+        dest_lon float not null,
+        distance integer not null,
+        duration integer not null,
+        raw_json text
+    )
+    '''
 ]

+ 28 - 0
geo_util.py

@@ -0,0 +1,28 @@
+import math
+
+def ggcd(lon1, lat1, lon2, lat2):
+    """
+    Returns the great-circle distance between two points, in metres
+    @param lon1: longitude #1
+    @param lat1: latitude #1
+    @param lon2: longitude #2
+    @param lat2: latitude #2
+    @return: the distance between the two points, in metres
+    """
+
+    if lat1 == lat2 and lon1 == lon2:
+        return 0
+
+    RADIUS = 6371000.0
+
+    rLon1 = math.radians(lon1)
+    rLat1 = math.radians(lat1)
+    rLon2 = math.radians(lon2)
+    rLat2 = math.radians(lat2)
+
+    cosdist = math.cos(rLat1) * math.cos(rLat2) * math.cos(rLon2 - rLon1) + math.sin(rLat1) * math.sin(rLat2)
+
+    if cosdist >= 1.0:
+        return 0.0
+    else:
+        return math.acos(cosdist) * RADIUS

+ 2 - 2
init_localities.py

@@ -12,7 +12,7 @@ def _extract_localities(api_response):
     return res
 
 def _init_relationships(conn, locality_id):
-    resp = requests.get('https://api.myhome.ie/localities/%s?ApiKey=%s&classId=1' % (locality_id, config.API_KEY))
+    resp = requests.get('https://api.myhome.ie/localities/%s?ApiKey=%s&classId=1' % (locality_id, config.MYHOME_API_KEY))
     resp.raise_for_status()
     data = resp.json()
 
@@ -38,7 +38,7 @@ def init_localities(conn, locality_id=None):
                 conn.execute('replace into localities (id, name) values (?,?)', x['id'], x['name'])
 
     else:
-        resp = requests.get('https://api.myhome.ie/localities/%s?ApiKey=%s&classId=1' % (locality_id, config.API_KEY))
+        resp = requests.get('https://api.myhome.ie/localities/%s?ApiKey=%s&classId=1' % (locality_id, config.MYHOME_API_KEY))
         resp.raise_for_status()
         data = resp.json()
 

+ 3 - 3
monitor.py

@@ -128,7 +128,7 @@ def fetch_properties(conn):
         params = []
 
         for property_id in batch:
-            resp = requests.get('https://api.myhome.ie/brochure/%i?ApiKey=%s&RequestTypeId=1' % (property_id, config.API_KEY))
+            resp = requests.get('https://api.myhome.ie/brochure/%i?ApiKey=%s&RequestTypeId=1' % (property_id, config.MYHOME_API_KEY))
 
             if resp.json() in ["The property you requested isn't available any more", "The property you requested is inactive and can't be found"]:
                 stmt += ' (?, ?, ?),'
@@ -174,7 +174,7 @@ def search(conn, locality_id):
         
         body = {
             'AddedSince': "",
-            'ApiKey': config.API_KEY,
+            'ApiKey': config.MYHOME_API_KEY,
             'Page': page,
             'PageSize': _SEARCH_PAGE_SIZE,
             'RequestTypeId': 2,
@@ -201,7 +201,7 @@ def search(conn, locality_id):
         else:
             print('Fetching page %i...' % page)
 
-        resp = requests.post('https://api.myhome.ie/search?ApiKey=%s' % config.API_KEY, json=body, headers=headers)
+        resp = requests.post('https://api.myhome.ie/search?ApiKey=%s' % config.MYHOME_API_KEY, json=body, headers=headers)
         resp.raise_for_status()
         data = resp.json()