service.py 12 KB

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