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. THRESHOLD = 30
  33. # Modos de procesamiento de queue
  34. #  - QUEQUE_SINGLE: procesa solo un segmento a la vez
  35. # - QUEUE_THREAD: inicia un hilo para cada segmento
  36. # Por default se usará el threaded.
  37. # TOOD: hacerlo configurable por medio de argumentos
  38. # de ejecución.
  39. QUEUE_SINGLE = 1
  40. QUEUE_THREAD = 2
  41. # Se pueden usar diferentes API's
  42. # la de threading y la de multiprocessing.
  43. MultiAPI = Process
  44. config = parse_config()
  45. queue = Queue()
  46. client = Client(config['device_id'],
  47. config['apiSecret'])
  48. cloud_base_url = 'https://storage.googleapis.com/{}'\
  49. .format(config['bucket'])
  50. base_path = config.get("basepath", "/var/fourier")
  51. fb_credentials = credentials.Certificate('/etc/Fourier-key.json')
  52. firebase_admin.initialize_app(fb_credentials, config['firebase'])
  53. dejavu = Dejavu({"database_type":"mem"})
  54. device_id = config['device_id']
  55. device_path = os.path.join(base_path, device_id)
  56. recognizer = FilePerSecondRecognizer
  57. queue_mode = QUEUE_THREAD
  58. db_path = config.get('localDatabase', os.path.join(device_path, 'files.db'))
  59. db = sqlite3.connect(db_path)
  60. cloud_cache = {}
  61. def feed_queue():
  62. """ Search for pending scheduled work in
  63. server and add them to a memory queue. """
  64. try:
  65. response = client.get_schedule_pending()
  66. downloaded_counter = len(response['items'])
  67. for item in response['items']:
  68. queue.put(item)
  69. if downloaded_counter:
  70. log.info(('[feed_queue] {} new '
  71. + 'pending schedule items.')\
  72. .format(downloaded_counter)
  73. )
  74. if queue.qsize() > 0:
  75. if queue_mode == QUEUE_THREAD:
  76. loop.add_callback(process_queue_with_threads)
  77. else:
  78. loop.add_callback(process_queue)
  79. else:
  80. loop.add_timeout(time.time() + 30, feed_queue)
  81. except ConnectionError as ex:
  82. log.error('[feed_queue] cannot feed: {}, retryig later'.format(ex))
  83. loop.add_timeout(time.time() + 15, feed_queue)
  84. except Exception as ex:
  85. """ Errores desconocidos """
  86. log.error('[feed_queue] {}'.format(ex))
  87. loop.add_timeout(time.time() + 60, feed_queue)
  88. def process_queue():
  89. """ Try to the next item in a queue and start
  90. processing it accordingly. If success, repeat
  91. the function or go to feed if no more items. """
  92. try:
  93. item = queue.get(False)
  94. process_segment(item)
  95. loop.add_callback(process_queue)
  96. except Empty:
  97. loop.add_callback(feed_queue)
  98. except Exception as ex:
  99. log.error(ex)
  100. loop.add_callback(process_queue)
  101. def process_queue_with_threads():
  102. threads = [None] * MAX_SEGMENT_THREADS
  103. is_drained = False
  104. log.info('Starting thread processing')
  105. while True:
  106. for index, t in enumerate(threads):
  107. if not t:
  108. try:
  109. item = queue.get(False)
  110. station = item['station']
  111. date = dateutil.parser.parse(item['date'])
  112. thread = MultiAPI(target=process_segment,
  113. args=(item,),
  114. kwargs={
  115. 'audios': [f for f in iterate_audios(date, station)]
  116. }
  117. )
  118. threads[index] = thread
  119. thread.start()
  120. except Empty:
  121. is_drained = True
  122. elif not t.is_alive():
  123. threads[index] = None
  124. if is_drained:
  125. if threads.count(None) == MAX_SEGMENT_THREADS:
  126. break
  127. log.info('Finished thread processing')
  128. loop.add_callback(feed_queue)
  129. def process_segment(item, audios=None):
  130. """ Procesa una hora de audio """
  131. station = item['station']
  132. date = dateutil.parser.parse(item['date'])
  133. log.info('processing segment: {}'.format(item))
  134. # 1. obtener el audio desde firebase
  135. # y calcular su fingerprint.
  136. filename, md5hash = cloud_download(ad_key=item['ad'])
  137. if not filename:
  138. log.info('ad file missing')
  139. return
  140. # 1.1 Calcular el número de segmentos requeridos
  141. # de acuerdo a la duración total del audio.
  142. try:
  143. audio = mutagen.mp3.MP3(filename)
  144. segments_needed = int(round(float(audio.info.length) / float(5)))
  145. except Exception as ex:
  146. log.error('file {} is not an mp3'.format(audio))
  147. log.error(str(ex))
  148. return
  149. try:
  150. dejavu.fingerprint_file(filename)
  151. except Exception as ex:
  152. log.error('cannot fingerprint: {}'.format(ex))
  153. """ Hay dos posibles escensarios al obtener los audios
  154. a. Los audios vienen por el parámetro "audios" de la
  155. función, siendo esta una lista.
  156. b. Los audios se obtienen directamente de la base
  157. de datos en modo de cursor.
  158. """
  159. audios_iterable = audios if audios \
  160. else iterate_audios(date, station)
  161. # 2. Read the list of files from local database
  162. audios_counter = 0
  163. results = []
  164. for path, name, ts in audios_iterable:
  165. log.info('file: {}'.format(path))
  166. audios_counter += os.path.isfile(path)
  167. for match in dejavu.recognize(recognizer, path, 5,
  168. ads_filter=[md5hash]):
  169. try:
  170. results.append({
  171. 'confidence': match['confidence'],
  172. 'timestamp': ts,
  173. 'offset': match['offset']
  174. })
  175. log.info("{} {}".format(ts, match['confidence']))
  176. except KeyError as ex:
  177. log.error(str(ex))
  178. ts += match['length'] / 1000
  179. try:
  180. response = client.put_schedule_results(
  181. item['schedule'],
  182. item['id'],
  183. None, # TODO: send results again
  184. found=find_repetitions(results,
  185. segments_needed=segments_needed
  186. ),
  187. missing_files=(12 - audios_counter) \
  188. if audios_counter < 12 else 0
  189. )
  190. log.info('API response: {}'.format(response))
  191. except ConnectionError as ex:
  192. log.error(str(ex))
  193. except UserWarning as warn:
  194. log.warning(str(warn))
  195. def find_repetitions(results, segments_needed=2):
  196. found_counter = 0
  197. found_index = None
  198. seconds_needed = 9
  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')