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.

590 line
24 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. 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. if not self.input_files or len(self.input_files) == 0:
  83. raise ValueError("No input files provided!")
  84. def run(self):
  85. """Extract laughter features for each input file.
  86. Heavy lifting is performed in _laughdetect()
  87. Tuples from _laughdetect are used to create Feature objects, which are appended to self.features by convention
  88. @see: utils.py:Feature, Interval
  89. """
  90. if self.input_files:
  91. for file in self.input_files:
  92. laughs = self._laughdetect(file.path)
  93. for laugh in laughs:
  94. start, end = laugh
  95. self.features.append(Feature(interval=Interval(start=start, end=end),
  96. source=file, feature_extractor="laughter"))
  97. # adjust features
  98. self._adjust_features()
  99. def teardown(self):
  100. """No cleanup needed!"""
  101. class RandomFeatureExtractor(FeatureExtractor):
  102. """Feature extractor for random feature generation.
  103. This class is responsible for generating random features for testing purposes.
  104. Here:
  105. setup() is not needed
  106. run() is used to generate random features
  107. teardown() is not needed
  108. """
  109. NUM_FEATURES = 30
  110. MAX_DURATION = 15.0
  111. MIN_DURATION = 5.0
  112. def __init__(self, input_files=None, config=None):
  113. """It is expected that input_files is a SourceMedia object"""
  114. self.input_files = input_files
  115. self.config = config
  116. self.features = []
  117. def setup(self):
  118. """Setup the random feature extractor -- validate input files & config"""
  119. logger.debug("RandomFeatureExtractor setup")
  120. # Validate input files
  121. if not self.input_files:
  122. raise ValueError("No input files provided")
  123. def run(self):
  124. """Generate random features for each input file"""
  125. # check self.input_files is of type SourceMedia
  126. if not self.input_files or not isinstance(self.input_files, SourceMedia):
  127. raise ValueError("No input files provided")
  128. for file in self.input_files:
  129. for _ in range(self.NUM_FEATURES):
  130. # determine duration between MIN and MAX, round to 3 decimal places
  131. duration = round(random.uniform(self.MIN_DURATION, self.MAX_DURATION), 3)
  132. start = random.random() * file.duration() - duration
  133. self.features.append(Feature(interval=Interval(start=start, duration=duration),
  134. source=file, feature_extractor="random"))
  135. def teardown(self):
  136. pass
  137. class LoudAudioFeatureExtractor(FeatureExtractor):
  138. """Feature extractor for loud audio detection.
  139. This class is responsible for extracting features corresponding to loud audio in media files.
  140. Here:
  141. setup() is used to validate input files & config, and extracting audio
  142. run() uses pyloudnorm to detect loud audio
  143. teardown() is used to clean up temporary files created during setup (if specified by config)
  144. """
  145. _CONFIG_DEFAULT_NUM_FEATURES = 15 # keep the top 5 loudnesses
  146. _CONFIG_DEFAULT_MIN_DURATION = 5.00 # seconds
  147. def __init__(self, input_files=None, config=None,
  148. num_features=_CONFIG_DEFAULT_NUM_FEATURES,
  149. min_duration=_CONFIG_DEFAULT_MIN_DURATION):
  150. if not input_files:
  151. raise ValueError("No input files provided!")
  152. self.input_files = input_files
  153. self.config = config
  154. self.features = []
  155. self._num_features = num_features
  156. self._min_duration = min_duration
  157. def _audio_file_from_path(self, path: str) -> str:
  158. """Return the audio file path given a video file path
  159. Example:
  160. - in = "/path/to/video.mp4"
  161. - out = "/tmp/video.mp4.wav"
  162. """
  163. OUTPUT_DIR = "/tmp"
  164. return f"{OUTPUT_DIR}/{os.path.basename(path)}.wav"
  165. def _get_loudnesses(self, data, meter, rate, window_size, stride_size):
  166. """Extract loudnesses from the audio data using pyloudnorm
  167. return a list of 2-tuples, each representing a timecode and loudness value
  168. """
  169. loudnesses = []
  170. for w in range(0, len(data)-window_size, stride_size):
  171. window = data[w:w+window_size, 0:2] # extract window
  172. loudnesses.append( (w/rate, meter.integrated_loudness(window)) )
  173. return loudnesses
  174. def _loudnorm(self, audio_file):
  175. """Run pyloudnorm on the audio file"""
  176. data, rate = soundfile.read(audio_file) # load audio (with shape (samples, channels))
  177. meter = pyloudnorm.Meter(rate=rate,block_size=0.3) # create BS.1770 meter
  178. loudness_features = []
  179. window_size = int(rate * 0.5) # 500ms
  180. stride_size = int(rate * 0.5) # 500ms -- no overlap
  181. # for w in range(data.shape[0]//100):
  182. # loudnesses.append(meter.integrated_loudness(data[w:w+int(0.3*rate),0:2]))
  183. loudnesses = self._get_loudnesses(data, meter, rate, window_size, stride_size)
  184. for timecode, loudval in sorted([l for l in loudnesses if float(l[1]) != float("-inf")], key=lambda x: x[1], reverse=True):
  185. # print(f"Timecode: {timecode}, Loudness: {loudval}")
  186. loudness_features.append((timecode, round(loudval, 3))) # round to 3 DP
  187. return loudness_features
  188. def _keep_num(self, features, num=_CONFIG_DEFAULT_NUM_FEATURES, trim_overlap=False) -> list:
  189. """Keep the top n features (default: 5)
  190. Approach:
  191. - for range in 0-n
  192. + expand the nth top feature to min duration
  193. (move start back by 0.5*min_duration, end forward by 0.5*min_duration)
  194. + drop any features that are now in that feature's range (optional)
  195. - return the top n features
  196. Each feature is a Feature object, with an Interval object
  197. """
  198. keep_features = []
  199. # ensure features are sorted by score
  200. features = sorted(features, key=lambda x: x.score, reverse=True)
  201. for i in range(num):
  202. current_feature = features.pop(0)
  203. # expand the feature to min_duration - try and keep centered at current start
  204. if self._min_duration > current_feature.interval.duration:
  205. current_feature.interval.move_start(-0.5*self._min_duration, relative=True)
  206. if current_feature.interval.duration < self._min_duration:
  207. current_feature.interval.update_duration(self._min_duration)
  208. keep_features.append(current_feature)
  209. # drop any features that are now in that feature's range (plus margin)
  210. # features = [f for f in features if
  211. # (f.interval.start < current_feature.interval.start-margin and
  212. # f.interval.end > current_feature.interval.start-margin) or
  213. # (f.interval.end > current_feature.interval.end+margin and
  214. # f.interval.start < current_feature.interval.end+margin)]
  215. if trim_overlap:
  216. features = [f for f in features if f.interval.overlaps(current_feature.interval)]
  217. return keep_features
  218. def setup(self):
  219. """extract audio from video files to be processed by pyloudnorm
  220. TODO: config -- hardcoded for now
  221. """
  222. # pyloudnorm expects WAV files
  223. for file in self.input_files:
  224. audio_file = self._audio_file_from_path(file.path)
  225. # ffmpeg -i input.mp4 -vn -acodec pcm_s16le output.wav
  226. subprocess.run(["ffmpeg", "-y", "-i", file.path, "-vn", "-acodec", "pcm_s16le", audio_file],
  227. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  228. def run(self):
  229. """Use pyloudnorm to detect loud audio"""
  230. for file in self.input_files:
  231. audio_file = self._audio_file_from_path(file.path)
  232. loudnesses = self._loudnorm(audio_file)
  233. features = []
  234. for time, loudness in loudnesses:
  235. features.append(Feature(interval=Interval(start=time, duration=0.500),
  236. source=file, feature_extractor="loudness",
  237. score=loudness))
  238. # prune features list to keep self.num_features
  239. if len(features) > self._num_features:
  240. self.features = self._keep_num(features, self._num_features)
  241. else:
  242. self.features = features
  243. class VideoActivityFeatureExtractor(FeatureExtractor):
  244. """Feature extractor for video activity detection.
  245. This class is responsible for extracting features corresponding to high activity in video files.
  246. Uses ffmpeg's scdet filter with threshold of zero.
  247. Here:
  248. setup() is used to validate input files & config
  249. run() is used to extract features from the video using OpenCV
  250. teardown() is used to clean up any temporary files created during setup according to the config
  251. #TODO: minimum duration -- consider whether to do here, or expand duration post-consolidation
  252. """
  253. _CONFIG_DEFAULT_NUM_FEATURES = 15 # keep the top 5 activity moments
  254. _CONFIG_DEFAULT_MIN_DURATION = 5.00 # seconds
  255. def __init__(self, input_files=None, config=None,
  256. num_features=_CONFIG_DEFAULT_NUM_FEATURES,
  257. min_duration=_CONFIG_DEFAULT_MIN_DURATION):
  258. if not input_files:
  259. raise ValueError("No input files provided!")
  260. self.input_files = input_files
  261. self.config = config
  262. self.features = []
  263. self._num_features = num_features
  264. self._min_duration = min_duration
  265. def _scdet(self, video_file):
  266. """Run scdet filter on the video file"""
  267. ffmpeg_cmd = ["ffmpeg", "-i", video_file, "-vf", "scdet=threshold=0", "-f", "null", "-"]
  268. # output is of the form:
  269. # [scdet @ 0x7f0798003d00] lavfi.scd.score: 0.031, lavfi.scd.time: 23.65
  270. # [scdet @ 0x7f0798003d00] lavfi.scd.score: 0.006, lavfi.scd.time: 23.70
  271. # capture output, extract time & score
  272. scdet_output = subprocess.run(ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stderr.decode("utf-8")
  273. # extract time & score
  274. scores = []
  275. for line in scdet_output.splitlines():
  276. if "lavfi.scd.score" in line:
  277. scores.append( (float(line.split(",")[1].split(":")[1]),
  278. float(line.split(",")[0].split(":")[1]))
  279. )
  280. return scores
  281. def _nonoverlap_mean(self, scores, window_size=0.500) -> list:
  282. """Take the mean of non-overlapping windows of scores
  283. Input: list of tuples in the format (time, score)
  284. Output: list of tuples in the format (time, mean_score) (reduced set)
  285. """
  286. means = []
  287. current_window = []
  288. current_window_start = 0.0
  289. for time, score in scores:
  290. if time - current_window_start > window_size:
  291. # calculate mean of current window
  292. mean_score = sum([s for _, s in current_window]) / len(current_window)
  293. means.append((current_window_start, round(mean_score, 3)))
  294. # reset window
  295. current_window = []
  296. current_window_start = time
  297. current_window.append((time, score))
  298. return means
  299. def _drop_lowest(self, scores, percent=33):
  300. """Drop the lowest n% scores from the list"""
  301. scores = sorted(scores, key=lambda x: x[1], reverse=True)
  302. return scores[:int(len(scores) * (percent / 100))]
  303. def _keep_num(self, features, num=_CONFIG_DEFAULT_NUM_FEATURES, trim_overlap=False) -> list:
  304. """Keep the top n features (default: 5)
  305. Approach:
  306. - for range in 0-n
  307. + expand the nth top feature to min duration
  308. (move start back by 0.5*min_duration, end forward by 0.5*min_duration)
  309. + drop any features that are now in that feature's range (optional)
  310. - return the top n features
  311. Each feature is a Feature object, with an Interval object
  312. """
  313. keep_features = []
  314. # ensure features are sorted by score
  315. features = sorted(features, key=lambda x: x.score, reverse=True)
  316. for i in range(num):
  317. current_feature = features.pop(0)
  318. # expand the feature to min_duration - try and keep centered at current start
  319. if self._min_duration > current_feature.interval.duration:
  320. current_feature.interval.move_start(-0.5*self._min_duration, relative=True)
  321. if current_feature.interval.duration < self._min_duration:
  322. current_feature.interval.update_duration(self._min_duration)
  323. keep_features.append(current_feature)
  324. # drop any features that are now in that feature's range (plus margin)
  325. # features = [f for f in features if
  326. # (f.interval.start < current_feature.interval.start-margin and
  327. # f.interval.end > current_feature.interval.start-margin) or
  328. # (f.interval.end > current_feature.interval.end+margin and
  329. # f.interval.start < current_feature.interval.end+margin)]
  330. if trim_overlap:
  331. features = [f for f in features if f.interval.overlaps(current_feature.interval)]
  332. return keep_features
  333. def setup(self):
  334. pass
  335. def run(self):
  336. for file in self.input_files:
  337. scores = self._scdet(file.path)
  338. means = sorted(self._nonoverlap_mean(scores), key=lambda x: x[1], reverse=True)
  339. features = []
  340. for time, score in self._drop_lowest(means, 66):
  341. features.append(Feature(interval=Interval(start=time, duration=0.500),
  342. source=file, feature_extractor="videoactivity",
  343. score=score))
  344. # prune features list to keep self.num_features
  345. if len(self.features) > self._num_features:
  346. self.features = self._keep_num(features, self._num_features)
  347. else:
  348. self.features = features
  349. def teardown(self):
  350. pass
  351. class JSONFeatureExtractor(FeatureExtractor):
  352. """(Re-)create features from a JSON file
  353. The JSON file can have one of two formats:
  354. - the format produced by the pipleline (@see: video_producers.py:JSONProducer)
  355. - a simplified format which is easier for manual creation
  356. """
  357. def __init__(self, input_files=None, config=None):
  358. if not input_files:
  359. raise ValueError("No input files provided!")
  360. self.input_files = input_files
  361. self.config = config
  362. self.features = []
  363. def setup(self):
  364. pass
  365. def _interval_from_dict(self, d):
  366. return Interval(start=d["start"], duration=d["duration"])
  367. def _source_from_dict(self, d):
  368. return Source(d["source"], d["path"], d["provider"])
  369. def _read_json_from_file(self, file):
  370. """Read a JSON file and return the contents
  371. Method exists to allow for mocking in tests
  372. """
  373. with open(file, "r") as f:
  374. return json.load(f)
  375. def run(self):
  376. # only pipeline JSON format for now
  377. # TODO: add support for simplified format
  378. for file in self.input_files:
  379. features_from_json = self._read_json_from_file(file.path)
  380. for feature in features_from_json:
  381. self.features.append(Feature(interval=self._interval_from_dict(feature["interval"]),
  382. source=self._source_from_dict(feature["source"]),
  383. feature_extractor=feature["feature_extractor"],
  384. score=feature["score"]))
  385. def teardown(self):
  386. pass
  387. class WordFeatureExtractor(FeatureExtractor):
  388. """Feature extractor for specific word detection (uses Whisper)"""
  389. # set defaults for whisper settings
  390. DEFAULT_MODEL_SIZE = "medium"
  391. DEFAULT_DEVICE = "cpu"
  392. DEFAULT_COMPUTE_TYPE = "int8"
  393. DEFAULT_BEAM_SIZE = 5
  394. DEFAULT_BATCH_SIZE = 16
  395. DEFAULT_PIPELINE_TYPE = "batched" # or "stream"
  396. words = []
  397. def _transcribe(self, model, file, **kwargs):
  398. """Defined here to allow for mocking in tests"""
  399. return model.transcribe(file, **kwargs)
  400. def _whispermodel(self, model_size=DEFAULT_MODEL_SIZE,
  401. device=DEFAULT_DEVICE, compute_type=DEFAULT_COMPUTE_TYPE):
  402. """Defined here to allow for mocking out in tests"""
  403. return WhisperModel(model_size, device=device, compute_type=compute_type)
  404. def _batched_inference_pipeline(self, model):
  405. """Defined here to allow for mocking out in tests"""
  406. return BatchedInferencePipeline(model=model)
  407. def __init__(self, input_files=None, config=None):
  408. if not input_files:
  409. raise ValueError("No input files provided!")
  410. self.input_files = input_files
  411. self.config = config
  412. self.features = []
  413. def setup(self, words=[]):
  414. """Setup the word feature extractor -- validate input files & config
  415. Whisper expects a list of words to search for in the audio
  416. """
  417. logger.debug("WordFeatureExtractor setup")
  418. # Validate words - raise a notice if none provided
  419. if len(words) == 0:
  420. logger.warning("No words provided for detection")
  421. self.words = words
  422. # TODO: consider stripping punctuation since Whisper produces words+punctuation
  423. # and we might want to strip the punctuation there too
  424. def run(self):
  425. """Extract features corresponding to supplied target words (defined in setup) for each input file
  426. Use Whisper to detect words in the audio, then match these to target words and create features
  427. Note: if no words are supplied we can exit early
  428. """
  429. if len(self.words) == 0: return
  430. if self.DEFAULT_PIPELINE_TYPE == "batched":
  431. batched = True
  432. else:
  433. batched = False
  434. # no early exit
  435. # TODO: consider maybe loglevel notice of estimated time! consider also: max execution time config?
  436. # TODO: config options for model size, device, compute type
  437. model = self._whispermodel() # NB uses defaults, TODO: add config options
  438. # NOTE: batched not available on pypi yet at time of writing
  439. if batched:
  440. batched_model = self._batched_inference_pipeline(model)
  441. for file in self.input_files:
  442. # transcribe the audio file
  443. if batched:
  444. segments, _ = self._transcribe(batched_model, file.path, batch_size=self.DEFAULT_BATCH_SIZE)
  445. else:
  446. segments, _ = self._transcribe(model, file.path, beam_size=self.DEFAULT_BEAM_SIZE)
  447. # process the segments
  448. # segment has: start, end, text
  449. for segment in segments:
  450. # check if any of the words are in the segment
  451. for word in segment.text.split():
  452. if word in self.words:
  453. self.features.append(Feature(interval=Interval(start=segment.start, end=segment.end),
  454. source=file, feature_extractor="word",
  455. score=1.0))