5 Commits baa6545650 ... 659d92f104

Autore SHA1 Messaggio Data
  Martin 659d92f104 scripts for generating html descriptions of properties, and script for adding favourites 6 anni fa
  Martin efdb6c72ce only load properties updated in the past 6 months 6 anni fa
  Martin 9ecd251db2 better commute analysis robustness 6 anni fa
  Martin 4f698ede4e add a min_price 6 anni fa
  Martin 36b18c3341 tweak rankings; add r_bathrooms 6 anni fa
9 ha cambiato i file con 268 aggiunte e 35 eliminazioni
  1. 3 1
      .gitignore
  2. 10 0
      annotations.py
  3. 28 8
      commute.py
  4. 3 2
      config.py
  5. 161 0
      create_htmls.py
  6. 10 0
      db_schema.py
  7. 4 1
      properties.py
  8. 21 10
      ranking.py
  9. 28 13
      visualize.py

+ 3 - 1
.gitignore

@@ -66,4 +66,6 @@ data.db*
 data
 *.kml
 .vscode
-.web-cache
+.web-cache
+
+htmls

+ 10 - 0
annotations.py

@@ -0,0 +1,10 @@
+import sys
+import db
+
+def fav(conn, pid):
+    conn.execute('insert into annotations (id, favourited, update_ts) values(?, ?, ?)', pid, 1, db.now())
+
+if __name__ == '__main__':
+    with db.connect() as conn:
+        if sys.argv[1] == 'fav':
+            fav(conn, int(sys.argv[2]))

+ 28 - 8
commute.py

@@ -87,6 +87,8 @@ def directions_call(source, destination, mode):
     resp_data = resp.json()
 
     if not resp_data.get('routes'):
+        if 'error_message' in resp_data:
+            print('Error: %s' % resp_data['error_message'])
         return
 
     _record_api_response(resp_data)
@@ -212,17 +214,17 @@ def log_graph(graph, commutes):
         print('')
 
 def analyze_locations(commutes, num_locations):
-    print('Loading new directions data for %i locations...' % num_locations)
-
     with db.connect() as conn:
         rows = conn.select('''select p.lat, p.lon, price from properties p
-                                where lat is not null and lon is not null and property_type != "Site"''')
+                                where lat is not null and lon is not null and property_type != "Site" and price is not null''')
 
         random.shuffle(rows)
         to_load = []
+        durations = []
+        paths = []
 
         for lat, lon, price in rows:
-            if not (250000 < price < 550000):
+            if not (config.MIN_PRICE < price < config.MAX_PRICE):
                 continue
 
             closest = None
@@ -235,21 +237,35 @@ def analyze_locations(commutes, num_locations):
                     closest_dist = dist
             
             target_loc = (lat, lon)
+            closest_dist = geo_util.ggcd(target_loc, closest)
 
-            if (geo_util.ggcd(target_loc, closest) > 300
-                and any(geo_util.inside(target_loc, bbox) for bbox in config.MONITORED_BBOXES)):
+            if (closest_dist > 300 and any(geo_util.inside(target_loc, bbox) for bbox in config.MONITORED_BBOXES)):
                 to_load.append(target_loc)
+            elif closest_dist <= 300:
+                durations.append(commutes[closest]['duration'] + closest_dist)
+                paths.append(commutes[closest]['path'])
         
+
         print('\tRemaining to load: %i' % len(to_load))
 
+        durations.sort()
+        print('Durations (min): ' + ', '.join(['%.2f' % (durations[int(len(durations) * x)] / 60.) 
+                                               for x in [0.05, 0.25, 0.5, 0.75, 0.95]]))
+
+        random.shuffle(paths)
+        for p in paths[:10]:
+            print(p)
+
+        return
         random.shuffle(to_load)
 
         # target = (53.699593,-6.259772)
         # scores = {loc: geo_util.ggcd(target, loc) for loc in to_load}
         # to_load.sort(key=lambda loc: scores[loc])
 
+        print('Loading new directions data for %i locations...' % num_locations)
         for loc in to_load[:num_locations]:
-            print('\tLoading %s...' % str(loc))
+            # print('\tLoading %s...' % str(loc))
             directions_call(loc, config.WORKPLACE, TransitMethod.TRANSIT)
 
 def add_commute_data(properties, commutes):
@@ -289,8 +305,12 @@ def add_commute_data(properties, commutes):
             'commute_path': best_path,
         })
 
-if __name__ == '__main__':
+def run():
     while True:
         graph = load_graph()
         commutes = determine_fastest_paths(graph, config.WORKPLACE)
         analyze_locations(commutes, 20)
+
+
+if __name__ == '__main__':
+    run()

+ 3 - 2
config.py

@@ -31,6 +31,7 @@ WORKPLACE_TARGET_TIME = 1540893600 # tue 10:00
 while WORKPLACE_TARGET_TIME < time.time():
     WORKPLACE_TARGET_TIME += 7*24*3600
 
+MIN_PRICE = 250000
 MAX_PRICE = 1000000
 
 SEARCH_PARAMS = {
@@ -44,12 +45,12 @@ SEARCH_PARAMS = {
     'LocalityIds': [],
     'MaxBeds': "",
     'MaxEnergyRating': "",
-    'MaxPrice': "1000000",
+    'MaxPrice': str(MAX_PRICE),
     'MaxSize': "",
     'MinBathrooms': "1",
     'MinBeds': "2",
     'MinEnergyRating': "",
-    'MinPrice': "200000",
+    'MinPrice': str(MIN_PRICE),
     'MinSize': "",
     'NegotiatorIds': [],
     'PreSixtyThree': False,

+ 161 - 0
create_htmls.py

@@ -0,0 +1,161 @@
+import json
+import sys
+import webbrowser
+import requests
+
+import db
+import monitor
+import ranking
+
+def _test_url(url):
+    r = requests.head(url)
+    return r.status_code < 300
+
+def _color(ratio):
+    # for ratio on scale [0, 1], return a color on the scale [red, white, green]
+
+    if ratio < 0.5:
+        num = 150+200*ratio
+        num_hex = hex(int(round(num)))[-2:]
+        return 'FF%s%s' % (num_hex, num_hex)
+    else:
+        num = 250-(ratio-0.5)*200
+        num_hex = hex(int(round(num)))[-2:]
+        return '%sFF%s' % (num_hex, num_hex)
+
+def run_single(conn, pid, check_bad_urls=False):
+    rows = conn.select('select raw_json, price, lat, lon, size, ber, address, property_type, bathrooms, bedrooms from properties where id=?', pid)
+    if not rows:
+        raise ValueError('Could not find a property with id %', pid)
+
+    raw_json, price, lat, lon, size, ber, address, property_type, bathrooms, bedrooms = rows[0]
+
+    data = json.loads(raw_json)
+
+    search_rows = conn.select('select time, price from search_results where property_id=? order by time asc', pid)
+
+    main_photo = None
+
+    fname = 'htmls/%i.html' % pid
+    with open(fname, 'w') as f:
+        f.write('''
+        <style>
+            img {width: 900px}
+            td {padding-right: 20px}
+        </style>
+        ''')
+        f.write('<h2>%s</h2>\n' %  address)
+
+        f.write('<h2>')
+        f.write('<span style="background-color: %s">%sk</span>, ' % (_color(ranking.r_price(int(price)/1000)), int(price/1000)))
+        f.write('<span style="background-color: %s">%s m<sup>2</sup></span>, ' % (_color(ranking.r_size(int(size))), size))
+        f.write('<span style="background-color: %s">%s br</span> / ' % (_color(ranking.r_bedrooms(int(bedrooms))), bedrooms))
+        f.write('<span style="background-color: %s">%s b</span>, ' % (_color(ranking.r_bathrooms(int(bathrooms))), bathrooms))
+        f.write('<span style="background-color: %s">%s</span>' % (_color(ranking.r_ber(ber)), ber))
+        f.write('</h2><br>\n')
+
+        f.write('<a href="https://www.myhome.ie/_/brochure/_/%i">myhome.ie</a>' % pid)
+        f.write(', <a href="https://www.google.ie/maps/search/%s">maps.ie</a>' % address)
+
+        if search_rows:
+            f.write('<p><hr><p>')
+            f.write('<table><tr><td><b>Time</b></td><td><b>Price</b></td></tr>')
+            for ts, price in search_rows:
+                f.write('<tr><td>%s</td><td>%s</td></tr>' % (ts, int(int(price)/1000) if price != 'GONE' else price))
+            f.write('</table>')
+        
+        f.write('<p><hr><p>')
+
+        seen = set()
+
+        if data.get('MainPhoto'):
+            main_photo = data['MainPhoto']
+            seen.add(main_photo)
+            f.write('<img src="%s"><br>\n' % main_photo)
+
+        for i, img in enumerate(data.get('FloorPlans', [])):
+            seen.add(img)
+            f.write('<img src="%s">\n' % img)
+            if (i+1) % 2 == 0:
+                f.write('<br>')
+        f.write('<br>')
+
+        i = 0
+        for img in data.get('Images', []):
+            if img['Url'] in seen:
+                continue
+            f.write('<img src="%s">\n' % img['Url'])
+            if (i+1) % 2 == 0:
+                f.write('<br>')
+            i += 1
+
+    if check_bad_urls and main_photo and not _test_url(main_photo):
+        print('Found bad photo URL. Refetching.')
+        monitor.fetch_properties(conn, property_ids=[pid])
+        monitor.process_properties(conn)
+        return run_single(conn, pid)
+
+    return size, ber, address, main_photo, bedrooms, bathrooms, price
+
+def run(conn, retry_bad_pids=True):
+    rows = conn.select('''
+        select a.id, a.update_ts, p.price 
+        from annotations a join properties p on a.id = p.id 
+        where a.favourited=1 order by a.update_ts desc
+    ''')
+    
+    if not rows:
+        raise Exception('No favourited properties.')
+
+    bad_pids = []
+
+    fname = 'htmls/index.html'
+    with open(fname, 'w') as f:
+        f.write('''
+        <style>
+            img {width: 500px}
+        </style>
+        ''')
+
+        for pid, ts, price in rows:
+            row = run_single(conn, pid)
+            size, ber, address, main_photo, bedrooms, bathrooms, price = row
+
+            f.write('<a href="%i.html"><h2>%s</h2></a>' % (pid, address))
+            f.write('<h2>%sk, %s m<sup>2</sup>, %s br / %s b, %s</h2>\n' %  (int(int(price)/1000), size, bedrooms, bathrooms, ber))
+            if main_photo:
+                f.write('<a href="%i.html"><img src="%s"></a>' % (pid, main_photo))
+                if not _test_url(main_photo):
+                    bad_pids.append(pid)
+            f.write('<hr>')
+
+    print('Found %i properties with bad photos' % len(bad_pids))
+    if bad_pids and retry_bad_pids:
+        monitor.fetch_properties(conn, property_ids=bad_pids)
+        monitor.process_properties(conn)
+        return run(conn, retry_bad_pids=False)
+
+    return fname
+
+def _get_pid(conn, possible_pid):
+    if possible_pid > 100000:
+        return possible_pid
+    
+    rows = conn.select('select id from properties where tmp_id=?', possible_pid)
+
+    if not rows:
+        raise ValueError('Could not find a pid for tmp_id=%i' % possible_pid)
+
+    return rows[0]
+
+
+if __name__ == '__main__':
+    with db.connect() as conn:
+        if len(sys.argv) > 1:
+            pid = int(sys.argv[1])
+            pid = _get_pid(conn, pid)
+            fname = run_single(conn, pid, check_bad_urls=True)[0]
+            webbrowser.open('htmls/%i.html' % pid)
+        else:
+            fname = run(conn)
+            webbrowser.open('htmls/index.html')

+ 10 - 0
db_schema.py

@@ -87,4 +87,14 @@ SCHEMA_STATEMENTS = [
         raw_json text
     )
     ''',
+
+    '''
+    create table if not exists annotations (
+        id integer not null primary key,
+        favourited tinyint default 0 not null,
+        update_ts datetime not null
+    )
+    ''',
+
+    'alter table properties add column tmp_id integer',
 ]

+ 4 - 1
properties.py

@@ -1,10 +1,13 @@
+import datetime
 import db
 import geo_util
 import config
 
 def load_properties(require_active=True):
+    ts = db.datetime_to_str(datetime.datetime.now() - datetime.timedelta(days=180))
     with db.connect() as conn:
-        rows = conn.select('select id, lat, lon, size, price, bedrooms, ber from properties where price<%i and property_type != "Site"' % config.MAX_PRICE)
+        rows = conn.select('select id, lat, lon, size, price, bedrooms, ber from properties '
+                           'where price<%i and property_type != "Site" and last_update > "%s"' % (config.MAX_PRICE, ts))
 
         res = {}
         for property_id, lat, lon, size, price, bedrooms, ber in rows:

+ 21 - 10
ranking.py

@@ -21,22 +21,32 @@ _BER_RANKINGS = {
 _BER_CONF = [
     (25, 1),
     (60, 0.9),
-    (140, 0.6),
+    # (140, 0.6),
+    # (300, 0.1),
+    (240, 0.5),
     (300, 0.1),
 ]
 
 _SIZE_CONF = [
-    (50, 0.3),
+    (60, 0.3),
     (150, 1),
     (400, 1),
 ]
 
 _BEDROOMS_CONF = [
-    (3, 0.6),
+    (2, 0.2),
+    (3, 0.8),
     (4, 1),
     (10, 1),
 ]
 
+_BATHROOMS_CONF = [
+    (1, 0.5),
+    (2, 1),
+    (3, 1),
+    (4, 0.5),
+]
+
 # disabled
 _COMMUTE_CONF = [
     (0, 1),
@@ -44,9 +54,8 @@ _COMMUTE_CONF = [
 ]
 
 _PRICE_CONF = [
-    (300, 1),
-    (400, 0.7),
-    (450, 0.3),
+    (400, 1),
+    (800, 0.0),
 ]
 
 
@@ -69,12 +78,14 @@ def r_price(price):
     return _linear(price, _PRICE_CONF)
 
 def r_commute_duration(duration):
-    return 1
-    # return _linear(duration, _COMMUTE_CONF)
+    return _linear(duration, _COMMUTE_CONF)
 
 def r_bedrooms(bedrooms):
     return _linear(bedrooms, _BEDROOMS_CONF)
 
+def r_bathrooms(bathrooms):
+    return _linear(bathrooms, _BATHROOMS_CONF)
+
 def r_ber(ber):
     ber = ber or 'Exempt'
 
@@ -88,12 +99,12 @@ def r_ber(ber):
     return _linear(value, _BER_CONF)
 
 def _rank(data):
-
     res = 1.0
 
     res *= r_size(data['size'])
     res *= r_price(data['price'])
-    res *= r_commute_duration(data['commute_duration'])
+    if 'commute_duration' in data:
+        res *= r_commute_duration(data['commute_duration'])
     res *= r_ber(data['ber'])
     res *= r_bedrooms(data['bedrooms'])
 

+ 28 - 13
visualize.py

@@ -45,7 +45,7 @@ def _write_commutes(f, commutes):
         </Placemark>\n''' % (loc[1], loc[0], color, int(duration / 60), loc))
     f.write('</Folder>')
 
-def _write_properties(f, properties_dict):
+def _write_properties(f, properties_dict, tmp_ids):
     f.write('<Folder><name>Properties</name><visibility>0</visibility>\n')
 
     properties_list = list(properties_dict.items())
@@ -61,7 +61,7 @@ def _write_properties(f, properties_dict):
         value = min(1, value)
         color = 20 + value * 235
 
-        title = '%.0f-%.0f' % (data['price'], data['size'])
+        title = '%.0f-%.0f-%s-%i' % (data['price'], data['size'], data.get('ber', ''), tmp_ids[pid])
 
         description = '<br>\n'.join([
             'https://www.myhome.ie/_/brochure/_/%i' % pid,
@@ -87,7 +87,7 @@ def _write_properties(f, properties_dict):
 
     f.write('</Folder>\n')    
 
-def _write_kml(commutes, properties_dict, fname):
+def _write_kml(commutes, properties_dict, fname, tmp_ids):
     print('Writing .kml visualization file...')
 
     with open(fname, 'w') as f:
@@ -98,34 +98,49 @@ def _write_kml(commutes, properties_dict, fname):
 
         _write_styles(f)
         _write_bboxes(f)
-        # _write_commutes(f, commutes)
-        _write_properties(f, properties_dict)
+        if commutes:
+            _write_commutes(f, commutes)
+        _write_properties(f, properties_dict, tmp_ids)
 
         f.write('''
         </Document>
         </kml>
         ''')
 
-def run():
-    graph = commute.load_graph()
+def _set_tmp_ids(properties_dict):
+    print ('Setting tmp ids...')
 
-    commutes = commute.determine_fastest_paths(graph, config.WORKPLACE)
+    res = {}
 
-    # import json
-    # print(json.dumps({str(k): v for k, v in commutes.items()}))
+    with db.connect() as conn:
+        conn.execute('update properties set tmp_id=null')
 
-    properties_dict = properties.load_properties()
+        properties_list = list(properties_dict.items())
+        properties_list.sort(key=lambda x: x[1]['score'], reverse=True)
+        for i, (pid, _) in enumerate(properties_list):
+            conn.execute('update properties set tmp_id=? where id=?', i, pid)
+            res[pid] = i
+
+    return res
 
+def run():
+    properties_dict = properties.load_properties()
     print('Loaded %i properties' % len(properties_dict))
 
-    commute.add_commute_data(properties_dict, commutes)
+    commutes = None
+    # graph = commute.load_graph()
+    # commutes = commute.determine_fastest_paths(graph, config.WORKPLACE)
+    # commute.add_commute_data(properties_dict, commutes)
+    
     ranking.add_scores(properties_dict)
 
     properties_dict = {k: v for k, v in properties_dict.items() if v['score'] > 0}
 
     print('Loaded %i locations with score>0' % len(properties_dict))
 
-    _write_kml(commutes, properties_dict, 'vis.kml')
+    tmp_ids = _set_tmp_ids(properties_dict)
+
+    _write_kml(commutes, properties_dict, 'vis.kml', tmp_ids)
 
 if __name__ == '__main__':
     run()