ondemand.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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/na/calendario/resultado'
  86. response = requests.post(url, json=trabajo)
  87. return response
  88. def llenar_pila():
  89. """ Search for pending scheduled work in
  90. server and add them to a memory queue. """
  91. try:
  92. response = obt_siguiente_trabajo()
  93. if len(response["elementos"]) > 0:
  94. queue.put(response)
  95. if queue.qsize() > 0:
  96. loop.add_callback(procesar_siguiente_pila)
  97. else:
  98. loop.add_timeout(time.time() + 30, llenar_pila)
  99. except Exception as ex:
  100. """ Errores desconocidos """
  101. log.error('[feed_queue] {}'.format(ex))
  102. loop.add_timeout(time.time() + 60, llenar_pila)
  103. raise ex
  104. def procesar_siguiente_pila():
  105. """ Try to the next item in a queue and start
  106. processing it accordingly. If success, repeat
  107. the function or go to feed if no more items. """
  108. try:
  109. item = queue.get(False)
  110. procesar_trabajo(item)
  111. loop.add_callback(procesar_siguiente_pila)
  112. except Empty:
  113. loop.add_callback(llenar_pila)
  114. except Exception as ex:
  115. log.error(ex)
  116. loop.add_callback(procesar_siguiente_pila)
  117. def procesar_trabajo(pendiente):
  118. ciudad = pendiente['origen']
  119. estacion = pendiente['estacion']
  120. # Descarga de anuncios
  121. log.info("Descargando anuncios")
  122. try:
  123. anuncios = []
  124. id_by_ad = {}
  125. item_ids = []
  126. for i in pendiente["elementos"]:
  127. id_by_ad[i['anuncio']] = i['id']
  128. if i['id'] not in item_ids:
  129. item_ids.append(i['id'])
  130. anuncio = descargar_anuncio(i["ruta"])
  131. if anuncio is not None:
  132. log.info("Listo %s" % (i['ruta'],))
  133. anuncios.append(anuncio)
  134. except Exception as err:
  135. log.info('[process_segment] [{}] {}'.format(estacion, err))
  136. # Descarga de media
  137. log.info("Descargando anuncios")
  138. try:
  139. media = []
  140. for i in pendiente["media"]:
  141. archivo = descargar_media(ciudad, estacion, i["ruta"])
  142. if archivo is not None:
  143. log.info("Listo %s %s %s" % (ciudad, estacion, i['ruta'],))
  144. media.append((archivo, i["fecha"], i["timestamp"]))
  145. except Exception as err:
  146. log.info(err)
  147. if len(media) == 0 or len(anuncio) == 0:
  148. log.info("No hay media o anuncios para comparar")
  149. return
  150. dejavu = None
  151. resultados = {}
  152. try:
  153. dejavu = Dejavu({"database_type": "mem"})
  154. try:
  155. x = 0
  156. for ruta, fecha, ts in media:
  157. log.info("Huellando %s" % (ruta,))
  158. dejavu.fingerprint_file(ruta, ts)
  159. except Exception as ex:
  160. log.info(ex)
  161. for anuncio in anuncios:
  162. log.info("Buscando anuncio %s" % (anuncio,))
  163. for i in dejavu.recognize(recognizer, anuncio, 5):
  164. if not "id" in i:
  165. continue
  166. if i["confidence"] < 50:
  167. continue
  168. obj = i
  169. obj["match_time"] = None
  170. nombre_anuncio = os.path.split(anuncio)[-1]
  171. id = id_by_ad[nombre_anuncio]
  172. dict = {
  173. "id": id,
  174. "anuncio": anuncio,
  175. "fecha": obj["name"],
  176. "timestamp": obj["name"] + int(obj['offset_seconds']),
  177. "confianza": obj["confidence"],
  178. "longitud": obj["length"],
  179. "desfase_segundos": obj["offset_seconds"]
  180. }
  181. if i["id"] in resultados.keys():
  182. resultados[i["id"]]["longitud"] = resultados[i["id"]]["longitud"] + dict["longitud"]
  183. resultados[i["id"]]["confianza"] = resultados[i["id"]]["confianza"] + dict["confianza"]
  184. continue
  185. resultados[i["id"]] = dict
  186. for id in resultados:
  187. e = resultados[id]
  188. for i in pendiente['elementos']:
  189. anuncio = e['anuncio'].replace('/tmp/ads/', '')
  190. if i['id'] == e['id'] and i['anuncio'] == anuncio:
  191. if 'encontrados' not in i:
  192. i['encontrados'] = []
  193. i['encontrados'].append(e)
  194. break
  195. log.info("[Resultado] %s" % (json.dumps(resultados)))
  196. enviar_resultados(pendiente)
  197. except Exception as ex:
  198. log.info(ex)
  199. app = setup_endpoint(queue=queue)
  200. loop = IOLoop.current()
  201. loop.add_callback(llenar_pila)
  202. if __name__ == '__main__':
  203. try:
  204. log.info('Starting ondemand service')
  205. loop.start()
  206. except KeyboardInterrupt:
  207. log.error('Process killed')