service.py 12 KB

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