-
Notifications
You must be signed in to change notification settings - Fork 228
/
fixer.go
413 lines (353 loc) · 14.3 KB
/
fixer.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
package sub_timeline_fixer
import (
"fmt"
"github.com/allanpk716/ChineseSubFinder/internal/pkg"
"github.com/allanpk716/ChineseSubFinder/internal/pkg/ffmpeg_helper"
"github.com/allanpk716/ChineseSubFinder/internal/pkg/log_helper"
"github.com/allanpk716/ChineseSubFinder/internal/pkg/vad"
"github.com/allanpk716/ChineseSubFinder/internal/types/sub_timeline_fiexer"
"github.com/allanpk716/ChineseSubFinder/internal/types/subparser"
"github.com/go-echarts/go-echarts/v2/opts"
"github.com/grd/stat"
"github.com/james-bowman/nlp/measures/pairwise"
"github.com/mndrix/tukey"
"gonum.org/v1/gonum/mat"
"os"
"strings"
"time"
)
type SubTimelineFixer struct {
fixerConfig sub_timeline_fiexer.SubTimelineFixerConfig
ffmpegHelper *ffmpeg_helper.FFMPEGHelper
}
func NewSubTimelineFixer(fixerConfig sub_timeline_fiexer.SubTimelineFixerConfig) *SubTimelineFixer {
return &SubTimelineFixer{
fixerConfig: fixerConfig,
ffmpegHelper: ffmpeg_helper.NewFFMPEGHelper(),
}
}
// StopWordCounter 停止词统计
func (s *SubTimelineFixer) StopWordCounter(inString string, per int) []string {
statisticTimes := make(map[string]int)
wordsLength := strings.Fields(inString)
for counts, word := range wordsLength {
// 判断key是否存在,这个word是字符串,这个counts是统计的word的次数。
word, ok := statisticTimes[word]
if ok {
word = word
statisticTimes[wordsLength[counts]] = statisticTimes[wordsLength[counts]] + 1
} else {
statisticTimes[wordsLength[counts]] = 1
}
}
stopWords := make([]string, 0)
mapByValue := sortMapByValue(statisticTimes)
breakIndex := len(mapByValue) * per / 100
for index, wordInfo := range mapByValue {
if index > breakIndex {
break
}
stopWords = append(stopWords, wordInfo.Name)
}
return stopWords
}
// FixSubTimeline 校正时间轴
func (s *SubTimelineFixer) FixSubTimeline(infoSrc *subparser.FileInfo, inOffsetTime float64, desSaveSubFileFullPath string) (string, error) {
/*
从解析的实例中,正常来说是可以匹配出所有的 Dialogue 对话的 Start 和 End time 的信息
然后找到对应的字幕的文件,进行文件内容的替换来做时间轴的校正
*/
// 偏移时间
offsetTime := time.Duration(inOffsetTime*1000) * time.Millisecond
timeFormat := infoSrc.GetTimeFormat()
fixContent := infoSrc.Content
for _, srcOneDialogue := range infoSrc.Dialogues {
timeStart, err := time.Parse(timeFormat, srcOneDialogue.StartTime)
if err != nil {
return "", err
}
timeEnd, err := time.Parse(timeFormat, srcOneDialogue.EndTime)
if err != nil {
return "", err
}
fixTimeStart := timeStart.Add(offsetTime)
fixTimeEnd := timeEnd.Add(offsetTime)
fixContent = strings.ReplaceAll(fixContent, srcOneDialogue.StartTime, fixTimeStart.Format(timeFormat))
fixContent = strings.ReplaceAll(fixContent, srcOneDialogue.EndTime, fixTimeEnd.Format(timeFormat))
}
dstFile, err := os.Create(desSaveSubFileFullPath)
if err != nil {
return "", err
}
defer func() {
_ = dstFile.Close()
}()
_, err = dstFile.WriteString(fixContent)
if err != nil {
return "", err
}
return fixContent, nil
}
/*
对于 V1 版本的字幕时间轴校正来说,是有特殊的前置要求的
1. 视频要有英文字幕
2. 外置的字幕必须是中文的双语字幕(简英、繁英)
*/
// GetOffsetTimeV1 暂时只支持英文的基准字幕,源字幕必须是双语中英字幕
func (s *SubTimelineFixer) GetOffsetTimeV1(infoBase, infoSrc *subparser.FileInfo, staticLineFileSavePath string, debugInfoFileSavePath string) (bool, float64, float64, error) {
var debugInfos = make([]string, 0)
// 构建基准语料库,目前阶段只需要考虑是 En 的就行了
var baseCorpus = make([]string, 0)
var baseDialogueFilterMap = make(map[int]int, 0)
/*
这里原来的写法是所有的 base 的都放进去匹配,这样会带来一些不必要的对白
需要剔除空白。那么就需要建立一个转换的字典
*/
for index, oneDialogueEx := range infoBase.DialoguesEx {
if oneDialogueEx.EnLine == "" {
continue
}
baseCorpus = append(baseCorpus, oneDialogueEx.EnLine)
baseDialogueFilterMap[len(baseCorpus)-1] = index
}
// 初始化
pipLine, tfidf, err := NewTFIDF(baseCorpus)
if err != nil {
return false, 0, 0, err
}
/*
确认两个字幕间的偏移,暂定的方案是两边都连续匹配上 5 个索引,再抽取一个对话的时间进行修正计算
*/
maxCompareDialogue := s.fixerConfig.MaxCompareDialogue
// 基线的长度
_, docsLength := tfidf.Dims()
var matchIndexList = make([]MatchIndex, 0)
sc := NewSubCompare(maxCompareDialogue)
// 开始比较相似度,默认认为是 Ch_en 就行了
for srcIndex := 0; srcIndex < len(infoSrc.DialoguesEx); {
srcOneDialogueEx := infoSrc.DialoguesEx[srcIndex]
// 这里只考虑 英文 的语言
if srcOneDialogueEx.EnLine == "" {
srcIndex++
continue
}
// run the query through the same pipeline that was fitted to the corpus and
// to project it into the same dimensional space
queryVector, err := pipLine.Transform(srcOneDialogueEx.EnLine)
if err != nil {
return false, 0, 0, err
}
// iterate over document feature vectors (columns) in the LSI matrix and compare
// with the query vector for similarity. Similarity is determined by the difference
// between the angles of the vectors known as the cosine similarity
highestSimilarity := -1.0
// 匹配上的基准的索引
var baseIndex int
// 这里理论上需要把所有的基线遍历一次,但是,一般来说,两个字幕不可能差距在 50 行
// 这样的好处是有助于提高搜索的性能
// 那么就以当前的 src 的位置,向前、向后各 50 来遍历
nowMaxScanLength := srcIndex + 50
nowMinScanLength := srcIndex - 50
if nowMinScanLength < 0 {
nowMinScanLength = 0
}
if nowMaxScanLength > docsLength {
nowMaxScanLength = docsLength
}
for i := nowMinScanLength; i < nowMaxScanLength; i++ {
similarity := pairwise.CosineSimilarity(queryVector.(mat.ColViewer).ColView(0), tfidf.(mat.ColViewer).ColView(i))
if similarity > highestSimilarity {
baseIndex = i
highestSimilarity = similarity
}
}
startBaseIndex, startSrcIndex := sc.GetStartIndex()
if sc.Add(baseIndex, srcIndex) == false {
sc.Clear()
srcIndex = startSrcIndex + 1
continue
//sc.Add(baseIndex, srcIndex)
}
if sc.Check() == false {
srcIndex++
continue
} else {
sc.Clear()
}
matchIndexList = append(matchIndexList, MatchIndex{
BaseNowIndex: startBaseIndex,
//BaseNowIndex: baseDialogueFilterMap[startBaseIndex],
SrcNowIndex: startSrcIndex,
Similarity: highestSimilarity,
})
//println(fmt.Sprintf("Similarity: %f Base[%d] %s-%s '%s' <--> Src[%d] %s-%s '%s'",
// highestSimilarity,
// baseIndex, infoBase.DialoguesEx[baseIndex].StartTime, infoBase.DialoguesEx[baseIndex].EndTime, baseCorpus[baseIndex],
// srcIndex, srcOneDialogueEx.StartTime, srcOneDialogueEx.EndTime, srcOneDialogueEx.EnLine))
srcIndex++
}
timeFormat := infoBase.GetTimeFormat()
var startDiffTimeLineData = make([]opts.LineData, 0)
var endDiffTimeLineData = make([]opts.LineData, 0)
var tmpStartDiffTime = make([]float64, 0)
var tmpEndDiffTime = make([]float64, 0)
var startDiffTimeList = make(stat.Float64Slice, 0)
var endDiffTimeList = make(stat.Float64Slice, 0)
var xAxis = make([]string, 0)
// 上面找出了连续匹配 maxCompareDialogue:N 次的字幕语句块
// 求出平均时间偏移
for mIndex, matchIndexItem := range matchIndexList {
for i := 0; i < maxCompareDialogue; i++ {
// 这里会统计连续的这 5 句话的时间差
//tmpBaseIndex := matchIndexItem.BaseNowIndex + i
tmpBaseIndex := baseDialogueFilterMap[matchIndexItem.BaseNowIndex+i]
tmpSrcIndex := matchIndexItem.SrcNowIndex + i
baseTimeStart, err := time.Parse(timeFormat, infoBase.DialoguesEx[tmpBaseIndex].StartTime)
if err != nil {
return false, 0, 0, err
}
baseTimeEnd, err := time.Parse(timeFormat, infoBase.DialoguesEx[tmpBaseIndex].EndTime)
if err != nil {
return false, 0, 0, err
}
srtTimeStart, err := time.Parse(timeFormat, infoSrc.DialoguesEx[tmpSrcIndex].StartTime)
if err != nil {
return false, 0, 0, err
}
srtTimeEnd, err := time.Parse(timeFormat, infoSrc.DialoguesEx[tmpSrcIndex].EndTime)
if err != nil {
return false, 0, 0, err
}
TimeDiffStart := baseTimeStart.Sub(srtTimeStart)
TimeDiffEnd := baseTimeEnd.Sub(srtTimeEnd)
startDiffTimeLineData = append(startDiffTimeLineData, opts.LineData{Value: TimeDiffStart.Seconds()})
endDiffTimeLineData = append(endDiffTimeLineData, opts.LineData{Value: TimeDiffEnd.Seconds()})
tmpStartDiffTime = append(tmpStartDiffTime, TimeDiffStart.Seconds())
tmpEndDiffTime = append(tmpEndDiffTime, TimeDiffEnd.Seconds())
startDiffTimeList = append(startDiffTimeList, TimeDiffStart.Seconds())
endDiffTimeList = append(endDiffTimeList, TimeDiffEnd.Seconds())
xAxis = append(xAxis, fmt.Sprintf("%d_%d", mIndex, i))
debugInfos = append(debugInfos, "bs "+infoBase.DialoguesEx[tmpBaseIndex].StartTime+" <-> "+infoBase.DialoguesEx[tmpBaseIndex].EndTime)
debugInfos = append(debugInfos, "sc "+infoSrc.DialoguesEx[tmpSrcIndex].StartTime+" <-> "+infoSrc.DialoguesEx[tmpSrcIndex].EndTime)
debugInfos = append(debugInfos, "StartDiffTime: "+fmt.Sprintf("%f", TimeDiffStart.Seconds()))
//println(fmt.Sprintf("Diff Start-End: %s - %s Base[%d] %s-%s '%s' <--> Src[%d] %s-%s '%s'",
// TimeDiffStart, TimeDiffEnd,
// tmpBaseIndex, infoBase.DialoguesEx[tmpBaseIndex].StartTime, infoBase.DialoguesEx[tmpBaseIndex].EndTime, infoBase.DialoguesEx[tmpBaseIndex].EnLine,
// tmpSrcIndex, infoSrc.DialoguesEx[tmpSrcIndex].StartTime, infoSrc.DialoguesEx[tmpSrcIndex].EndTime, infoSrc.DialoguesEx[tmpSrcIndex].EnLine))
}
debugInfos = append(debugInfos, "---------------------------------------------")
//println("---------------------------------------------")
}
oldMean := stat.Mean(startDiffTimeList)
oldSd := stat.Sd(startDiffTimeList)
newMean := -1.0
newSd := -1.0
per := 1.0
// 如果 SD 较大的时候才需要剔除
if oldSd > 0.1 {
var outliersMap = make(map[float64]int, 0)
outliers, _, _ := tukey.Outliers(0.3, tmpStartDiffTime)
for _, outlier := range outliers {
outliersMap[outlier] = 0
}
var newStartDiffTimeList = make([]float64, 0)
for _, f := range tmpStartDiffTime {
_, ok := outliersMap[f]
if ok == true {
continue
}
newStartDiffTimeList = append(newStartDiffTimeList, f)
}
orgLen := startDiffTimeList.Len()
startDiffTimeList = make(stat.Float64Slice, 0)
for _, f := range newStartDiffTimeList {
startDiffTimeList = append(startDiffTimeList, f)
}
newLen := startDiffTimeList.Len()
per = float64(newLen) / float64(orgLen)
newMean = stat.Mean(startDiffTimeList)
newSd = stat.Sd(startDiffTimeList)
}
if newMean == -1.0 {
newMean = oldMean
}
if newSd == -1.0 {
newSd = oldSd
}
// 不为空的时候,生成调试文件
if staticLineFileSavePath != "" {
//staticLineFileSavePath = "bar.html"
err = SaveStaticLine(staticLineFileSavePath, infoBase.Name, infoSrc.Name,
per, oldMean, oldSd, newMean, newSd, xAxis,
startDiffTimeLineData, endDiffTimeLineData)
if err != nil {
return false, 0, 0, err
}
}
// 跳过的逻辑是 mean 是 0 ,那么现在如果判断有问题,缓存的调试文件继续生成,然后强制返回 0 来跳过后续的逻辑
// 这里需要考虑,找到的连续 5 句话匹配的有多少句,占比整体所有的 Dialogue 是多少,太低也需要跳过
matchIndexLineCount := len(matchIndexList) * maxCompareDialogue
//perMatch := float64(matchIndexLineCount) / float64(len(infoSrc.DialoguesEx))
perMatch := float64(matchIndexLineCount) / float64(len(baseCorpus))
if perMatch < s.fixerConfig.MinMatchedPercent {
tmpContent := infoSrc.Name + fmt.Sprintf(" Sequence match %d dialogues (< %f%%), Skip,", s.fixerConfig.MaxCompareDialogue, s.fixerConfig.MinMatchedPercent*100) + fmt.Sprintf(" %f%% ", perMatch*100)
debugInfos = append(debugInfos, tmpContent)
log_helper.GetLogger().Infoln(tmpContent)
} else {
tmpContent := infoSrc.Name + fmt.Sprintf(" Sequence match %d dialogues,", s.fixerConfig.MaxCompareDialogue) + fmt.Sprintf(" %f%% ", perMatch*100)
debugInfos = append(debugInfos, tmpContent)
log_helper.GetLogger().Infoln(tmpContent)
}
// 输出调试的匹配时间轴信息的列表
if debugInfoFileSavePath != "" {
err = pkg.WriteStrings2File(debugInfoFileSavePath, debugInfos)
if err != nil {
return false, 0, 0, err
}
}
// 虽然有条件判断是认为有问题的,但是返回值还是要填写除去的
if perMatch < s.fixerConfig.MinMatchedPercent {
return false, newMean, newSd, nil
}
return true, newMean, newSd, nil
}
// GetOffsetTimeV2 使用 VAD 检测语音是否有人声,输出连续的点标记,再通过 SimHash 进行匹配,找到最佳的偏移时间
func (s *SubTimelineFixer) GetOffsetTimeV2(audioInfo vad.AudioInfo, infoSrc *subparser.FileInfo, staticLineFileSavePath string, debugInfoFileSavePath string) (bool, float64, float64, error) {
/*
分割字幕成若干段,然后得到若干段的时间轴,将这些段从字幕文字转换成 VADInfo
从上面若干段时间轴,把音频给分割成多段
然后使用 simhash 的进行比较,输出分析的曲线图等信息
*/
bok, duration, err := s.ffmpegHelper.GetAudioInfo(audioInfo.FileFullPath)
if err != nil || bok == false {
return false, 0, 0, err
}
/*
这里的字幕要求是完整的一个字幕
1. 抽取字幕的时间片段的时候,暂定,前 15% 和后 15% 要避开,前奏、主题曲、结尾曲
2. 将整个字幕,抽取连续 5 句对话为一个单元,提取时间片段信息
*/
timeFormat := infoSrc.GetTimeFormat()
for _, oneDialogueEx := range infoSrc.DialoguesEx {
oneDialogueExTimeStart, err := time.Parse(timeFormat, oneDialogueEx.StartTime)
if err != nil {
return false, 0, 0, err
}
oneDialogueExTimeEnd, err := time.Parse(timeFormat, oneDialogueEx.EndTime)
if err != nil {
return false, 0, 0, err
}
oneStart := pkg.Time2Number(oneDialogueExTimeStart)
oneEnd := pkg.Time2Number(oneDialogueExTimeEnd)
if duration*0.15 > oneStart || duration*(1.0-0.15) < oneStart {
continue
}
if oneDialogueEx.ChLine == "" {
continue
}
//baseCorpus = append(baseCorpus, oneDialogueEx.EnLine)
//baseDialogueFilterMap[len(baseCorpus)-1] = index
}
return false, -1, -1, nil
}
const FixMask = "-fix"