service.py 15 KB

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