service.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # -*- coding: utf8 -*-
  2. from __future__ import print_function
  3. from tornado.ioloop import IOLoop
  4. from tornado.web import Application
  5. from fourier.api.client import Client, ConnectionError
  6. from fourier.boxconfig import parse_config
  7. from fourier.dejavu.recognize import FilePerSecondRecognizer
  8. from datetime import datetime, timedelta
  9. from fourier.dejavu import Dejavu
  10. from Queue import Queue, Empty
  11. from firebase_admin import credentials
  12. from firebase_admin import db as fbdb
  13. from binascii import hexlify
  14. from base64 import b64decode
  15. import firebase_admin
  16. import requests
  17. import dateutil
  18. import sqlite3
  19. import time
  20. import sys
  21. import os
  22. AUDIOS_PATH = '/tmp'
  23. AHEAD_TIME_AUDIO_TOLERANCE = 1 # second
  24. config = parse_config()
  25. queue = Queue()
  26. client = Client(config['device_id'],
  27. config['apiSecret'])
  28. cloud_base_url = 'https://storage.googleapis.com/{}'\
  29. .format(config['bucket'])
  30. base_path = config.get("basepath", "/var/fourier")
  31. fb_credentials = credentials.Certificate('/etc/Fourier-key.json')
  32. firebase_admin.initialize_app(fb_credentials, config['firebase'])
  33. dejavu = Dejavu({"database_type":"mem"})
  34. device_id = config['device_id']
  35. device_path = os.path.join(base_path, device_id)
  36. recognizer = FilePerSecondRecognizer
  37. db_path = os.path.join(device_path, 'files.db')
  38. db = sqlite3.connect(db_path)
  39. cloud_cache = {}
  40. def feed_queue():
  41. """ Search for pending scheduled work in
  42. server and add them to a memory queue. """
  43. try:
  44. response = client.get_schedule_pending()
  45. for item in response['items']:
  46. queue.put(item)
  47. if queue.qsize() > 0:
  48. loop.add_callback(process_queue)
  49. else:
  50. loop.add_timeout(time.time() + 30, feed_queue)
  51. except ConnectionError as ex:
  52. print('cannot feed: {}, retryig later'.format(ex),
  53. file=sys.stderr)
  54. loop.add_timeout(time.time() + 15, feed_queue)
  55. except Exception as ex:
  56. """ Errores desconocidos """
  57. print(ex, file=sys.stderr)
  58. loop.add_timeout(time.time() + 60, feed_queue)
  59. def process_queue():
  60. """ Try to the next item in a queue and start
  61. processing it accordingly. If success, repeat
  62. the function or go to feed if no more items. """
  63. try:
  64. item = queue.get(False)
  65. process_segment(item)
  66. loop.add_callback(process_queue)
  67. except Empty:
  68. loop.add_callback(feed_queue)
  69. except Exception as ex:
  70. print(str(ex), file=sys.stderr)
  71. loop.add_callback(process_queue)
  72. def process_segment(item):
  73. """ Procesa una hora de audio """
  74. station = item['station']
  75. date = dateutil.parser.parse(item['date'])
  76. # 1. obtener el audio desde firebase
  77. # y calcular su fingerprint.
  78. filename, md5hash = cloud_download(ad_key=item['ad'])
  79. if not filename:
  80. print('ad file missing', file=sys.stderr)
  81. return
  82. try:
  83. dejavu.fingerprint_file(filename)
  84. except Exception as ex:
  85. print('cannot fingerprint: {}'.format(ex))
  86. # 2. Read the list of files from local database
  87. results = []
  88. for path, name, ts in iterate_audios(date, station):
  89. print(path)
  90. for match in dejavu.recognize(recognizer, path, 5,
  91. ads_filter=[md5hash]):
  92. try:
  93. results.append({
  94. 'confidence': match['confidence'],
  95. 'timestamp': ts,
  96. 'offset': match['offset']
  97. })
  98. print("{} {}".format(ts, match['confidence']))
  99. except KeyError as ex:
  100. print(ex, file=sys.stderr)
  101. ts += match['length'] / 1000
  102. try:
  103. response = client.put_schedule_results(
  104. item['schedule'],
  105. item['id'],
  106. None, # TODO: send results again
  107. found=find_repetitions(results),
  108. )
  109. print("api response: {}".format(response))
  110. except ConnectionError as ex:
  111. print(ex, file=sys.stderr)
  112. except UserWarning as warn:
  113. print(str(warn), file=sys.stderr)
  114. def find_repetitions(results):
  115. found_counter = 0
  116. found_index = None
  117. segments_needed = 2
  118. seconds_needed = 9
  119. threshold = 20
  120. expect_space = False
  121. found = []
  122. for index, result in enumerate(results):
  123. if not expect_space:
  124. if result['confidence'] > threshold:
  125. found_counter += 1
  126. if found_index is None:
  127. found_index = index
  128. else:
  129. found_counter = 0
  130. found_index = None
  131. else:
  132. if result['confidence'] <= threshold:
  133. expect_space = False
  134. if found_counter >= segments_needed:
  135. found.append(results[found_index]['timestamp'])
  136. found_counter = 0
  137. expect_space = True
  138. return found
  139. def iterate_audios(dt, station):
  140. """ Given a datetime object and an station,
  141. iterate a list of files that are between
  142. the the date and itself plus 5 minutes;
  143. station must match too """
  144. from_time = time.mktime(dt.timetuple()) \
  145. - AHEAD_TIME_AUDIO_TOLERANCE
  146. to_time = from_time + 3599
  147. print('from {} to {}'.format(from_time, to_time))
  148. cursor = db.cursor()
  149. cursor.execute((
  150. 'select "filename", "timestamp" '
  151. 'from "file" '
  152. 'where "timestamp" between ? and ? '
  153. 'and "station" = ? '
  154. 'order by "timestamp" asc'
  155. ),
  156. (from_time, to_time, station, ),
  157. )
  158. files = [file for file in cursor]
  159. cursor.close()
  160. for mp3 in files:
  161. mp3path, ts = mp3
  162. mp3name = os.path.basename(mp3path)
  163. yield (mp3path, mp3name, ts)
  164. def cloud_download(ad_key=None):
  165. """ Given an ad key, the file is downloaded to
  166. the system temporal folder to be processed """
  167. if ad_key in cloud_cache:
  168. """ If this file has already been downloaded,
  169. will not be downloaded again, instead will
  170. be taken from cloud_cache dictionary """
  171. filename, md5hash = cloud_cache[ad_key]
  172. if os.path.isfile(filename):
  173. return filename, md5hash
  174. ad = fbdb.reference('ads/{}'.format(ad_key)).get()
  175. filename = os.path.basename(ad['path'])
  176. out_file = os.path.join(AUDIOS_PATH, filename)
  177. url = '{}/{}'.format(cloud_base_url, ad['path'])
  178. response = requests.get(url)
  179. if response.status_code == 200:
  180. hashes = response.headers['x-goog-hash']
  181. hashes = hashes.split(',')
  182. hashes = [h.split('=', 1) for h in hashes]
  183. hashes = {h[0].strip(): hexlify(b64decode(h[1])) for h in hashes}
  184. md5sum = hashes['md5']
  185. with open(out_file, "wb") as fp:
  186. fp.write(response.content)
  187. tp = (out_file, md5sum)
  188. cloud_cache[ad_key] = tp
  189. return tp
  190. app = Application()
  191. loop = IOLoop.current()
  192. loop.add_callback(feed_queue)
  193. if __name__ == '__main__':
  194. loop.start()