service.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 fourier.dejavu import Dejavu
  11. from Queue import Queue, Empty
  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. import firebase_admin
  17. import mutagen.mp3
  18. import requests
  19. import dateutil
  20. import sqlite3
  21. import time
  22. import sys
  23. import os
  24. AUDIOS_PATH = '/tmp'
  25. AHEAD_TIME_AUDIO_TOLERANCE = 2 # second
  26. config = parse_config()
  27. queue = Queue()
  28. client = Client(config['device_id'],
  29. config['apiSecret'])
  30. cloud_base_url = 'https://storage.googleapis.com/{}'\
  31. .format(config['bucket'])
  32. base_path = config.get("basepath", "/var/fourier")
  33. fb_credentials = credentials.Certificate('/etc/Fourier-key.json')
  34. firebase_admin.initialize_app(fb_credentials, config['firebase'])
  35. dejavu = Dejavu({"database_type":"mem"})
  36. device_id = config['device_id']
  37. device_path = os.path.join(base_path, device_id)
  38. recognizer = FilePerSecondRecognizer
  39. db_path = config.get('localDatabase', os.path.join(device_path, 'files.db'))
  40. db = sqlite3.connect(db_path)
  41. cloud_cache = {}
  42. def feed_queue():
  43. """ Search for pending scheduled work in
  44. server and add them to a memory queue. """
  45. try:
  46. response = client.get_schedule_pending()
  47. for item in response['items']:
  48. queue.put(item)
  49. if queue.qsize() > 0:
  50. loop.add_callback(process_queue)
  51. else:
  52. loop.add_timeout(time.time() + 30, feed_queue)
  53. except ConnectionError as ex:
  54. print('cannot feed: {}, retryig later'.format(ex),
  55. file=sys.stderr)
  56. loop.add_timeout(time.time() + 15, feed_queue)
  57. except Exception as ex:
  58. """ Errores desconocidos """
  59. print(ex, file=sys.stderr)
  60. loop.add_timeout(time.time() + 60, feed_queue)
  61. def process_queue():
  62. """ Try to the next item in a queue and start
  63. processing it accordingly. If success, repeat
  64. the function or go to feed if no more items. """
  65. try:
  66. item = queue.get(False)
  67. process_segment(item)
  68. loop.add_callback(process_queue)
  69. except Empty:
  70. loop.add_callback(feed_queue)
  71. except Exception as ex:
  72. print(str(ex), file=sys.stderr)
  73. loop.add_callback(process_queue)
  74. def process_segment(item):
  75. """ Procesa una hora de audio """
  76. station = item['station']
  77. date = dateutil.parser.parse(item['date'])
  78. # 1. obtener el audio desde firebase
  79. # y calcular su fingerprint.
  80. filename, md5hash = cloud_download(ad_key=item['ad'])
  81. if not filename:
  82. print('ad file missing', file=sys.stderr)
  83. return
  84. # 1.1 Calcular el número de segmentos requeridos
  85. # de acuerdo a la duración total del audio.
  86. try:
  87. audio = mutagen.mp3.MP3(filename)
  88. segments_needed = int(round(float(audio.info.length) / float(5)))
  89. except Exception as ex:
  90. print('file {} is not an mp3'.format(audio))
  91. print(ex)
  92. return
  93. try:
  94. dejavu.fingerprint_file(filename)
  95. except Exception as ex:
  96. print('cannot fingerprint: {}'.format(ex))
  97. # 2. Read the list of files from local database
  98. audios_counter = 0
  99. results = []
  100. for path, name, ts in iterate_audios(date, station):
  101. print(path)
  102. audios_counter += os.path.isfile(path)
  103. for match in dejavu.recognize(recognizer, path, 5,
  104. ads_filter=[md5hash]):
  105. try:
  106. results.append({
  107. 'confidence': match['confidence'],
  108. 'timestamp': ts,
  109. 'offset': match['offset']
  110. })
  111. print("{} {}".format(ts, match['confidence']))
  112. except KeyError as ex:
  113. print(ex, file=sys.stderr)
  114. ts += match['length'] / 1000
  115. try:
  116. response = client.put_schedule_results(
  117. item['schedule'],
  118. item['id'],
  119. None, # TODO: send results again
  120. found=find_repetitions(results,
  121. segments_needed=segments_needed
  122. ),
  123. missing_files=(12 - audios_counter) \
  124. if audios_counter < 12 else 0
  125. )
  126. print("api response: {}".format(response))
  127. except ConnectionError as ex:
  128. print(ex, file=sys.stderr)
  129. except UserWarning as warn:
  130. print(str(warn), file=sys.stderr)
  131. def find_repetitions(results, segments_needed=2):
  132. found_counter = 0
  133. found_index = None
  134. seconds_needed = 9
  135. threshold = 20
  136. expect_space = False
  137. found = []
  138. if segments_needed < 1:
  139. segments_needed = 1
  140. for index, result in enumerate(results):
  141. if not expect_space:
  142. if result['confidence'] > threshold:
  143. found_counter += 1
  144. if found_index is None:
  145. found_index = index
  146. else:
  147. found_counter = 0
  148. found_index = None
  149. else:
  150. if result['confidence'] <= threshold:
  151. expect_space = False
  152. if found_counter >= segments_needed:
  153. found.append(results[found_index]['timestamp'])
  154. found_counter = 0
  155. expect_space = True
  156. return found
  157. def iterate_audios(dt, station):
  158. """ Given a datetime object and an station,
  159. iterate a list of files that are between
  160. the the date and itself plus 5 minutes;
  161. station must match too """
  162. from_time = time.mktime(dt.timetuple()) \
  163. - AHEAD_TIME_AUDIO_TOLERANCE
  164. to_time = from_time + 3599 + AHEAD_TIME_AUDIO_TOLERANCE
  165. print('from {} to {}'.format(from_time, to_time))
  166. cursor = db.cursor()
  167. cursor.execute((
  168. 'select "filename", "timestamp" '
  169. 'from "file" '
  170. 'where "timestamp" between ? and ? '
  171. 'and "station" = ? '
  172. 'order by "timestamp" asc'
  173. ),
  174. (from_time, to_time, station, ),
  175. )
  176. files = [file for file in cursor]
  177. cursor.close()
  178. for mp3 in files:
  179. mp3path, ts = mp3
  180. mp3name = os.path.basename(mp3path)
  181. yield (mp3path, mp3name, ts)
  182. def cloud_download(ad_key=None):
  183. """ Given an ad key, the file is downloaded to
  184. the system temporal folder to be processed """
  185. if ad_key in cloud_cache:
  186. """ If this file has already been downloaded,
  187. will not be downloaded again, instead will
  188. be taken from cloud_cache dictionary """
  189. filename, md5hash = cloud_cache[ad_key]
  190. if os.path.isfile(filename):
  191. return filename, md5hash
  192. ad = fbdb.reference('ads/{}'.format(ad_key)).get()
  193. filename = os.path.basename(ad['path'])
  194. out_file = os.path.join(AUDIOS_PATH, filename)
  195. url = '{}/{}'.format(cloud_base_url, ad['path'])
  196. response = requests.get(url)
  197. if response.status_code == 200:
  198. hashes = response.headers['x-goog-hash']
  199. hashes = hashes.split(',')
  200. hashes = [h.split('=', 1) for h in hashes]
  201. hashes = {h[0].strip(): hexlify(b64decode(h[1])) for h in hashes}
  202. md5sum = hashes['md5']
  203. with open(out_file, "wb") as fp:
  204. fp.write(response.content)
  205. tp = (out_file, md5sum,)
  206. cloud_cache[ad_key] = tp
  207. return tp
  208. app = setup_endpoint(queue=queue)
  209. loop = IOLoop.current()
  210. loop.add_callback(feed_queue)
  211. if __name__ == '__main__':
  212. try:
  213. loop.start()
  214. except KeyboardInterrupt:
  215. print('process killed')