service.py 10 KB

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