구글 번역기는 너무 구림.
팟플레이어에서 실시간 번역으로 deepl를 하려니깐 가끔 놓치는 경우가 생기거나, 볼때마다 토큰이 소비되는게 맘에 안들어서 하나 만듬.
o3-mini 쩌네... 나보다 더 잘하는거 같은데??........ 이젠 짧은 코드는 AI한테 밀리는구나.. 무섭네..(나 나름 코딩 오래해온 사람인데.. AI한테 따임)
참고로 파이썬이 컴에 설치되어 있어야 하며, 파이썬 파일 실행할 줄 알아야 함. (GPT한테 물어보면 됨)
1. 아래의 파일을 .py 로 만들어서 저장한다.
import os
import glob
import srt
import deepl
def translate_srt_individual(input_file: str, output_file: str, target_language: str) -> None:
"""
SRT 파일을 읽어 각 블록을 개별 번역한 후 번역된 결과를 output_file에 저장합니다.
번역된 각 블록은 터미널에 실시간으로 출력됩니다.
:param input_file: 입력 SRT 파일 경로
:param output_file: 번역된 SRT 파일 경로
:param target_language: 번역 대상 언어의 코드 (예: 'EN-GB', 'DE', 'FR' 등, 대문자 사용)
"""
# 1. SRT 파일 읽기 및 파싱
with open(input_file, 'r', encoding='utf-8') as f:
srt_content = f.read()
subtitles = list(srt.parse(srt_content))
# 2. DeepL API 클라이언트 초기화
auth_key = os.environ.get("DEEPL_AUTH_KEY")
if not auth_key:
raise ValueError("DEEPL_AUTH_KEY 환경변수가 설정되어 있지 않습니다.")
translator = deepl.Translator(auth_key)
# 3. 각 블록을 개별 번역하고 터미널에 출력
for idx, sub in enumerate(subtitles):
try:
result = translator.translate_text(sub.content, target_lang=target_language.upper())
sub.content = result.text
print(f"[{input_file}] 번역 블록 {idx+1}: {sub.content}")
except Exception as e:
print(f"[{input_file}] 번역 블록 {idx+1} 번역 실패: {e}")
# 4. 번역된 자막 블록들을 SRT 형식으로 조합 후 저장
translated_srt = srt.compose(subtitles)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(translated_srt)
def translate_all_srt_files(input_directory: str, done_directory: str, target_language: str) -> None:
"""
지정한 폴더 내의 모든 SRT 파일을 개별 번역하여 done_directory에 저장합니다.
:param input_directory: 원본 SRT 파일들이 있는 폴더 경로
:param done_directory: 번역된 SRT 파일들을 저장할 폴더 경로
:param target_language: 번역 대상 언어의 코드 (예: 'EN-GB', 'DE', 'FR' 등)
"""
if not os.path.exists(done_directory):
os.makedirs(done_directory)
pattern = os.path.join(input_directory, "*.srt")
files = glob.glob(pattern)
if not files:
print("번역할 SRT 파일이 없습니다.")
return
for input_file in files:
filename = os.path.basename(input_file)
output_file = os.path.join(done_directory, filename)
print(f"번역 시작: {input_file}")
translate_srt_individual(input_file, output_file, target_language)
print(f"번역 완료: {output_file}")
if __name__ == '__main__':
# 원본 SRT 파일들이 있는 폴더 경로
input_dir = r"G:\python\deepl\files"
# 번역된 파일들을 저장할 폴더 경로
done_dir = os.path.join(input_dir, "done")
# 번역 대상 언어 코드 (예: DeepL에서는 'EN-GB', 'EN-US', 'DE' 등 사용)
target_lang = "KO"
translate_all_srt_files(input_dir, done_dir, target_lang)
print("모든 파일 번역 완료!")
2. 필요한 모듈을 설치한다.
터미널에서 pip install google-cloud-translate srt
2. 파일을 Input 경로에 넣는다.
input_dir = r"G:\python\deepl\files" << 이 부분을 본인의 경로에 맞게 수정한다.
3. 완료되면 자막 파일이 저장될 위치를 output에 넣는다.
done_dir = os.path.join(input_dir, "done") << 이 부분을 수정한다.
4. 터미널에서 deepl apl 키를 입력한 후 파이썬 파일을 추가한다.
# 파워쉘
$set DEEPL_AUTH_KEY="deepl api key"
# 터미널
set DEEPL_AUTH_KEY=deepl api key
위의 방법이 잘 안되는 경우 아래의 코드의 맨 윗줄에 넣는다.
os.environ["DEEPL_AUTH_KEY"] = "deepl api key"
5. 파이썬 파일을 실행한다.
API 문서는
https://developers.deepl.com/docs/api-reference/translate
위의 코드는 자막 블록 하나씩 집어넣는데 리스트로 만들어서 한번에 번역기 돌리는 방법도 있음. 그럼, 번역 속도가 매우 빨라짐. API 키 보면 할 수 있을듯 코드는 짧음.
누가크롬 확장프로그램 안만들어주려나
있긴 있는데 srt처럼 파일통으로 해주는건 못 찾아서.. - dc App
deepl api키로 통번역 해주는 gui들 몇 개 있는데 뭐하러 이런 걸 만들었어. 좀만 구글링하면 나와.