forked from pemistahl/lingua-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
540 lines (477 loc) · 11.9 KB
/
writer.go
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
/*
* Copyright © 2021-present Peter M. Stahl [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expressed or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package lingua
import (
"archive/zip"
"bufio"
"errors"
"fmt"
"github.com/pemistahl/lingua-go/serialization"
"google.golang.org/protobuf/proto"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
)
// CreateAndWriteLanguageModelFiles creates language model files for
// accuracy report generation and writes them to a directory.
//
// `inputFilePath` is the path to a txt file used for language model creation.
// The assumed enconding of the txt file is UTF-8.
//
// `outputDirectoryPath` is the path to an existing directory where the language
// model files are to be written.
//
// `language` is the language for which to create the language models.
//
// `charClass` is a regex character class such as `\\p{L}` to restrict the
// set of characters that the language models are built from.
//
// An error is returned if:
//
// - the input file path is not absolute or does not point to an existing txt file
//
// - the input file's encoding is not UTF-8
//
// - the output directory path is not absolute or does not point to an existing directory
//
// Panics if the character class cannot be compiled to a valid regular expression.
func CreateAndWriteLanguageModelFiles(
inputFilePath string,
outputDirectoryPath string,
language Language,
charClass string,
) error {
err := checkInputFilePath(inputFilePath)
if err != nil {
return err
}
err = checkOutputDirectoryPath(outputDirectoryPath)
if err != nil {
return err
}
unigramModel, err := createLanguageModel(
inputFilePath,
language,
1,
charClass,
map[ngram]uint32{},
)
if err != nil {
return err
}
bigramModel, err := createLanguageModel(
inputFilePath,
language,
2,
charClass,
unigramModel.absoluteFrequencies,
)
if err != nil {
return err
}
trigramModel, err := createLanguageModel(
inputFilePath,
language,
3,
charClass,
bigramModel.absoluteFrequencies,
)
if err != nil {
return err
}
quadrigramModel, err := createLanguageModel(
inputFilePath,
language,
4,
charClass,
trigramModel.absoluteFrequencies,
)
if err != nil {
return err
}
fivegramModel, err := createLanguageModel(
inputFilePath,
language,
5,
charClass,
quadrigramModel.absoluteFrequencies,
)
if err != nil {
return err
}
err = writeCompressedLanguageModel(
unigramModel,
1,
outputDirectoryPath,
"unigrams.pb.bin",
)
if err != nil {
return err
}
err = writeCompressedLanguageModel(
bigramModel,
2,
outputDirectoryPath,
"bigrams.pb.bin",
)
if err != nil {
return err
}
err = writeCompressedLanguageModel(
trigramModel,
3,
outputDirectoryPath,
"trigrams.pb.bin",
)
if err != nil {
return err
}
err = writeCompressedLanguageModel(
quadrigramModel,
4,
outputDirectoryPath,
"quadrigrams.pb.bin",
)
if err != nil {
return err
}
err = writeCompressedLanguageModel(
fivegramModel,
5,
outputDirectoryPath,
"fivegrams.pb.bin",
)
if err != nil {
return err
}
return nil
}
// CreateAndWriteTestDataFiles creates test data files for accuracy report
// generation and writes them to a directory.
//
// `inputFilePath` is the path to a txt file used for test data creation.
// The assumed enconding of the txt file is UTF-8.
//
// `outputDirectoryPath` is the path to an existing directory where the test
// data files are to be written.
//
// `charClass` is a regex character class such as `\\p{L}` to restrict the
// set of characters that the language models are built from.
//
// `maximumLines` is the maximum number of lines each test data file should have.
//
// An error is returned if:
//
// - the input file path is not absolute or does not point to an existing txt file
//
// - the input file's encoding is not UTF-8
//
// - the output directory path is not absolute or does not point to an existing directory
//
// Panics if the character class cannot be compiled to a valid regular expression.
func CreateAndWriteTestDataFiles(
inputFilePath string,
outputDirectoryPath string,
charClass string,
maximumLines int,
) error {
err := checkInputFilePath(inputFilePath)
if err != nil {
return err
}
err = checkOutputDirectoryPath(outputDirectoryPath)
if err != nil {
return err
}
err = createAndWriteSentencesFile(
inputFilePath,
outputDirectoryPath,
maximumLines,
)
if err != nil {
return err
}
singleWords, err := createAndWriteSingleWordsFile(
inputFilePath,
outputDirectoryPath,
charClass,
maximumLines,
)
if err != nil {
return err
}
err = createAndWriteWordPairsFile(
singleWords,
outputDirectoryPath,
maximumLines,
)
if err != nil {
return err
}
return nil
}
func createAndWriteSentencesFile(
inputFilePath string,
outputDirectoryPath string,
maximumLines int,
) error {
sentencesFilePath := filepath.Join(outputDirectoryPath, "sentences.txt")
if _, err := os.Stat(sentencesFilePath); errors.Is(err, os.ErrExist) {
err = os.Remove(sentencesFilePath)
if err != nil {
return err
}
}
inputFile, err := os.Open(inputFilePath)
if err != nil {
return err
}
defer inputFile.Close()
var inputLines []string
scanner := bufio.NewScanner(inputFile)
for scanner.Scan() {
line := scanner.Text()
if len(strings.TrimSpace(line)) > 0 {
inputLines = append(inputLines, line)
}
}
sentencesFile, err := os.Create(sentencesFilePath)
if err != nil {
return err
}
defer sentencesFile.Close()
lineCounter := 0
for _, line := range inputLines {
normalizedWhitespace := multipleWhitespace.ReplaceAllString(line, " ")
removedQuotes := strings.ReplaceAll(normalizedWhitespace, "\"", "")
if lineCounter < maximumLines {
_, err = sentencesFile.WriteString(fmt.Sprintf("%s\n", removedQuotes))
if err != nil {
return err
}
lineCounter++
} else {
break
}
}
return nil
}
func createAndWriteSingleWordsFile(
inputFilePath string,
outputDirectoryPath string,
charClass string,
maximumLines int,
) ([]string, error) {
singleWordsFilePath := filepath.Join(outputDirectoryPath, "single-words.txt")
wordRegex, err := regexp.Compile(fmt.Sprintf("[%s]{5,}", charClass))
if err != nil {
return nil, err
}
if _, err := os.Stat(singleWordsFilePath); errors.Is(err, os.ErrExist) {
err = os.Remove(singleWordsFilePath)
if err != nil {
return nil, err
}
}
var words []string
inputFile, err := os.Open(inputFilePath)
if err != nil {
return nil, err
}
defer inputFile.Close()
var inputLines []string
scanner := bufio.NewScanner(inputFile)
for scanner.Scan() {
line := scanner.Text()
if len(strings.TrimSpace(line)) > 0 {
inputLines = append(inputLines, line)
}
}
singleWordsFile, err := os.Create(singleWordsFilePath)
if err != nil {
return nil, err
}
defer singleWordsFile.Close()
lineCounter := 0
for _, line := range inputLines {
removedPunctuation := punctuation.ReplaceAllString(line, "")
removedNumbers := numbers.ReplaceAllString(removedPunctuation, "")
normalizedWhitespace := multipleWhitespace.ReplaceAllString(removedNumbers, " ")
removedQuotes := strings.ReplaceAll(normalizedWhitespace, "\"", "")
for _, word := range strings.Split(removedQuotes, " ") {
word = strings.ToLower(strings.TrimSpace(word))
if wordRegex.MatchString(word) {
words = append(words, word)
}
}
}
for _, word := range words {
if lineCounter < maximumLines {
_, err = singleWordsFile.WriteString(fmt.Sprintf("%s\n", word))
if err != nil {
return nil, err
}
lineCounter++
} else {
break
}
}
return words, nil
}
func createAndWriteWordPairsFile(
words []string,
outputDirectoryPath string,
maximumLines int,
) error {
wordPairsFilePath := filepath.Join(outputDirectoryPath, "word-pairs.txt")
if _, err := os.Stat(wordPairsFilePath); errors.Is(err, os.ErrExist) {
err = os.Remove(wordPairsFilePath)
if err != nil {
return err
}
}
var wordPairs []string
for i := 0; i <= len(words)-2; i++ {
if i%2 == 0 {
wordPairs = append(wordPairs, strings.Join(words[i:i+2], " "))
}
}
wordPairsFile, err := os.Create(wordPairsFilePath)
if err != nil {
return err
}
defer wordPairsFile.Close()
lineCounter := 0
for _, wordPair := range wordPairs {
if lineCounter < maximumLines {
_, err = wordPairsFile.WriteString(fmt.Sprintf("%s\n", wordPair))
if err != nil {
return err
}
lineCounter++
} else {
break
}
}
return nil
}
func createLanguageModel(
inputFilePath string,
language Language,
ngramLength int,
charClass string,
lowerNgramAbsoluteFrequencies map[ngram]uint32,
) (trainingDataLanguageModel, error) {
file, err := os.Open(inputFilePath)
if err != nil {
return trainingDataLanguageModel{}, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if len(strings.TrimSpace(line)) > 0 {
lines = append(lines, line)
}
}
return newTrainingDataLanguageModel(
lines,
language,
ngramLength,
charClass,
lowerNgramAbsoluteFrequencies,
), nil
}
func writeCompressedLanguageModel(
model trainingDataLanguageModel,
ngramLength int,
outputDirectoryPath string,
fileName string,
) error {
languageName := strings.ToUpper(model.language.String())
languageEnumValue := serialization.SerializableLanguage_value[languageName]
serializableLanguage := serialization.SerializableLanguage(languageEnumValue)
probabilitiesToNgrams := make(map[float64][]string)
for ngrm, probability := range model.relativeFrequencies {
probabilitiesToNgrams[probability] = append(probabilitiesToNgrams[probability], ngrm.value)
}
var ngramSets []*serialization.SerializableNgramSet
for probability, ngrams := range probabilitiesToNgrams {
sort.Strings(ngrams)
ngramSet := serialization.SerializableNgramSet{
Probability: probability,
Ngrams: ngrams,
}
ngramSets = append(ngramSets, &ngramSet)
}
serializableModel := serialization.SerializableLanguageModel{
Language: serializableLanguage,
NgramLength: uint32(ngramLength),
TotalNgrams: uint32(len(model.relativeFrequencies)),
NgramSets: ngramSets,
}
serializedModel, err := proto.Marshal(&serializableModel)
if err != nil {
return err
}
zipFileName := fmt.Sprintf("%s.zip", fileName)
zipFilePath := filepath.Join(outputDirectoryPath, zipFileName)
zipFile, err := os.Create(zipFilePath)
if err != nil {
return err
}
defer zipFile.Close()
zipWriter := zip.NewWriter(zipFile)
defer zipWriter.Close()
protobufFileWriter, err := zipWriter.Create(fileName)
if err != nil {
return err
}
_, err = protobufFileWriter.Write(serializedModel)
if err != nil {
return err
}
return nil
}
func checkInputFilePath(inputFilePath string) error {
if !filepath.IsAbs(inputFilePath) {
return fmt.Errorf("input file path '%s' is not absolute", inputFilePath)
}
fileInfo, err := os.Stat(inputFilePath)
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("input file '%s' does not exist", inputFilePath)
}
if !fileInfo.Mode().IsRegular() {
return fmt.Errorf("input file path '%s' does not represent a regular file", inputFilePath)
}
return nil
}
func checkOutputDirectoryPath(outputDirectoryPath string) error {
if !filepath.IsAbs(outputDirectoryPath) {
return fmt.Errorf("output directory path '%s' is not absolute", outputDirectoryPath)
}
fileInfo, err := os.Stat(outputDirectoryPath)
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("output directory '%s' does not exist", outputDirectoryPath)
}
if !fileInfo.IsDir() {
return fmt.Errorf("output directory path '%s' does not exist", outputDirectoryPath)
}
return nil
}