service.py 5.8 KB

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