You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

553 lines
21 KiB

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