service.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 = get_pendings()
  82. # response = client.get_schedule_pending()
  83. # downloaded_counter = len(response['items'])
  84. # for item in response['items']:
  85. queue.put(response)
  86. if queue.qsize() > 0:
  87. if queue_mode == QUEUE_THREAD:
  88. loop.add_callback(process_queue_with_threads)
  89. else:
  90. loop.add_callback(process_queue)
  91. else:
  92. loop.add_timeout(time.time() + 30, feed_queue)
  93. except ConnectionError as ex:
  94. log.error('[feed_queue] cannot feed: {}, retryig later'.format(ex))
  95. loop.add_timeout(time.time() + 15, feed_queue)
  96. except Exception as ex:
  97. """ Errores desconocidos """
  98. log.error('[feed_queue] {}'.format(ex))
  99. loop.add_timeout(time.time() + 60, feed_queue)
  100. raise ex
  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. calibration = calibrations.get(station)
  126. audios = [f for f in iterate_audios(
  127. date, station,
  128. calibration=calibration
  129. )]
  130. thread = MultiAPI(target=process_segment,
  131. args=(item,),
  132. kwargs={
  133. 'audios': audios,
  134. 'calibration': calibration,
  135. }
  136. )
  137. threads[index] = thread
  138. thread.start()
  139. except Empty:
  140. is_drained = True
  141. except Exception as err:
  142. log.error('[process_queue_with_threads] [{}] {}'.format(
  143. station,
  144. err,
  145. ))
  146. continue
  147. elif not t.is_alive():
  148. threads[index] = None
  149. if is_drained:
  150. if threads.count(None) == MAX_SEGMENT_THREADS:
  151. break
  152. log.info('Finished thread processing')
  153. loop.add_callback(feed_queue)
  154. def process_segment(item, audios=None, calibration=None):
  155. """ Procesa una hora de audio """
  156. station = item['estacion']
  157. if not calibration:
  158. calibration = calibrations.get(station)
  159. tolerance = calibration['tolerance']
  160. date = dateutil.parser.parse(item['fecha'])
  161. segment_size = calibration['segmentSize']
  162. audio_length = 0
  163. log.info('[process_segment] (th: {}, tl: {}, ft: {}, ss: {}, ho: {}) {}' \
  164. .format(
  165. calibration['threshold'],
  166. calibration['tolerance'],
  167. calibration['fallTolerance'],
  168. calibration['segmentSize'],
  169. calibration['hourlyOffset'],
  170. item,
  171. )
  172. )
  173. # 1. obtener el audio desde firebase
  174. # y calcular su fingerprint.
  175. try:
  176. filenames = []
  177. for i in item["elementos"]:
  178. filename, md5hash = cloud_download(ad_key=i["anuncio"])
  179. if filename:
  180. filenames.append((filename, md5hash))
  181. else:
  182. log.info('[process_segment] ad file missing')
  183. except Exception as err:
  184. log.error('[process_segment] [{}] {}'.format(station, err))
  185. return
  186. # 1.1 Calcular el número de segmentos requeridos
  187. # de acuerdo a la duración total del audio.
  188. try:
  189. filename, md5hash = filenames[0]
  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. for i in filenames:
  205. filename = i[0]
  206. dejavu.fingerprint_file(filename)
  207. except Exception as ex:
  208. log.error('[process_segment] cannot fingerprint: {}'.format(ex))
  209. """ Hay dos posibles escensarios al obtener los audios
  210. a. Los audios vienen por el parámetro "audios" de la
  211. función, siendo esta una lista.
  212. b. Los audios se obtienen directamente de la base
  213. de datos en modo de cursor.
  214. """
  215. try:
  216. audios_iterable = audios if audios \
  217. else iterate_audios(date, station, calibration=calibration)
  218. except sqlite3.OperationalError as err:
  219. log.error('[process_segment] [{}] {}'.format(station, err))
  220. return
  221. # 2. Read the list of files from local database
  222. audios_counter = 0
  223. results = []
  224. v = []
  225. for path, name, ts in audios_iterable:
  226. short_path = os.path.join(station, name)
  227. audios_counter += os.path.isfile(path)
  228. values = []
  229. if not os.path.isfile(path):
  230. download_file(path)
  231. try:
  232. for match in dejavu.recognize(recognizer, path, segment_size):
  233. name = None
  234. try:
  235. name = match['name']
  236. except KeyError:
  237. pass
  238. results.append({
  239. 'confidence': match['confidence'],
  240. 'timestamp': ts,
  241. 'offset': match['offset'],
  242. 'name': name
  243. })
  244. values.append(str(match['confidence']))
  245. ts += match['length'] / 1000
  246. v.append(','.join(values))
  247. log.info('[process_segment] [{2}] {0}) {1}'.format(
  248. os.path.split(path)[-1],
  249. ','.join(values),
  250. station,
  251. ))
  252. except CouldntDecodeError as ex:
  253. log.error('[process_segment] {}'.format(ex))
  254. try:
  255. for i in item["elementos"]:
  256. r = [result for result in results if result["name"] == i["anuncio"]]
  257. i['encontrados'] = find_repetitions(r, segments_needed=segments_needed, calibration=calibration,)
  258. item["archivos_perdidos"] = (12 - audios_counter) if audios_counter < 12 else 0
  259. response = send_results(item)
  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_row = results[found_index]
  319. found.append(found_row)
  320. found_counter = 0
  321. expect_space = True
  322. return found
  323. def iterate_audios(dt, station, calibration=None):
  324. """ Given a datetime object and an station,
  325. iterate a list of files that are between
  326. the the date and itself plus 5 minutes;
  327. station must match too """
  328. tm = time.mktime(dt.timetuple())
  329. if calibration and calibration['hourlyOffset']:
  330. hoffset = calibration['hourlyOffset']
  331. from_time = tm + hoffset
  332. to_time = tm + 3599 + hoffset
  333. elif AHEAD_TIME_AUDIO_TOLERANCE:
  334. """ Conventional mode """
  335. from_time = tm + AHEAD_TIME_AUDIO_TOLERANCE
  336. to_time = from_time + 3599 + AHEAD_TIME_AUDIO_TOLERANCE
  337. log.info('from {} to {}'.format(int(from_time), int(to_time)))
  338. cursor = db.cursor()
  339. cursor.execute((
  340. 'select "filename", "timestamp" '
  341. 'from "file" '
  342. 'where "timestamp" between ? and ? '
  343. 'and "station" = ? '
  344. 'order by "timestamp" asc'
  345. ),
  346. (from_time, to_time, station,),
  347. )
  348. files = [file for file in cursor]
  349. cursor.close()
  350. for mp3 in files:
  351. mp3path, ts = mp3
  352. mp3name = os.path.basename(mp3path)
  353. yield (mp3path, mp3name, ts)
  354. def cloud_download(ad_key=None):
  355. """ Given an ad key, the file is downloaded to
  356. the system temporal folder to be processed """
  357. if ad_key in cloud_cache:
  358. """ If this file has already been downloaded,
  359. will not be downloaded again, instead will
  360. be taken from cloud_cache dictionary """
  361. filename, md5hash = cloud_cache[ad_key]
  362. if os.path.isfile(filename):
  363. return filename, md5hash
  364. ad = fbdb.reference('ads/{}'.format(ad_key)).get()
  365. filename = os.path.basename(ad['path'])
  366. out_file = os.path.join(AUDIOS_PATH, filename)
  367. url = '{}/{}'.format(cloud_base_url, ad['path'])
  368. response = requests.get(url)
  369. if response.status_code == 200:
  370. hashes = response.headers['x-goog-hash']
  371. hashes = hashes.split(',')
  372. hashes = [h.split('=', 1) for h in hashes]
  373. hashes = {h[0].strip(): hexlify(b64decode(h[1])) for h in hashes}
  374. md5sum = hashes['md5']
  375. with open(out_file, "wb") as fp:
  376. fp.write(response.content)
  377. tp = (out_file, md5sum,)
  378. p = Popen(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_name', '-of',
  379. 'default=nokey=1:noprint_wrappers=1', out_file], stdin=PIPE, stdout=PIPE, stderr=PIPE)
  380. rc = p.returncode
  381. if rc != 'mp3\n':
  382. subprocess.call(['mv', out_file, out_file + '.old'])
  383. subprocess.call(
  384. ['ffmpeg', '-hide_banner', '-loglevel', 'panic', '-i', out_file + '.old', '-codec:a', 'libmp3lame',
  385. '-qscale:a', '2', '-f', 'mp3', out_file])
  386. subprocess.call(['rm', '-rf', out_file + '.old'])
  387. cloud_cache[ad_key] = tp
  388. return tp
  389. def download_file(file_path=None):
  390. file_path_cloud = file_path.replace("/var/fourier/", "")
  391. url = '{}/{}'.format(cloud_base_url, file_path_cloud)
  392. response = requests.get(url)
  393. if response.status_code == 200:
  394. with open(file_path, "wb") as fp:
  395. fp.write(response.content)
  396. cursor = db.cursor()
  397. cursor.execute('update "file" set uploaded = 0 where filename = ?', (file_path,), )
  398. cursor.close()
  399. def get_pendings():
  400. url = 'https://api.fourier.audio/v1/calendario/pendiente?id={}'.format(config['device_id'], )
  401. headers = {
  402. 'Authorization': 'Bearer {}'.format(config['apiSecret'], )
  403. }
  404. response = requests.get(url, headers=headers)
  405. return response.json()
  406. def send_results(item):
  407. url = 'https://api.fourier.audio/v1/calendario/resultado'
  408. # url = "http://requestbin.net/r/1bcyvg91"
  409. headers = {
  410. 'Authorization': 'Bearer {}'.format(config['apiSecret'], )
  411. }
  412. log.info('url: {}'.format(url))
  413. response = requests.post(url, json=item, headers=headers)
  414. return response
  415. app = setup_endpoint(queue=queue)
  416. loop = IOLoop.current()
  417. loop.add_callback(feed_queue)
  418. if __name__ == '__main__':
  419. try:
  420. log.info('Starting ondemand service')
  421. loop.start()
  422. except KeyboardInterrupt:
  423. log.error('Process killed')