feat: add backup option and move some logic from main to utils
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from typing import List
|
||||
|
||||
from config import SYNC_CONFIG
|
||||
from .types import SubtitleEntry
|
||||
|
||||
|
||||
@@ -41,9 +43,28 @@ class SubtitleHandler:
|
||||
entries.append(SubtitleEntry(int(match.group(1)), start, end, match.group(4).strip()))
|
||||
return entries
|
||||
|
||||
@staticmethod
|
||||
def create_backup(filepath: str):
|
||||
"""Creates a .bak copy of the subtitles if one doesn't exist."""
|
||||
backup_path = filepath + ".bak"
|
||||
if not os.path.exists(backup_path):
|
||||
try:
|
||||
shutil.copy2(filepath, backup_path)
|
||||
print(f"Backup created: {os.path.basename(backup_path)}")
|
||||
except IOError as e:
|
||||
print(f"Warning: Could not create backup: {e}")
|
||||
|
||||
@staticmethod
|
||||
def write_srt(filepath: str, entries: List[SubtitleEntry]):
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
for entry in entries:
|
||||
f.write(
|
||||
f"{entry.index}\n{SubtitleHandler.format_time(entry.start_ms)} --> {SubtitleHandler.format_time(entry.end_ms)}\n{entry.raw_text}\n\n")
|
||||
# 1. Ensure backup exists before overwriting
|
||||
if SYNC_CONFIG['create_backup']:
|
||||
SubtitleHandler.create_backup(filepath)
|
||||
|
||||
# 2. Overwrite
|
||||
try:
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
for entry in entries:
|
||||
f.write(
|
||||
f"{entry.index}\n{SubtitleHandler.format_time(entry.start_ms)} --> {SubtitleHandler.format_time(entry.end_ms)}\n{entry.raw_text}\n\n")
|
||||
except IOError as e:
|
||||
print(f"Error writing subtitle file: {e}")
|
||||
|
||||
18
core/utils.py
Normal file
18
core/utils.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from .types import SubtitleInfo
|
||||
|
||||
|
||||
def parse_bazarr_args(args: list) -> SubtitleInfo:
|
||||
"""Parses key=value arguments passed by Bazarr."""
|
||||
arg_dict = {}
|
||||
for arg in args[1:]:
|
||||
if '=' in arg:
|
||||
key, value = arg.split('=', 1)
|
||||
arg_dict[key] = value.strip('"').strip("'") # Clean quotes if present
|
||||
|
||||
return SubtitleInfo(
|
||||
episode_path=arg_dict.get('episode', ''),
|
||||
episode_name=arg_dict.get('episode_name', 'Unknown'),
|
||||
subtitle_path=arg_dict.get('subtitles', ''),
|
||||
episode_language=arg_dict.get('episode_language', 'English'),
|
||||
subtitles_language=arg_dict.get('subtitles_language', 'English')
|
||||
)
|
||||
Reference in New Issue
Block a user