service.py 14 KB

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