-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhanzitopinyin.py
208 lines (174 loc) · 7.94 KB
/
hanzitopinyin.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python3
import os
import argparse
import deepl
import pysrt
from xpinyin import Pinyin
import configparser
import glob
from os import walk
import tempfile
import zipfile
import xml.etree.ElementTree as ET
def zipdir(path, ziph):
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, '.')))
def hanzi_to_pinyin(my_input, my_output, my_format, my_tones, my_translator, extension):
if extension == ".srt":
hanzi_to_pinyin_srt(my_input, my_output, my_format, my_tones, my_translator)
elif extension == ".txt":
hanzi_to_pinyin_txt(my_input, my_output, my_format, my_tones, my_translator)
elif extension == ".docx":
hanzi_to_pinyin_docx(my_input, my_output, my_format, my_tones, my_translator)
else:
print("ERROR: unsupported file type.")
print("Go to https://github.com/pgquiles/hanzitopinyin/issues and open an issue to"
"request support for more file types.")
exit(1)
def hanzi_to_pinyin_srt(my_input, my_output, my_format, my_tones, my_translator):
subs = pysrt.open(my_input)
p = Pinyin()
for sub in subs:
my_pinyin: str
my_text: str
if sub and sub.text:
my_text = sub.text
my_pinyin = p.get_pinyin(my_text, tone_marks=my_tones)
if my_format == 1:
sub.text = my_pinyin
elif my_format == 2:
sub.text = my_text + '\n' + my_pinyin
elif my_format == 3:
my_english = my_translator.translate_text(my_text, source_lang="ZH", target_lang="EN-US")
sub.text = my_english.text + '\n' + my_text + '\n' + my_pinyin
subs.save(my_output)
def hanzi_to_pinyin_txt(my_input, my_output, my_format, my_tones, my_translator):
with open(my_input, 'r') as reader:
p = Pinyin()
output_text = []
for my_text in reader.readlines():
my_pinyin: str
if my_text:
my_pinyin = p.get_pinyin(my_text, tone_marks=my_tones)
if my_format == 1:
output_text.append(my_pinyin)
elif my_format == 2:
output_text.append(my_text + my_pinyin + '\n')
elif my_format == 3:
my_english = my_translator.translate_text(my_text, source_lang="ZH", target_lang="EN-US")
output_text.append(my_english.text + my_text + my_pinyin + '\n')
try:
with open(my_output, 'w') as writer:
writer.writelines(output_text)
except OSError:
print("ERROR: cannot open " + my_output + " to write in it. Check permissions.")
exit(1)
def hanzi_to_pinyin_docx(my_input, my_output, my_format, my_tones, my_translator):
tempdir = tempfile.TemporaryDirectory()
with zipfile.ZipFile(my_input, 'r') as zip_ref:
zip_ref.extractall(tempdir.name)
res = []
for (dir_path, dir_names, file_names) in walk(tempdir.name):
res.extend(file_names)
pinyinize_word_xml(tempdir.name, "document.xml", my_format, my_tones, my_translator)
headers = glob.glob(os.path.join(tempdir.name, "word", "header*.xml"))
for header in headers:
pinyinize_word_xml(tempdir.name, header, my_format, my_tones, my_translator)
footers = glob.glob(os.path.join(tempdir.name, "word", "footer*.xml"))
for footer in footers:
pinyinize_word_xml(tempdir.name, footer, my_format, my_tones, my_translator)
with zipfile.ZipFile(my_output, 'w', zipfile.ZIP_DEFLATED) as zipf:
zipdir(tempdir.name, zipf)
def pinyinize_word_xml(dir, file, my_format, my_tones, my_translator):
tree = ET.parse(os.path.join(dir, "word", file))
namespace = {'w': "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
ET.register_namespace("w", namespace["w"])
text_elements = tree.findall('.//w:t', namespace)
p = Pinyin()
for text_element in text_elements:
my_pinyin = p.get_pinyin(text_element.text, tone_marks=my_tones)
if my_format == 1:
if my_pinyin == text_element.text:
pass
else:
text_element.text = my_pinyin
elif my_format == 2:
break_element = ET.SubElement(text_element, "w:br")
if my_pinyin == text_element.text:
pass
else:
pinyin_element = ET.SubElement(text_element, "w:t")
pinyin_element.text = my_pinyin
text_element.append(break_element)
elif my_format == 3:
my_english = my_translator.translate_text(text_element.text, source_lang="ZH", target_lang="EN-US")
break_element = ET.SubElement(text_element, "w:br")
if my_pinyin == text_element.text:
pass
else:
english_element = ET.SubElement(text_element, "w:t")
english_element.text = my_english.text
text_element.append(break_element)
pinyin_element = ET.SubElement(text_element, "w:t")
pinyin_element.text = my_pinyin
ET.SubElement(pinyin_element, "w:br")
tree.write(os.path.join(dir, "word", file))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output", nargs='?', type=str, help="Output file", action="store", default="")
parser.add_argument("-f", "--format", type=int,
help="Destination format. 1=Pinyin (default), 2=Hanzi+Pinyin, 3=English+Hanzi+Pinyin",
action="store", default=1)
parser.add_argument("-t", "--tones", type=int, help="Tones: 1=marks (default), 2=numbers", action="store",
default=1)
parser.add_argument("-v", "--verbose", action="count", default=0, help="Verbose output, showing intermediate steps")
parser.add_argument("file", type=str, help="Input SRT file")
args = parser.parse_args()
if not os.path.isfile(args.file):
print("ERROR: need file input")
exit(1)
extension = os.path.splitext(args.file)[1]
output = ""
translator = ""
if args.output:
output = args.output
else:
if args.format == 1:
output = os.path.splitext(args.file)[0].replace('.zh_CN-hanzi', '') + '.zh_CN-pinyin' + extension
elif args.format == 2:
output = os.path.splitext(args.file)[0].replace('.zh_CN-hanzi', '') + '.zh_CN-hanzi+pinyin' + extension
elif args.format == 3:
output = os.path.splitext(args.file)[0].replace('.zh_CN-hanzi',
'') + '.zh_CN-english+hanzi+pinyin' + extension
config = configparser.ConfigParser()
config.read("hanzitopinyin.conf")
auth_key = config['deepl']['auth_key']
if auth_key == "":
print("ERROR: Translation with DeepL requested but no authentication key provided. "
"Please edit hanzitopinyin.conf and add it.")
exit(1)
translator = deepl.Translator(auth_key)
tones = ''
if args.tones:
if args.tones == 1:
tones = 'marks'
elif args.tones == 2:
tones = 'numbers'
else:
print("Unknown tone format" + args.tones)
exit(-1)
else:
tones = 'marks'
hanzi_to_pinyin(args.file, output, args.format, tones, translator, extension)
if args.format == 3 and args.verbose:
usage = translator.get_usage()
if usage.any_limit_reached:
print('ERROR DeepL translation limit reached.')
exit(1)
if usage.character.valid:
print(f"Character usage: {usage.character.count} of {usage.character.limit}")
if usage.document.valid:
print(f"Document usage: {usage.document.count} of {usage.document.limit}")