From 78331d1f75caabb266a064352e75fa319eebbbbe Mon Sep 17 00:00:00 2001 From: Jordi Mas Date: Thu, 19 Dec 2024 22:49:18 +0100 Subject: [PATCH] Fix --- open_dubbing/subtitles.py | 26 +++++++++++++++++--------- tests/subtitles_test.py | 1 + 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/open_dubbing/subtitles.py b/open_dubbing/subtitles.py index f96ab47..3567425 100644 --- a/open_dubbing/subtitles.py +++ b/open_dubbing/subtitles.py @@ -20,22 +20,30 @@ class Subtitles: def write(self, *, utterance_metadata, directory, filename, translated): - srt_file_path = filename - srt_file_path = os.path.join(directory, srt_file_path) + srt_file_path = os.path.join(directory, filename) with open(srt_file_path, "w", encoding="utf-8") as subtitles_file: for i, utterance in enumerate(utterance_metadata): - start_time = str(timedelta(seconds=utterance["start"]))[:-3] - end_time = str(timedelta(seconds=utterance["end"]))[:-3] - start_time = start_time.replace(".", ",").zfill(12) - end_time = end_time.replace(".", ",").zfill(12) + # Convert start and end times to the proper format + start_time = self.format_srt_time(utterance["start"]) + end_time = self.format_srt_time(utterance["end"]) + idx = i + 1 srt_content = f"{idx}\n" - srt_content += ( - f"{start_time.replace('.', ',')} --> {end_time.replace('.', ',')}\n" - ) + srt_content += f"{start_time} --> {end_time}\n" text = utterance["translated_text"] if translated else utterance["text"] srt_content += f"{text}\n\n" subtitles_file.write(srt_content) return srt_file_path + + @staticmethod + def format_srt_time(seconds): + """Format seconds as HH:MM:SS,mmm for SRT files.""" + time_delta = timedelta(seconds=seconds) + total_seconds = int(time_delta.total_seconds()) + milliseconds = int((time_delta.total_seconds() - total_seconds) * 1000) + hours = total_seconds // 3600 + minutes = (total_seconds % 3600) // 60 + seconds = total_seconds % 60 + return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}" diff --git a/tests/subtitles_test.py b/tests/subtitles_test.py index 9c461b5..ced2115 100644 --- a/tests/subtitles_test.py +++ b/tests/subtitles_test.py @@ -126,4 +126,5 @@ def test_write_original_small_digits(self): "1", "00:00:01,000 --> 00:00:03,100", "Good morning, my name is Jordi Mas.", + "" ]