-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
58 lines (50 loc) · 1.48 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from googletrans import Translator
import pysrt
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument(
'-f',
'--file',
type=str,
help='select srt file'
)
parser.add_argument(
'-d',
'--dir',
type=str,
help='select directory'
)
translator = Translator()
def translate(fp):
subs = pysrt.open(fp)
arrayToTranslate = []
translatedArray = []
for sub in subs:
stripSub = sub.text.strip()
stringToTranslate = '\n\n'.join(arrayToTranslate)
if len(stringToTranslate + stripSub) > 5000:
result = translator.translate(stringToTranslate, dest='fa')
translatedArray.extend(result.text.split('\n\n'))
arrayToTranslate.clear()
arrayToTranslate.append(stripSub)
stringToTranslate = '\n\n'.join(arrayToTranslate)
result = translator.translate(stringToTranslate, dest='fa')
translatedArray.extend(result.text.split('\n\n'))
for i in range(len(subs)):
subs[i].text = translatedArray[i]
subs.save(
os.path.join(
os.path.dirname(fp),
'fa-' + os.path.basename(fp)
),
encoding='utf-8'
)
args = parser.parse_args()
if args.file and os.path.isfile(args.file):
translate(args.file)
elif args.dir and os.path.isdir(args.dir):
for p in os.listdir(args.dir):
rp = os.path.join(args.dir, p)
if os.path.isfile(rp) and os.path.splitext(rp)[1] == '.srt':
translate(rp)