Skip to content

Instantly share code, notes, and snippets.

@MawCeron
Last active March 28, 2019 15:00
Show Gist options
  • Select an option

  • Save MawCeron/2ef2d4bee8006e045a94b52cdcdd0b8a to your computer and use it in GitHub Desktop.

Select an option

Save MawCeron/2ef2d4bee8006e045a94b52cdcdd0b8a to your computer and use it in GitHub Desktop.
Express subtitle translation using Google Translator
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Express subtitle translation using Google Translator
#
# Notes:
# - python fansub.py [file] [from language] [to languaje] // i.e.(python fansub.py mySubs.ass en es)
# - Only for ASS Subtitle files
# - Just for fun
# - Too slow
# - Translation is very bad in most cases
#
# (c) 2019 Mauricio Cerón <maw.ceron@gmail.com>
#
import re, sys, os
import urllib, urllib2, HTMLParser
def translation(text, to_lang, from_lang):
agent = {'User-Agent':"Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.04506.30)"}
base_link = "http://translate.google.com/m?hl=%s&sl=%s&q=%s"
to_trans = urllib.quote_plus(text)
link = base_link % (to_lang,from_lang,to_trans)
req = urllib2.Request(link, headers = agent)
response = urllib2.urlopen(req).read()
data = response.decode("utf-8")
expr = r'class="t0">(.*?)>'
re_result = re.findall(expr, data)
if len(re_result) == 0:
result = ""
else:
result = unescape(re_result[0])
return result.encode('utf-8')
def unescape(text):
if sys.version_info[0] < 3:
parser = HTMLParser.HTMLParser()
else:
parser = html.parser.HTMLParser()
return (parser.unescape(text))
def main(argv):
if len(argv) != 3:
print("[!] Error. There is not enough information, please enter the information as follows:\n")
print("[*] python fansub.py [file] [from language] [to languaje]")
else:
original_subs = argv[0] # Here goes the path to the subtitles script
original_lang = argv[1]
translate_lang = argv[2]
new_script = []
with open(original_subtitles) as fp:
for line in fp:
line = line.strip()
if line.startswith('Dialogue:') or line.startswith('Comment:'):
event_type, rest = line.split(": ", 1)
buf = rest.split(',')
dialogue = buf[9]
text = buf[9].replace('\N','\n')
text = re.sub(r'{.*}','',text)
trans = translation(text,translate_lang,original_lang)
buf[9] = trans
rest = ','.join(buf)
new_line = "%s: %s" %(event_type,rest)
new_script.append(new_line)
else
new_script.append(line)
name, ext = os.path.splitext(original_subs)
translated_subs
nfp = open(translated_subs, 'w')
for line in new_script:
nfp.write("%s\n" %line)
fp.close()
nfp.close()
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment