ondemand.py 7.7 KB

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