service.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. # TODO: 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. device_id = config['device_id']
  67. device_path = os.path.join(base_path, device_id)
  68. recognizer = FilePerSecondRecognizer
  69. device_ref = fbdb.reference('devices').child(config['device_id'])
  70. calibrations = Calibrations(config['device_id'], client=client)
  71. # settings
  72. queue_mode = QUEUE_SINGLE
  73. threshold_mode = THRESHOLD_FIXED
  74. db_path = config.get('localDatabase', os.path.join(device_path, 'files.db'))
  75. db = sqlite3.connect(db_path)
  76. cloud_cache = {}
  77. def feed_queue():
  78. """ Search for pending scheduled work in
  79. server and add them to a memory queue. """
  80. try:
  81. response = client.get_schedule_pending()
  82. downloaded_counter = len(response['items'])
  83. for item in response['items']:
  84. queue.put(item)
  85. if downloaded_counter:
  86. log.info(('[feed_queue] {} new '
  87. + 'pending schedule items.') \
  88. .format(downloaded_counter)
  89. )
  90. if queue.qsize() > 0:
  91. if queue_mode == QUEUE_THREAD:
  92. loop.add_callback(process_queue_with_threads)
  93. else:
  94. loop.add_callback(process_queue)
  95. else:
  96. loop.add_timeout(time.time() + 30, feed_queue)
  97. except ConnectionError as ex:
  98. log.error('[feed_queue] cannot feed: {}, retryig later'.format(ex))
  99. loop.add_timeout(time.time() + 15, feed_queue)
  100. except Exception as ex:
  101. """ Errores desconocidos """
  102. log.error('[feed_queue] {}'.format(ex))
  103. loop.add_timeout(time.time() + 60, feed_queue)
  104. raise ex
  105. def process_queue():
  106. """ Try to the next item in a queue and start
  107. processing it accordingly. If success, repeat
  108. the function or go to feed if no more items. """
  109. try:
  110. item = queue.get(False)
  111. process_segment(item)
  112. loop.add_callback(process_queue)
  113. except Empty:
  114. loop.add_callback(feed_queue)
  115. except Exception as ex:
  116. log.error(ex)
  117. loop.add_callback(process_queue)
  118. def process_queue_with_threads():
  119. threads = [None] * MAX_SEGMENT_THREADS
  120. is_drained = False
  121. log.info('Starting thread processing')
  122. while True:
  123. for index, t in enumerate(threads):
  124. if not t:
  125. try:
  126. item = queue.get(False)
  127. station = item['station']
  128. date = dateutil.parser.parse(item['date'])
  129. calibration = calibrations.get(station)
  130. audios = [f for f in iterate_audios(
  131. date, station,
  132. calibration=calibration
  133. )]
  134. thread = MultiAPI(target=process_segment,
  135. args=(item,),
  136. kwargs={
  137. 'audios': audios,
  138. 'calibration': calibration,
  139. }
  140. )
  141. threads[index] = thread
  142. thread.start()
  143. except Empty:
  144. is_drained = True
  145. except Exception as err:
  146. log.error('[process_queue_with_threads] [{}] {}'.format(
  147. station,
  148. err,
  149. ))
  150. continue
  151. elif not t.is_alive():
  152. threads[index] = None
  153. if is_drained:
  154. if threads.count(None) == MAX_SEGMENT_THREADS:
  155. break
  156. log.info('Finished thread processing')
  157. loop.add_callback(feed_queue)
  158. def process_segment(item, audios=None, calibration=None):
  159. """ Procesa una hora de audio """
  160. station = item['station']
  161. if not calibration:
  162. calibration = calibrations.get(station)
  163. tolerance = calibration['tolerance']
  164. date = dateutil.parser.parse(item['date'])
  165. segment_size = calibration['segmentSize']
  166. audio_length = 0
  167. log.info('[process_segment] (th: {}, tl: {}, ft: {}, ss: {}, ho: {}) {}' \
  168. .format(
  169. calibration['threshold'],
  170. calibration['tolerance'],
  171. calibration['fallTolerance'],
  172. calibration['segmentSize'],
  173. calibration['hourlyOffset'],
  174. item,
  175. )
  176. )
  177. # 1. obtener el audio desde firebase
  178. # y calcular su fingerprint.
  179. try:
  180. filename, md5hash = cloud_download(ad_key=item['ad'])
  181. if not filename:
  182. log.info('[process_segment] ad file missing')
  183. return
  184. except Exception as err:
  185. log.error('[process_segment] [{}] {}'.format(station, err))
  186. return
  187. # 1.1 Calcular el número de segmentos requeridos
  188. # de acuerdo a la duración total del audio.
  189. try:
  190. audio = mutagen.mp3.MP3(filename)
  191. audio_length = audio.info.length
  192. if segment_size == 'integer':
  193. segment_size = int(audio_length)
  194. elif segment_size == 'ceil':
  195. segment_size = int(math.ceil(audio_length / 5)) * 5
  196. segments_needed = int(round(float(audio_length) / float(segment_size)))
  197. segments_needed = int(round(segments_needed * tolerance))
  198. except Exception as ex:
  199. log.error('[process_segment] file {} is not an mp3'.format(filename))
  200. log.error(str(ex))
  201. return
  202. dejavu = Dejavu({"database_type": "mem"})
  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. download_file(path)
  228. try:
  229. for match in dejavu.recognize(recognizer, path, segment_size,
  230. ads_filter=[md5hash]):
  231. results.append({
  232. 'confidence': match['confidence'],
  233. 'timestamp': ts,
  234. 'offset': match['offset']
  235. })
  236. values.append(str(match['confidence']))
  237. ts += match['length'] / 1000
  238. log.info('[process_segment] [{3}] {2} {0}) {1}'.format(
  239. os.path.split(path)[-1],
  240. ','.join(values),
  241. item['ad'],
  242. station,
  243. ))
  244. except CouldntDecodeError as ex:
  245. log.error('[process_segment] {}'.format(ex))
  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_down_counter = 0
  266. found_index = None
  267. expect_space = False
  268. expect_recover = False
  269. last_value_in_threshold_index = -1
  270. fall_tolerance = calibration['fallTolerance']
  271. found = []
  272. if threshold_mode == THRESHOLD_FIXED:
  273. threshold = calibration['threshold']
  274. elif threshold_mode == THRESHOLD_AVERAGE:
  275. values = [x['confidence'] for x in results]
  276. threshold = math.ceil(float(sum(values)) / float(len(values)))
  277. if segments_needed < 1:
  278. segments_needed = 1
  279. for index, result in enumerate(results):
  280. if not expect_space:
  281. if result['confidence'] >= threshold:
  282. found_counter += 1
  283. last_value_in_threshold_index = index
  284. if found_index is None:
  285. found_index = index
  286. if expect_recover:
  287. found_counter += found_down_counter
  288. expect_recover = False
  289. elif fall_tolerance:
  290. if not expect_recover:
  291. if last_value_in_threshold_index != -1:
  292. """ Solo cuando ya haya entrado por lo menos
  293. un valor en el rango del threshold, es cuando
  294. se podrá esperar un valor bajo """
  295. expect_recover = True
  296. found_down_counter += 1
  297. else:
  298. pass
  299. else:
  300. """ Si después de haber pasado tolerado 1 elemento
  301. vuelve a salir otro fuera del threshold continuo,
  302. entonces ya se da por perdido """
  303. found_counter = 0
  304. found_down_counter = 0
  305. found_index = None
  306. expect_recover = False
  307. else:
  308. found_counter = 0
  309. found_down_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. p = Popen(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_name', '-of',
  376. 'default=nokey=1:noprint_wrappers=1', out_file], stdin=PIPE, stdout=PIPE, stderr=PIPE)
  377. rc = p.returncode
  378. if rc != 'mp3\n':
  379. subprocess.call(['mv', out_file, out_file + '.old'])
  380. subprocess.call(
  381. ['ffmpeg', '-hide_banner', '-loglevel', 'panic', '-i', out_file + '.old', '-f', 'mp3', out_file])
  382. subprocess.call(['rm', '-rf', out_file + '.old'])
  383. cloud_cache[ad_key] = tp
  384. return tp
  385. def download_file(file_path=None):
  386. file_path_cloud = file_path.replace("/var/fourier/", "")
  387. url = '{}/{}'.format(cloud_base_url, file_path_cloud)
  388. response = requests.get(url)
  389. if response.status_code == 200:
  390. with open(file_path, "wb") as fp:
  391. fp.write(response.content)
  392. cursor = db.cursor()
  393. cursor.execute('update "file" set uploaded = 0 where filename = ?', (file_path,), )
  394. cursor.close()
  395. app = setup_endpoint(queue=queue)
  396. loop = IOLoop.current()
  397. loop.add_callback(feed_queue)
  398. if __name__ == '__main__':
  399. try:
  400. log.info('Starting ondemand service')
  401. loop.start()
  402. except KeyboardInterrupt:
  403. log.error('Process killed')