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.

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