فهرست منبع

add better support for "sites" as opposed to properties

Martin 6 سال پیش
والد
کامیت
07f84160ae
7فایلهای تغییر یافته به همراه157 افزوده شده و 73 حذف شده
  1. 11 11
      config.py
  2. 26 9
      create_htmls.py
  3. 1 1
      monitor.py
  4. 10 4
      properties.py
  5. 73 42
      ranking.py
  6. 23 0
      util.py
  7. 13 6
      visualize.py

+ 11 - 11
config.py

@@ -31,24 +31,24 @@ 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
+MIN_PRICE = 150000
+MAX_PRICE = 1500000
 
 SEARCH_PARAMS = {
     'ChannelIds': [1],
-    'Destinations': [],
-    'EnergyRatings': [],
+    # 'Destinations': [],
+    # 'EnergyRatings': [],
     'GroupIds': [],
-    'IsAuction': "",
-    'IsSaleAgreed': "",
-    'IsSold': False,
+    # 'IsAuction': "",
+    # 'IsSaleAgreed': "",
+    # 'IsSold': False,
     'LocalityIds': [],
-    'MaxBeds': "",
-    'MaxEnergyRating': "",
+    # 'MaxBeds': "",
+    # 'MaxEnergyRating': "",
     'MaxPrice': str(MAX_PRICE),
     'MaxSize': "",
-    'MinBathrooms': "1",
-    'MinBeds': "2",
+    # 'MinBathrooms': "1",
+    # 'MinBeds': "2",
     'MinEnergyRating': "",
     'MinPrice': str(MIN_PRICE),
     'MinSize': "",

+ 26 - 9
create_htmls.py

@@ -30,6 +30,11 @@ def run_single(conn, pid, check_bad_urls=False):
 
     raw_json, price, lat, lon, size, ber, address, property_type, bathrooms, bedrooms = rows[0]
 
+    price = int(price) if price is not None else price
+    size = int(size) if size is not None else size
+    bedrooms = int(bedrooms) if bedrooms is not None else bedrooms
+    bathrooms = int(bathrooms) if bathrooms is not None else bathrooms
+
     data = json.loads(raw_json)
 
     search_rows = conn.select('select time, price from search_results where property_id=? order by time asc', pid)
@@ -42,17 +47,28 @@ def run_single(conn, pid, check_bad_urls=False):
         <style>
             img {width: 900px}
             td {padding-right: 20px}
+
+            #top {
+                position: fixed;
+                top: 0;
+                left: 0;
+                z-index: 999;
+                width: 100%;
+                height: 23px;
+            }
         </style>
         ''')
         f.write('<h2>%s</h2>\n' %  address)
 
+        # f.write('<div id="top">')
         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">%sk</span>, ' % (_color(ranking.r_price(price/1000)), int(price/1000)))
+        f.write('<span style="background-color: %s">%s m<sup>2</sup></span>, ' % (_color(ranking.r_size(size)), size))
+        f.write('<span style="background-color: %s">%s br</span> / ' % (_color(ranking.r_bedrooms(bedrooms)), bedrooms))
+        f.write('<span style="background-color: %s">%s b</span>, ' % (_color(ranking.r_bathrooms(bathrooms)), bathrooms))
         f.write('<span style="background-color: %s">%s</span>' % (_color(ranking.r_ber(ber)), ber))
         f.write('</h2><br>\n')
+        # f.write('</div>')
 
         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)
@@ -61,7 +77,7 @@ def run_single(conn, pid, check_bad_urls=False):
             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('<tr><td>%s</td><td>%s</td></tr>' % (ts, int(int(price)/1000) if price and price.isdigit() else price))
             f.write('</table>')
         
         f.write('<p><hr><p>')
@@ -152,10 +168,11 @@ def _get_pid(conn, possible_pid):
 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)
+            for pid in sys.argv[1:]:
+                pid = int(pid)
+                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')

+ 1 - 1
monitor.py

@@ -118,7 +118,7 @@ def check_bad_locations(conn):
         by_locality[locality_id].append((pid, last_update, lat, lon))
 
     suspect_locations = []
-    time_cutoff = datetime.datetime.now() - datetime.timedelta(days=14)
+    time_cutoff = datetime.datetime.now() - datetime.timedelta(days=31)
     time_cutoff_str = db.datetime_to_str(time_cutoff)
 
     for locality_id, properties in by_locality.items():

+ 10 - 4
properties.py

@@ -4,13 +4,13 @@ import geo_util
 import config
 
 def load_properties(require_active=True):
-    ts = db.datetime_to_str(datetime.datetime.now() - datetime.timedelta(days=180))
+    ts = db.datetime_to_str(datetime.datetime.now() - datetime.timedelta(days=90))
     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" and last_update > "%s"' % (config.MAX_PRICE, ts))
+        rows = conn.select('select id, lat, lon, size, price, bedrooms, ber, bathrooms, property_type from properties '
+                           'where price<%i and last_update > "%s"' % (config.MAX_PRICE, ts))
 
         res = {}
-        for property_id, lat, lon, size, price, bedrooms, ber in rows:
+        for property_id, lat, lon, size, price, bedrooms, ber, bathrooms, property_type in rows:
             if not price or not size or not lat or not lon:
                 continue
 
@@ -19,13 +19,19 @@ def load_properties(require_active=True):
 
             price = price/1000
 
+            if isinstance(bedrooms, str) and bedrooms.endswith(' bed'):
+                bedrooms = int(bedrooms[:-4])
+
             res[property_id] = {
+                'id': property_id,
                 'loc': (lat, lon),
                 'size': size,
                 'price': price,
                 'bedrooms': bedrooms,
+                'bathrooms': bathrooms,
                 'price_history': [],
                 'ber': ber,
+                'type': property_type,
             }
 
         rows = conn.select('select property_id, price from search_results order by time asc')

+ 73 - 42
ranking.py

@@ -18,48 +18,61 @@ _BER_RANKINGS = {
     'Exempt': (500 + 500) / 2.0,
 }
 
-_BER_CONF = [
-    (25, 1),
-    (60, 0.9),
-    # (140, 0.6),
-    # (300, 0.1),
-    (240, 0.5),
-    (300, 0.1),
-]
-
-_SIZE_CONF = [
-    (60, 0.3),
-    (150, 1),
-    (400, 1),
-]
-
-_BEDROOMS_CONF = [
-    (2, 0.2),
-    (3, 0.8),
-    (4, 1),
-    (10, 1),
-]
-
-_BATHROOMS_CONF = [
-    (1, 0.5),
-    (2, 1),
-    (3, 1),
-    (4, 0.5),
-]
+_TYPE_CONF = {
+    'Site': 0,
+    'Other': 1,
+}
+
+_BER_CONF = {
+    25: 1,
+    70: 0.9,
+    260: 0.5,
+}
+
+_SIZE_CONF = {
+    90: 0,
+    100: 0.5,
+    180: 1,
+    400: 1,
+}
+
+_BEDROOMS_CONF = {
+    None: 0.4,
+    2: 0.4,
+    3: 0.8,
+    4: 1,
+    10: 1,
+}
+
+_BATHROOMS_CONF = {
+    None: 0.7,
+    1: 0.5,
+    2: 1,
+    5: 1,
+}
 
 # disabled
-_COMMUTE_CONF = [
-    (0, 1),
-    (60*70, 1),
-]
+_COMMUTE_CONF = {
+    0: 1,
+    60 * 70: 1,
+}
 
-_PRICE_CONF = [
-    (400, 1),
-    (800, 0.0),
-]
+_PRICE_CONF = {
+    400: 1,
+    800: 0.6,
+}
 
+_RERANKING_CONF = {
+    0: 0,
+    1: 1,
+}
 
 def _linear(signal, configuration):
+    if signal in configuration:
+        return configuration[signal]
+    
+    configuration = sorted([(k, v) for k, v in configuration.items() if k is not None])
+
     if signal < configuration[0][0] or signal > configuration[-1][0]:
         return 0
 
@@ -98,18 +111,36 @@ def r_ber(ber):
 
     return _linear(value, _BER_CONF)
 
+def r_type(ptype):
+    return _TYPE_CONF.get(ptype, _TYPE_CONF['Other'])
+
+def r_rerank(score):
+    return _linear(score, _RERANKING_CONF)
+
 def _rank(data):
     res = 1.0
 
-    res *= r_size(data['size'])
-    res *= r_price(data['price'])
-    if 'commute_duration' in data:
-        res *= r_commute_duration(data['commute_duration'])
-    res *= r_ber(data['ber'])
-    res *= r_bedrooms(data['bedrooms'])
+    if data['type'] != 'Site':
+        res *= r_price(data['price'])
+        res *= r_size(data['size'])
+        if 'commute_duration' in data:
+            res *= r_commute_duration(data['commute_duration'])
+        res *= r_ber(data['ber'])
+        res *= r_bedrooms(data['bedrooms'])
+        res *= r_bathrooms(data['bathrooms'])
+        res *= r_type(data['type'])
+    else:
+        res *= r_type(data['type'])
+
 
     return res
 
 def add_scores(properties_dict):
     for p in properties_dict.values():
         p['score'] = _rank(p)
+    return {k: v for k, v in properties_dict.items() if v['score'] > 0}
+
+def rerank(properties_dict):
+    for p in properties_dict.values():
+        p['score'] = r_rerank(p['score'])
+    return {k: v for k, v in properties_dict.items() if v['score'] > 0}

+ 23 - 0
util.py

@@ -19,3 +19,26 @@ def median(arr):
 
     return arr[int(len(arr) / 2)]
         
+def print_distribution(values):
+    if not values:
+        return
+    
+    n_points = 30.
+
+    ns = []
+    for i in range(int(n_points)):
+        start = i/n_points
+        end = (i+1)/n_points
+        n = len([v for v in values if start < v <= end])
+        ns.append(n)
+    
+    max_val = max(ns)
+
+    for i in range(int(n_points)):
+        start = i/n_points
+        end = (i+1)/n_points
+        n = len([v for v in values if start < v <= end])
+        bar = '.' * int((n / float(max_val)) * 40)
+
+        print('%.2f - %.2f: %i\t%s' % (start, end, n, bar))
+

+ 13 - 6
visualize.py

@@ -4,6 +4,7 @@ import db
 import geo_util
 import properties
 import ranking
+import util
 
 def _write_bboxes(f):
     f.write('''
@@ -57,7 +58,7 @@ def _write_properties(f, properties_dict, tmp_ids):
     min_max_delta = max_score - min_score
 
     for pid, data in properties_list:
-        value = (data['score'] - min_score) / min_max_delta
+        value = ((data['score'] - min_score) / min_max_delta) if min_max_delta else 1
         value = min(1, value)
         color = 20 + value * 235
 
@@ -69,7 +70,9 @@ def _write_properties(f, properties_dict, tmp_ids):
             'Price: %s (%.3f)' % (data.get('price', '---'), ranking.r_price(data.get('price'))),
             'Size: %s (%.3f)' % (int(data.get('size', 0)), ranking.r_size(data.get('size'))),
             'Bedrooms: %s (%.3f)' % (data.get('bedrooms') or '---', ranking.r_bedrooms(data.get('bedrooms'))),
+            'Bathrooms: %s (%.3f)' % (data.get('bathrooms') or '---', ranking.r_bathrooms(data.get('bathrooms'))),
             'BER: %s (%.3f)' % (data.get('ber') or '---', ranking.r_ber(data.get('ber'))),
+            'Type: %s (%.3f)' % (data.get('type') or '---', ranking.r_type(data.get('type'))),
         ])
 
         total_duration = sum(x['duration'] for x in data.get('commute_path', []))
@@ -132,14 +135,18 @@ def run():
     # commutes = commute.determine_fastest_paths(graph, config.WORKPLACE)
     # commute.add_commute_data(properties_dict, commutes)
     
-    ranking.add_scores(properties_dict)
+    properties_dict = ranking.add_scores(properties_dict)
+    n1 = len(properties_dict)
+    print('\nLoaded %i properties with score > 0' % len(properties_dict))
+    util.print_distribution([v['score'] for v in properties_dict.values()])
 
-    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))
+    properties_dict = ranking.rerank(properties_dict)
+    n2 = len(properties_dict)
+    if n1 != n2:
+        print('\nAfter reranking, %i properties with score > 0' % len(properties_dict))
+        util.print_distribution([v['score'] for v in properties_dict.values()])
 
     tmp_ids = _set_tmp_ids(properties_dict)
-
     _write_kml(commutes, properties_dict, 'vis.kml', tmp_ids)
 
 if __name__ == '__main__':