Browse Source

scripts for generating html descriptions of properties, and script for adding favourites

Martin 6 năm trước cách đây
mục cha
commit
659d92f104
5 tập tin đã thay đổi với 212 bổ sung và 14 xóa
  1. 3 1
      .gitignore
  2. 10 0
      annotations.py
  3. 161 0
      create_htmls.py
  4. 10 0
      db_schema.py
  5. 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]))

+ 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',
 ]

+ 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()