service.py 6.9 KB

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