service.py 9.3 KB

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