File size: 2,369 Bytes
a0984c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import json
from pydub import AudioSegment
import os
import sys

def segment_audio_from_alignment(audio_path, alignment_path):
    """
    Segments a long audio file into chunks based on a word-level
    timestamped alignment file.
    """
    
    output_dir = "wavs"
    metadata_path = "metadata.csv"
    os.makedirs(output_dir, exist_ok=True)
    
    print(f"Loading full audio from: {audio_path}")
    try:
        full_audio = AudioSegment.from_file(audio_path)
    except Exception as e:
        print(f"--- ERROR: Could not load the audio file. ---")
        print(f"Ensure ffmpeg is correctly installed and the path is correct.")
        print(f"Details: {e}")
        sys.exit(1)

    print(f"Loading alignment data from: {alignment_path}")
    with open(alignment_path, 'r', encoding='utf-8') as f:
        alignment_data = json.load(f)

    with open(metadata_path, 'w', encoding='utf-8') as metadata_file:
        print(f"Writing chunks to '{output_dir}' and metadata to '{metadata_path}'...")
        
        chunk_counter = 0
        for segment in alignment_data.get('segments', []):
            for word_data in segment.get('words', []):
                start_time = word_data.get('start')
                end_time = word_data.get('end')
                text = word_data.get('word', '').strip()

                if start_time is None or end_time is None or not text:
                    continue

                start_ms = int(start_time * 1000)
                end_ms = int(end_time * 1000)

                audio_chunk = full_audio[start_ms:end_ms]

                chunk_counter += 1
                chunk_filename = os.path.join(output_dir, f"chunk_{chunk_counter:05d}.wav")

                audio_chunk.export(chunk_filename, format="wav")

                metadata_file.write(f"{os.path.basename(output_dir)}/{os.path.basename(chunk_filename)}|{text}\n")
        
        print(f"Processed {chunk_counter} audio chunks.")

def main():
    audio_file = "master.mp3"
    alignment_file = "aligned_transcription.json"
    
    if not os.path.exists(audio_file) or not os.path.exists(alignment_file):
        print("--- ERROR: Make sure 'master.mp3' and 'aligned_transcription.json' are in the project directory. ---")
        sys.exit(1)
        
    segment_audio_from_alignment(audio_file, alignment_file)

if __name__ == "__main__":
    main()