Browse Source

automatic detection of suspect coordinates

Martin 7 years ago
parent
commit
69d198e6f0
3 changed files with 71 additions and 10 deletions
  1. 4 1
      db.py
  2. 58 9
      monitor.py
  3. 9 0
      util.py

+ 4 - 1
db.py

@@ -8,7 +8,10 @@ import db_schema
 _DATETIME_FORMAT = r'%Y-%m-%d %H:%M:%S'
 
 def now():
-    return datetime.datetime.now().strftime(_DATETIME_FORMAT)
+    return datetime_to_str(datetime.datetime.now())
+
+def datetime_to_str(dt):
+    return dt.strftime(_DATETIME_FORMAT)
 
 class connect:
     conn = None

+ 58 - 9
monitor.py

@@ -11,6 +11,7 @@ import config
 
 import init_localities
 import util
+import geo_util
 
 _SEARCH_PAGE_SIZE = 50
 
@@ -106,27 +107,72 @@ def process_properties(conn):
         rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 10')
 
 
+def check_bad_locations(conn):
+    data = conn.select('''
+        select id, last_update, lat, lon, locality_id from properties where processed=1
+    ''')
+
+    by_locality = collections.defaultdict(list)
+
+    for pid, last_update, lat, lon, locality_id in data:
+        by_locality[locality_id].append((pid, last_update, lat, lon))
+
+    suspect_locations = []
+    time_cutoff = datetime.datetime.now() - datetime.timedelta(days=14)
+    time_cutoff_str = db.datetime_to_str(time_cutoff)
+
+    for locality_id, properties in by_locality.items():
+        if len(properties) <= 2:
+            continue
+
+        with_loc = [p for p in properties if p[2] and p[3]]
+
+
+        median_lat = util.median([p[2] for p in with_loc])
+        median_lon = util.median([p[3] for p in with_loc])
+        median_loc = median_lat, median_lon
+
+        distances = [geo_util.ggcd(median_loc, (p[2], p[3])) for p in with_loc]
 
-def fetch_properties(conn):
+        median_distance = util.median(distances)
+        if median_distance == 0:
+            median_distance = 2000
 
-    unknown_properties = conn.select('''
+        for i, (pid, last_update, _, _) in enumerate(with_loc):
+            relative_distance = distances[i] / median_distance
+            if last_update < time_cutoff_str and relative_distance > 10:
+                suspect_locations.append(pid)
+
+        for pid, last_update, lat, lon in properties:
+            if last_update < time_cutoff_str and (not lat or not lon):
+                suspect_locations.append(pid)
+
+    print('Found %i properties with suspect coordinates.' % len(suspect_locations))
+
+    return suspect_locations
+
+def fetch_properties(conn, property_ids=None):
+
+    if not property_ids:
+        property_ids = []
+
+    property_ids.extend(conn.select('''
         select distinct sr.property_id 
         from search_results sr left join properties p on sr.property_id = p.id 
         where p.id is null
-    ''')
-    
+    '''))
     
     complete = 0
-    for batch in util.batches(unknown_properties, 10):
-        print('Fetching property details (complete: %i/%i)...' % (complete, len(unknown_properties)))
+    for batch in util.batches(property_ids, 10):
+        print('Fetching property details (complete: %i/%i)...' % (complete, len(property_ids)))
 
-        stmt = 'insert into properties (id, last_update, raw_json) values'
+        stmt = 'replace into properties (id, last_update, raw_json) values'
         params = []
 
         for property_id in batch:
             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"]:
+            if resp.status_code == 404 or resp.json() in ["The property you requested isn't available any more", "The property you requested is inactive and can't be found"]:
                 stmt += ' (?, ?, ?),'
                 params.extend([
                     property_id,
@@ -144,6 +190,7 @@ def fetch_properties(conn):
                         json.dumps(data)
                     ])
                 except Exception as e:
+                    print('Error for %s: %s' % (property_id, resp.status_code))
                     print(str(e))
                     print(resp.json())
         
@@ -274,7 +321,9 @@ def run():
             print('You must set MONITORED_LOCATIONS. Possible values: ')
             init_localities.init_localities(conn)
 
-        fetch_properties(conn)
+        suspect_locations = check_bad_locations(conn)
+
+        fetch_properties(conn, property_ids=suspect_locations)
         process_properties(conn)
 
 if __name__ == '__main__':

+ 9 - 0
util.py

@@ -10,3 +10,12 @@ def batches(iterable, n):
     while i < len(iterable):
         yield iterable[i:i+n]
         i += n
+
+def median(arr):
+    if not arr:
+        return None
+    
+    arr = sorted(arr)
+
+    return arr[int(len(arr) / 2)]
+