ondemand.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. from __future__ import print_function, absolute_import
  2. import warnings
  3. warnings.simplefilter("ignore", UserWarning)
  4. from tornado.ioloop import IOLoop
  5. from boxconfig import parse_config
  6. from dejavu.recognize import FilePerSecondRecognizer
  7. from dejavu import Dejavu
  8. from endpoint import setup_endpoint
  9. import logging as log
  10. import requests
  11. import json
  12. import time
  13. import os
  14. from queue import Queue, Empty
  15. log.basicConfig(format='[%(asctime)s] [%(module)s] %(message)s', level=log.INFO)
  16. PATH = '/tmp'
  17. AHEAD_TIME_AUDIO_TOLERANCE = 2 # second
  18. MAX_SEGMENT_THREADS = 4
  19. THRESHOLD = 10
  20. SEGMENTS_TOLERANCE_RATE = 0.6
  21. FALL_TOLERANCE_SEGMENTS = 1
  22. THRESHOLD_FIXED = 1
  23. THRESHOLD_AVERAGE = 2
  24. QUEUE_SINGLE = 1
  25. config = parse_config()
  26. queue = Queue()
  27. cloud_base_url = 'https://storage.googleapis.com/{}' \
  28. .format(config['bucket'])
  29. recognizer = FilePerSecondRecognizer
  30. threshold_mode = THRESHOLD_FIXED
  31. def obt_siguiente_trabajo():
  32. url = 'https://api.fourier.audio/na/calendario/pendiente?id=%s' % (config['device_id'],)
  33. response = requests.get(url)
  34. return response.json()
  35. def descargar_anuncio(ad_path):
  36. anuncio = os.path.basename(ad_path)
  37. path = os.path.join(PATH, 'ads')
  38. os.makedirs(path, exist_ok=True)
  39. ruta_anuncio = os.path.join(path, anuncio)
  40. if os.path.isfile(ruta_anuncio):
  41. return ruta_anuncio
  42. url = '{}/{}'.format(cloud_base_url, ad_path)
  43. response = requests.get(url)
  44. # TODO: Agregar alerta cuando la respuesta no sea 200
  45. if response.status_code == 200:
  46. with open(ruta_anuncio, "wb") as fp:
  47. fp.write(response.content)
  48. return ruta_anuncio
  49. else:
  50. log.info("Error al descargar")
  51. log.info(response)
  52. return None
  53. def descargar_media(box, station, media):
  54. ref = '{}/{}/{}'.format(box, station, media)
  55. file = os.path.basename(ref)
  56. path = os.path.join(PATH, 'fourier', box, station)
  57. os.makedirs(path, exist_ok=True)
  58. out_file = os.path.join(path, file)
  59. if os.path.isfile(out_file):
  60. return out_file
  61. filename = ref.replace("/","%2F") \
  62. .replace("+","%2B")
  63. url = '{}/{}'.format(cloud_base_url, filename)
  64. response = requests.get(url)
  65. if response.status_code == 200:
  66. with open(out_file, "wb") as fp:
  67. fp.write(response.content)
  68. return out_file
  69. else:
  70. log.info("Error al descargar")
  71. log.info(response)
  72. return None
  73. def obt_calibracion(calibracion):
  74. default = {
  75. 'threshold': 12,
  76. 'tolerance': 0.8,
  77. 'fallTolerance': 1,
  78. 'segmentSize': 5,
  79. }
  80. if 'threshold' in calibracion:
  81. default['threshold'] = calibracion['threshold']
  82. if 'tolerance' in calibracion:
  83. default['tolerance'] = calibracion['tolerance']
  84. if 'segmentSize' in calibracion:
  85. default['segmentSize'] = calibracion['segmentSize']
  86. if 'fallTolerance' in calibracion:
  87. default['fallTolerance'] = calibracion['fallTolerance']
  88. return default
  89. def enviar_resultados(trabajo):
  90. url = 'https://api.fourier.audio/na/calendario/resultado'
  91. response = requests.post(url, json=trabajo)
  92. return response
  93. def llenar_pila():
  94. """ Search for pending scheduled work in
  95. server and add them to a memory queue. """
  96. try:
  97. response = obt_siguiente_trabajo()
  98. if len(response["elementos"]) > 0:
  99. queue.put(response)
  100. if queue.qsize() > 0:
  101. loop.add_callback(procesar_siguiente_pila)
  102. else:
  103. loop.add_timeout(time.time() + 30, llenar_pila)
  104. except Exception as ex:
  105. """ Errores desconocidos """
  106. log.error('[feed_queue] {}'.format(ex))
  107. loop.add_timeout(time.time() + 60, llenar_pila)
  108. raise ex
  109. def procesar_siguiente_pila():
  110. """ Try to the next item in a queue and start
  111. processing it accordingly. If success, repeat
  112. the function or go to feed if no more items. """
  113. try:
  114. item = queue.get(False)
  115. procesar_trabajo(item)
  116. loop.add_callback(procesar_siguiente_pila)
  117. except Empty:
  118. loop.add_callback(llenar_pila)
  119. except Exception as ex:
  120. log.error(ex)
  121. loop.add_callback(procesar_siguiente_pila)
  122. def procesar_trabajo(pendiente):
  123. ciudad = pendiente['origen']
  124. estacion = pendiente['estacion']
  125. # Descarga de anuncios
  126. try:
  127. anuncios = []
  128. id_by_ad = {}
  129. item_ids = []
  130. for i in pendiente["elementos"]:
  131. id_by_ad[i['anuncio']] = i['id']
  132. if i['id'] not in item_ids:
  133. item_ids.append(i['id'])
  134. anuncio = descargar_anuncio(i["ruta"])
  135. if anuncio is not None:
  136. anuncios.append(anuncio)
  137. except Exception as err:
  138. log.info('[process_segment] [{}] {}'.format(estacion, err))
  139. # Descarga de media
  140. try:
  141. media = []
  142. for i in pendiente["media"]:
  143. archivo = descargar_media(ciudad, estacion, i["ruta"])
  144. if archivo is not None:
  145. media.append((archivo, i["fecha"], i["timestamp"]))
  146. except Exception as err:
  147. log.info(err)
  148. dejavu = None
  149. resultados = {}
  150. try:
  151. dejavu = Dejavu({"database_type": "mem"})
  152. try:
  153. x = 0
  154. for ruta, fecha, ts in media:
  155. log.info("Huellando %s" % (ruta,))
  156. dejavu.fingerprint_file(ruta, ts)
  157. except Exception as ex:
  158. log.info(ex)
  159. for anuncio in anuncios:
  160. log.info("Buscando anuncio %s" % (anuncio,))
  161. for i in dejavu.recognize(recognizer, anuncio, 5):
  162. if not "id" in i:
  163. continue
  164. if i["confidence"] < 50:
  165. continue
  166. obj = i
  167. obj["match_time"] = None
  168. nombre_anuncio = os.path.split(anuncio)[-1]
  169. id = id_by_ad[nombre_anuncio]
  170. dict = {
  171. "id": id,
  172. "anuncio": anuncio,
  173. "fecha": obj["name"],
  174. "timestamp": obj["name"] + int(obj['offset_seconds']),
  175. "confianza": obj["confidence"],
  176. "longitud": obj["length"],
  177. "desfase_segundos": obj["offset_seconds"]
  178. }
  179. if i["id"] in resultados.keys():
  180. resultados[i["id"]]["longitud"] = resultados[i["id"]]["longitud"] + dict["longitud"]
  181. resultados[i["id"]]["confianza"] = resultados[i["id"]]["confianza"] + dict["confianza"]
  182. continue
  183. resultados[i["id"]] = dict
  184. for id in resultados:
  185. e = resultados[id]
  186. for i in pendiente['elementos']:
  187. anuncio = e['anuncio'].replace('/tmp/ads/', '')
  188. if i['id'] == id and i['anuncio'] == anuncio:
  189. if 'encontrados' not in i:
  190. i['encontrados'] = []
  191. i['encontrados'].append(e)
  192. break
  193. enviar_resultados(pendiente)
  194. except Exception as ex:
  195. log.info(ex)
  196. app = setup_endpoint(queue=queue)
  197. loop = IOLoop.current()
  198. loop.add_callback(llenar_pila)
  199. if __name__ == '__main__':
  200. try:
  201. log.info('Starting ondemand service')
  202. loop.start()
  203. except KeyboardInterrupt:
  204. log.error('Process killed')