-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrbg2p_inits.go
509 lines (468 loc) · 14.7 KB
/
rbg2p_inits.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
package rbg2p
import (
"bufio"
"fmt"
"net/http"
u "net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"github.com/dlclark/regexp2"
)
func isVar(s string) bool {
return strings.HasPrefix(s, "VAR ")
}
func isTest(s string) bool {
return strings.HasPrefix(s, "TEST ")
}
func isFilter(s string) bool {
return strings.HasPrefix(s, "FILTER ")
}
func isPrefilter(s string) bool {
return strings.HasPrefix(s, "PREFILTER ")
}
//var g2pLineRe = regexp.MustCompile("^(CHARACTER_SET|TEST|DEFAULT_PHONEME|FILTER|VAR|) .*")
var g2pLineRe = regexp.MustCompile("^(CHARACTER_SET|TEST|DEFAULT_PHONEME|FILTER|PREFILTER|VAR|DOWNCASE_INPUT) .*")
func isG2PLine(s string) bool {
return g2pLineRe.MatchString(s) || ruleRe.MatchString(s)
}
type usedVars map[string]int
// LoadURL loads a g2p rule set from an URL
func LoadURL(url string) (RuleSet, error) {
urlP, err := u.Parse(url)
if err != nil {
return RuleSet{}, err
}
resp, err := http.Get(urlP.String())
if err != nil {
return RuleSet{}, err
}
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
return load(scanner, url)
}
// LoadFile loads a g2p rule set from the specified file
func LoadFile(fName string) (RuleSet, error) {
fh, err := os.Open(filepath.Clean(fName))
if err != nil {
return RuleSet{}, err
}
/* #nosec G307 */
defer fh.Close()
scanner := bufio.NewScanner(fh)
return load(scanner, fName)
}
func load(scanner *bufio.Scanner, inputPath string) (RuleSet, error) {
var err error
usedVars := usedVars{}
ruleSet := RuleSet{Vars: map[string]string{}}
//log.Println("[rbg2p] New ruleset created with new mutex instance")
ruleSet.RulesApplied = make(map[string]int)
ruleSet.RulesAppliedMutex = &sync.RWMutex{}
ruleSet.DefaultPhoneme = "_"
ruleSet.PhonemeDelimiter = " "
ruleSet.DowncaseInput = true // Default, might be changed by value in rule file
syllDefLines := []string{}
var inputLines []string
var ruleLines []string
var ruleLinesWithLineNumber = make(map[string]int)
var filterLines []string
var prefilterLines []string
var phonemeSetLine string
var n = 0
for scanner.Scan() {
if err = scanner.Err(); err != nil {
return ruleSet, err
}
n++
lOrig := strings.TrimSpace(scanner.Text())
l := trimComment(lOrig)
inputLines = append(inputLines, lOrig)
if isBlankLine(l) || isComment(l) {
} else if isPhonemeDelimiter(l) {
delim, err := parsePhonemeDelimiter(l)
if err != nil {
return ruleSet, err
}
ruleSet.PhonemeDelimiter = delim
} else if isPhonemeSet(l) {
phonemeSetLine = l
} else if isConst(l) {
err = parseConst(l, &ruleSet)
if err != nil {
return ruleSet, err
}
} else if isVar(l) {
name, value, err := newVar(l)
if err != nil {
return ruleSet, err
}
ruleSet.Vars[name] = value
} else if isSyllDefLine(l) {
syllDefLines = append(syllDefLines, l)
} else if isFilter(l) {
filterLines = append(filterLines, l)
} else if isPrefilter(l) {
prefilterLines = append(prefilterLines, l)
} else if isTest(l) {
t, err := newTest(l)
if err != nil {
return ruleSet, err
}
ruleSet.Tests = append(ruleSet.Tests, t)
} else { // is a rule
ruleLines = append(ruleLines, l)
ruleLinesWithLineNumber[l] = n
}
}
for k, v := range ruleSet.Vars {
v, _, err := expandVarsWithBrackets(v, ruleSet.Vars)
if err != nil {
return ruleSet, err
}
ruleSet.Vars[k] = v
}
if len(syllDefLines) > 0 {
syllDef, stressPlacement, err := loadSyllDef(syllDefLines, ruleSet.PhonemeDelimiter)
if err != nil {
return ruleSet, err
}
ruleSet.Syllabifier = Syllabifier{}
ruleSet.SyllableDelimiter = syllDef.SyllableDelimiter()
ruleSet.Syllabifier.SyllDef = syllDef
ruleSet.Syllabifier.StressPlacement = stressPlacement
ruleSet.Syllabifier.PhonemeSet = ruleSet.PhonemeSet
}
if len(phonemeSetLine) > 0 {
phnSet, err := parsePhonemeSet(phonemeSetLine, ruleSet.Syllabifier.SyllDef, ruleSet.PhonemeDelimiter)
if err != nil {
return ruleSet, err
}
ruleSet.PhonemeSet = phnSet
}
for _, l := range filterLines {
t, usedVarsTmp, err := newFilter(l, ruleSet.Vars)
if err != nil {
return ruleSet, err
}
ruleSet.Filters = append(ruleSet.Filters, t)
for k, v := range usedVarsTmp {
usedVars[k] += v
}
}
for _, l := range prefilterLines {
t, usedVarsTmp, err := newPrefilter(l, ruleSet.Vars)
if err != nil {
return ruleSet, err
}
ruleSet.Prefilters = append(ruleSet.Prefilters, t)
for k, v := range usedVarsTmp {
usedVars[k] += v
}
}
//ruleSet.Rules = append(ruleSet.Rules, Rule{Input: " ", Output: []string{" "}})
for _, l := range ruleLines {
r, usedVarsTmp, err := newRule(l, ruleSet.Vars)
if err != nil {
return ruleSet, err
}
lineNo, ok := ruleLinesWithLineNumber[l]
if !ok {
return ruleSet, fmt.Errorf("no line number for rule %s", r)
}
r.LineNumber = lineNo
for _, r0 := range ruleSet.Rules {
if r0.equalsExceptOutput(r) {
return ruleSet, fmt.Errorf("duplicate rules for input file %s: %s vs. %s", inputPath, r0, r)
}
}
for k, v := range usedVarsTmp {
usedVars[k] += v
}
ruleSet.Rules = append(ruleSet.Rules, r)
}
if ruleSet.CharacterSet == nil || len(ruleSet.CharacterSet) == 0 {
return ruleSet, fmt.Errorf("no character set defined for input file %s", inputPath)
}
ruleSet.Content = strings.Join(inputLines, "\n")
unusedVars := []string{}
for vName := range ruleSet.Vars {
if _, ok := usedVars[vName]; !ok {
unusedVars = append(unusedVars, vName)
}
}
if len(unusedVars) > 0 {
sort.Strings(unusedVars)
return ruleSet, fmt.Errorf("unused variable(s) %s in %s", strings.Join(unusedVars, ", "), inputPath)
}
return ruleSet, nil
}
var constRe = regexp.MustCompile("^(CHARACTER_SET|DEFAULT_PHONEME|DOWNCASE_INPUT) (?:\"(.+)\"|([^\"]+))$")
var isConstRe = regexp.MustCompile("^(CHARACTER_SET|DEFAULT_PHONEME|DOWNCASE_INPUT) .*")
var isTrueRe = regexp.MustCompile("^(true|TRUE|1)$")
var isFalseRe = regexp.MustCompile("^(false|FALSE|0)$")
func isConst(s string) bool {
return isConstRe.MatchString(s)
}
func parseConst(s string, ruleSet *RuleSet) error {
fmt.Println("parseConst", s)
matchRes := constRe.FindStringSubmatch(s)
//var downcaseInputIsSet = false
if matchRes != nil {
name := matchRes[1]
value := matchRes[2]
if value == "" {
value = matchRes[3]
}
if name == "CHARACTER_SET" {
ruleSet.CharacterSet = strings.Split(value, "")
} else if name == "DEFAULT_PHONEME" {
ruleSet.DefaultPhoneme = value
} else if name == "DOWNCASE_INPUT" {
fmt.Println("DOWNCASE_INPUT", value)
if isTrueRe.MatchString(value) {
ruleSet.DowncaseInput = true
//downcaseInputIsSet = true
} else if isFalseRe.MatchString(value) {
ruleSet.DowncaseInput = false
//downcaseInputIsSet = true
} else {
return fmt.Errorf("invalid boolean value for %s: %s", name, value)
}
} else {
return fmt.Errorf("invalid const definition: %s", s)
}
} else {
return fmt.Errorf("invalid const definition: %s", s)
}
// if !downcaseInputIsSet {
// ruleSet.DowncaseInput = true
// }
fmt.Println("ruleSet.DowncaseInput", ruleSet.DowncaseInput)
return nil
}
var varRe = regexp.MustCompile("^VAR +([^ \"]+) +([^ \"]+|[^ ].*[^ ])$")
var varReQuoteFix = regexp.MustCompile(`^"(.*)"$`)
func newVar(s string) (string, string, error) {
// VAR NAME VALUE
matchRes := varRe.FindStringSubmatch(s)
if matchRes == nil {
return "", "", fmt.Errorf("invalid VAR definition: %s", s)
}
name := matchRes[1]
value := matchRes[2]
_, err := regexp2.Compile(value, regexp2.None)
if err != nil {
msg := fmt.Sprintf("invalid VAR input - regular expression failed: %s : %v", s, err)
return "", "", fmt.Errorf(msg)
}
if strings.Contains(name, "_") {
return "", "", fmt.Errorf("invalid VAR input - var names cannot contain underscore: %s", s)
}
if strings.HasPrefix(strings.TrimSpace(value), "=") {
return "", "", fmt.Errorf("invalid VAR input - var names cannot start with equal sign: %s", s)
}
quoteFix := varReQuoteFix.FindStringSubmatch(value)
if quoteFix != nil {
value = quoteFix[1]
}
return name, value, nil
}
var testReSimple = regexp.MustCompile("^TEST +([^ ]+) +-> +([^,()]+)$")
var testReVariants = regexp.MustCompile("^TEST +([^ ]+) +-> +[(](.+,.+)[)]$")
func newTest(s string) (Test, error) {
var outputS string
var matchRes []string
matchRes = testReSimple.FindStringSubmatch(s)
if matchRes != nil {
outputS = matchRes[2]
} else {
matchRes = testReVariants.FindStringSubmatch(s)
if matchRes == nil {
return Test{}, fmt.Errorf("invalid TEST definition: %s", s)
}
outputS = matchRes[2]
}
if strings.Contains(outputS, "->") {
return Test{}, fmt.Errorf("invalid TEST definition: %s", s)
}
input := matchRes[1]
output := commaSplit.Split(outputS, -1)
return Test{Input: input, Output: output}, nil
}
var filterRe = regexp.MustCompile("^FILTER +\"(.+)\" +-> +\"(.*)\"$")
func newFilter(s string, vars map[string]string) (Filter, usedVars, error) {
matchRes := filterRe.FindStringSubmatch(s)
if matchRes == nil {
return Filter{}, usedVars{}, fmt.Errorf("invalid FILTER definition: %s", s)
}
input := matchRes[1]
output := strings.Replace(matchRes[2], "\\\"", "\"", -1)
if strings.Contains(output, "->") {
return Filter{}, usedVars{}, fmt.Errorf("invalid FILTER definition: %s", s)
}
input, usedVars, err := expandVarsWithBrackets(input, vars)
if err != nil {
return Filter{}, usedVars, fmt.Errorf("invalid FILTER definition %s : %v", s, err)
}
re, err := regexp2.Compile(input, regexp2.None)
if err != nil {
return Filter{}, usedVars, fmt.Errorf("invalid FILTER definition (invalid regexp /%s/): %v", re, err)
}
return Filter{Regexp: re, Output: output}, usedVars, nil
}
var prefilterRe = regexp.MustCompile("^PREFILTER +\"(.+)\" +-> +\"(.*)\"$")
func newPrefilter(s string, vars map[string]string) (Prefilter, usedVars, error) {
matchRes := prefilterRe.FindStringSubmatch(s)
if matchRes == nil {
return Prefilter{}, usedVars{}, fmt.Errorf("invalid PREFILTER definition: %s", s)
}
input := matchRes[1]
output := strings.Replace(matchRes[2], "\\\"", "\"", -1)
if strings.Contains(output, "->") {
return Prefilter{}, usedVars{}, fmt.Errorf("invalid PREFILTER definition: %s", s)
}
input, usedVars, err := expandVarsWithBrackets(input, vars)
if err != nil {
return Prefilter{}, usedVars, fmt.Errorf("invalid PREFILTER definition %s : %v", s, err)
}
re, err := regexp2.Compile(input, regexp2.None)
if err != nil {
return Prefilter{}, usedVars, fmt.Errorf("invalid PREFILTER definition (invalid regexp /%s/): %v", re, err)
}
return Prefilter{Regexp: re, Output: output}, usedVars, nil
}
var unexpandedBracketVar = regexp.MustCompile(`(?:^|[^\\]){([^},\\]+)}`)
func expandVarsWithBrackets(re0 string, vars map[string]string) (string, usedVars, error) {
usedVars := usedVars{}
re := re0
for k, v := range vars {
k0 := k
k = fmt.Sprintf("{%s}", k)
reTmp := re
re = strings.Replace(re, k, v, -1)
if re != reTmp {
usedVars[k0]++
}
}
unexpandedMatch := unexpandedBracketVar.FindStringSubmatch(re)
if len(unexpandedMatch) > 1 {
return "", usedVars, fmt.Errorf("undefined variable %s", unexpandedMatch[1])
}
return re, usedVars, nil
}
var unexpandedContextVar1 = regexp.MustCompile("^[A-Z0-9]{2,}$")
var unexpandedContextVar2 = regexp.MustCompile("^[A-Z]")
func expandContextVars(s0 string, isLeft bool, vars map[string]string) (*regexp2.Regexp, usedVars, error) {
usedVars := usedVars{}
if isLeft {
s0 = strings.Replace(s0, "#", "^", -1)
} else {
s0 = strings.Replace(s0, "#", "$", -1)
}
splitted := strings.Split(s0, " ")
for i, s := range splitted {
if val, ok := vars[strings.TrimSpace(s)]; ok {
splitted[i] = val
usedVars[s]++
} else { // if it's not a VAR, it should be valid orthographic
if unexpandedContextVar1.MatchString(s) && unexpandedContextVar2.MatchString(s) {
//if unexpandedContextVar1.MatchString(s) {
return ®exp2.Regexp{}, usedVars, fmt.Errorf("undefined variable %s", s)
}
}
}
if isLeft {
res, err := regexp2.Compile(strings.Join(splitted, "")+"$", regexp2.None)
return res, usedVars, err
}
res, err := regexp2.Compile("^"+strings.Join(splitted, ""), regexp2.None)
return res, usedVars, err
}
var contextRe = regexp.MustCompile("^ +/ +((?:[^_>]+)?) *_ *((?:[^_>]+)?)$")
func newContext(s string, vars map[string]string) (Context, Context, usedVars, error) {
usedVars := usedVars{}
if len(strings.TrimSpace(s)) == 0 {
return Context{}, Context{}, usedVars, nil
}
matchRes := contextRe.FindStringSubmatch(s)
if matchRes == nil {
return Context{}, Context{}, usedVars, fmt.Errorf("invalid context definition: %s", s)
}
left := Context{}
right := Context{}
leftS := strings.TrimSpace(matchRes[1])
if len(leftS) > 0 {
re, usedVarsTmp, err := expandContextVars(leftS, true, vars)
if err != nil {
return Context{}, Context{}, usedVars, fmt.Errorf("invalid context definition: %s", err)
}
left.Regexp = re
left.Input = leftS
for k, v := range usedVarsTmp {
usedVars[k] += v
}
}
rightS := strings.TrimSpace(matchRes[2])
if len(rightS) > 0 {
re, usedVarsTmp, err := expandContextVars(rightS, false, vars)
if err != nil {
return Context{}, Context{}, usedVars, fmt.Errorf("invalid context definition: %s", err)
}
right.Regexp = re
right.Input = rightS
for k, v := range usedVarsTmp {
usedVars[k] += v
}
}
return left, right, usedVars, nil
}
var ruleRe = regexp.MustCompile("^([^ ]+) +-> +([^/]+)( +/.*$|$)")
var ruleOutputReSimple = regexp.MustCompile("^([^,()]+)$")
var ruleOutputReVariants = regexp.MustCompile("^[(](.+,.+)[)]$")
var emptyOutput = "∅"
func newRuleOutput(s string, l string) ([]string, error) {
s = strings.TrimSpace(s)
var outputS string
var matchRes []string
matchRes = ruleOutputReSimple.FindStringSubmatch(s)
if matchRes != nil {
outputS = matchRes[1]
} else {
matchRes = ruleOutputReVariants.FindStringSubmatch(s)
if matchRes == nil {
return []string{}, fmt.Errorf("invalid rule output definition: %s", l)
}
outputS = matchRes[1]
}
if strings.Contains(outputS, "->") {
return []string{}, fmt.Errorf("invalid rule output definition: %s", l)
}
outputS = strings.Replace(outputS, emptyOutput, "", -1)
return commaSplit.Split(outputS, -1), nil
}
func newRule(s string, vars map[string]string) (Rule, usedVars, error) {
usedVars := usedVars{}
// INPUT -> OUTPUT
// INPUT -> OUTPUT / LEFTCONTEXT _ RIGHTCONTEXT
matchRes := ruleRe.FindStringSubmatch(s)
if matchRes == nil {
return Rule{}, usedVars, fmt.Errorf("invalid rule definition: %s", s)
}
input := matchRes[1]
if input == "\u00a0" { // nbsp
input = " "
}
output, err := newRuleOutput(matchRes[2], s)
if err != nil {
return Rule{}, usedVars, err
}
left, right, usedVars, err := newContext(matchRes[3], vars)
if err != nil {
return Rule{}, usedVars, err
}
return Rule{Input: input, Output: output, LeftContext: left, RightContext: right}, usedVars, nil
}