-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocess.js
202 lines (182 loc) · 5.39 KB
/
preprocess.js
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
// @ts-check
import { access, constants, createReadStream, createWriteStream, unlink } from "fs";
import { createInterface } from "readline";
import { get } from "https";
import { pipeline } from "stream/promises";
import { 音韻地位 } from "qieyun";
import { kyonh, unt, tupa } from "qieyun-examples";
// File Downloading
/**
* @param {string} url
* @param {string} path
* @returns {Promise<void>}
*/
function download(url, path) {
return new Promise((resolve, reject) => {
access(path, constants.F_OK, error => {
if (error) {
console.log(`downloading ${path}`);
get(url, response => {
if (response.statusCode === 200) {
response.pipe(
createWriteStream(path)
.on("finish", resolve)
.on("error", error => unlink(path, () => reject(error)))
);
} else {
reject(new Error(`Server responded with ${response.statusCode}: ${response.statusMessage}`));
}
}).on("error", reject);
} else {
console.log(`${path} already exists, skip downloading`);
resolve();
}
});
});
}
// Sorting
/**
* Compare two strings by (full) Unicode code point order.
* @param {string} x
* @param {string} y
* @returns {number}
*/
function compareFullUnicode(x, y) {
const ix = x[Symbol.iterator]();
const iy = y[Symbol.iterator]();
for (;;) {
const nx = ix.next();
const ny = iy.next();
if (nx.done && ny.done) {
return 0;
}
const cx = nx.done ? -1 : /** @type {number} */ (nx.value.codePointAt(0));
const cy = ny.done ? -1 : /** @type {number} */ (ny.value.codePointAt(0));
const diff = cx - cy;
if (diff) {
return diff;
}
}
}
/**
* @param {string[]} x
* @param {string[]} y
* @returns {number}
*/
function compareRow(x, y) {
const diffWordLen = [...x[0]].length - [...y[0]].length;
if (diffWordLen) {
return diffWordLen;
}
const l = Math.min(x.length, y.length);
for (let i = 0; i < l; i++) {
const diff = compareFullUnicode(x[i], y[i]);
if (diff) {
return diff;
}
}
return x.length - y.length;
}
/**
* @param {string[][]} rows
* @returns {IterableIterator<string>}
*/
function* uniqSortedLines(rows) {
let lastLine;
for (let row of rows.slice().sort(compareRow)) {
const line = row.join("\t") + "\n";
if (line !== lastLine) {
yield line;
}
lastLine = line;
}
}
// Converter utils
/**
* @param {(地位: 音韻地位) => string} derive
* @param {{ [x: string]: string }} special地位
* @returns {(描述: string) => string}
*/
function makeConverter(derive, special地位) {
const cache = new Map();
return x => {
if (x.startsWith("!")) {
const sub = special地位[x.slice(1)];
if (!sub) {
throw new Error(`unhandled special 地位: ${x}`);
} else if (sub.startsWith(">")) {
return sub.slice(1);
} else if (sub.startsWith("=")) {
x = sub.slice(1);
} else {
throw new Error(`invalid instruction for special 地位 ${x}: ${sub}`);
}
}
if (cache.has(x)) {
return cache.get(x);
}
const res = derive(音韻地位.from描述(x));
cache.set(x, res);
return res;
};
}
// File reading
/**
* @param {string} path
* @param {(描述: string) => string} conv
* @returns {AsyncIterableIterator<string[]>}
*/
async function* loadTsv(path, conv) {
for await (const line of createInterface({
input: createReadStream(path),
crlfDelay: Infinity,
})) {
const [word, input] = line.split("\t");
const codes = input.split(" ").map(conv).join(" ");
yield [word, codes];
}
}
/**
* @param {string[][]} dict
* @param {string} path
* @param {(描述: string) => string} conv
*/
async function extendFromTsv(dict, path, conv) {
for await (const row of loadTsv(path, conv)) {
dict.push(row);
}
}
// Main
const sourceFiles = ["chars.tsv", "words.tsv", "extra_words.tsv"];
/**
* @param {string} name
* @param {(描述: string) => string} conv
*/
async function generate(name, conv) {
const dict = [];
for (const path of sourceFiles) {
console.log(`${name}:\treading ${path}`);
await extendFromTsv(dict, path, conv);
}
console.log(`${name}:\twriting dict`);
await pipeline(
uniqSortedLines(dict),
createWriteStream(`src/ToMiddleChinese/dict/${name}.dict.yaml`)
);
}
/** @type {(地位: 音韻地位) => string} */
const derivePos = 地位 => 地位.描述;
const deriveTupa = tupa.schema({ 模式: "寬鬆" });
/** @type {[string, (描述: string) => string][]} */
const schemas = [
["pos", makeConverter(derivePos, { 精一侵上: ">精開一侵上" })],
["tupa", makeConverter(deriveTupa, { 精一侵上: ">tsoimq" })],
["kyonh", makeConverter(kyonh, { 精一侵上: "=莊侵上" })],
["unt", makeConverter(unt, { 精一侵上: "=精三侵上" })],
];
download("https://raw.githubusercontent.com/fxsjy/jieba/237dc66/extra_dict/dict.txt.big", "src/ToMiddleChinese/dict/dict.big.txt")
download("https://cdn.jsdelivr.net/npm/[email protected]/data/HKVariantsRev.txt", "src/ToMiddleChinese/dict/HKVariantsRev.txt")
download("https://cdn.jsdelivr.net/npm/[email protected]/data/HKVariantsRevPhrases.txt", "src/ToMiddleChinese/dict/HKVariantsRevPhrases.txt")
Promise
.all(sourceFiles.map(path => download(`https://raw.githubusercontent.com/nk2028/rime-dict-source/df307c8/${path}`, path)))
.then(() => schemas.map(args => generate(...args)));