ass.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. package ass
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "github.com/ChineseSubFinder/ChineseSubFinder/pkg/types/subparser"
  7. "github.com/ChineseSubFinder/ChineseSubFinder/pkg/language"
  8. "github.com/ChineseSubFinder/ChineseSubFinder/pkg/regex_things"
  9. "github.com/emirpasic/gods/maps/treemap"
  10. "github.com/sirupsen/logrus"
  11. )
  12. type Parser struct {
  13. log *logrus.Logger
  14. }
  15. func NewParser(log *logrus.Logger) *Parser {
  16. return &Parser{log: log}
  17. }
  18. func (p Parser) GetParserName() string {
  19. return "ass"
  20. }
  21. /*
  22. DetermineFileTypeFromFile 确定字幕文件的类型,是双语字幕或者某一种语言等等信息
  23. 当 error 是 common.DetermineFileTypeFromFileExtNotFitASSorSSA
  24. 需要额外的处理逻辑,比如不用报错,而是跳过后续的逻辑
  25. */
  26. func (p Parser) DetermineFileTypeFromFile(filePath string) (bool, *subparser.FileInfo, error) {
  27. nowExt := filepath.Ext(filePath)
  28. if p.log != nil {
  29. p.log.Debugln("DetermineFileTypeFromFile", p.GetParserName(), filePath)
  30. }
  31. fBytes, err := os.ReadFile(filePath)
  32. if err != nil {
  33. return false, nil, err
  34. }
  35. inBytes, err := language.ChangeFileCoding2UTF8(fBytes)
  36. if err != nil {
  37. return false, nil, err
  38. }
  39. return p.DetermineFileTypeFromBytes(inBytes, nowExt)
  40. }
  41. // DetermineFileTypeFromBytes 确定字幕文件的类型,是双语字幕或者某一种语言等等信息
  42. func (p Parser) DetermineFileTypeFromBytes(inBytes []byte, nowExt string) (bool, *subparser.FileInfo, error) {
  43. allString := string(inBytes)
  44. subFileInfo := subparser.FileInfo{}
  45. // 找到 Dialogue: 之前的信息
  46. prefixDialogueIndex := strings.Index(allString, "Dialogue:")
  47. if prefixDialogueIndex > 0 {
  48. subFileInfo.PrefixDialogueString = allString[:prefixDialogueIndex]
  49. }
  50. // 注意,需要替换掉 \r 不然正则表达式会有问题
  51. allString = strings.ReplaceAll(allString, "\r", "")
  52. // 找到 start end text
  53. matched := regex_things.ReMatchDialogueASS.FindAllStringSubmatch(allString, -1)
  54. if matched == nil || len(matched) < 1 {
  55. if p.log != nil {
  56. p.log.Debugln("DetermineFileTypeFromBytes can't found DialoguesFilter, Skip")
  57. }
  58. return false, nil, nil
  59. }
  60. subFileInfo.Content = string(inBytes)
  61. subFileInfo.Ext = nowExt
  62. subFileInfo.Dialogues = make([]subparser.OneDialogue, 0)
  63. subFileInfo.DialoguesFilter = make([]subparser.OneDialogue, 0)
  64. // 这里需要统计一共有几个 \N,以及这个数量在整体行数中的比例,这样就知道是不是双语字幕了
  65. countLineFeed := 0
  66. // 有意义的对话统计数,排除 Style 类型
  67. usefullyDialogueCount := 0
  68. // 先进行字幕 StyleName 的出现次数排序,找到最多的,就是常规字幕的,不是特效的
  69. var nameMap = make(map[string]int)
  70. for _, oneLine := range matched {
  71. nowStyleName := oneLine[3]
  72. _, ok := nameMap[nowStyleName]
  73. if ok == false {
  74. nameMap[nowStyleName] = 1
  75. } else {
  76. nameMap[nowStyleName]++
  77. }
  78. }
  79. /*
  80. 现在可能会遇到两种可能出现的双语字幕:
  81. 1.
  82. 一个 Dialogue 中,直接描述两个语言
  83. 2.
  84. 排序的目标是找出 Name 有几种,一般来说都是 Default 一种
  85. 但是目前也会有用这个 Name 来做双语标记的
  86. 比如相同的时间点:一个 Name 是 Chs Subtitle
  87. 一个 Name 是 Eng Subtitle
  88. 那么排序来说,就应该是 Top1、2 两个
  89. 但是之前是为了剔除某一些特效动画,进行排序后只找 Top 1,但是遇到上面 2 的情况
  90. 解析就只读取到一个语言的字幕了
  91. 那么现在的解决方案就是,一开始先进行 Name 的统计。
  92. 然后统计是否有一个相同的时间段,出现了两个 Dialogue,比如:
  93. 0:01:01.00-0:01:11.00 这个时间段,一共有两个 Dialogue 使用了,然后需要统计这种情况占比所有的 Dialogue 的比例
  94. 如果比例很高,那么就认为是情况 2 的双语字幕
  95. 如果没有那么多,或者就没得。就任务是情况 1 的双语字幕,这个也不能说就是双语字幕,只不过走之前的逻辑就够了。
  96. */
  97. mapByValue := sortMapByValue(nameMap)
  98. // 把所有的对白缓存下来,其实优先是把时间信息缓存,其他信息无所谓
  99. p.oneLineSubDialogueParser0(matched, &subFileInfo)
  100. if p.detectOneOrTwoLineDialogue(matched, mapByValue) == true {
  101. // 情况1
  102. usefullyDialogueCount, countLineFeed = p.oneLineSubDialogueParser1(matched, mapByValue, &subFileInfo)
  103. } else {
  104. // 情况2
  105. usefullyDialogueCount, countLineFeed = p.oneLineSubDialogueParser2(matched, mapByValue, &subFileInfo)
  106. }
  107. // 再分析
  108. // 需要判断每一个 Line 是啥语言,[语言的code]次数
  109. var langDict map[int]int
  110. langDict = make(map[int]int)
  111. // 抽取出所有的中文对话
  112. var chLines = make([]string, 0)
  113. // 抽取出所有的第二语言对话
  114. var otherLines = make([]string, 0)
  115. // 抽取出来的对话数组,为了后续用来匹配和修改时间轴
  116. var usefulDialogueExs = make([]subparser.OneDialogueEx, 0)
  117. // 在这之前需要把 subFileInfo.DialoguesFilter 的内容填好,Lines 这里如果是单种语言应该就是一个元素,如果是双语就需要拆分成两个元素
  118. // 这样向后传递就简单了,也统一了
  119. emptyLines := 0
  120. for _, dialogue := range subFileInfo.DialoguesFilter {
  121. emptyLines += language.DetectSubLangAndStatistics(dialogue, langDict, &usefulDialogueExs, &chLines, &otherLines)
  122. }
  123. // 从统计出来的字典,找出 Top 1 或者 2 的出来,然后计算出是什么语言的字幕
  124. detectLang := language.SubLangStatistics2SubLangType(float32(countLineFeed), float32(usefullyDialogueCount-emptyLines), langDict, chLines)
  125. subFileInfo.Lang = detectLang
  126. subFileInfo.Data = inBytes
  127. subFileInfo.DialoguesFilterEx = usefulDialogueExs
  128. subFileInfo.CHLines = chLines
  129. subFileInfo.OtherLines = otherLines
  130. return true, &subFileInfo, nil
  131. }
  132. // oneLineSubDialogueParser0 情况 0 时候的解析器,不过滤,只要是对白都加进去
  133. func (p Parser) oneLineSubDialogueParser0(matched [][]string, subFileInfo *subparser.FileInfo) {
  134. for _, oneLine := range matched {
  135. startTime := oneLine[1]
  136. endTime := oneLine[2]
  137. nowStyleName := oneLine[3]
  138. nowText := oneLine[4]
  139. odl := subparser.OneDialogue{
  140. StyleName: nowStyleName,
  141. StartTime: startTime,
  142. EndTime: endTime,
  143. Lines: []string{nowText},
  144. }
  145. subFileInfo.Dialogues = append(subFileInfo.Dialogues, odl)
  146. }
  147. }
  148. // oneLineSubDialogueParser1 情况 1 时候的解析器
  149. func (p Parser) oneLineSubDialogueParser1(matched [][]string, mapByValue StyleNameInfos, subFileInfo *subparser.FileInfo) (int, int) {
  150. var countLineFeed = 0
  151. var usefullyDialogueCount = 0
  152. // 先读取一次字幕文件
  153. for _, oneLine := range matched {
  154. if len(oneLine) < 1 {
  155. continue
  156. }
  157. // 排除特效内容,只统计有意义的对话部分
  158. if strings.Contains(oneLine[0], mapByValue[0].Name) == false {
  159. continue
  160. }
  161. usefullyDialogueCount++
  162. startTime := oneLine[1]
  163. endTime := oneLine[2]
  164. nowStyleName := oneLine[3]
  165. nowText := oneLine[4]
  166. odl := subparser.OneDialogue{
  167. StyleName: nowStyleName,
  168. StartTime: startTime,
  169. EndTime: endTime,
  170. }
  171. odl.Lines = make([]string, 0)
  172. countLineFeed = p.parseOneDialogueText(nowText, &odl, countLineFeed)
  173. subFileInfo.DialoguesFilter = append(subFileInfo.DialoguesFilter, odl)
  174. }
  175. return usefullyDialogueCount, countLineFeed
  176. }
  177. // oneLineSubDialogueParser2 情况 2 时候的解析器
  178. func (p Parser) oneLineSubDialogueParser2(matched [][]string, mapByValue StyleNameInfos, subFileInfo *subparser.FileInfo) (int, int) {
  179. var countLineFeed = 0
  180. var usefullyDialogueCount = 0
  181. //var timeMap = make(map[string]subparser.OneDialogue, 0)
  182. // 更换数据结构的原因是为了能够使用顺序,go 内置的 map 不是顺序的,是随机的,会导致后续的逻辑出问题
  183. var timeMap = treemap.NewWithStringComparator()
  184. // 先读取一次字幕文件
  185. for _, oneLine := range matched {
  186. usefullyDialogueCount++
  187. // 这里可能会统计到特效的部分,但是这里忽略这个问题,因为目标不是这个
  188. // 统计 Dialogue 的开始和结束时间
  189. startTime := oneLine[1]
  190. endTime := oneLine[2]
  191. nowStyleName := oneLine[3]
  192. nowText := oneLine[4]
  193. mergeTime := startTime + "_" + endTime
  194. value, ok := timeMap.Get(mergeTime)
  195. if ok == false {
  196. // 首次新增
  197. odl := subparser.OneDialogue{
  198. StyleName: nowStyleName,
  199. StartTime: startTime,
  200. EndTime: endTime,
  201. }
  202. odl.Lines = make([]string, 0)
  203. countLineFeed = p.parseOneDialogueText(nowText, &odl, countLineFeed)
  204. timeMap.Put(mergeTime, odl)
  205. } else {
  206. // 双语
  207. odl := value.(subparser.OneDialogue)
  208. countLineFeed = p.parseOneDialogueText(nowText, &odl, countLineFeed)
  209. timeMap.Put(mergeTime, odl)
  210. }
  211. }
  212. for _, value := range timeMap.Values() {
  213. odl := value.(subparser.OneDialogue)
  214. subFileInfo.DialoguesFilter = append(subFileInfo.DialoguesFilter, odl)
  215. }
  216. return usefullyDialogueCount, countLineFeed
  217. }
  218. // parseOneDialogueText 对话的对白内容解析
  219. func (p Parser) parseOneDialogueText(nowText string, odl *subparser.OneDialogue, countLineFeed int) int {
  220. // nowText 优先移除 \h 这个是替换空格, \h 是让两个词在一行,不换行显示
  221. nowText = strings.ReplaceAll(nowText, `\h`, " ")
  222. // nowText 这个需要先把 {} 花括号内的内容给移除
  223. nowText1 := regex_things.ReMatchBrace.ReplaceAllString(nowText, "")
  224. nowText1 = regex_things.ReMatchBracket.ReplaceAllString(nowText1, "")
  225. nowText1 = strings.TrimRight(nowText1, "\r")
  226. // 然后判断是否有 \N 或者 \n
  227. // 直接把 \n 替换为 \N 来解析
  228. nowText1 = strings.ReplaceAll(nowText1, `\n`, `\N`)
  229. if strings.Contains(nowText1, `\N`) {
  230. // 有,那么就需要再次切割,一般是双语字幕
  231. for _, matched2 := range regex_things.ReCutDoubleLanguage.FindAllStringSubmatch(nowText1, -1) {
  232. if matched2 == nil {
  233. continue
  234. }
  235. for i, s := range matched2 {
  236. if i == 0 {
  237. continue
  238. }
  239. s = strings.ReplaceAll(s, `\N`, "")
  240. odl.Lines = append(odl.Lines, s)
  241. }
  242. }
  243. countLineFeed++
  244. } else {
  245. // 无,则可以直接添加
  246. nowText1 = strings.ReplaceAll(nowText1, `\N`, "")
  247. odl.Lines = append(odl.Lines, nowText1)
  248. }
  249. return countLineFeed
  250. }
  251. // detectOneOrTwoLineDialogue 优先检测一次字幕文件,可能存在的双语字幕的情况,是 1 还是 2 ,详细解释看调用此函数前的解释
  252. func (p Parser) detectOneOrTwoLineDialogue(matched [][]string, mapByValue StyleNameInfos) bool {
  253. if mapByValue.Len() == 1 {
  254. // 如果只有一个类型,那么直接返回 true
  255. return true
  256. }
  257. /*
  258. 初版的方案:
  259. 这里判断的方法粗暴一点,直接判断两个 Dialogue 都是一个时间段的比例是多少,达到了就是情况2,不是就是情况1
  260. 实现的方式是用一个 map 来存储,key 是时间段,如果重复出现相同 key,那么就认为是双语字幕,出现两句话,切时间轴一致
  261. */
  262. allDialogue := len(matched)
  263. twoLine := 0
  264. var timeMap = make(map[string]int, 0)
  265. // 先读取一次字幕文件
  266. for _, oneLine := range matched {
  267. // 这里可能会统计到特效的部分,但是这里忽略这个问题,因为目标不是这个
  268. // 统计 Dialogue 的开始和结束时间
  269. startTime := oneLine[1]
  270. endTime := oneLine[2]
  271. mergeTime := startTime + "_" + endTime
  272. _, ok := timeMap[mergeTime]
  273. if ok == false {
  274. timeMap[mergeTime] = 1
  275. } else {
  276. timeMap[mergeTime]++
  277. if timeMap[mergeTime] == 2 {
  278. twoLine++
  279. }
  280. }
  281. }
  282. // 目前看到的文件大概再 47% 以上,考虑到更多的“注释”、“特效”,至少有 38% 就够了
  283. per := float64(twoLine) / float64(allDialogue)
  284. if per > 0.38 {
  285. // 使用情况2的字幕分析方式
  286. return false
  287. }
  288. /*
  289. 新版本的方案,相较于初版方案,这里优先考虑排序后 Dialogue 的类型的统计行数
  290. 之所以新增这个判断逻辑,就是因为现在可能出现一种情况,双语字幕:
  291. 00:00:01.000 --> 00:00:02.000 haha
  292. 00:00:01.011 --> 00:00:01.990 哈哈
  293. 这种情况对于老的方案是无法正确区分的,因为时间轴不是一致的,差那么几毫秒,导致 Map 的 Key 无法正确匹配统计
  294. */
  295. /*
  296. 首先可以确认,这里 mapByValue.Len() 肯定不为零,那么这里 else 的可能性就只会是 > 1 的情况
  297. 居然确定没法匹配老方案的双语字幕,那么就只能使用新方案了。
  298. 新方案的思路:
  299. 1. Dialogue 的类型,前两个类型的行数统计要接近,小的除以大的值,要大于90%
  300. 2. 前两个类型的行数统计,要大于 80%,相对于所有的 Dialogue 来说
  301. 如果符合这两个条件,那么就是双语,否则就是单语。
  302. */
  303. if float64(mapByValue[0].Count+mapByValue[1].Count)/float64(allDialogue) < 0.8 {
  304. // 使用情况1的字幕分析方式
  305. return true
  306. } else {
  307. // 因为是按照行数排序的,所以这里可以直接取前两个,前是从大到小排序的
  308. per2 := float64(mapByValue[1].Count) / float64(mapByValue[0].Count)
  309. if per2 > 0.9 {
  310. // 使用情况2的字幕分析方式
  311. return false
  312. } else {
  313. // 使用情况1的字幕分析方式
  314. return true
  315. }
  316. }
  317. }