|
import csv |
|
import os |
|
from typing import Literal |
|
|
|
import pysrt |
|
from pydub import AudioSegment |
|
|
|
|
|
def srt_to_segments_with_metadata(srt_file, episode, audio_file, output_dir, metadata_file, subset: Literal["saamgwokjinji", "seoiwuzyun"]): |
|
|
|
subs = pysrt.open(srt_file) |
|
|
|
|
|
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 |
|
|
|
|
|
os.makedirs(output_dir, exist_ok=True) |
|
|
|
|
|
with open(metadata_file, mode='a', newline='', encoding='utf-8') as csvfile: |
|
csvwriter = csv.writer(csvfile) |
|
|
|
|
|
if os.stat(metadata_file).st_size == 0: |
|
csvwriter.writerow(['id', 'episode_id', 'file_name', 'audio_duration', 'transcription']) |
|
|
|
if subset == "saamgwokjinji": |
|
prefix = "sg" |
|
elif subset == "seoiwuzyun": |
|
prefix = "sw" |
|
|
|
for index, sub in enumerate(subs): |
|
|
|
start_time = sub.start.ordinal |
|
end_time = sub.end.ordinal |
|
|
|
|
|
duration = (end_time - start_time) / 1000 |
|
|
|
|
|
segment = audio[start_time:end_time] |
|
|
|
|
|
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) |
|
|
|
|
|
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 |
|
|
|
|
|
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 = "seoiwuzyun" |
|
|
|
print(f"Processing subset: {subset}") |
|
|
|
metadata_file = os.path.join("opus", subset, "metadata.csv") |
|
|
|
for episode in range(46, 51): |
|
|
|
|
|
episode_str = f'{episode:03d}' |
|
|
|
srt_file = f'srt/{subset}/{episode_str}.srt' |
|
audio_file = f'source/{subset}/{episode_str}.opus' |
|
output_dir = f'opus/{subset}/{episode_str}' |
|
|
|
|
|
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.") |
|
|