service.py 7.0 KB

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