Skip to content

Instantly share code, notes, and snippets.

@abhishekkr
Created February 26, 2025 16:31
Show Gist options
  • Save abhishekkr/2cb15e646195894dd959a1365e984ff3 to your computer and use it in GitHub Desktop.
Save abhishekkr/2cb15e646195894dd959a1365e984ff3 to your computer and use it in GitHub Desktop.
Subtitle Translator
"""
pip install -U deep-translator srt
This translates a non-english SRT subtitle file to english, with lame accuracy.
Persists at every 5 subtitles.
"""
from deep_translator import GoogleTranslator
import srt
import time
FILEPATH = '/app/filename.srt'
NEW_FILEPATH = '/app/new.srt'
def get_subs(filepath):
fyl = open(filepath, "r", encoding='ISO-8859-1')
data = fyl.read()
subs = list(srt.parse(data))
fyl.close()
return subs
def put_subs(subs, filepath):
data = srt.compose(subs)
fyl = open(filepath, 'w')
fyl.write(data)
fyl.close()
subs = get_subs(FILEPATH)
index = 0
for s in subs:
try:
translated = GoogleTranslator(source='auto', target='en').translate(s.content)
print(f"{index}: {s.content} => {translated}")
subs[index].content = translated
if index % 5 == 0:
put_subs(subs, NEW_FILEPATH)
time.sleep(2)
except e as Exception:
print(e)
index += 1
put_subs(subs, NEW_FILEPATH)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment