-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsrtcondenser.go
More file actions
96 lines (75 loc) · 1.72 KB
/
Copy pathsrtcondenser.go
File metadata and controls
96 lines (75 loc) · 1.72 KB
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
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type srt struct {
count int
timestamp string
subtitle string
}
func newSrt(blob string) *srt {
lines := strings.Split(strings.TrimSpace(blob), "\n")
if len(lines) < 3 {
panic(fmt.Sprintf("Invalid SRT block (expected at least 3 lines): %q", blob))
}
count, err := strconv.Atoi(lines[0])
if err != nil {
panic(fmt.Sprintf("Invalid count in block: %q", lines[0]))
}
timestamp := strings.TrimSpace(lines[1])
subtle := strings.Join(lines[2:], "\n")
return &srt{
count: count,
timestamp: timestamp,
subtitle: subtle,
}
}
func ParseSrt(file *os.File) []srt {
parsedSrts := []srt{}
scanner := bufio.NewScanner(file)
unparsedSection := ""
for scanner.Scan() {
line := scanner.Text()
unparsedSection += fmt.Sprintf("%s\n", line)
if strings.TrimSpace(line) == "" {
parsedSrts = append(parsedSrts, *newSrt(unparsedSection))
unparsedSection = ""
}
}
if strings.TrimSpace(unparsedSection) != "" {
parsedSrts = append(parsedSrts, *newSrt(unparsedSection))
}
return parsedSrts
}
func CondenseSrt(parsedSrts []srt) []srt {
if len(parsedSrts) == 0 {
return []srt{}
}
var result []srt
i := 0
for i < len(parsedSrts) {
curr := parsedSrts[i]
j := i + 1
for j < len(parsedSrts) && parsedSrts[j].timestamp == curr.timestamp {
curr.subtitle += "\n" + parsedSrts[j].subtitle
j++
}
result = append(result, curr)
i = j
}
for i := range result {
result[i].count = i + 1
}
return result
}
func WriteSrt(parsedSrts []srt, path string) {
output := ""
for _, srt := range parsedSrts {
output += fmt.Sprintf("%d\n%s\n%s\n\n", srt.count, srt.timestamp, srt.subtitle)
}
os.WriteFile(path, []byte(output), 0644)
}