Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

feature_extractors.py 19 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. from abc import ABC
  2. import json
  3. import logging
  4. import os
  5. import random
  6. import subprocess
  7. from ast import literal_eval
  8. from pipeline.utils import SourceMedia, Source, Feature, Interval
  9. # for loudness detection
  10. import soundfile
  11. import pyloudnorm
  12. # for word detection
  13. from faster_whisper import WhisperModel, BatchedInferencePipeline
  14. logger = logging.getLogger(__name__)
  15. class FeatureExtractor(ABC):
  16. """Feature extractor interface."""
  17. def _run_get_output(self, cmd: list, cwd:str=".") -> str:
  18. """Run a command and return the output as a string
  19. Defined to be mocked out in tests via unittest.mock.patch
  20. """
  21. return subprocess.run(cmd, stdout=subprocess.PIPE, cwd=cwd).stdout.decode("utf-8")
  22. def setup(self):
  23. """Setup the feature extractor -- validate input files & config"""
  24. def run(self):
  25. """Run the feature extractor -- extract features"""
  26. def teardown(self):
  27. """Teardown the feature extractor -- clean up any temporary files created during setup"""
  28. class LaughterFeatureExtractor(FeatureExtractor):
  29. """Feature extractor for laughter detection.
  30. This class is responsible for extracting features corresponding to laughter in media files. Uses jrgillick's laughter-detection library.
  31. Here:
  32. setup() (not needed for laughter-detection, as it can work with AV files directly)
  33. run() is used to extract features from the audio using jrgillick's laughter-detection
  34. teardown() (not needed)
  35. @see: https://github.com/jrgillick/laughter-detection for the laughter-detection library
  36. """
  37. _PREPEND_TIME = 7.0 # seconds before the laugh to capture whatever was funny
  38. _APPEND_TIME = 3.0 # seconds after the laugh to capture the reaction
  39. _CONFIG_LAUGH_DETECTOR_DIR = "/home/robert/mounts/980data/code/laughter-detection/"
  40. def __init__(self, input_files=None, config=None):
  41. """It is expected that input_files is a SourceMedia object"""
  42. self.input_files = input_files
  43. self.config = config
  44. self.features = []
  45. def _laughdetect(self, audio_file, laugh_detector_dir=_CONFIG_LAUGH_DETECTOR_DIR) -> list:
  46. """Run laughter detection on the audio file
  47. Returns a list of 2-tuples, each representing a laugh instance in the audio file
  48. in the format: (start, end) in seconds
  49. """
  50. laugh_detector_script = "segment_laughter.py"
  51. # fake output for testing
  52. # laugh_detector_path = "tests/fake_segment_laughter.py"
  53. laugh_detector_cmd = ["python", f"{laugh_detector_dir}{laugh_detector_script}",
  54. f"--input_audio_file={audio_file}"]
  55. # run command, capture output, ignore exit status
  56. # use self._run_get_output to allow mocking in tests
  57. laugh_output = self._run_get_output(laugh_detector_cmd, laugh_detector_dir)
  58. # ↑ have to include cwd to keep laughter-detection imports happy
  59. # also, it isn't happy if no output dir is specified but we get laughs so it's grand
  60. # laughs are lines in stdout that start with "instance:", followed by a space and a 2-tuple of floats
  61. # so jump to the 10th character and evaluate the rest of the line
  62. return [literal_eval(instance[10:])
  63. for instance in laugh_output.splitlines()
  64. if instance.startswith("instance: ")]
  65. def _adjust_features(self) -> None:
  66. """Adjust features according to config
  67. Generically, this ensures features conform to config - min/max feature length, etc.
  68. In the context of LaughterFeatureExtractor, there is some secret sauce: things that
  69. cause a laugh generally /precede/ the laugh, so we want more team before the detected start
  70. than at the end. For example, for a minimum feature length of 15s, we might prepend 10 seconds,
  71. and append 5 seconds (for example), or 12s and 3s. We may wish to do this pre/post adjustment
  72. for all laughter features found, regardless of length.
  73. """
  74. for feature in self.features:
  75. # do the pre & post adjustment
  76. feature.interval.move_start(-self._PREPEND_TIME, relative=True)
  77. feature.interval.move_end(self._APPEND_TIME, relative=True)
  78. def setup(self):
  79. """Setup the laughter feature extractor -- not needed.
  80. jrgillick's laughter-detection library can work with AV files directly!
  81. """
  82. def run(self):
  83. """Extract laughter features for each input file.
  84. Heavy lifting is performed in _laughdetect()
  85. Tuples from _laughdetect are used to create Feature objects, which are appended to self.features by convention
  86. @see: utils.py:Feature, Interval
  87. """
  88. if self.input_files:
  89. for file in self.input_files:
  90. laughs = self._laughdetect(file.path)
  91. for laugh in laughs:
  92. start, end = laugh
  93. self.features.append(Feature(interval=Interval(start=start, end=end),
  94. source=file, feature_extractor="laughter"))
  95. # adjust features
  96. self._adjust_features()
  97. def teardown(self):
  98. """No cleanup needed!"""
  99. class RandomFeatureExtractor(FeatureExtractor):
  100. """Feature extractor for random feature generation.
  101. This class is responsible for generating random features for testing purposes.
  102. Here:
  103. setup() is not needed
  104. run() is used to generate random features
  105. teardown() is not needed
  106. """
  107. NUM_FEATURES = 30
  108. MAX_DURATION = 15.0
  109. MIN_DURATION = 5.0
  110. def __init__(self, input_files=None, config=None):
  111. """It is expected that input_files is a SourceMedia object"""
  112. self.input_files = input_files
  113. self.config = config
  114. self.features = []
  115. def setup(self):
  116. """Setup the random feature extractor -- validate input files & config"""
  117. logger.debug("RandomFeatureExtractor setup")
  118. # Validate input files
  119. if not self.input_files:
  120. raise ValueError("No input files provided")
  121. def run(self):
  122. """Generate random features for each input file"""
  123. # check self.input_files is of type SourceMedia
  124. if not self.input_files or not isinstance(self.input_files, SourceMedia):
  125. raise ValueError("No input files provided")
  126. for file in self.input_files:
  127. for _ in range(self.NUM_FEATURES):
  128. # determine duration between MIN and MAX, round to 3 decimal places
  129. duration = round(random.uniform(self.MIN_DURATION, self.MAX_DURATION), 3)
  130. start = random.random() * file.duration() - duration
  131. self.features.append(Feature(interval=Interval(start=start, duration=duration),
  132. source=file, feature_extractor="random"))
  133. def teardown(self):
  134. pass
  135. class LoudAudioFeatureExtractor(FeatureExtractor):
  136. """Feature extractor for loud audio detection.
  137. This class is responsible for extracting features corresponding to loud audio in media files.
  138. Here:
  139. setup() is used to validate input files & config, and extracting audio
  140. run() uses pyloudnorm to detect loud audio
  141. teardown() is used to clean up temporary files created during setup (if specified by config)
  142. """
  143. _CONFIG_DEFAULT_NUM_FEATURES = 5 # keep the top 5 loudnesses
  144. def __init__(self, input_files=None, config=None, num_features=_CONFIG_DEFAULT_NUM_FEATURES):
  145. if not input_files:
  146. raise ValueError("No input files provided!")
  147. self.input_files = input_files
  148. self.config = config
  149. self.features = []
  150. self._num_features = num_features
  151. def _audio_file_from_path(self, path: str) -> str:
  152. """Return the audio file path given a video file path
  153. Example:
  154. - in = "/path/to/video.mp4"
  155. - out = "/tmp/video.mp4.wav"
  156. """
  157. OUTPUT_DIR = "/tmp"
  158. return f"{OUTPUT_DIR}/{os.path.basename(path)}.wav"
  159. def _get_loudnesses(self, data, meter, rate, window_size, stride_size):
  160. """Extract loudnesses from the audio data using pyloudnorm
  161. return a list of 2-tuples, each representing a timecode and loudness value
  162. """
  163. loudnesses = []
  164. for w in range(0, len(data)-window_size, stride_size):
  165. window = data[w:w+window_size, 0:2] # extract window
  166. loudnesses.append( (w/rate, meter.integrated_loudness(window)) )
  167. return loudnesses
  168. def _loudnorm(self, audio_file):
  169. """Run pyloudnorm on the audio file"""
  170. data, rate = soundfile.read(audio_file) # load audio (with shape (samples, channels))
  171. meter = pyloudnorm.Meter(rate=rate,block_size=0.3) # create BS.1770 meter
  172. loudness_features = []
  173. window_size = int(rate * 0.5) # 500ms
  174. stride_size = int(rate * 0.5) # 500ms -- no overlap
  175. # for w in range(data.shape[0]//100):
  176. # loudnesses.append(meter.integrated_loudness(data[w:w+int(0.3*rate),0:2]))
  177. loudnesses = self._get_loudnesses(data, meter, rate, window_size, stride_size)
  178. for timecode, loudval in sorted([l for l in loudnesses if float(l[1]) != float("-inf")], key=lambda x: x[1], reverse=True):
  179. # print(f"Timecode: {timecode}, Loudness: {loudval}")
  180. loudness_features.append((timecode, round(loudval, 3))) # round to 3 DP
  181. return loudness_features
  182. def _keep_num(self, loudnesses, num=_CONFIG_DEFAULT_NUM_FEATURES) -> list:
  183. """Keep the top n loudnesses (default: 5)"""
  184. return sorted(loudnesses, key=lambda x: x[1], reverse=True)[:num]
  185. def setup(self):
  186. """extract audio from video files to be processed by pyloudnorm
  187. TODO: config -- hardcoded for now
  188. """
  189. # pyloudnorm expects WAV files
  190. for file in self.input_files:
  191. audio_file = self._audio_file_from_path(file.path)
  192. # ffmpeg -i input.mp4 -vn -acodec pcm_s16le output.wav
  193. subprocess.run(["ffmpeg", "-y", "-i", file.path, "-vn", "-acodec", "pcm_s16le", audio_file],
  194. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  195. def run(self):
  196. """Use pyloudnorm to detect loud audio"""
  197. for file in self.input_files:
  198. audio_file = self._audio_file_from_path(file.path)
  199. loudnesses = self._loudnorm(audio_file)
  200. top_loudnesses = self._keep_num(loudnesses, self._num_features)
  201. for time, loudness in top_loudnesses:
  202. self.features.append(Feature(interval=Interval(start=time, duration=0.500),
  203. source=file, feature_extractor="loudness",
  204. score=loudness))
  205. class VideoActivityFeatureExtractor(FeatureExtractor):
  206. """Feature extractor for video activity detection.
  207. This class is responsible for extracting features corresponding to high activity in video files.
  208. Uses ffmpeg's scdet filter with threshold of zero.
  209. Here:
  210. setup() is used to validate input files & config
  211. run() is used to extract features from the video using OpenCV
  212. teardown() is used to clean up any temporary files created during setup according to the config
  213. #TODO: minimum duration -- consider whether to do here, or expand duration post-consolidation
  214. """
  215. def __init__(self, input_files=None, config=None):
  216. if not input_files:
  217. raise ValueError("No input files provided!")
  218. self.input_files = input_files
  219. self.config = config
  220. self.features = []
  221. def _scdet(self, video_file):
  222. """Run scdet filter on the video file"""
  223. ffmpeg_cmd = ["ffmpeg", "-i", video_file, "-vf", "scdet=threshold=0", "-f", "null", "-"]
  224. # output is of the form:
  225. # [scdet @ 0x7f0798003d00] lavfi.scd.score: 0.031, lavfi.scd.time: 23.65
  226. # [scdet @ 0x7f0798003d00] lavfi.scd.score: 0.006, lavfi.scd.time: 23.70
  227. # capture output, extract time & score
  228. scdet_output = subprocess.run(ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stderr.decode("utf-8")
  229. # extract time & score
  230. scores = []
  231. for line in scdet_output.splitlines():
  232. if "lavfi.scd.score" in line:
  233. scores.append( (float(line.split(",")[1].split(":")[1]),
  234. float(line.split(",")[0].split(":")[1]))
  235. )
  236. return scores
  237. def _nonoverlap_mean(self, scores, window_size=0.500) -> list:
  238. """Take the mean of non-overlapping windows of scores
  239. Input: list of tuples in the format (time, score)
  240. Output: list of tuples in the format (time, mean_score) (reduced set)
  241. """
  242. means = []
  243. current_window = []
  244. current_window_start = 0.0
  245. for time, score in scores:
  246. if time - current_window_start > window_size:
  247. # calculate mean of current window
  248. mean_score = sum([s for _, s in current_window]) / len(current_window)
  249. means.append((current_window_start, round(mean_score, 3)))
  250. # reset window
  251. current_window = []
  252. current_window_start = time
  253. current_window.append((time, score))
  254. return means
  255. def _drop_lowest(self, scores, percent=33):
  256. """Drop the lowest n% scores from the list"""
  257. scores = sorted(scores, key=lambda x: x[1], reverse=True)
  258. return scores[:int(len(scores) * (percent / 100))]
  259. def setup(self):
  260. pass
  261. def run(self):
  262. for file in self.input_files:
  263. scores = self._scdet(file.path)
  264. means = sorted(self._nonoverlap_mean(scores), key=lambda x: x[1], reverse=True)
  265. for time, score in self._drop_lowest(means, 66):
  266. self.features.append(Feature(interval=Interval(start=time, duration=0.500),
  267. source=file, feature_extractor="videoactivity",
  268. score=score))
  269. def teardown(self):
  270. pass
  271. class JSONFeatureExtractor(FeatureExtractor):
  272. """(Re-)create features from a JSON file
  273. The JSON file can have one of two formats:
  274. - the format produced by the pipleline (@see: video_producers.py:JSONProducer)
  275. - a simplified format which is easier for manual creation
  276. """
  277. def __init__(self, input_files=None, config=None):
  278. if not input_files:
  279. raise ValueError("No input files provided!")
  280. self.input_files = input_files
  281. self.config = config
  282. self.features = []
  283. def setup(self):
  284. pass
  285. def _interval_from_dict(self, d):
  286. return Interval(start=d["start"], duration=d["duration"])
  287. def _source_from_dict(self, d):
  288. return Source(d["source"], d["path"], d["provider"])
  289. def _read_json_from_file(self, file):
  290. """Read a JSON file and return the contents
  291. Method exists to allow for mocking in tests
  292. """
  293. with open(file, "r") as f:
  294. return json.load(f)
  295. def run(self):
  296. # only pipeline JSON format for now
  297. # TODO: add support for simplified format
  298. for file in self.input_files:
  299. features_from_json = self._read_json_from_file(file.path)
  300. for feature in features_from_json:
  301. self.features.append(Feature(interval=self._interval_from_dict(feature["interval"]),
  302. source=self._source_from_dict(feature["source"]),
  303. feature_extractor=feature["feature_extractor"],
  304. score=feature["score"]))
  305. def teardown(self):
  306. pass
  307. class WordFeatureExtractor(FeatureExtractor):
  308. """Feature extractor for specific word detection (uses Whisper)"""
  309. # set defaults for whisper settings
  310. DEFAULT_MODEL_SIZE = "medium"
  311. DEFAULT_DEVICE = "cpu"
  312. DEFAULT_COMPUTE_TYPE = "int8"
  313. DEFAULT_BEAM_SIZE = 5
  314. DEFAULT_BATCH_SIZE = 16
  315. DEFAULT_PIPELINE_TYPE = "batched" # or "stream"
  316. words = []
  317. def _transcribe(self, model, file, **kwargs):
  318. """Defined here to allow for mocking in tests"""
  319. return model.transcribe(file, **kwargs)
  320. def _whispermodel(self, model_size=DEFAULT_MODEL_SIZE,
  321. device=DEFAULT_DEVICE, compute_type=DEFAULT_COMPUTE_TYPE):
  322. """Defined here to allow for mocking out in tests"""
  323. return WhisperModel(model_size, device=device, compute_type=compute_type)
  324. def _batched_inference_pipeline(self, model):
  325. """Defined here to allow for mocking out in tests"""
  326. return BatchedInferencePipeline(model=model)
  327. def __init__(self, input_files=None, config=None):
  328. if not input_files:
  329. raise ValueError("No input files provided!")
  330. self.input_files = input_files
  331. self.config = config
  332. self.features = []
  333. def setup(self, words=[]):
  334. """Setup the word feature extractor -- validate input files & config
  335. Whisper expects a list of words to search for in the audio
  336. """
  337. logger.debug("WordFeatureExtractor setup")
  338. # Validate words - raise a notice if none provided
  339. if len(words) == 0:
  340. logger.warning("No words provided for detection")
  341. self.words = words
  342. # TODO: consider stripping punctuation since Whisper produces words+punctuation
  343. # and we might want to strip the punctuation there too
  344. def run(self):
  345. """Extract features corresponding to supplied target words (defined in setup) for each input file
  346. Use Whisper to detect words in the audio, then match these to target words and create features
  347. Note: if no words are supplied we can exit early
  348. """
  349. if len(self.words) == 0: return
  350. if self.DEFAULT_PIPELINE_TYPE == "batched":
  351. batched = True
  352. else:
  353. batched = False
  354. # no early exit
  355. # TODO: consider maybe loglevel notice of estimated time! consider also: max execution time config?
  356. # TODO: config options for model size, device, compute type
  357. model = self._whispermodel() # NB uses defaults, TODO: add config options
  358. # NOTE: batched not available on pypi yet at time of writing
  359. if batched:
  360. batched_model = self._batched_inference_pipeline(model)
  361. for file in self.input_files:
  362. # transcribe the audio file
  363. if batched:
  364. segments, _ = self._transcribe(batched_model, file.path, batch_size=self.DEFAULT_BATCH_SIZE)
  365. else:
  366. segments, _ = self._transcribe(model, file.path, beam_size=self.DEFAULT_BEAM_SIZE)
  367. # process the segments
  368. # segment has: start, end, text
  369. for segment in segments:
  370. # check if any of the words are in the segment
  371. for word in segment.text.split():
  372. if word in self.words:
  373. self.features.append(Feature(interval=Interval(start=segment.start, end=segment.end),
  374. source=file, feature_extractor="word",
  375. score=1.0))