service.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. if len(response["elementos"]) > 0:
  86. queue.put(response)
  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. raise ex
  102. def process_queue():
  103. """ Try to the next item in a queue and start
  104. processing it accordingly. If success, repeat
  105. the function or go to feed if no more items. """
  106. try:
  107. item = queue.get(False)
  108. process_segment(item)
  109. loop.add_callback(process_queue)
  110. except Empty:
  111. loop.add_callback(feed_queue)
  112. except Exception as ex:
  113. log.error(ex)
  114. loop.add_callback(process_queue)
  115. def process_queue_with_threads():
  116. threads = [None] * MAX_SEGMENT_THREADS
  117. is_drained = False
  118. log.info('Starting thread processing')
  119. while True:
  120. for index, t in enumerate(threads):
  121. if not t:
  122. try:
  123. item = queue.get(False)
  124. station = item['station']
  125. date = dateutil.parser.parse(item['date'])
  126. calibration = calibrations.get(station)
  127. audios = [f for f in iterate_audios(
  128. date, station,
  129. calibration=calibration
  130. )]
  131. thread = MultiAPI(target=process_segment,
  132. args=(item,),
  133. kwargs={
  134. 'audios': audios,
  135. 'calibration': calibration,
  136. }
  137. )
  138. threads[index] = thread
  139. thread.start()
  140. except Empty:
  141. is_drained = True
  142. except Exception as err:
  143. log.error('[process_queue_with_threads] [{}] {}'.format(
  144. station,
  145. err,
  146. ))
  147. continue
  148. elif not t.is_alive():
  149. threads[index] = None
  150. if is_drained:
  151. if threads.count(None) == MAX_SEGMENT_THREADS:
  152. break
  153. log.info('Finished thread processing')
  154. loop.add_callback(feed_queue)
  155. def process_segment(item, audios=None, calibration=None):
  156. """ Procesa una hora de audio """
  157. station = item['estacion']
  158. if not calibration:
  159. calibration = calibrations.get(station)
  160. tolerance = calibration['tolerance']
  161. date = dateutil.parser.parse(item['fecha'])
  162. segment_size = calibration['segmentSize']
  163. audio_length = 0
  164. log.info('[process_segment] (th: {}, tl: {}, ft: {}, ss: {}, ho: {}) {}' \
  165. .format(
  166. calibration['threshold'],
  167. calibration['tolerance'],
  168. calibration['fallTolerance'],
  169. calibration['segmentSize'],
  170. calibration['hourlyOffset'],
  171. item,
  172. )
  173. )
  174. # 1. obtener el audio desde firebase
  175. # y calcular su fingerprint.
  176. try:
  177. filenames = []
  178. for i in item["elementos"]:
  179. filename, md5hash = cloud_download(ad_key=i["anuncio"])
  180. if filename:
  181. filenames.append((filename, md5hash))
  182. else:
  183. log.info('[process_segment] ad file missing')
  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. filename, md5hash = filenames[0]
  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. dejavu = Dejavu({"database_type": "mem"})
  204. try:
  205. for i in filenames:
  206. filename = i[0]
  207. dejavu.fingerprint_file(filename)
  208. except Exception as ex:
  209. log.error('[process_segment] cannot fingerprint: {}'.format(ex))
  210. """ Hay dos posibles escensarios al obtener los audios
  211. a. Los audios vienen por el parámetro "audios" de la
  212. función, siendo esta una lista.
  213. b. Los audios se obtienen directamente de la base
  214. de datos en modo de cursor.
  215. """
  216. try:
  217. audios_iterable = audios if audios \
  218. else iterate_audios(date, station, calibration=calibration)
  219. except sqlite3.OperationalError as err:
  220. log.error('[process_segment] [{}] {}'.format(station, err))
  221. return
  222. # 2. Read the list of files from local database
  223. audios_counter = 0
  224. results = []
  225. v = []
  226. for path, name, ts in audios_iterable:
  227. short_path = os.path.join(station, name)
  228. audios_counter += os.path.isfile(path)
  229. values = []
  230. if not os.path.isfile(path):
  231. download_file(path)
  232. try:
  233. for match in dejavu.recognize(recognizer, path, segment_size):
  234. name = None
  235. try:
  236. name = match['name']
  237. except KeyError:
  238. pass
  239. results.append({
  240. 'confidence': match['confidence'],
  241. 'timestamp': ts,
  242. 'offset': match['offset'],
  243. 'name': name
  244. })
  245. values.append(str(match['confidence']))
  246. ts += match['length'] / 1000
  247. v.append(','.join(values))
  248. log.info('[process_segment] [{2}] {0}) {1}'.format(
  249. os.path.split(path)[-1],
  250. ','.join(values),
  251. station,
  252. ))
  253. except CouldntDecodeError as ex:
  254. log.error('[process_segment] {}'.format(ex))
  255. try:
  256. for i in item["elementos"]:
  257. r = [result for result in results if result["name"] == i["anuncio"]]
  258. i['encontrados'] = find_repetitions(r, segments_needed=segments_needed, calibration=calibration,)
  259. item["archivos_perdidos"] = (12 - audios_counter) if audios_counter < 12 else 0
  260. response = send_results(item)
  261. log.info('[{}] API response: {}'.format(station, response))
  262. except ConnectionError as ex:
  263. log.error('[process_segment] {}'.format(str(ex)))
  264. except UserWarning as warn:
  265. log.warning(str(warn))
  266. def find_repetitions(results, segments_needed=2, calibration=None):
  267. found_counter = 0
  268. found_down_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. found_counter += found_down_counter
  291. expect_recover = False
  292. elif fall_tolerance:
  293. if not expect_recover:
  294. if last_value_in_threshold_index != -1:
  295. """ Solo cuando ya haya entrado por lo menos
  296. un valor en el rango del threshold, es cuando
  297. se podrá esperar un valor bajo """
  298. expect_recover = True
  299. found_down_counter += 1
  300. else:
  301. pass
  302. else:
  303. """ Si después de haber pasado tolerado 1 elemento
  304. vuelve a salir otro fuera del threshold continuo,
  305. entonces ya se da por perdido """
  306. found_counter = 0
  307. found_down_counter = 0
  308. found_index = None
  309. expect_recover = False
  310. else:
  311. found_counter = 0
  312. found_down_counter = 0
  313. found_index = None
  314. expect_recover = False
  315. else:
  316. if result['confidence'] <= threshold:
  317. expect_space = False
  318. if found_counter >= segments_needed:
  319. found_row = results[found_index]
  320. found.append(found_row)
  321. found_counter = 0
  322. expect_space = True
  323. return found
  324. def iterate_audios(dt, station, calibration=None):
  325. """ Given a datetime object and an station,
  326. iterate a list of files that are between
  327. the the date and itself plus 5 minutes;
  328. station must match too """
  329. tm = time.mktime(dt.timetuple())
  330. if calibration and calibration['hourlyOffset']:
  331. hoffset = calibration['hourlyOffset']
  332. from_time = tm + hoffset
  333. to_time = tm + 3599 + hoffset
  334. elif AHEAD_TIME_AUDIO_TOLERANCE:
  335. """ Conventional mode """
  336. from_time = tm + AHEAD_TIME_AUDIO_TOLERANCE
  337. to_time = from_time + 3599 + AHEAD_TIME_AUDIO_TOLERANCE
  338. log.info('from {} to {}'.format(int(from_time), int(to_time)))
  339. cursor = db.cursor()
  340. cursor.execute((
  341. 'select "filename", "timestamp" '
  342. 'from "file" '
  343. 'where "timestamp" between ? and ? '
  344. 'and "station" = ? '
  345. 'order by "timestamp" asc'
  346. ),
  347. (from_time, to_time, station,),
  348. )
  349. files = [file for file in cursor]
  350. cursor.close()
  351. for mp3 in files:
  352. mp3path, ts = mp3
  353. mp3name = os.path.basename(mp3path)
  354. yield (mp3path, mp3name, ts)
  355. def cloud_download(ad_key=None):
  356. """ Given an ad key, the file is downloaded to
  357. the system temporal folder to be processed """
  358. if ad_key in cloud_cache:
  359. """ If this file has already been downloaded,
  360. will not be downloaded again, instead will
  361. be taken from cloud_cache dictionary """
  362. filename, md5hash = cloud_cache[ad_key]
  363. if os.path.isfile(filename):
  364. return filename, md5hash
  365. ad = fbdb.reference('ads/{}'.format(ad_key)).get()
  366. filename = os.path.basename(ad['path'])
  367. out_file = os.path.join(AUDIOS_PATH, filename)
  368. url = '{}/{}'.format(cloud_base_url, ad['path'])
  369. response = requests.get(url)
  370. if response.status_code == 200:
  371. hashes = response.headers['x-goog-hash']
  372. hashes = hashes.split(',')
  373. hashes = [h.split('=', 1) for h in hashes]
  374. hashes = {h[0].strip(): hexlify(b64decode(h[1])) for h in hashes}
  375. md5sum = hashes['md5']
  376. with open(out_file, "wb") as fp:
  377. fp.write(response.content)
  378. tp = (out_file, md5sum,)
  379. p = Popen(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_name', '-of',
  380. 'default=nokey=1:noprint_wrappers=1', out_file], stdin=PIPE, stdout=PIPE, stderr=PIPE)
  381. rc = p.returncode
  382. if rc != 'mp3\n':
  383. subprocess.call(['mv', out_file, out_file + '.old'])
  384. subprocess.call(
  385. ['ffmpeg', '-hide_banner', '-loglevel', 'panic', '-i', out_file + '.old', '-codec:a', 'libmp3lame',
  386. '-qscale:a', '2', '-f', 'mp3', out_file])
  387. subprocess.call(['rm', '-rf', out_file + '.old'])
  388. cloud_cache[ad_key] = tp
  389. return tp
  390. def download_file(file_path=None):
  391. file_path_cloud = file_path.replace("/var/fourier/", "")
  392. url = '{}/{}'.format(cloud_base_url, file_path_cloud)
  393. response = requests.get(url)
  394. if response.status_code == 200:
  395. with open(file_path, "wb") as fp:
  396. fp.write(response.content)
  397. cursor = db.cursor()
  398. cursor.execute('update "file" set uploaded = 0 where filename = ?', (file_path,), )
  399. cursor.close()
  400. def get_pendings():
  401. url = 'https://api.fourier.audio/v1/calendario/pendiente?id={}'.format(config['device_id'], )
  402. headers = {
  403. 'Authorization': 'Bearer {}'.format(config['apiSecret'], )
  404. }
  405. response = requests.get(url, headers=headers)
  406. return response.json()
  407. def send_results(item):
  408. url = 'https://api.fourier.audio/v1/calendario/resultado'
  409. # url = "http://requestbin.net/r/1bcyvg91"
  410. headers = {
  411. 'Authorization': 'Bearer {}'.format(config['apiSecret'], )
  412. }
  413. log.info('url: {}'.format(url))
  414. response = requests.post(url, json=item, headers=headers)
  415. return response
  416. app = setup_endpoint(queue=queue)
  417. loop = IOLoop.current()
  418. loop.add_callback(feed_queue)
  419. if __name__ == '__main__':
  420. try:
  421. log.info('Starting ondemand service')
  422. loop.start()
  423. except KeyboardInterrupt:
  424. log.error('Process killed')