service.py 13 KB

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