-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpreprocessing.py
executable file
·232 lines (185 loc) · 9.61 KB
/
preprocessing.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# Import Module
import argparse
import os
import pickle
import re
from glob import glob
import numpy as np
import ujson as json
from vocab_utils import (hanja_vocab_processing, korean_vocab_train,
train_test_split)
def main(args):
np.random.seed(0)
j_path = glob(f'{args.joseon_record_path}/*/*.txt')
s_path = glob(f'{args.sjw_path}/*/*.json')
s_hj_path = glob(f'{args.sjw_hj_path}/*/*.json')
# Preprocessing data path make
if not os.path.exists(f'{args.output_path}'):
os.mkdir(f'{args.output_path}')
## Missing processing
# sjw_hanja_korean 기준 전체 262732 중 □: 2380,
# 자 빠짐: 7, 원문 빠짐: 10414, 자 결락: 19, 원문 결락: 571, 원문 훼손: 114, 자 훼손: 4
damage_words = ['자 빠짐', '원문 빠짐', '□', '자 결락', '원문 결락', '원문 훼손', '자 훼손']
# Pre-processing
record_list = []
print('Joseon dynasty data pre-processing...', end=' ')
for filename in j_path:
with open(filename) as f:
text = f.read()
for record in text.split('\n\n=====\n\n')[:-1]:
korean_content, hanja_content = record.split('\n\n-----\n\n')
date, title, *korean_content = korean_content.split("\n")
korean_content = " ".join(korean_content).strip()
if '。' in korean_content:
continue
hanja_partition = hanja_content.partition('。')
if '日' in hanja_partition[0] and len(hanja_partition[0]) <= 10:
hanja_content = hanja_partition[2]
if len(hanja_content) > 0:
if '/' in hanja_content.split()[0]:
hanja_content = ' '.join(hanja_content.split('/')[1:])
hanja_content = hanja_content.replace('○', ' ')
hanja_content = hanja_content.replace('。', '。 ')
hanja_content = hanja_content.replace(',', ', ')
hanja_content = " ".join(hanja_content.split()).strip()
is_damaged = False
for w in damage_words:
if w in korean_content:
is_damaged = True
break
if is_damaged:
continue
korean_content = " ".join(korean_content.split()).strip()
korean_content = " ".join(re.sub(r'\(\w+\)', '', korean_content).split()).strip()
korean_content = re.sub(r'\d{3}\)', '', korean_content)
if korean_content != '' and hanja_content != '':
record_list.append({
'date': date, 'title': title, 'korean': korean_content, 'hanja': hanja_content
})
print(len(record_list))
print('Seungjeongwon data pre-processing...', end=' ')
for json_data in s_path:
# Json file load
with open(json_data) as json_file:
record_json = json.load(json_file)
for i in range(len(record_json)):
# Hanja Preprocessing
hanja_content = record_json[i]['hanja']
if '□' in hanja_content:
continue
if '◆' in hanja_content:
continue
hanja_content = hanja_content.replace('○', ' ')
hanja_content = hanja_content.replace('。', '。 ')
hanja_content = hanja_content.replace(',', ', ')
hanja_content = " ".join(hanja_content.split()).strip()
# Korean Preprocessing
korean_content = record_json[i]['korean']
if '。' in korean_content:
continue
is_damaged = False
for w in damage_words:
if w in korean_content:
is_damaged = True
break
if is_damaged:
continue
korean_content = korean_content.replace("“", ' "')
korean_content = korean_content.replace("”", '" ')
korean_content = " ".join(re.sub(r'\(\w+\)', ' ', korean_content).split()).strip()
if hanja_content != '' and korean_content != '':
record_list.append({
'date': record_json[i]['date'], 'korean': korean_content, 'hanja': hanja_content
})
print(len(record_list))
print('Seungjeongwon hanja only data pre-processing...')
additional_record_list = []
for json_data in s_hj_path:
with open(json_data, 'rb') as json_file:
record_json = json.load(json_file)
for i in range(len(record_json)):
# Hanja Preprocessing
hanja_content = record_json[i]['hanja']
if '□' in hanja_content:
continue
if '◆' in hanja_content:
continue
hanja_content = hanja_content.replace('○', '')
hanja_content = hanja_content.replace('〔○〕', '')
hanja_content = hanja_content.strip()
if hanja_content != '':
additional_record_list.append({
'date': record_json[i]['date'], 'hanja': hanja_content
})
print(len(additional_record_list))
# Train, test split. Codes in vocab_train.py
split_record, split_additional_record = train_test_split(record_list, additional_record_list)
print('Paired data num:')
print(f"\ttrain: {len(split_record['train'])}")
print(f"\tvalid: {len(split_record['valid'])}")
print(f"\ttest: {len(split_record['test'])}")
print('Additional data num:')
print(f"\ttrain: {len(split_additional_record['train'])}")
print(f"\tvalid: {len(split_additional_record['valid'])}")
print(f"\ttest: {len(split_additional_record['test'])}")
train_hanja_list = tuple(r['hanja'] for r in split_record['train'])
train_korean_list = tuple(r['korean'] for r in split_record['train'])
valid_hanja_list = tuple(r['hanja'] for r in split_record['valid'])
valid_korean_list = tuple(r['korean'] for r in split_record['valid'])
test_hanja_list = tuple(r['hanja'] for r in split_record['test'])
test_korean_list = tuple(r['korean'] for r in split_record['test'])
train_additional_hanja = tuple(r['hanja'] for r in split_additional_record['train'])
valid_additional_hanja = tuple(r['hanja'] for r in split_additional_record['valid'])
test_additional_hanja = tuple(r['hanja'] for r in split_additional_record['test'])
hanja_list = (train_hanja_list, valid_hanja_list, test_hanja_list)
additional_hanja_list = (train_additional_hanja, valid_additional_hanja, test_additional_hanja)
print('Hanja Vocab Training...')
(
hanja_word2id,
train_hanja_indices, valid_hanja_indices, test_hanja_indices,
train_additional_hanja_indices, valid_additional_hanja_indices, test_additional_hanja_indices
) = hanja_vocab_processing(args, hanja_list, additional_hanja_list)
print('Korean Vocab Training...')
(
korean_word2id, train_korean_indices, valid_korean_indices, test_korean_indices
) = korean_vocab_train(args, train_korean_list, valid_korean_list, test_korean_list)
with open(f"{args.output_path}/hanja_korean_word2id.pkl", "wb") as f:
pickle.dump({
'hanja_word2id': hanja_word2id,
'korean_word2id': korean_word2id
}, f ,protocol=pickle.HIGHEST_PROTOCOL)
with open(f"{args.output_path}/preprocessed_train.pkl", "wb") as f:
pickle.dump({
'hanja_indices': train_hanja_indices,
'korean_indices': train_korean_indices,
'additional_hanja_indices': train_additional_hanja_indices
}, f, protocol=pickle.HIGHEST_PROTOCOL)
with open(f'{args.output_path}/preprocessed_valid.pkl', 'wb') as f:
pickle.dump({
'hanja_indices': valid_hanja_indices,
'korean_indices': valid_korean_indices,
'additional_hanja_indices': valid_additional_hanja_indices
}, f, protocol=pickle.HIGHEST_PROTOCOL)
with open(f'{args.output_path}/preprocessed_test.pkl', 'wb') as f:
pickle.dump({
'hanja_indices': test_hanja_indices,
'korean_indices': test_korean_indices,
'additional_hanja_indices': test_additional_hanja_indices
}, f, protocol=pickle.HIGHEST_PROTOCOL)
if __name__=='__main__':
parser = argparse.ArgumentParser(description='Parsing Method')
parser.add_argument('--vocab_size', type=int, default=24000, help='Korean Vocabulary Size')
parser.add_argument('--joseon_record_path', type=str, help='path of Joseon record',
default='/home/nas1_userC/rudvlf0413/joseon_translation/dataset/joseon_record')
parser.add_argument('--sjw_path', type=str, help='path of Seungjeongwon diary',
default='/home/nas1_userC/rudvlf0413/joseon_translation/dataset/sjw_hanja_korean')
parser.add_argument('--sjw_hj_path', type=str, help='path of Seungjeongwon diary of hanja',
default='/home/nas1_userC/rudvlf0413/joseon_translation/dataset/sjw_hanja')
parser.add_argument('--output_path', type=str, help='path of preprocessed results',
default='/home/nas1_userC/rudvlf0413/joseon_translation/dataset/preprocessed')
parser.add_argument('--pad_id', default=0, type=int, help='pad index')
parser.add_argument('--bos_id', default=1, type=int, help='index of bos token')
parser.add_argument('--eos_id', default=2, type=int, help='index of eos token')
parser.add_argument('--unk_id', default=3, type=int, help='index of unk token')
args = parser.parse_args()
main(args)