segment_finder.py 3.19 KB
Newer Older
Matteo's avatar
update    
Matteo committed
1
2
import os
import tempfile
Matteo's avatar
update  
Matteo committed
3
4
5
6
from uuid import uuid4
import numpy as np

from mpai_cae_arp.audio import AudioWave, Noise
Matteo's avatar
update    
Matteo committed
7
from mpai_cae_arp.files import File, FileType
Matteo's avatar
update  
Matteo committed
8
from mpai_cae_arp.types.irregularity import Irregularity, IrregularityFile, Source
Matteo's avatar
update    
Matteo committed
9
from mpai_cae_arp.time import frames_to_seconds, seconds_to_frames
Matteo's avatar
update  
Matteo committed
10

Matteo's avatar
update    
Matteo committed
11
12
temp_dir = tempfile.gettempdir()
TMP_CHANNELS_MAP = os.path.join(temp_dir, "channels_map.json")
Matteo's avatar
update  
Matteo committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

def calculate_offset(audio: AudioWave, video: AudioWave) -> float:
    """
    Calculates the offset between two audio files based on their cross-correlation.

    Parameters
    ----------
    audio : AudioWave
        The audio file to be used as reference.
    video : AudioWave
        The audio file to be used as target.
    
    Returns
    -------
    float
    """

    corr = np.correlate(audio.array, video.array, mode="full")
    lags = np.arange(-len(audio.array) + 1, len(video.array))
    lag_idx = np.argmax(np.abs(corr))

    return lags[lag_idx] / audio.samplerate


Matteo's avatar
update    
Matteo committed
37
def get_irregularities_from_audio(audio_src: AudioWave) -> list[Irregularity]:
Matteo's avatar
update  
Matteo committed
38
    input_channels: list[AudioWave] = []
Matteo's avatar
update    
Matteo committed
39
40
41
42
    for channel in audio_src.channels:
        input_channels.append(audio_src.get_channel(channel))

    channels_map = {}
Matteo's avatar
update  
Matteo committed
43
44

    irreg_list: list[Irregularity] = []
Matteo's avatar
update    
Matteo committed
45
    for idx, audio in enumerate(input_channels):
Matteo's avatar
update  
Matteo committed
46
47
48
49
50
51
        for _, noise_list in audio.get_silence_slices([
            Noise("A", -50, -63),
            Noise("B", -63, -69),
            Noise("C", -69, -72)],
            length=500).items():
            for start, _ in noise_list:
Matteo's avatar
update    
Matteo committed
52
                id = uuid4()
Matteo's avatar
update  
Matteo committed
53
54
                irreg_list.append(
                    Irregularity(
Matteo's avatar
update    
Matteo committed
55
                        uuid=id,
Matteo's avatar
update  
Matteo committed
56
57
58
59
                        source=Source.AUDIO,
                        time_label=frames_to_seconds(start, audio.samplerate)
                    )
                )
Matteo's avatar
update    
Matteo committed
60
61
62
                channels_map[id] = idx

    File(TMP_CHANNELS_MAP, FileType.JSON).write_content(channels_map)
Matteo's avatar
update  
Matteo committed
63
64
65

    return irreg_list

Matteo's avatar
update    
Matteo committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

def create_irreg_file(audio_src: str, video_src: str) -> IrregularityFile:

    audio = AudioWave.from_file(audio_src, bufferize=True)
    
    offset = calculate_offset(audio, video_src)
    return IrregularityFile(get_irregularities_from_audio(audio), offset=offset)


def merge_irreg_files(
    file1: IrregularityFile,
    file2: IrregularityFile) -> IrregularityFile:
    new_file = IrregularityFile(
        irregularities=file1.irregularities + file2.irregularities,
        offset=np.argmax([file1.offset, file2.offset]))

    new_file.irregularities.sort(key=lambda x: x.time_label)

    return new_file


def extract_audio_irregularities(
    audio: AudioWave,
    irreg_file: IrregularityFile,
    path: str) -> None:
    channels_map = File(TMP_CHANNELS_MAP, FileType.JSON).get_content()
    for irreg in irreg_file.irregularities:
        if irreg.source == Source.AUDIO:
            chunk = audio.get_channel(channels_map[irreg.irregularity_ID])[
                seconds_to_frames(
                    irreg.time_label, audio.samplerate
                ):seconds_to_frames(
                    irreg.time_label, audio.samplerate)+audio.samplerate//2]
            chunk.save(f"{path}/AudioBlocks/{irreg.irregularity_ID}.wav")
    os.remove(TMP_CHANNELS_MAP)