monitor.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import collections
  2. import math
  3. import json
  4. import logging
  5. import datetime
  6. import requests
  7. import db
  8. import config
  9. import init_localities
  10. import util
  11. import geo_util
  12. _SEARCH_PAGE_SIZE = 50
  13. def get_locality_tree(conn):
  14. parents = {}
  15. for parent, child in conn.select('select parent, child from locality_relationships'):
  16. parents[child] = parent
  17. roots = set()
  18. locality_ancestors = collections.defaultdict(list)
  19. for child, parent in parents.items():
  20. locality_ancestors[child].append(parent)
  21. while parents.get(parent):
  22. locality_ancestors[child].append(parents[parent])
  23. parent = parents[parent]
  24. roots.add(parent)
  25. return roots, parents, locality_ancestors
  26. def process_properties(conn):
  27. count = conn.select('select count(1) from properties where processed=0')[0]
  28. if not count:
  29. return
  30. _, _, locality_ancestors = get_locality_tree(conn)
  31. print('Processing %i properties...' % count)
  32. rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 50')
  33. while rows:
  34. stmt = 'replace into properties (id, last_update, raw_json, processed, price, lat, lon, size, ber, address, locality_id, property_type, bathrooms, bedrooms) values'
  35. params = []
  36. property_localities = []
  37. for property_id, last_update, raw_json in rows:
  38. stmt += ' (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
  39. params.extend([
  40. property_id,
  41. last_update,
  42. raw_json,
  43. ])
  44. if raw_json is None:
  45. params.extend([None] * 10)
  46. else:
  47. data = json.loads(raw_json)
  48. size = None
  49. if data.get('SizeStringMeters'):
  50. size = data.get('SizeStringMeters')
  51. elif data.get('SizeStringFeet'):
  52. size = round(data.get('SizeStringFeet') * 0.09290304, 2)
  53. params.extend([
  54. data.get('Price', {}).get('MinPrice'),
  55. data.get('BrochureMap', {}).get('latitude'),
  56. data.get('BrochureMap', {}).get('longitude'),
  57. size,
  58. data.get('BerRating'),
  59. data.get('DisplayAddress', data.get('Address')),
  60. data.get('LocalityId'),
  61. data.get('PropertyType'),
  62. data.get('Bathrooms', data.get('BathString', '').replace(' baths', '') or None),
  63. data.get('BedsString', '').replace(' beds', '') or None,
  64. ])
  65. if data.get('LocalityId'):
  66. property_localities.append((property_id, data.get('LocalityId')))
  67. if params:
  68. conn.execute(stmt[:-1], *params)
  69. stmt = 'replace into property_locality_map (id, property_id, locality_id) values'
  70. params = []
  71. for property_id, locality_id in property_localities:
  72. ancestors = [locality_id] + locality_ancestors.get(locality_id, [])
  73. for ancestor in ancestors:
  74. stmt += ' (?, ?, ?),'
  75. params.extend([
  76. '%i_%i' % (property_id, ancestor),
  77. property_id,
  78. ancestor
  79. ])
  80. if params:
  81. conn.execute(stmt[:-1], *params)
  82. rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 10')
  83. def check_bad_locations(conn):
  84. data = conn.select('''
  85. select id, last_update, lat, lon, locality_id from properties where processed=1
  86. ''')
  87. by_locality = collections.defaultdict(list)
  88. for pid, last_update, lat, lon, locality_id in data:
  89. by_locality[locality_id].append((pid, last_update, lat, lon))
  90. suspect_locations = []
  91. time_cutoff = datetime.datetime.now() - datetime.timedelta(days=14)
  92. time_cutoff_str = db.datetime_to_str(time_cutoff)
  93. for locality_id, properties in by_locality.items():
  94. if len(properties) <= 2:
  95. continue
  96. with_loc = [p for p in properties if p[2] and p[3]]
  97. median_lat = util.median([p[2] for p in with_loc])
  98. median_lon = util.median([p[3] for p in with_loc])
  99. median_loc = median_lat, median_lon
  100. distances = [geo_util.ggcd(median_loc, (p[2], p[3])) for p in with_loc]
  101. median_distance = util.median(distances)
  102. if median_distance == 0:
  103. median_distance = 2000
  104. for i, (pid, last_update, _, _) in enumerate(with_loc):
  105. relative_distance = distances[i] / median_distance
  106. if last_update < time_cutoff_str and relative_distance > 10:
  107. suspect_locations.append(pid)
  108. for pid, last_update, lat, lon in properties:
  109. if last_update < time_cutoff_str and (not lat or not lon):
  110. suspect_locations.append(pid)
  111. print('Found %i properties with suspect coordinates.' % len(suspect_locations))
  112. return suspect_locations
  113. def fetch_properties(conn, property_ids=None):
  114. if not property_ids:
  115. property_ids = []
  116. property_ids.extend(conn.select('''
  117. select distinct sr.property_id
  118. from search_results sr left join properties p on sr.property_id = p.id
  119. where p.id is null
  120. '''))
  121. complete = 0
  122. for batch in util.batches(property_ids, 10):
  123. print('Fetching property details (complete: %i/%i)...' % (complete, len(property_ids)))
  124. stmt = 'replace into properties (id, last_update, raw_json) values'
  125. params = []
  126. for property_id in batch:
  127. resp = requests.get('https://api.myhome.ie/brochure/%i?ApiKey=%s&RequestTypeId=1' % (property_id, config.MYHOME_API_KEY))
  128. 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"]:
  129. stmt += ' (?, ?, ?),'
  130. params.extend([
  131. property_id,
  132. db.now(),
  133. None,
  134. ])
  135. else:
  136. try:
  137. data = resp.json()['Brochure']['Property']
  138. stmt += ' (?, ?, ?),'
  139. params.extend([
  140. property_id,
  141. db.now(),
  142. json.dumps(data)
  143. ])
  144. except Exception as e:
  145. print('Error for %s: %s' % (property_id, resp.status_code))
  146. print(str(e))
  147. print(resp.json())
  148. if params:
  149. conn.execute(stmt[:-1], *params)
  150. complete += len(batch)
  151. def search(conn, locality_id):
  152. logging.info('Searching %i...', locality_id)
  153. known_prices = conn.select('select property_id, max(time), price from search_results where search_locality_id=? group by property_id', locality_id)
  154. known_prices = {row[0]: str(row[2]) for row in known_prices}
  155. page = 1
  156. num_pages = None
  157. added = 0
  158. modified = 0
  159. seen_properties = set()
  160. while True:
  161. config.SEARCH_PARAMS['RegionId'] = str(locality_id)
  162. body = {
  163. 'AddedSince': "",
  164. 'ApiKey': config.MYHOME_API_KEY,
  165. 'Page': page,
  166. 'PageSize': _SEARCH_PAGE_SIZE,
  167. 'RequestTypeId': 2,
  168. 'SearchRequest': config.SEARCH_PARAMS,
  169. 'SortColumn': 2,
  170. 'SortDirection': 2,
  171. 'endpoint': {
  172. 'name': "Search",
  173. 'paramsName': "SearchRequest",
  174. },
  175. 'params': {
  176. 'RegionId': locality_id
  177. },
  178. }
  179. headers = {
  180. 'content-type': 'application/json',
  181. 'accept': 'application/json',
  182. }
  183. if num_pages:
  184. print('Fetching page %i/%i...' % (page, num_pages))
  185. else:
  186. print('Fetching page %i...' % page)
  187. resp = requests.post('https://api.myhome.ie/search?ApiKey=%s' % config.MYHOME_API_KEY, json=body, headers=headers)
  188. resp.raise_for_status()
  189. data = resp.json()
  190. if not isinstance(data, dict):
  191. print('Error: %s' % data)
  192. return
  193. stmt = 'insert into search_results (search_locality_id, time, property_id, price, raw_json) VALUES '
  194. params = []
  195. for result in data.get('SearchResults', []):
  196. if not result.get('PriceAsString'):
  197. continue
  198. property_id = result['id']
  199. price = result['PriceAsString'].replace(',', '').replace('\u20ac', '')
  200. seen_properties.add(property_id)
  201. if property_id in known_prices and known_prices[property_id] == price:
  202. continue
  203. stmt += ' (?, ?, ?, ?, ?),'
  204. params.extend([
  205. locality_id,
  206. db.now(),
  207. property_id,
  208. price,
  209. json.dumps(result)
  210. ])
  211. if property_id not in known_prices:
  212. added += 1
  213. else:
  214. modified += 1
  215. if params:
  216. conn.execute(stmt[:-1], *params)
  217. num_pages = math.ceil(data['ResultCount'] / float(_SEARCH_PAGE_SIZE))
  218. if page >= num_pages:
  219. break
  220. page += 1
  221. gone = {pid for pid, price in known_prices.items() if price != 'GONE'}.difference(seen_properties)
  222. if gone:
  223. stmt = 'insert into search_results (search_locality_id, time, property_id, price) VALUES'
  224. params = []
  225. for property_id in gone:
  226. stmt += ' (?, ?, ?, ?),'
  227. params.extend([
  228. locality_id,
  229. db.now(),
  230. property_id,
  231. 'GONE',
  232. ])
  233. conn.execute(stmt[:-1], *params)
  234. print('Search complete. %i records fetched; %i new records added; %i records modified; %i records marked as gone.' % (len(seen_properties), added, modified, len(gone)))
  235. def run():
  236. with db.connect() as conn:
  237. if config.MONITORED_LOCALITIES:
  238. for locality_id in config.MONITORED_LOCALITIES:
  239. init_localities.init_localities(conn, locality_id=locality_id)
  240. search(conn, locality_id)
  241. else:
  242. print('You must set MONITORED_LOCATIONS. Possible values: ')
  243. init_localities.init_localities(conn)
  244. suspect_locations = check_bad_locations(conn)
  245. fetch_properties(conn, property_ids=suspect_locations)
  246. process_properties(conn)
  247. if __name__ == '__main__':
  248. run()