-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtrain.ts
293 lines (257 loc) · 8.67 KB
/
train.ts
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import fs from 'fs'
import readline from 'readline'
import { ngramTokenizer } from './tokenizer'
import { processSentencesLineByLine } from './train/splitter'
import pLimit from 'p-limit'
import {
configSet,
getLangTopStatsGram,
isSkipProba,
langs,
langToId,
supportedLanguages,
TOP_LANGUAGE_UNIQUE_GRAMS,
TRAINING_UNIQUE_GRAMS
} from './core'
const banWordList = new Set(['tatoeba', 'facebook', 'tom', '=', '-', '﹣'])
async function processLang(lang: string) {
const wordRank = new Map<string, number>()
if (!fs.existsSync(`data/tmp`)) fs.mkdirSync(`data/tmp`)
if (!fs.existsSync(`data/tmp/${lang}`)) fs.mkdirSync(`data/tmp/${lang}`)
if (!fs.existsSync(`data/tmp/${lang}/sentences.txt`)) {
console.log(`Create ${lang} sentences.txt`)
const fileStream = fs.createReadStream('data/tatoeba.csv')
const writeStream = fs.createWriteStream(`data/tmp/${lang}/sentences.txt`, { flags: 'a' })
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
})
for await (const line of rl) {
const [, country, text] = line.split('\t')
if (country != lang) continue
writeStream.write(`${text}\n`)
}
if (fs.existsSync(`data/udhr/udhr_${lang}.txt`)) {
const udhrFileStream = fs.createReadStream(`data/udhr/udhr_${lang}.txt`)
const rl2 = readline.createInterface({
input: udhrFileStream,
crlfDelay: Infinity
})
let useLine = false
for await (const line of rl2) {
if (line === '---') {
useLine = true
continue
}
if (!useLine) continue
if (!line.trim() || line.length < 24) continue
writeStream.write(`${line.trim()}\n`)
}
}
writeStream.close()
rl.close()
}
if (!fs.existsSync(`data/tmp/${lang}/words.txt`)) {
console.log(`Create ${lang} words.txt`)
// parse sentences file
const res = await processSentencesLineByLine(`data/tmp/${lang}/sentences.txt`)
res.forEach((x) => wordRank.set(x.word, (wordRank.get(x.word) || 0) + x.count))
// words
const wordOutStream = fs.createWriteStream(`data/tmp/${lang}/words.txt`, { flags: 'a' })
const values = [...wordRank.entries()]
values.sort((a, b) => b[1] - a[1])
const wordMax = values[0][1]
values.forEach((x) => {
if (x[1] < 10 || x[1] / wordMax < 0.00001) return
if (banWordList.has(x[0])) return
wordOutStream.write(`${x[0]}\t${x[1] / wordMax}\n`)
})
wordOutStream.close()
for (const gram of [1, 2, 3, 4, 5]) {
const gramRank = new Map<string, number>()
for (const word of wordRank.keys()) {
const count = wordRank.get(word) || 0
ngramTokenizer(word, gram).forEach((x) => {
gramRank.set(x, (gramRank.get(x) || 0) + count)
})
}
const gramOutStream = fs.createWriteStream(`data/tmp/${lang}/${gram}-gram.txt`, { flags: 'a' })
const gramValues = [...gramRank.entries()]
gramValues.sort((a, b) => b[1] - a[1])
const max = gramValues[0][1]
gramValues.forEach((x) => {
if (x[1] < 10 || x[1] / max < 0.00001) return
gramOutStream.write(`${x[0]}\t${x[1] / max}\n`)
})
gramOutStream.close()
}
}
}
const checkNgramContains = (txt: string, gram: number, uniques: Set<string>) => {
for (let i = 1; i < gram; i++) {
const grams = ngramTokenizer(txt, i)
if (grams.some((x) => uniques.has(x))) return true
}
return false
}
async function processUniqueGrams(langs: string[], gram: number, uniques: Set<string>) {
const map = new Map<string, Map<string, { count: number; index: number }>>()
for (const lang of langs) {
// console.log('process Gram', lang, gram)
const fileStream = fs.createReadStream(`data/tmp/${lang}/${gram}-gram.txt`)
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
})
let index = 0
for await (const line of rl) {
const [txt, usage] = line.split('\t')
if (banWordList.has(txt)) continue
if (checkNgramContains(txt, gram, uniques)) continue
if (!map.has(txt)) map.set(txt, new Map())
const gramData = map.get(txt) as Map<string, { count: number; index: number }>
gramData.set(lang, { count: parseFloat(usage), index })
index++
}
fileStream.close()
}
const uniqueMap = new Map<string, [number, string][]>()
;[...map.entries()].forEach((gram) => {
if (gram[1].size !== 1) return
const txt = gram[0]
const country = [...gram[1].keys()][0]
const index = gram[1].get(country)?.index || 0
if (!uniqueMap.has(country)) uniqueMap.set(country, [])
uniqueMap.get(country)?.push([index, txt])
})
const result: { [id: string]: string } = {}
;[...uniqueMap.entries()].forEach((x) => {
let count = 0
x[1].forEach((y) => {
if (count > TOP_LANGUAGE_UNIQUE_GRAMS) return
count++
result[y[1]] = x[0]
})
})
return result
}
async function processLangGrams(langs: string[], gram: number, uniques: Set<string>) {
const allGrams = new Map<string, string[]>()
for (const lang of langs) {
if (isSkipProba(lang)) continue
const fileStream = fs.createReadStream(`data/tmp/${lang}/${gram}-gram.txt`)
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
})
for await (const line of rl) {
const [txt] = line.split('\t')
if (txt in uniques) continue
allGrams.set(txt, [...(allGrams.get(txt) || []), txt])
}
fileStream.close()
}
const grams = new Set()
for (const lang of langs) {
if (isSkipProba(lang)) continue
const fileStream = fs.createReadStream(`data/tmp/${lang}/${gram}-gram.txt`)
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
})
let normal = getLangTopStatsGram(lang)
for await (const line of rl) {
const [txt] = line.split('\t')
if (txt in uniques) continue
if ((allGrams.get(txt)?.length || 0) > 12) continue
grams.add(txt)
normal--
if (normal <= 0) break
}
fileStream.close()
}
const langGrams = new Map<string, Record<string, number>>()
for (const lang of langs) {
if (isSkipProba(lang)) continue
const fileStream = fs.createReadStream(`data/tmp/${lang}/${gram}-gram.txt`)
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
})
for await (const line of rl) {
const [txt, usage] = line.split('\t')
const value = parseFloat(usage)
if (!grams.has(txt)) continue
const data = langGrams.get(txt) || {}
const rnd = Math.round(1024 * (1 - (1 - value) * (1 - value)))
if (rnd <= 1) break
data[lang] = rnd
langGrams.set(txt, data)
}
fileStream.close()
}
return Object.fromEntries(langGrams.entries())
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function sortKeys(_key: string, value: any) {
if (value == null || value.constructor != Object) {
return value
}
return (
Object.keys(value)
.sort()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.reduce((s: any, k: any) => {
s[k] = value[k]
return s
}, {})
)
}
async function processFiles() {
const processLangs = [...langs.values()]
const limit = pLimit(4)
await Promise.all(
processLangs.map((lang) => {
return limit(() => processLang(lang))
})
)
let uniques: Record<string, string> = {}
for (const gram of TRAINING_UNIQUE_GRAMS) {
const un = new Set([...Object.keys(uniques)])
uniques = { ...uniques, ...(await processUniqueGrams(processLangs, gram, un)) }
}
let multiples: Record<string, Record<string, number>> = {}
for (const gram of TRAINING_UNIQUE_GRAMS) {
const un = new Set([...Object.keys(uniques)])
multiples = { ...multiples, ...(await processLangGrams(processLangs, gram, un)) }
}
fs.writeFileSync(
`src/profiles/${configSet}.json`,
JSON.stringify(
{
id: 'tinyld-dict',
uniques: Object.fromEntries(
Object.entries(uniques).map((x) => {
const val = langToId[x[1]].toString(36)
return [x[0], isNaN(val as unknown as number) ? val : parseInt(val)]
})
),
multiples: Object.fromEntries(
Object.entries(multiples).map((x) => {
let str = ''
Object.entries(x[1]).forEach((y) => {
const country = langToId[y[0]].toString(36).padStart(supportedLanguages.length > 36 ? 2 : 1, '0')
const value = y[1].toString(36).padStart(2, '0')
str += `${country.toUpperCase()}${value.toUpperCase()}`
})
return [x[0], str]
})
)
},
sortKeys,
2
)
)
console.log('End')
}
processFiles()