service.py 8.0 KB

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