service.py 10 KB

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