service.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. ads_filter=[md5hash]):
  91. try:
  92. results.append({
  93. 'confidence': match['confidence'],
  94. 'timestamp': ts,
  95. 'offset': match['offset']
  96. })
  97. print("{} {}".format(ts, match['confidence']))
  98. except KeyError as ex:
  99. print(ex, file=sys.stderr)
  100. ts += match['length'] / 1000
  101. try:
  102. response = client.put_schedule_results(
  103. item['schedule'],
  104. item['id'],
  105. None, # TODO: send results again
  106. found=find_repetitions(results),
  107. )
  108. print("api response: {}".format(response))
  109. except ConnectionError as ex:
  110. print(ex, file=sys.stderr)
  111. except UserWarning as warn:
  112. print(str(warn), file=sys.stderr)
  113. def find_repetitions(results):
  114. found_counter = 0
  115. found_index = None
  116. segments_needed = 2
  117. seconds_needed = 9
  118. threshold = 20
  119. expect_space = False
  120. found = []
  121. for index, result in enumerate(results):
  122. if not expect_space:
  123. if result['confidence'] > threshold:
  124. found_counter += 1
  125. if found_index is None:
  126. found_index = index
  127. else:
  128. found_counter = 0
  129. found_index = None
  130. else:
  131. if result['confidence'] <= threshold:
  132. expect_space = False
  133. if found_counter >= segments_needed:
  134. """ TODO: It will be neccessary to improve this
  135. further, so it can recognize more than one
  136. audio in the same segment of 1 hour. Also the
  137. seconds transcurred is important; a time
  138. difference is needed """
  139. found.append(results[found_index]['timestamp'])
  140. found_counter = 0
  141. expect_space = True
  142. return found
  143. def iterate_audios(dt, station):
  144. """ Given a datetime object and an station,
  145. iterate a list of files that are between
  146. the the date and itself plus 5 minutes;
  147. station must match too """
  148. from_time = time.mktime(dt.timetuple())
  149. to_time = from_time + 3599
  150. print('from {} to {}'.format(from_time, to_time))
  151. cursor = db.cursor()
  152. cursor.execute((
  153. 'select "filename", "timestamp" '
  154. 'from "file" '
  155. 'where "timestamp" between ? and ? '
  156. 'and "station" = ? '
  157. 'order by "timestamp" asc'
  158. ),
  159. (from_time, to_time, station, ),
  160. )
  161. files = [file for file in cursor]
  162. cursor.close()
  163. for mp3 in files:
  164. mp3path, ts = mp3
  165. mp3name = os.path.basename(mp3path)
  166. yield (mp3path, mp3name, ts)
  167. def cloud_download(ad_key=None):
  168. """ Given an ad key, the file is downloaded to
  169. the system temporal folder to be processed """
  170. if ad_key in cloud_cache:
  171. """ If this file has already been downloaded,
  172. will not be downloaded again, instead will
  173. be taken from cloud_cache dictionary """
  174. filename, md5hash = cloud_cache[ad_key]
  175. if os.path.isfile(filename):
  176. return filename, md5hash
  177. ad = fbdb.reference('ads/{}'.format(ad_key)).get()
  178. filename = os.path.basename(ad['path'])
  179. out_file = os.path.join(AUDIOS_PATH, filename)
  180. url = '{}/{}'.format(cloud_base_url, ad['path'])
  181. response = requests.get(url)
  182. if response.status_code == 200:
  183. hashes = response.headers['x-goog-hash']
  184. hashes = hashes.split(',')
  185. hashes = [h.split('=', 1) for h in hashes]
  186. hashes = {h[0].strip(): hexlify(b64decode(h[1])) for h in hashes}
  187. md5sum = hashes['md5']
  188. with open(out_file, "wb") as fp:
  189. fp.write(response.content)
  190. tp = (out_file, md5sum)
  191. cloud_cache[ad_key] = tp
  192. return tp
  193. app = Application()
  194. loop = IOLoop.current()
  195. loop.add_callback(feed_queue)
  196. if __name__ == '__main__':
  197. loop.start()