service.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 hashlib
  28. import sqlite3
  29. import math
  30. import time
  31. import sys
  32. import os
  33. if sys.version_info >= (3, 0):
  34. from queue import Queue, Empty
  35. else:
  36. from Queue import Queue, Empty
  37. log.basicConfig(format='[%(asctime)s] [%(module)s] %(message)s', level=log.INFO)
  38. AUDIOS_PATH = '/tmp'
  39. AHEAD_TIME_AUDIO_TOLERANCE = 2 # second
  40. MAX_SEGMENT_THREADS = 4
  41. THRESHOLD = 10
  42. SEGMENTS_TOLERANCE_RATE = 0.6
  43. FALL_TOLERANCE_SEGMENTS = 1
  44. # THRESHOLD
  45. THRESHOLD_FIXED = 1
  46. THRESHOLD_AVERAGE = 2
  47. # Modos de procesamiento de queue
  48. # - QUEQUE_SINGLE: procesa solo un segmento a la vez
  49. # - QUEUE_THREAD: inicia un hilo para cada segmento
  50. # Por default se usará el threaded.
  51. # TODO: hacerlo configurable por medio de argumentos
  52. # de ejecución.
  53. QUEUE_SINGLE = 1
  54. QUEUE_THREAD = 2
  55. # Se pueden usar diferentes API's
  56. # la de threading y la de multiprocessing.
  57. MultiAPI = Process
  58. config = parse_config()
  59. queue = Queue()
  60. client = Client(config['device_id'],
  61. config['apiSecret'])
  62. cloud_base_url = 'https://storage.googleapis.com/{}' \
  63. .format(config['bucket'])
  64. base_path = config.get("basepath", "/var/fourier")
  65. fb_credentials = credentials.Certificate('/etc/Fourier-key.json')
  66. firebase_admin.initialize_app(fb_credentials, config['firebase'])
  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_SINGLE
  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 = get_pendings()
  83. # response = client.get_schedule_pending()
  84. # downloaded_counter = len(response['items'])
  85. # for item in response['items']:
  86. if len(response["elementos"]) > 0:
  87. queue.put(response)
  88. if queue.qsize() > 0:
  89. if queue_mode == QUEUE_THREAD:
  90. loop.add_callback(process_queue_with_threads)
  91. else:
  92. loop.add_callback(process_queue)
  93. else:
  94. loop.add_timeout(time.time() + 30, feed_queue)
  95. except ConnectionError as ex:
  96. log.error('[feed_queue] cannot feed: {}, retryig later'.format(ex))
  97. loop.add_timeout(time.time() + 15, feed_queue)
  98. except Exception as ex:
  99. """ Errores desconocidos """
  100. log.error('[feed_queue] {}'.format(ex))
  101. loop.add_timeout(time.time() + 60, feed_queue)
  102. raise ex
  103. def process_queue():
  104. """ Try to the next item in a queue and start
  105. processing it accordingly. If success, repeat
  106. the function or go to feed if no more items. """
  107. try:
  108. item = queue.get(False)
  109. process_segment(item)
  110. loop.add_callback(process_queue)
  111. except Empty:
  112. loop.add_callback(feed_queue)
  113. except Exception as ex:
  114. log.error(ex)
  115. loop.add_callback(process_queue)
  116. def process_queue_with_threads():
  117. threads = [None] * MAX_SEGMENT_THREADS
  118. is_drained = False
  119. log.info('Starting thread processing')
  120. while True:
  121. for index, t in enumerate(threads):
  122. if not t:
  123. try:
  124. item = queue.get(False)
  125. station = item['station']
  126. date = dateutil.parser.parse(item['date'], ignoretz=True)
  127. calibration = calibrations.get(station)
  128. audios = [f for f in iterate_audios(
  129. date, station,
  130. calibration=calibration
  131. )]
  132. thread = MultiAPI(target=process_segment,
  133. args=(item,),
  134. kwargs={
  135. 'audios': audios,
  136. 'calibration': calibration,
  137. }
  138. )
  139. threads[index] = thread
  140. thread.start()
  141. except Empty:
  142. is_drained = True
  143. except Exception as err:
  144. log.error('[process_queue_with_threads] [{}] {}'.format(
  145. station,
  146. err,
  147. ))
  148. continue
  149. elif not t.is_alive():
  150. threads[index] = None
  151. if is_drained:
  152. if threads.count(None) == MAX_SEGMENT_THREADS:
  153. break
  154. log.info('Finished thread processing')
  155. loop.add_callback(feed_queue)
  156. def process_segment(item, audios=None, calibration=None):
  157. """ Procesa una hora de audio """
  158. station = item['estacion']
  159. if not calibration:
  160. calibration = calibrations.get(station)
  161. tolerance = calibration['tolerance']
  162. date = dateutil.parser.parse(item['fecha'], ignoretz=True)
  163. segment_size = calibration['segmentSize']
  164. audio_length = 0
  165. log.info('[process_segment] (th: {}, tl: {}, ft: {}, ss: {}, ho: {}) {}' \
  166. .format(
  167. calibration['threshold'],
  168. calibration['tolerance'],
  169. calibration['fallTolerance'],
  170. calibration['segmentSize'],
  171. calibration['hourlyOffset'],
  172. item,
  173. )
  174. )
  175. # 1. obtener el audio desde firebase
  176. # y calcular su fingerprint.
  177. try:
  178. filenames = []
  179. x = 0
  180. for i in item["elementos"]:
  181. x = x + 1
  182. log.info('[process_segment] {} downloading ad {}'.format(x, i["anuncio"]))
  183. filename, md5hash = cloud_download(ad_key=i["anuncio"])
  184. if filename:
  185. filenames.append((filename, md5hash))
  186. else:
  187. log.info('[process_segment] ad file missing')
  188. except Exception as err:
  189. log.error('[process_segment] [{}] {}'.format(station, err))
  190. return
  191. # 1.1 Calcular el número de segmentos requeridos
  192. # de acuerdo a la duración total del audio.
  193. try:
  194. filename, md5hash = filenames[0]
  195. audio = mutagen.mp3.MP3(filename)
  196. audio_length = audio.info.length
  197. if segment_size == 'integer':
  198. segment_size = int(audio_length)
  199. elif segment_size == 'ceil':
  200. segment_size = int(math.ceil(audio_length / 5)) * 5
  201. segments_needed = int(round(float(audio_length) / float(segment_size)))
  202. segments_needed = int(round(segments_needed * tolerance))
  203. except Exception as ex:
  204. log.error('[process_segment] file {} is not an mp3'.format(filename))
  205. log.error(str(ex))
  206. return
  207. dejavu = Dejavu({"database_type": "mem"})
  208. try:
  209. for i in filenames:
  210. filename = i[0]
  211. dejavu.fingerprint_file(filename)
  212. except Exception as ex:
  213. log.error('[process_segment] cannot fingerprint: {}'.format(ex))
  214. """ Hay dos posibles escensarios al obtener los audios
  215. a. Los audios vienen por el parámetro "audios" de la
  216. función, siendo esta una lista.
  217. b. Los audios se obtienen directamente de la base
  218. de datos en modo de cursor.
  219. """
  220. try:
  221. audios_iterable = audios if audios \
  222. else iterate_audios(date, station, calibration=calibration)
  223. except sqlite3.OperationalError as err:
  224. log.error('[process_segment] [{}] {}'.format(station, err))
  225. return
  226. # 2. Read the list of files from local database
  227. audios_counter = 0
  228. results = []
  229. v = []
  230. for path, name, ts in audios_iterable:
  231. short_path = os.path.join(station, name)
  232. audios_counter += os.path.isfile(path)
  233. values = []
  234. if not os.path.isfile(path):
  235. download_file(path)
  236. try:
  237. for match in dejavu.recognize(recognizer, path, segment_size):
  238. name = None
  239. try:
  240. name = match['name']
  241. except KeyError:
  242. pass
  243. results.append({
  244. 'confidence': match['confidence'],
  245. 'timestamp': ts,
  246. 'offset': match['offset'],
  247. 'name': name
  248. })
  249. values.append(str(match['confidence']))
  250. ts += match['length'] / 1000
  251. v.append(','.join(values))
  252. log.info('[process_segment] [{2}] {0}) {1}'.format(
  253. os.path.split(path)[-1],
  254. ','.join(values),
  255. station,
  256. ))
  257. except CouldntDecodeError as ex:
  258. log.error('[process_segment] {}'.format(ex))
  259. try:
  260. for i in item["elementos"]:
  261. r = [result for result in results if result["name"] == i["anuncio"]]
  262. i['encontrados'] = find_repetitions(r, segments_needed=segments_needed, calibration=calibration,)
  263. item["archivos_perdidos"] = (12 - audios_counter) if audios_counter < 12 else 0
  264. response = send_results(item)
  265. log.info('[{}] API response: {}'.format(station, response))
  266. except ConnectionError as ex:
  267. log.error('[process_segment] {}'.format(str(ex)))
  268. except UserWarning as warn:
  269. log.warning(str(warn))
  270. def find_repetitions(results, segments_needed=2, calibration=None):
  271. found_counter = 0
  272. found_down_counter = 0
  273. found_index = None
  274. expect_space = False
  275. expect_recover = False
  276. last_value_in_threshold_index = -1
  277. fall_tolerance = calibration['fallTolerance']
  278. found = []
  279. if threshold_mode == THRESHOLD_FIXED:
  280. threshold = calibration['threshold']
  281. elif threshold_mode == THRESHOLD_AVERAGE:
  282. values = [x['confidence'] for x in results]
  283. threshold = math.ceil(float(sum(values)) / float(len(values)))
  284. if segments_needed < 1:
  285. segments_needed = 1
  286. for index, result in enumerate(results):
  287. if not expect_space:
  288. if result['confidence'] >= threshold:
  289. found_counter += 1
  290. last_value_in_threshold_index = index
  291. if found_index is None:
  292. found_index = index
  293. if expect_recover:
  294. found_counter += found_down_counter
  295. expect_recover = False
  296. elif fall_tolerance:
  297. if not expect_recover:
  298. if last_value_in_threshold_index != -1:
  299. """ Solo cuando ya haya entrado por lo menos
  300. un valor en el rango del threshold, es cuando
  301. se podrá esperar un valor bajo """
  302. expect_recover = True
  303. found_down_counter += 1
  304. else:
  305. pass
  306. else:
  307. """ Si después de haber pasado tolerado 1 elemento
  308. vuelve a salir otro fuera del threshold continuo,
  309. entonces ya se da por perdido """
  310. found_counter = 0
  311. found_down_counter = 0
  312. found_index = None
  313. expect_recover = False
  314. else:
  315. found_counter = 0
  316. found_down_counter = 0
  317. found_index = None
  318. expect_recover = False
  319. else:
  320. if result['confidence'] <= threshold:
  321. expect_space = False
  322. if found_counter >= segments_needed:
  323. found_row = results[found_index]
  324. found.append(found_row)
  325. found_counter = 0
  326. expect_space = True
  327. return found
  328. def iterate_audios(dt, station, calibration=None):
  329. """ Given a datetime object and an station,
  330. iterate a list of files that are between
  331. the the date and itself plus 5 minutes;
  332. station must match too """
  333. tm = time.mktime(dt.timetuple())
  334. if calibration and calibration['hourlyOffset']:
  335. hoffset = calibration['hourlyOffset']
  336. from_time = tm + hoffset
  337. to_time = tm + 3599 + hoffset
  338. elif AHEAD_TIME_AUDIO_TOLERANCE:
  339. """ Conventional mode """
  340. from_time = tm + AHEAD_TIME_AUDIO_TOLERANCE
  341. to_time = from_time + 3599 + AHEAD_TIME_AUDIO_TOLERANCE
  342. log.info('from {} to {}'.format(int(from_time), int(to_time)))
  343. cursor = db.cursor()
  344. cursor.execute((
  345. 'select "filename", "timestamp" '
  346. 'from "file" '
  347. 'where "timestamp" between ? and ? '
  348. 'and "station" = ? '
  349. 'order by "timestamp" asc'
  350. ),
  351. (from_time, to_time, station,),
  352. )
  353. files = [file for file in cursor]
  354. cursor.close()
  355. for mp3 in files:
  356. mp3path, ts = mp3
  357. mp3name = os.path.basename(mp3path)
  358. yield (mp3path, mp3name, ts)
  359. def cloud_download(ad_key=None):
  360. """ Given an ad key, the file is downloaded to
  361. the system temporal folder to be processed """
  362. if ad_key in cloud_cache:
  363. """ If this file has already been downloaded,
  364. will not be downloaded again, instead will
  365. be taken from cloud_cache dictionary """
  366. filename, md5hash = cloud_cache[ad_key]
  367. if os.path.isfile(filename):
  368. return filename, md5hash
  369. ad = fbdb.reference('ads/{}'.format(ad_key)).get()
  370. filename = os.path.basename(ad['path'])
  371. out_file = os.path.join(AUDIOS_PATH, filename)
  372. url = '{}/{}'.format(cloud_base_url, ad['path'])
  373. response = requests.get(url)
  374. if(os.path.isfile(out_file)):
  375. return out_file, md5_checksum(out_file)
  376. if response.status_code == 200:
  377. hashes = response.headers['x-goog-hash']
  378. hashes = hashes.split(',')
  379. hashes = [h.split('=', 1) for h in hashes]
  380. hashes = {h[0].strip(): hexlify(b64decode(h[1])) for h in hashes}
  381. md5sum = hashes['md5']
  382. with open(out_file, "wb") as fp:
  383. fp.write(response.content)
  384. tp = (out_file, md5sum,)
  385. p = Popen(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_name', '-of',
  386. 'default=nokey=1:noprint_wrappers=1', out_file], stdin=PIPE, stdout=PIPE, stderr=PIPE)
  387. rc = p.returncode
  388. if rc != 'mp3\n':
  389. subprocess.call(['mv', out_file, out_file + '.old'])
  390. subprocess.call(
  391. ['ffmpeg', '-hide_banner', '-loglevel', 'panic', '-i', out_file + '.old', '-codec:a', 'libmp3lame',
  392. '-qscale:a', '2', '-f', 'mp3', out_file])
  393. subprocess.call(['rm', '-rf', out_file + '.old'])
  394. cloud_cache[ad_key] = tp
  395. return tp
  396. def download_file(file_path=None):
  397. file_path_cloud = file_path.replace("/var/fourier/", "")
  398. url = '{}/{}'.format(cloud_base_url, file_path_cloud)
  399. response = requests.get(url)
  400. if response.status_code == 200:
  401. with open(file_path, "wb") as fp:
  402. fp.write(response.content)
  403. cursor = db.cursor()
  404. cursor.execute('update "file" set uploaded = 0 where filename = ?', (file_path,), )
  405. cursor.close()
  406. def get_pendings():
  407. url = 'https://api.fourier.audio/v1/calendario/pendiente?id={}'.format(config['device_id'], )
  408. headers = {
  409. 'Authorization': 'Bearer {}'.format(config['apiSecret'], )
  410. }
  411. response = requests.get(url, headers=headers)
  412. return response.json()
  413. def send_results(item):
  414. url = 'https://api.fourier.audio/v1/calendario/resultado'
  415. # url = "http://requestbin.net/r/1bcyvg91"
  416. headers = {
  417. 'Authorization': 'Bearer {}'.format(config['apiSecret'], )
  418. }
  419. log.info('url: {}'.format(url))
  420. response = requests.post(url, json=item, headers=headers)
  421. return response
  422. def md5_checksum(filename):
  423. hash_md5 = hashlib.md5()
  424. with open(filename, "rb") as f:
  425. for chunk in iter(lambda: f.read(4096), b""):
  426. hash_md5.update(chunk)
  427. return hash_md5.hexdigest()
  428. app = setup_endpoint(queue=queue)
  429. loop = IOLoop.current()
  430. loop.add_callback(feed_queue)
  431. if __name__ == '__main__':
  432. try:
  433. log.info('Starting ondemand service')
  434. loop.start()
  435. except KeyboardInterrupt:
  436. log.error('Process killed')