67 lines
2.7 KiB
Python
67 lines
2.7 KiB
Python
import re
|
|
import sys
|
|
import os
|
|
from datetime import timedelta
|
|
|
|
def format_timestamp(timestamp):
|
|
hours, remainder = divmod(timestamp.total_seconds(), 3600)
|
|
minutes, seconds = divmod(remainder, 60)
|
|
milliseconds = timestamp.microseconds // 1000
|
|
return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d},{int(milliseconds):03d}"
|
|
|
|
def lrc_to_srt(lrc_filename, srt_filename):
|
|
with open(lrc_filename, 'r', encoding='utf-8') as lrc_file:
|
|
lrc_content = lrc_file.readlines()
|
|
|
|
srt_content = []
|
|
subtitle_counter = 1
|
|
previous_end_time = None
|
|
|
|
for i, line in enumerate(lrc_content):
|
|
match = re.match(r'\[(\d{2}):(\d{2})\.(\d{2})\](.*)', line)
|
|
## Explanation to the regex:
|
|
## \[ (\d{2}) : (\d{2}) \. (\d{2}) \] (.*)
|
|
## bracket minutes (2 digits) colon seconds (2 digits) dot millisecs (2 digits) bracket lyrical line (can be blank)
|
|
if match:
|
|
print(f'debug: matched line {line.strip()}')
|
|
start_minutes = int(match.group(1))
|
|
start_seconds = int(match.group(2))
|
|
start_milliseconds = int(match.group(3)) * 10
|
|
print(f'matched text: {match.group(4)}')
|
|
|
|
start_time = timedelta(minutes=start_minutes, seconds=start_seconds, milliseconds=start_milliseconds)
|
|
if len(srt_content) > 0:
|
|
# srt_content[-1] += f"{format_timestamp(start_time - timedelta(milliseconds=1))}\n"
|
|
srt_content[-1] += f"{format_timestamp(start_time)}\n"
|
|
srt_content.append(f"{subtitle_text}\n\n")
|
|
|
|
srt_content.append(f"{subtitle_counter}\n")
|
|
srt_content.append(f"{format_timestamp(start_time)} --> ")
|
|
|
|
subtitle_text = match.group(4).strip()
|
|
subtitle_counter += 1
|
|
previous_end_time = start_time
|
|
|
|
if previous_end_time is not None:
|
|
srt_content[-1] += f"{format_timestamp(previous_end_time)}\n"
|
|
srt_content.append(f"{subtitle_text}\n\n")
|
|
|
|
|
|
with open(srt_filename, 'w', encoding='utf-8') as srt_file:
|
|
srt_file.writelines(srt_content)
|
|
|
|
print(f"Conversion from LRC to SRT completed. SRT file saved as '{srt_filename}'.")
|
|
|
|
if __name__ == "__main__":
|
|
if not(len(sys.argv) == 3 or len(sys.argv) == 2):
|
|
print("Usage: python lrc2srt.py <input_lrc_file> <output_srt_file>")
|
|
print("or: python lrc2srt.py <input_lrc_file>")
|
|
print("If no output file name is supplied, the input file name will be used by default.")
|
|
else:
|
|
lrc_filename = sys.argv[1]
|
|
if len(sys.argv) == 3:
|
|
srt_filename = sys.argv[2]
|
|
else:
|
|
raw_filename, ext = os.path.splitext(lrc_filename)
|
|
srt_filename = raw_filename + '.srt'
|
|
lrc_to_srt(lrc_filename, srt_filename) |