service.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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'], client=client)
  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 Empty:
  142. is_drained = True
  143. except Exception as err:
  144. log.error('[process_queue_with_threads] [{}] {}'.format(
  145. station,
  146. err,
  147. ))
  148. continue
  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. try:
  178. filename, md5hash = cloud_download(ad_key=item['ad'])
  179. if not filename:
  180. log.info('[process_segment] ad file missing')
  181. return
  182. except Exception as err:
  183. log.error('[process_segment] [{}] {}'.format(station, err))
  184. return
  185. # 1.1 Calcular el número de segmentos requeridos
  186. # de acuerdo a la duración total del audio.
  187. try:
  188. audio = mutagen.mp3.MP3(filename)
  189. audio_length = audio.info.length
  190. if segment_size == 'integer':
  191. segment_size = int(audio_length)
  192. elif segment_size == 'ceil':
  193. segment_size = int(math.ceil(audio_length / 5)) * 5
  194. segments_needed = int(round(float(audio_length) / float(segment_size)))
  195. segments_needed = int(round(segments_needed * tolerance))
  196. except Exception as ex:
  197. log.error('[process_segment] file {} is not an mp3'.format(filename))
  198. log.error(str(ex))
  199. return
  200. try:
  201. dejavu.fingerprint_file(filename)
  202. except Exception as ex:
  203. log.error('[process_segment] cannot fingerprint: {}'.format(ex))
  204. """ Hay dos posibles escensarios al obtener los audios
  205. a. Los audios vienen por el parámetro "audios" de la
  206. función, siendo esta una lista.
  207. b. Los audios se obtienen directamente de la base
  208. de datos en modo de cursor.
  209. """
  210. try:
  211. audios_iterable = audios if audios \
  212. else iterate_audios(date, station, calibration=calibration)
  213. except sqlite3.OperationalError as err:
  214. log.error('[process_segment] [{}] {}'.format(station, err))
  215. return
  216. # 2. Read the list of files from local database
  217. audios_counter = 0
  218. results = []
  219. for path, name, ts in audios_iterable:
  220. short_path = os.path.join(station, name)
  221. audios_counter += os.path.isfile(path)
  222. values = []
  223. if not os.path.isfile(path):
  224. log.error('[process_segment] file not found: {}'\
  225. .format(short_path))
  226. continue
  227. for match in dejavu.recognize(recognizer, path, segment_size,
  228. ads_filter=[md5hash]):
  229. try:
  230. results.append({
  231. 'confidence': match['confidence'],
  232. 'timestamp': ts,
  233. 'offset': match['offset']
  234. })
  235. values.append(str(match['confidence']))
  236. except KeyError as ex:
  237. # TODO: eliminar esta parte, ya no será necesario
  238. if 'confidence' in str(ex):
  239. log.error('Invalid confidence')
  240. log.error(match)
  241. else:
  242. log.error(str(ex))
  243. ts += match['length'] / 1000
  244. log.info('[process_segment] [{3}] {2} {0}) {1}'.format(
  245. os.path.split(path)[-1],
  246. ','.join(values),
  247. item['ad'],
  248. station,
  249. ))
  250. try:
  251. response = client.put_schedule_results(
  252. item['schedule'],
  253. item['id'],
  254. None, # TODO: send results again
  255. found=find_repetitions(results,
  256. segments_needed=segments_needed,
  257. calibration=calibration,
  258. ),
  259. missing_files=(12 - audios_counter) \
  260. if audios_counter < 12 else 0
  261. )
  262. log.info('[{}] API response: {}'.format(station, response))
  263. except ConnectionError as ex:
  264. log.error('[process_segment] {}'.format(str(ex)))
  265. except UserWarning as warn:
  266. log.warning(str(warn))
  267. def find_repetitions(results, segments_needed=2, calibration=None):
  268. found_counter = 0
  269. found_index = None
  270. expect_space = False
  271. expect_recover = False
  272. last_value_in_threshold_index = -1
  273. fall_tolerance = calibration['fallTolerance']
  274. found = []
  275. if threshold_mode == THRESHOLD_FIXED:
  276. threshold = calibration['threshold']
  277. elif threshold_mode == THRESHOLD_AVERAGE:
  278. values = [x['confidence'] for x in results]
  279. threshold = math.ceil(float(sum(values)) / float(len(values)))
  280. if segments_needed < 1:
  281. segments_needed = 1
  282. for index, result in enumerate(results):
  283. if not expect_space:
  284. if result['confidence'] >= threshold:
  285. found_counter += 1
  286. last_value_in_threshold_index = index
  287. if found_index is None:
  288. found_index = index
  289. if expect_recover:
  290. expect_recover = False
  291. elif fall_tolerance:
  292. if not expect_recover:
  293. if last_value_in_threshold_index != -1:
  294. """ Solo cuando ya haya entrado por lo menos
  295. un valor en el rango del threshold, es cuando
  296. se podrá esperar un valor bajo """
  297. expect_recover = True
  298. found_counter += 1
  299. else:
  300. pass
  301. else:
  302. """ Si después de haber pasado tolerado 1 elemento
  303. vuelve a salir otro fuera del threshold continuo,
  304. entonces ya se da por perdido """
  305. found_counter = 0
  306. found_index = None
  307. expect_recover = False
  308. else:
  309. found_counter = 0
  310. found_index = None
  311. expect_recover = False
  312. else:
  313. if result['confidence'] <= threshold:
  314. expect_space = False
  315. if found_counter >= segments_needed:
  316. found.append(results[found_index]['timestamp'])
  317. found_counter = 0
  318. expect_space = True
  319. return found
  320. def iterate_audios(dt, station, calibration=None):
  321. """ Given a datetime object and an station,
  322. iterate a list of files that are between
  323. the the date and itself plus 5 minutes;
  324. station must match too """
  325. tm = time.mktime(dt.timetuple())
  326. if calibration and calibration['hourlyOffset']:
  327. hoffset = calibration['hourlyOffset']
  328. from_time = tm + hoffset
  329. to_time = tm + 3599 + hoffset
  330. elif AHEAD_TIME_AUDIO_TOLERANCE:
  331. """ Conventional mode """
  332. from_time = tm + AHEAD_TIME_AUDIO_TOLERANCE
  333. to_time = from_time + 3599 + AHEAD_TIME_AUDIO_TOLERANCE
  334. log.info('from {} to {}'.format(int(from_time), int(to_time)))
  335. cursor = db.cursor()
  336. cursor.execute((
  337. 'select "filename", "timestamp" '
  338. 'from "file" '
  339. 'where "timestamp" between ? and ? '
  340. 'and "station" = ? '
  341. 'order by "timestamp" asc'
  342. ),
  343. (from_time, to_time, station, ),
  344. )
  345. files = [file for file in cursor]
  346. cursor.close()
  347. for mp3 in files:
  348. mp3path, ts = mp3
  349. mp3name = os.path.basename(mp3path)
  350. yield (mp3path, mp3name, ts)
  351. def cloud_download(ad_key=None):
  352. """ Given an ad key, the file is downloaded to
  353. the system temporal folder to be processed """
  354. if ad_key in cloud_cache:
  355. """ If this file has already been downloaded,
  356. will not be downloaded again, instead will
  357. be taken from cloud_cache dictionary """
  358. filename, md5hash = cloud_cache[ad_key]
  359. if os.path.isfile(filename):
  360. return filename, md5hash
  361. ad = fbdb.reference('ads/{}'.format(ad_key)).get()
  362. filename = os.path.basename(ad['path'])
  363. out_file = os.path.join(AUDIOS_PATH, filename)
  364. url = '{}/{}'.format(cloud_base_url, ad['path'])
  365. response = requests.get(url)
  366. if response.status_code == 200:
  367. hashes = response.headers['x-goog-hash']
  368. hashes = hashes.split(',')
  369. hashes = [h.split('=', 1) for h in hashes]
  370. hashes = {h[0].strip(): hexlify(b64decode(h[1])) for h in hashes}
  371. md5sum = hashes['md5']
  372. with open(out_file, "wb") as fp:
  373. fp.write(response.content)
  374. tp = (out_file, md5sum,)
  375. cloud_cache[ad_key] = tp
  376. return tp
  377. app = setup_endpoint(queue=queue)
  378. loop = IOLoop.current()
  379. loop.add_callback(feed_queue)
  380. if __name__ == '__main__':
  381. try:
  382. log.info('Starting ondemand service')
  383. loop.start()
  384. except KeyboardInterrupt:
  385. log.error('Process killed')