File size: 3,650 Bytes
5304b62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import csv
import os
from typing import Literal

import pysrt
from pydub import AudioSegment
from tqdm import tqdm

SUBSET_MAP = {
    "saamgwokjinji": "sg",
    "seoiwuzyun": "sw",
    "mouzaakdung": "mzd",
    "lukdinggei": "ldg"
}


def srt_to_segments_with_metadata(srt_file, episode, audio_file, output_dir, metadata_file, subset: Literal["saamgwokjinji", "seoiwuzyun", "mouzaakdung"]):
    # Load the SRT file
    subs = pysrt.open(srt_file)

    # Load the audio file (handling Opus)
    try:
        audio = AudioSegment.from_file(audio_file, codec="opus")
    except Exception as e:
        print(f"Error loading audio file: {audio_file}")
        print(f"Error message: {e}")
        return  # Skip this file and move to the next

    # Ensure the output directory exists
    os.makedirs(output_dir, exist_ok=True)

    # Prepare the metadata file (appending to a single file)
    with open(metadata_file, mode='a', newline='', encoding='utf-8') as csvfile:
        csvwriter = csv.writer(csvfile)

        # Write header row if the file is empty
        if os.stat(metadata_file).st_size == 0:
            csvwriter.writerow(['id', 'episode_id', 'file_name', 'audio_duration', 'transcription'])

        if subset in SUBSET_MAP:
            prefix = SUBSET_MAP[subset]
        else:
            raise ValueError(f"Unknown subset: {subset}. Must be one of {SUBSET_MAP.keys()}")

        for index, sub in tqdm(enumerate(subs)):
            # Get start and end times in milliseconds
            start_time = sub.start.ordinal
            end_time = sub.end.ordinal

            # Calculate duration in seconds
            duration = (end_time - start_time) / 1000

            # Extract the audio segment
            segment = audio[start_time:end_time]

            # Define output filenames (using .opus extension)
            segment_filename = f"{episode}_{index + 1:03d}.opus"
            segment_id = f"{prefix}_{episode}_{index + 1:03d}"
            audio_filename = os.path.join(output_dir, segment_filename)

            # Export the audio segment as Opus
            try:
                segment.export(audio_filename, format="opus", codec="libopus")
            except Exception as e:
                print(f"Error exporting segment: {audio_filename}")
                print(f"Error message: {e}")
                continue  # Skip to the next segment

            # Write to the metadata CSV file
            csvwriter.writerow(
                [segment_id, episode, f'{episode}/{segment_filename}', f'{duration:.3f}', sub.text])

    print(f"Segmentation of {audio_file} complete. Files saved to: {output_dir}")
    print(f"Metadata appended to: {metadata_file}")


if __name__ == "__main__":
    # subset = "saamgwokjinji"
    # subset = "seoiwuzyun"
    SUBSET = "lukdinggei"  # Change this to the desired subset

    print(f"Processing subset: {SUBSET}")
    # If append to existing metadata file
    metadata_file = os.path.join("opus", SUBSET, "metadata.csv")  # Define metadata file path here

    for episode in range(20, 21):
        # If creating new csv
        # metadata_file = f"{episode}.csv"
        episode_str = f'{episode:03d}'  # Format episode as 3-digit string

        SRT_FILE = f'srt/{SUBSET}/{episode_str}.srt'
        AUDIO_FILE = f'source/{SUBSET}/{episode_str}.opus'
        OUTPUT_DIR = f'opus/{SUBSET}/{episode_str}'

        # Only process if the audio file exists
        if os.path.exists(AUDIO_FILE):
            srt_to_segments_with_metadata(SRT_FILE, episode_str, AUDIO_FILE, OUTPUT_DIR, metadata_file, SUBSET)
        else:
            print(f"Audio file not found: {AUDIO_FILE}. Skipping.")