Files
podcast-search-go/utils/json_parser.go
2025-03-28 22:27:08 +08:00

92 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package utils 提供工具函数
package utils
import (
"encoding/json"
"fmt"
"time"
"gitea.malaihome.work/ans/podcast_search/model"
)
// JsonParser 用于解析JSON格式的转录文件
type JsonParser struct{}
// NewJsonParser 创建新的JSON解析器
func NewJsonParser() *JsonParser {
return &JsonParser{}
}
// Parse 解析JSON格式的转录文件
func (p *JsonParser) Parse(jsonData string) (*model.Transcript, error) {
// 解析JSON
var data map[string]interface{}
if err := json.Unmarshal([]byte(jsonData), &data); err != nil {
return nil, fmt.Errorf("解析JSON失败: %w", err)
}
// 创建转录
transcript := &model.Transcript{
Subtitles: make([]model.Subtitle, 0),
}
// 解析版本
_, ok := data["version"].(string)
if !ok {
return nil, fmt.Errorf("无效的JSON格式: 缺少版本信息")
}
// 解析段落
segments, ok := data["segments"].([]interface{})
if !ok {
return nil, fmt.Errorf("无效的JSON格式: 缺少段落信息")
}
// 解析每个段落
for i, segment := range segments {
seg, ok := segment.(map[string]interface{})
if !ok {
continue
}
// 解析开始时间
startTime, ok := seg["startTime"].(float64)
if !ok {
continue
}
// 解析结束时间
endTime, ok := seg["endTime"].(float64)
if !ok {
continue
}
// 解析内容
body, ok := seg["body"].(string)
if !ok {
continue
}
// 解析发言人
speaker := ""
if s, ok := seg["speaker"].(string); ok {
speaker = s
}
// 创建字幕
subtitle := model.Subtitle{
Index: i,
Start: time.Duration(startTime * float64(time.Second)),
End: time.Duration(endTime * float64(time.Second)),
Data: body,
Speaker: speaker,
}
transcript.Subtitles = append(transcript.Subtitles, subtitle)
}
// 我们已经解析了版本信息但Transcript结构体中没有Version字段
// 所以这里只返回解析好的transcript对象
return transcript, nil
}