ondemand.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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.metrico.fourier.audio/comparacion/pendiente.json'
  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 enviar_resultados(trabajo):
  68. print('[Pendiente] %s' % (json.dumps(trabajo),))
  69. url = 'https://api.metrico.fourier.audio/comparacion/resultado.json'
  70. response = requests.post(url, json=trabajo)
  71. print('[Response] %s' % (response.text))
  72. return response
  73. def llenar_pila():
  74. """ Search for pending scheduled work in
  75. server and add them to a memory queue. """
  76. try:
  77. response = obt_siguiente_trabajo()
  78. if len(response["elementos"]) > 0:
  79. queue.put(response)
  80. if queue.qsize() > 0:
  81. loop.add_callback(procesar_siguiente_pila)
  82. else:
  83. loop.add_timeout(time.time() + 30, llenar_pila)
  84. except Exception as ex:
  85. """ Errores desconocidos """
  86. log.error('[feed_queue] {}'.format(ex))
  87. loop.add_timeout(time.time() + 60, llenar_pila)
  88. raise ex
  89. def procesar_siguiente_pila():
  90. """ Try to the next item in a queue and start
  91. processing it accordingly. If success, repeat
  92. the function or go to feed if no more items. """
  93. try:
  94. item = queue.get(False)
  95. procesar_trabajo(item)
  96. loop.add_callback(procesar_siguiente_pila)
  97. except Empty:
  98. loop.add_callback(llenar_pila)
  99. except Exception as ex:
  100. log.error(ex)
  101. loop.add_callback(procesar_siguiente_pila)
  102. def procesar_trabajo(pendiente):
  103. ciudad = pendiente['origen']
  104. estacion = pendiente['estacion']
  105. confianza = 35
  106. segmento = 5
  107. #if "segmento" in pendiente:
  108. # segmento = int(pendiente["segmento"])
  109. #if "confianza" in pendiente:
  110. # confianza = int(pendiente["confianza"])
  111. # Descarga de anuncios
  112. log.info("Descargando anuncios")
  113. try:
  114. anuncios = []
  115. id_by_ad = {}
  116. item_ids = []
  117. for i in pendiente["elementos"]:
  118. id_by_ad[i['anuncio']] = i['id']
  119. if i['id'] not in item_ids:
  120. item_ids.append(i['id'])
  121. anuncio = descargar_anuncio(i["ruta"])
  122. if anuncio is not None:
  123. anuncios.append(anuncio)
  124. except Exception as err:
  125. log.info('[process_segment] [{}] {}'.format(estacion, err))
  126. # Descarga de media
  127. log.info("Descargando media")
  128. try:
  129. media = []
  130. for i in pendiente["media"]:
  131. archivo = descargar_media(ciudad, estacion, i["ruta"])
  132. if archivo is not None:
  133. media.append((archivo, i["fecha"], i["timestamp"]))
  134. except Exception as err:
  135. log.info(err)
  136. log.info("Inicia la comparacion, tamaño de segmento %s" % (segmento,))
  137. try:
  138. dejavu = None
  139. resultados = {}
  140. aux = {}
  141. if len(media) > 0 and len(anuncio) > 0:
  142. dejavu = Dejavu({"database_type": "mem"})
  143. try:
  144. x = 0
  145. for ruta, fecha, ts in media:
  146. log.info("Huellando %s" % (ruta,))
  147. dejavu.fingerprint_file(ruta, ts)
  148. except Exception as ex:
  149. log.info(ex)
  150. for anuncio in anuncios:
  151. for i in dejavu.recognize(recognizer, anuncio, 5):
  152. if not "id" in i:
  153. continue
  154. nombre_anuncio = os.path.split(anuncio)[-1]
  155. id = id_by_ad[nombre_anuncio]
  156. if id not in resultados:
  157. resultados[id] = []
  158. obj = i
  159. obj["match_time"] = None
  160. dict = {
  161. "id": id,
  162. "anuncio": anuncio,
  163. "fecha": obj["name"],
  164. "timestamp": obj["name"] + int(obj['offset_seconds']),
  165. "confianza": obj["confidence"],
  166. "longitud": obj["length"],
  167. "desfase_segundos": obj["offset_seconds"]
  168. }
  169. resultados[id].append(dict)
  170. for k in resultados.keys():
  171. lista = sorted(resultados[k], key=lambda d: d['timestamp'])
  172. lista_nueva = []
  173. ult = None
  174. for x in range(0, len(lista)):
  175. if x == 0:
  176. ult = x
  177. lista_nueva.append(lista[ult])
  178. else:
  179. dif = lista[x]['timestamp'] - lista[x - 1]['timestamp']
  180. if dif <= 30:
  181. lista_nueva[ult]['confianza'] = int(lista_nueva[ult]['confianza']) + int(lista[x]['confianza'])
  182. lista_nueva[ult]['longitud'] = int(lista_nueva[ult]['longitud']) +int(lista[x]['longitud'])
  183. else:
  184. lista_nueva.append(lista[x])
  185. ult = len(lista_nueva) - 1
  186. aux[k] = lista_nueva
  187. else:
  188. for i in pendiente['elementos']:
  189. i['comentario'] = 'Problemas técnicos'
  190. for id in aux:
  191. for e in aux[id]:
  192. for i in pendiente['elementos']:
  193. i['comentario'] = ''
  194. anuncio = e['anuncio'].replace('/tmp/ads/', '')
  195. if i['id'] == e['id'] and i['anuncio'] == anuncio:
  196. if 'encontrados' not in i:
  197. i['encontrados'] = []
  198. obj = {
  199. "fecha": e["fecha"],
  200. "anuncio": anuncio,
  201. "longitud": int(e["longitud"] / 1000),
  202. "confianza": e["confianza"],
  203. "timestamp": e["timestamp"],
  204. "desfase_segundos": e["desfase_segundos"]
  205. }
  206. i['encontrados'].append(obj)
  207. break
  208. # log.info(json.dumps(extras))
  209. log.info("[Resultado] %s" % (json.dumps(resultados)))
  210. pendiente["media"] = None
  211. enviar_resultados(pendiente)
  212. except Exception as ex:
  213. log.info(ex)
  214. app = setup_endpoint(queue=queue)
  215. loop = IOLoop.current()
  216. loop.add_callback(llenar_pila)
  217. if __name__ == '__main__':
  218. try:
  219. log.info('Starting ondemand service')
  220. loop.start()
  221. except KeyboardInterrupt:
  222. log.error('Process killed')