service.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. station = item['station']
  106. date = dateutil.parser.parse(item['date'])
  107. thread = Thread(target=process_segment,
  108. args=(item,),
  109. kwargs={
  110. 'audios': [f for f in iterate_audios(date, station)]
  111. }
  112. )
  113. threads[index] = thread
  114. thread.start()
  115. except Empty:
  116. is_drained = True
  117. elif not t.is_alive():
  118. threads[index] = None
  119. if is_drained:
  120. if threads.count(None) == MAX_SEGMENT_THREADS:
  121. break
  122. log.info('Finished thread processing')
  123. loop.add_callback(feed_queue)
  124. def process_segment(item, audios=None):
  125. """ Procesa una hora de audio """
  126. station = item['station']
  127. date = dateutil.parser.parse(item['date'])
  128. log.info('processing segment: {}'.format(item))
  129. # 1. obtener el audio desde firebase
  130. # y calcular su fingerprint.
  131. filename, md5hash = cloud_download(ad_key=item['ad'])
  132. if not filename:
  133. log.info('ad file missing')
  134. return
  135. # 1.1 Calcular el número de segmentos requeridos
  136. # de acuerdo a la duración total del audio.
  137. try:
  138. audio = mutagen.mp3.MP3(filename)
  139. segments_needed = int(round(float(audio.info.length) / float(5)))
  140. except Exception as ex:
  141. log.error('file {} is not an mp3'.format(audio))
  142. log.error(str(ex))
  143. return
  144. try:
  145. dejavu.fingerprint_file(filename)
  146. except Exception as ex:
  147. log.error('cannot fingerprint: {}'.format(ex))
  148. """ Hay dos posibles escensarios al obtener los audios
  149. a. Los audios vienen por el parámetro "audios" de la
  150. función, siendo esta una lista.
  151. b. Los audios se obtienen directamente de la base
  152. de datos en modo de cursor.
  153. """
  154. audios_iterable = audios if audios \
  155. else iterate_audios(date, station)
  156. # 2. Read the list of files from local database
  157. audios_counter = 0
  158. results = []
  159. for path, name, ts in audios_iterable:
  160. log.info('file: {}'.format(path))
  161. audios_counter += os.path.isfile(path)
  162. for match in dejavu.recognize(recognizer, path, 5,
  163. ads_filter=[md5hash]):
  164. try:
  165. results.append({
  166. 'confidence': match['confidence'],
  167. 'timestamp': ts,
  168. 'offset': match['offset']
  169. })
  170. log.info("{} {}".format(ts, match['confidence']))
  171. except KeyError as ex:
  172. log.error(str(ex))
  173. ts += match['length'] / 1000
  174. try:
  175. response = client.put_schedule_results(
  176. item['schedule'],
  177. item['id'],
  178. None, # TODO: send results again
  179. found=find_repetitions(results,
  180. segments_needed=segments_needed
  181. ),
  182. missing_files=(12 - audios_counter) \
  183. if audios_counter < 12 else 0
  184. )
  185. log.info('API response: {}'.format(response))
  186. except ConnectionError as ex:
  187. log.error(str(ex))
  188. except UserWarning as warn:
  189. log.warning(str(warn))
  190. def find_repetitions(results, segments_needed=2):
  191. found_counter = 0
  192. found_index = None
  193. seconds_needed = 9
  194. threshold = 20
  195. expect_space = False
  196. found = []
  197. if segments_needed < 1:
  198. segments_needed = 1
  199. for index, result in enumerate(results):
  200. if not expect_space:
  201. if result['confidence'] > threshold:
  202. found_counter += 1
  203. if found_index is None:
  204. found_index = index
  205. else:
  206. found_counter = 0
  207. found_index = None
  208. else:
  209. if result['confidence'] <= threshold:
  210. expect_space = False
  211. if found_counter >= segments_needed:
  212. found.append(results[found_index]['timestamp'])
  213. found_counter = 0
  214. expect_space = True
  215. return found
  216. def iterate_audios(dt, station):
  217. """ Given a datetime object and an station,
  218. iterate a list of files that are between
  219. the the date and itself plus 5 minutes;
  220. station must match too """
  221. from_time = time.mktime(dt.timetuple()) \
  222. - AHEAD_TIME_AUDIO_TOLERANCE
  223. to_time = from_time + 3599 + AHEAD_TIME_AUDIO_TOLERANCE
  224. log.info('from {} to {}'.format(int(from_time), int(to_time)))
  225. cursor = db.cursor()
  226. cursor.execute((
  227. 'select "filename", "timestamp" '
  228. 'from "file" '
  229. 'where "timestamp" between ? and ? '
  230. 'and "station" = ? '
  231. 'order by "timestamp" asc'
  232. ),
  233. (from_time, to_time, station, ),
  234. )
  235. files = [file for file in cursor]
  236. cursor.close()
  237. for mp3 in files:
  238. mp3path, ts = mp3
  239. mp3name = os.path.basename(mp3path)
  240. yield (mp3path, mp3name, ts)
  241. def cloud_download(ad_key=None):
  242. """ Given an ad key, the file is downloaded to
  243. the system temporal folder to be processed """
  244. if ad_key in cloud_cache:
  245. """ If this file has already been downloaded,
  246. will not be downloaded again, instead will
  247. be taken from cloud_cache dictionary """
  248. filename, md5hash = cloud_cache[ad_key]
  249. if os.path.isfile(filename):
  250. return filename, md5hash
  251. ad = fbdb.reference('ads/{}'.format(ad_key)).get()
  252. filename = os.path.basename(ad['path'])
  253. out_file = os.path.join(AUDIOS_PATH, filename)
  254. url = '{}/{}'.format(cloud_base_url, ad['path'])
  255. response = requests.get(url)
  256. if response.status_code == 200:
  257. hashes = response.headers['x-goog-hash']
  258. hashes = hashes.split(',')
  259. hashes = [h.split('=', 1) for h in hashes]
  260. hashes = {h[0].strip(): hexlify(b64decode(h[1])) for h in hashes}
  261. md5sum = hashes['md5']
  262. with open(out_file, "wb") as fp:
  263. fp.write(response.content)
  264. tp = (out_file, md5sum,)
  265. cloud_cache[ad_key] = tp
  266. return tp
  267. app = setup_endpoint(queue=queue)
  268. loop = IOLoop.current()
  269. loop.add_callback(feed_queue)
  270. if __name__ == '__main__':
  271. try:
  272. log.info('Starting ondemand service')
  273. loop.start()
  274. except KeyboardInterrupt:
  275. log.error('Process killed')