-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrbg2p.go
420 lines (382 loc) · 12 KB
/
rbg2p.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
package rbg2p
import (
"fmt"
"os"
"reflect"
"sort"
"strings"
"sync"
"github.com/dlclark/regexp2"
)
var Debug = false
// Context in which the rule applies (left hand/right hand context specified by a regular expression)
type Context struct {
// Input is the regexp as written in the input string
Input string
// Regexp is the input string converted to a regular expression for internal use (with variables expanded, and adapted anchoring)
Regexp *regexp2.Regexp
}
// Matches checks if the input string matches the context rule
func (c Context) Matches(s string) (bool, error) {
if c.IsDefined() {
res, err := c.Regexp.MatchString(s)
if err != nil {
return false, err
}
return res, nil
}
return true, nil
}
// IsDefined returns true if the contained regexp is defined
func (c Context) IsDefined() bool {
return (nil != c.Regexp)
}
// String returns a string representation of the Context
func (c Context) String() string {
if c.IsDefined() {
return c.Input
}
return ""
}
// equals checks for equality (including underlying regexps); used for unit tests
func (c Context) equals(c2 Context) bool {
if c.IsDefined() && !c2.IsDefined() {
return false
} else if c2.IsDefined() && !c.IsDefined() {
return false
} else if !c2.IsDefined() && !c.IsDefined() {
return true
}
return c.Input == c2.Input
}
// Filter is a regexp filter for rules that cannot be expressed using the standard rule systme
type Filter struct {
Regexp *regexp2.Regexp
Output string
}
// Apply is used to apply the filter to an input string
func (f Filter) Apply(s string) (string, error) {
//return f.Regexp.ReplaceAllString(s, f.Output)
return f.Regexp.Replace(s, f.Output, -1, -1)
}
// Prefilter is a regexp filter
type Prefilter struct {
Regexp *regexp2.Regexp
Output string
}
// Apply is used to apply the prefilter to an input string
func (pf Prefilter) Apply(s string) (string, error) {
//return f.Regexp.ReplaceAllString(s, f.Output)
return pf.Regexp.Replace(s, pf.Output, -1, -1)
}
// Rule is a g2p rule representation
type Rule struct {
Input string
Output []string
LeftContext Context
RightContext Context
LineNumber int // for debugging
}
// String returns a string representation of the Rule
func (r Rule) String() string {
var output string
if len(r.Output) == 1 {
output = r.Output[0]
} else {
output = fmt.Sprintf("(%s)", strings.Join(r.Output, ", "))
}
return fmt.Sprintf("%s -> %s / %s _ %s", r.Input, output, r.LeftContext, r.RightContext)
}
// equals: checks for equality (including underlying slices and regexps); used for unit tests
func (r Rule) equals(r2 Rule) bool {
return r.Input == r2.Input &&
reflect.DeepEqual(r.Output, r2.Output) &&
r.LeftContext.equals(r2.LeftContext) &&
r.RightContext.equals(r2.RightContext)
}
// equalsExceptOutput: checks for equality except for output (including underlying slices and regexps); used for unit tests
func (r Rule) equalsExceptOutput(r2 Rule) bool {
return r.Input == r2.Input &&
r.LeftContext.equals(r2.LeftContext) &&
r.RightContext.equals(r2.RightContext)
}
// Test defines a rule test (input -> output)
type Test struct {
Input string
Output []string
}
// equals checks for equality (including underlying slices); used for unit tests
func (t1 Test) equals(t2 Test) bool {
return t1.Input == t2.Input && reflect.DeepEqual(t1.Output, t2.Output)
}
// RuleSet is a set of g2p rules, with variables and built-in tests
type RuleSet struct {
CharacterSet []string
PhonemeSet PhonemeSet
PhonemeDelimiter string
SyllableDelimiter string
DefaultPhoneme string
DowncaseInput bool
Vars map[string]string
Rules []Rule
RulesAppliedMutex *sync.RWMutex
RulesApplied map[string]int // for coverage checks
Tests []Test
Filters []Filter
Prefilters []Prefilter
Syllabifier Syllabifier
Content string
Debug bool
}
func (rs RuleSet) isInitialized() bool {
return len(rs.Rules) > 0
}
func (rs RuleSet) checkForUnusedChars(coveredChars map[string]bool, individualChars map[string]bool, validation *TestResult) {
var errors = []string{}
for _, char := range rs.CharacterSet {
if _, ok := individualChars[char]; !ok {
errors = append(errors, char)
}
}
sort.Strings(errors)
if len(errors) > 0 {
validation.Errors = append(validation.Errors, fmt.Sprintf("no default rule for character(s): %s", strings.Join(errors, ",")))
}
}
func (rs RuleSet) checkForUndefinedChars(coveredChars map[string]bool, individualChars map[string]bool, validation *TestResult) {
var definedChars = make(map[string]bool)
var errors = []string{}
for _, char := range rs.CharacterSet {
definedChars[char] = true
}
for char := range individualChars {
for _, ch := range strings.Split(char, "") {
if _, ok := definedChars[ch]; !ok {
errors = append(errors, ch)
}
}
}
sort.Strings(errors)
if len(errors) > 0 {
validation.Errors = append(validation.Errors, fmt.Sprintf("undefined character(s) used in rule set: %s", strings.Join(errors, ",")))
}
}
func (rs RuleSet) hasPhonemeSet() bool {
return len(rs.PhonemeSet.Symbols) > 0
}
// Test runs the built-in tests. Returns a test result with errors and warnings, if any.
func (rs RuleSet) Test() TestResult {
var result = TestResult{}
var coveredChars = map[string]bool{}
var individualChars = map[string]bool{}
for _, rule := range rs.Rules {
for _, char := range strings.Split(rule.Input, "") {
coveredChars[char] = true
}
coveredChars[rule.Input] = true
if !rule.LeftContext.IsDefined() && !rule.RightContext.IsDefined() {
individualChars[rule.Input] = true
}
}
rs.checkForUnusedChars(coveredChars, individualChars, &result)
rs.checkForUndefinedChars(coveredChars, individualChars, &result)
if rs.hasPhonemeSet() {
validation, err := compareToPhonemeSet(rs)
if err != nil {
result.Errors = append(result.Errors, fmt.Sprintf("%v", err))
}
result.Warnings = append(result.Warnings, validation.Warnings...)
result.Errors = append(result.Errors, validation.Errors...)
}
for _, test := range rs.Tests {
input := test.Input
expect := test.Output
if rs.DowncaseInput {
input = strings.ToLower(input)
}
res, err := rs.Apply(input)
if err != nil {
result.Errors = append(result.Errors, fmt.Sprintf("%v", err))
}
//delim := rs.PhonemeDelimiter
if !reflect.DeepEqual(expect, res) {
result.FailedTests = append(result.FailedTests, fmt.Sprintf("for '%s', expected /%s/, got /%s/", input, strings.Join(expect, "/ + /"), strings.Join(res, "/ + /")))
}
}
return result
}
func (rs RuleSet) expandLoop(head g2p, tail []g2p, acc []trans) []trans {
res := []trans{}
for i := 0; i < len(acc); i++ {
for _, add := range head.p {
appendRange := []g2p{}
// build prefix from previous rounds
appendRange = append(appendRange, acc[i].phonemes...)
// append current phonemes
g2p := g2p{g: head.g, p: strings.Split(add, rs.PhonemeDelimiter)}
appendRange = append(appendRange, g2p)
res = append(res, trans{phonemes: appendRange})
}
}
if len(tail) == 0 {
return res
}
return rs.expandLoop(tail[0], tail[1:], res)
}
func (rs RuleSet) expand(phonemes []g2p) []trans {
if len(phonemes) > 1 {
return rs.expandLoop(phonemes[0], phonemes[1:], []trans{{}})
} else if len(phonemes) == 1 {
return rs.expandLoop(phonemes[0], []g2p{}, []trans{{}})
}
// empty trans
return []trans{}
}
func (rs RuleSet) applyFilters(trans string) (string, error) {
res := trans
var err error
for _, f := range rs.Filters {
input := res
res, err = f.Apply(res)
if err != nil {
return res, fmt.Errorf("couldn't execute regexp : %v", err)
}
if rs.Debug {
fmt.Fprintf(os.Stderr, "FILTER\t%s\t%s\t%s\n", f, input, res)
}
}
return res, nil
}
func (rs RuleSet) applyPrefilters(trans string) (string, error) {
res := trans
var err error
for _, pf := range rs.Prefilters {
res, err = pf.Apply(res)
if err != nil {
return res, fmt.Errorf("couldn't execute regexp : %v", err)
}
}
return res, nil
}
// Apply applies the rules to an input string, returns a slice of transcriptions. If unknown input characters are found, an error will be created, and an underscore will be appended to the transcription. Even if an error is returned, the loop will continue until the end of the input string.
func (rs RuleSet) Apply(s string) ([]string, error) {
if !rs.isInitialized() {
return []string{}, fmt.Errorf("RuleSet is not initialized")
}
var i = 0
if rs.DowncaseInput {
s = strings.ToLower(s)
}
var prefiltered string
pfted, pferr := rs.applyPrefilters(s)
if pferr != nil {
return []string{}, fmt.Errorf("couldn't apply prefilter: %s", s)
}
prefiltered = pfted
var s0 = []rune(prefiltered)
res := []g2p{}
var couldntMap = []string{}
for i < len(s0) {
ss := string(s0[i:])
thisChar := string(s0[i : i+1])
left := string(s0[0:i])
var matchFound = false
for _, rule := range rs.Rules {
leftMatch, err := rule.LeftContext.Matches(left)
if err != nil {
return []string{}, fmt.Errorf("couldn't execute regexp /%s/ : %s", rule.LeftContext.Regexp, err)
}
if strings.HasPrefix(ss, rule.Input) && leftMatch {
ruleInputLen := len([]rune(rule.Input))
right := string(s0[i+ruleInputLen:])
rightMatch, err := rule.RightContext.Matches(right)
if err != nil {
return []string{}, fmt.Errorf("couldn't execute regexp /%s/ : %s", rule.RightContext.Regexp, err)
}
if rightMatch {
i = i + ruleInputLen
res = append(res, g2p{g: rule.Input, p: rule.Output})
matchFound = true
ruleString := rule.String()
rs.RulesAppliedMutex.Lock()
rs.RulesApplied[ruleString]++
rs.RulesAppliedMutex.Unlock()
if Debug {
fmt.Fprintf(os.Stderr, "%s\t%v\t%v\t%v\t%v\n", "RULE APPLIED", rule, s, ss, res)
}
break
}
}
}
if !matchFound {
res = append(res, g2p{g: thisChar, p: []string{rs.DefaultPhoneme}})
i = i + 1
couldntMap = append(couldntMap, thisChar)
}
}
expanded := rs.expand(res)
transes := []string{}
for _, t := range expanded {
if rs.Syllabifier.IsDefined() {
s := rs.Syllabifier.syllabifyToString(t)
transes = append(transes, s)
} else {
transes = append(transes, t.string(rs.PhonemeDelimiter))
}
}
var filtered []string
for _, t := range transes {
fted, err := rs.applyFilters(t)
if err != nil {
return filtered, err
}
filtered = append(filtered, fted)
}
if len(couldntMap) > 0 {
return filtered, fmt.Errorf("found unmappable symbol(s) in input string: %v in %s", couldntMap, s)
}
return filtered, nil
}
// compareToPhonemeSet validates the phonemes in the g2p rule set against the specified phonemeset. Returns an array of invalid phonemes, if any; or if errors are found, this is returned instead.
func compareToPhonemeSet(ruleSet RuleSet) (TestResult, error) {
var validation = TestResult{}
var usedSymbols = map[string]bool{}
for _, rule := range ruleSet.Rules {
for _, output := range rule.Output {
invalid, err := ruleSet.PhonemeSet.validate(output)
if err != nil {
return TestResult{}, fmt.Errorf("found error in rule output /%s/ : %s", output, err)
}
splitted, err := ruleSet.PhonemeSet.SplitTranscription(output)
if err != nil {
return TestResult{}, err
}
for _, symbol := range splitted {
usedSymbols[symbol] = true
}
for _, symbol := range invalid {
validation.Errors = append(validation.Errors, fmt.Sprintf("invalid symbol in rule output %s: %s", rule, symbol))
}
}
}
for _, test := range ruleSet.Tests {
for _, output := range test.Output {
invalid, err := ruleSet.PhonemeSet.validate(output)
if err != nil {
return TestResult{}, fmt.Errorf("found error in test output /%s/ : %s", output, err)
}
splitted, err := ruleSet.PhonemeSet.SplitTranscription(output)
if err != nil {
return TestResult{}, err
}
for _, symbol := range splitted {
usedSymbols[symbol] = true
}
for _, symbol := range invalid {
validation.Errors = append(validation.Errors, fmt.Sprintf("invalid symbol in test output %s: %s", test, symbol))
}
}
}
validation.Warnings = append(validation.Warnings, checkForUnusedSymbols(usedSymbols, ruleSet.PhonemeSet)...)
return validation, nil
}