service.py 14 KB

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