Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
refactor: remove old complex short subtitle functions
wulien43e6497f5c9d
diff --git a/internal/service/youtube_subtitle.go b/internal/service/youtube_subtitle.goindex cd20f2b5..35611754 100644--- a/internal/service/youtube_subtitle.go+++ b/internal/service/youtube_subtitle.go@@ -997,9 +997,12 @@ func (s *YouTubeSubtitleService) writeVttWordsToSrt(vttWords []VttWord, srtFile// 步骤7: 生成短字幕文件shortSrtFile := filepath.Join(filepath.Dir(srtFile), types.SubtitleTaskShortOriginMixedSrtFileName)- err = s.writeShortMixedSrtFile(srtBlocks, shortSrtFile, sentences)+ err = s.writeShortSubtitleFile(srtBlocks, sentences, shortSrtFile, req.TargetLanguageFirst)if err != nil {- return err+ log.GetLogger().Warn("生成短字幕失败", zap.Error(err))+ // 不影响主流程,继续执行+ } else {+ log.GetLogger().Info("生成短字幕完成", zap.String("文件", shortSrtFile))}// 最终更新进度到90%(所有操作完成)@@ -2244,144 +2247,6 @@ func (s *YouTubeSubtitleService) generateTextFiles(blocks []*util.SrtBlock, origreturn nil}-// writeShortMixedSrtFile 生成短字幕文件,基于已拆分的长字幕SRT块-func (s *YouTubeSubtitleService) writeShortMixedSrtFile(srtBlocks []*util.SrtBlock, shortSrtFile string, sentences []Sentence) error {- file, err := os.Create(shortSrtFile)- if err != nil {- return fmt.Errorf("failed to create short SRT file: %w", err)- }- defer file.Close()-- blockIndex := 1- wordsPerSegment := 6 // 每个短字幕显示的单词数量-- // 添加usedIndices跟踪已使用的VTT单词- allWords := s.getAllWordsFromSentences(sentences)- usedIndices := make(map[int]bool)-- for _, srtBlock := range srtBlocks {- // 先写入完整的目标语言字幕块(中文翻译)- if srtBlock.TargetLanguageSentence != "" {- _, err = file.WriteString(fmt.Sprintf("%d\n", blockIndex))- if err != nil {- return err- }-- _, err = file.WriteString(srtBlock.Timestamp + "\n")- if err != nil {- return err- }-- _, err = file.WriteString(srtBlock.TargetLanguageSentence + "\n\n")- if err != nil {- return err- }- blockIndex++- }-- // 处理对应的原始语言(英文),按单词拆分- if srtBlock.OriginLanguageSentence != "" {- // 将原始语言句子按空格分割成单词,并清理多余的引号- originText := strings.TrimSpace(srtBlock.OriginLanguageSentence)- // 清理开头和结尾的多余引号- originText = strings.Trim(originText, `"'`)- words := strings.Fields(originText)-- // 找到整个SRT块对应的VttWord序列,使用跟踪版本避免重复匹配- correspondingVttWords := s.findCorrespondingWordsWithTracking(srtBlock, allWords, usedIndices)-- log.GetLogger().Debug("Processing SRT block for short subtitles",- zap.String("originText", originText),- zap.Int("wordsCount", len(words)),- zap.Int("correspondingVttWordsCount", len(correspondingVttWords)))-- // 按指定数量拆分单词- for wordStart := 0; wordStart < len(words); wordStart += wordsPerSegment {- wordEnd := wordStart + wordsPerSegment- if wordEnd > len(words) {- wordEnd = len(words)- }-- segmentWords := words[wordStart:wordEnd]- if len(segmentWords) == 0 {- continue- }-- segmentText := strings.Join(segmentWords, " ")-- // 计算这个片段对应的VTT单词时间戳- var srtTimestamp string- if len(correspondingVttWords) > 0 && len(words) > 0 {- // 计算片段在整个SRT块中的相对位置- startRatio := float64(wordStart) / float64(len(words))- endRatio := float64(wordEnd) / float64(len(words))-- // 映射到correspondingVttWords中的位置- vttStartIdx := int(startRatio * float64(len(correspondingVttWords)))- vttEndIdx := int(endRatio * float64(len(correspondingVttWords)))-- // 确保索引在有效范围内- if vttStartIdx >= len(correspondingVttWords) {- vttStartIdx = len(correspondingVttWords) - 1- }- if vttEndIdx > len(correspondingVttWords) {- vttEndIdx = len(correspondingVttWords)- }- if vttEndIdx <= vttStartIdx {- vttEndIdx = vttStartIdx + 1- }-- // 获取时间戳- startTime := correspondingVttWords[vttStartIdx].Start- endTime := correspondingVttWords[vttEndIdx-1].End-- log.GetLogger().Debug("Calculated segment timestamps",- zap.String("segmentText", segmentText),- zap.Int("vttStartIdx", vttStartIdx),- zap.Int("vttEndIdx", vttEndIdx),- zap.String("startTime", startTime),- zap.String("endTime", endTime))-- var err error- srtTimestamp, err = s.convertToSrtTimestamp(startTime, endTime)- if err != nil {- srtTimestamp = srtBlock.Timestamp- log.GetLogger().Warn("Failed to convert timestamp, using SRT block timestamp", zap.Error(err))- }- } else {- // Fallback到SRT块时间戳- srtTimestamp = srtBlock.Timestamp- log.GetLogger().Warn("No corresponding VTT words found, using SRT block timestamp",- zap.Int("correspondingVttWordsCount", len(correspondingVttWords)),- zap.Int("wordsCount", len(words)))- }-- // 写入源语言片段- _, err = file.WriteString(fmt.Sprintf("%d\n", blockIndex))- if err != nil {- return err- }-- _, err = file.WriteString(srtTimestamp + "\n")- if err != nil {- return err- }-- _, err = file.WriteString(segmentText + "\n\n")- if err != nil {- return err- }- blockIndex++- }- }- }-- log.GetLogger().Info("Short mixed SRT file written successfully",- zap.String("文件", shortSrtFile),- zap.Int("总块数", blockIndex-1))-- return nil-}// findVttWordsForText 根据文本内容在句子中找到对应的VttWordfunc (s *YouTubeSubtitleService) findVttWordsForText(text string, sentences []Sentence) []VttWord {@@ -2468,138 +2333,6 @@ func (s *YouTubeSubtitleService) findVttWordsForSrtBlock(return []VttWord{}}-// getAllWordsFromSentences 从所有句子中获取所有单词的扁平列表-func (s *YouTubeSubtitleService) getAllWordsFromSentences(sentences []Sentence) []VttWord {- var allWords []VttWord- for _, sentence := range sentences {- allWords = append(allWords, sentence.Words...)- }- return allWords-}--// findCorrespondingWords 根据SRT块的原始文本找到对应的原始单词-func (s *YouTubeSubtitleService) findCorrespondingWords(srtBlock *util.SrtBlock, allWords []VttWord) []VttWord {- if srtBlock.OriginLanguageSentence == "" {- return []VttWord{}- }-- // 基于文本内容匹配,而不是时间戳匹配- originText := strings.TrimSpace(srtBlock.OriginLanguageSentence)- // 清理开头和结尾的引号- originText = strings.Trim(originText, `"'`)-- // 将原始文本按空格分割成单词- expectedWords := strings.Fields(originText)- if len(expectedWords) == 0 {- return []VttWord{}- }-- log.GetLogger().Debug("Finding corresponding words",- zap.String("originText", originText),- zap.Int("expectedWordsCount", len(expectedWords)),- zap.Int("allWordsCount", len(allWords)))-- // 在所有单词中查找匹配的序列- var correspondingWords []VttWord-- for i := 0; i <= len(allWords)-len(expectedWords); i++ {- // 检查从位置i开始是否匹配expectedWords序列- match := true- candidateWords := make([]VttWord, len(expectedWords))-- for j, expectedWord := range expectedWords {- if i+j >= len(allWords) {- match = false- break- }-- actualWord := strings.TrimSpace(allWords[i+j].Text)- // 移除标点符号进行比较- expectedWordClean := strings.Trim(expectedWord, ".,!?;:")- actualWordClean := strings.Trim(actualWord, ".,!?;:")-- if !strings.EqualFold(expectedWordClean, actualWordClean) {- match = false- break- }- candidateWords[j] = allWords[i+j]- }-- if match {- correspondingWords = candidateWords- break- }- }-- log.GetLogger().Debug("Found corresponding words",- zap.String("originText", originText),- zap.Int("foundWords", len(correspondingWords)))-- return correspondingWords-}--// findCorrespondingWordsWithTracking 根据SRT块的原始文本找到对应的原始单词,并追踪已使用的单词-func (s *YouTubeSubtitleService) findCorrespondingWordsWithTracking(srtBlock *util.SrtBlock, allWords []VttWord, usedIndices map[int]bool) []VttWord {- if srtBlock.OriginLanguageSentence == "" {- return []VttWord{}- }-- // 基于文本内容匹配- originText := strings.TrimSpace(srtBlock.OriginLanguageSentence)- expectedWords := strings.Fields(originText)- if len(expectedWords) == 0 {- return []VttWord{}- }-- // 在所有单词中查找匹配的序列,跳过已使用的单词- var correspondingWords []VttWord-- for i := 0; i <= len(allWords)-len(expectedWords); i++ {- // 跳过已使用的起始位置- if usedIndices[i] {- continue- }-- // 检查从位置i开始是否匹配expectedWords序列- match := true- candidateWords := make([]VttWord, len(expectedWords))- candidateIndices := make([]int, len(expectedWords))-- for j, expectedWord := range expectedWords {- wordIndex := i + j- if wordIndex >= len(allWords) || usedIndices[wordIndex] {- match = false- break- }-- actualWord := strings.TrimSpace(allWords[wordIndex].Text)- expectedWordClean := strings.Trim(expectedWord, ".,!?;:")- actualWordClean := strings.Trim(actualWord, ".,!?;:")-- if !strings.EqualFold(expectedWordClean, actualWordClean) {- match = false- break- }- candidateWords[j] = allWords[wordIndex]- candidateIndices[j] = wordIndex- }-- if match {- correspondingWords = candidateWords- // 标记这些单词为已使用- for _, idx := range candidateIndices {- usedIndices[idx] = true- }- break- }- }-- log.GetLogger().Debug("Found corresponding words with tracking",- zap.String("originText", originText),- zap.Int("foundWords", len(correspondingWords)))-- return correspondingWords-}// parseSrtTimestamp 解析SRT时间戳格式 "HH:MM:SS,mmm --> HH:MM:SS,mmm"func (s *YouTubeSubtitleService) parseSrtTimestamp(timestamp string) (float64, float64, error) {