Updated webvtt voice name parsing

This commit is contained in:
Quentin Renard
2020-09-22 12:20:06 +02:00
parent fe67dc6838
commit df8443fe45
3 changed files with 25 additions and 35 deletions
+18 -26
View File
@@ -196,8 +196,10 @@ func ReadFromWebVTT(i io.Reader) (o *Subtitles, err error) {
case webvttBlockNameStyle:
// TODO Do something with the style
case webvttBlockNameText:
// Voice Tag to extract Speaker Name
item.Lines = append(item.Lines, parseTextWebVTT(line))
// Parse line
if l := parseTextWebVTT(line); len(l.Items) > 0 {
item.Lines = append(item.Lines, l)
}
default:
// This is the ID
index, _ = strconv.Atoi(line)
@@ -209,43 +211,33 @@ func ReadFromWebVTT(i io.Reader) (o *Subtitles, err error) {
// parseTextWebVTT parses the input line to fill the Line
func parseTextWebVTT(i string) (o Line) {
// Create tokenizer
tr := html.NewTokenizer(strings.NewReader(i))
var voiceName, endTag, text string
// Loop
for {
// Get next tag
t := tr.Next()
// Process error
if err := tr.Err(); err != nil {
break
}
switch t {
case html.StartTagToken:
matches := webVTTRegexpStartTag.FindStringSubmatch(string(tr.Raw()))
if matches == nil {
return
// Parse voice name
if matches := webVTTRegexpStartTag.FindStringSubmatch(string(tr.Raw())); matches != nil && len(matches) > 3 {
if s := strings.TrimSpace(matches[3]); s != "" {
o.VoiceName = s
}
}
if len(matches[1]) == 0 {
return
}
voiceName = matches[3]
case html.EndTagToken:
endTag = string(tr.Raw())
case html.TextToken:
text = string(tr.Raw())
if s := strings.TrimSpace(string(tr.Raw())); s != "" {
o.Items = append(o.Items, LineItem{Text: s})
}
}
}
// should be either no tag, or match voice tag
if endTag != "" && endTag != "</v>" {
return
}
o.VoiceName = strings.TrimSpace(voiceName)
o.Items = []LineItem{{Text: strings.TrimSpace(text)}}
return
}
+3 -2
View File
@@ -30,7 +30,8 @@ func TestParseTextWebVTT(t *testing.T) {
testData := `<v Bob>Incorrect end tag</vi>`
s := parseTextWebVTT(testData)
assert.Equal(t, "", s.VoiceName)
assert.Equal(t, 0, len(s.Items))
assert.Equal(t, "Bob", s.VoiceName)
assert.Equal(t, 1, len(s.Items))
assert.Equal(t, "Incorrect end tag", s.Items[0].Text)
})
}
+4 -7
View File
@@ -47,9 +47,6 @@ func TestBroken1WebVTT(t *testing.T) {
}
func TestWebVTTWithVoiceName(t *testing.T) {
voiceName1 := "Roger Bingham"
voiceName2 := "Bingham"
voiceName3 := "Lee"
testData := `WEBVTT
NOTE this a example with voicename
@@ -74,8 +71,8 @@ func TestWebVTTWithVoiceName(t *testing.T) {
assert.NoError(t, err)
assert.Len(t, s.Items, 4)
assert.Equal(t, voiceName1, s.Items[0].Lines[0].VoiceName)
assert.Equal(t, voiceName2, s.Items[1].Lines[0].VoiceName)
assert.Equal(t, voiceName3, s.Items[2].Lines[0].VoiceName)
assert.Equal(t, "", s.Items[3].Lines[0].VoiceName)
assert.Equal(t, "Roger Bingham", s.Items[0].Lines[0].VoiceName)
assert.Equal(t, "Bingham", s.Items[1].Lines[0].VoiceName)
assert.Equal(t, "Lee", s.Items[2].Lines[0].VoiceName)
assert.Equal(t, "Bob", s.Items[3].Lines[0].VoiceName)
}