This commit is contained in:
CDN 2025-04-23 08:01:13 +08:00
parent aedc4a4518
commit 9b0e2ed6dc
Signed by: CDN
GPG key ID: 0C656827F9F80080
15 changed files with 693 additions and 540 deletions

182
internal/format/lrc/lrc.go Normal file
View file

@ -0,0 +1,182 @@
package lrc
import (
"bufio"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"sub-cli/internal/model"
)
// Parse parses an LRC file and returns a Lyrics struct
func Parse(filePath string) (model.Lyrics, error) {
lyrics := model.Lyrics{
Metadata: make(map[string]string),
}
file, err := os.Open(filePath)
if err != nil {
return lyrics, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
metadataRegex := regexp.MustCompile(`\[([\w:]+):(.*?)\]`)
timestampRegex := regexp.MustCompile(`\[(\d+:\d+(?:\.\d+)?)\]`)
for scanner.Scan() {
line := scanner.Text()
// Extract metadata
metadataMatches := metadataRegex.FindAllStringSubmatch(line, -1)
for _, match := range metadataMatches {
if len(match) >= 3 {
key := match[1]
value := match[2]
lyrics.Metadata[key] = value
}
}
// Extract timestamp and content
timestampMatches := timestampRegex.FindAllStringSubmatch(line, -1)
if len(timestampMatches) > 0 {
var timestamps []model.Timestamp
lineContent := line
for _, match := range timestampMatches {
if len(match) >= 2 {
timestamp, err := ParseTimestamp(match[1])
if err == nil {
timestamps = append(timestamps, timestamp)
}
lineContent = strings.Replace(lineContent, match[0], "", 1)
}
}
lineContent = strings.TrimSpace(lineContent)
if lineContent != "" {
for range timestamps {
lyrics.Timeline = append(lyrics.Timeline, timestamps...)
lyrics.Content = append(lyrics.Content, lineContent)
}
}
}
}
return lyrics, nil
}
// ParseTimestamp parses an LRC timestamp string into a Timestamp struct
func ParseTimestamp(timeStr string) (model.Timestamp, error) {
// remove brackets
timeStr = strings.Trim(timeStr, "[]")
parts := strings.Split(timeStr, ":")
var hours, minutes, seconds, milliseconds int
var err error
switch len(parts) {
case 2: // minutes:seconds.milliseconds
minutes, err = strconv.Atoi(parts[0])
if err != nil {
return model.Timestamp{}, err
}
secParts := strings.Split(parts[1], ".")
seconds, err = strconv.Atoi(secParts[0])
if err != nil {
return model.Timestamp{}, err
}
if len(secParts) > 1 {
milliseconds, err = strconv.Atoi(secParts[1])
if err != nil {
return model.Timestamp{}, err
}
// adjust milliseconds based on the number of digits
switch len(secParts[1]) {
case 1:
milliseconds *= 100
case 2:
milliseconds *= 10
}
}
case 3: // hours:minutes:seconds.milliseconds
hours, err = strconv.Atoi(parts[0])
if err != nil {
return model.Timestamp{}, err
}
minutes, err = strconv.Atoi(parts[1])
if err != nil {
return model.Timestamp{}, err
}
secParts := strings.Split(parts[2], ".")
seconds, err = strconv.Atoi(secParts[0])
if err != nil {
return model.Timestamp{}, err
}
if len(secParts) > 1 {
milliseconds, err = strconv.Atoi(secParts[1])
if err != nil {
return model.Timestamp{}, err
}
// adjust milliseconds based on the number of digits
switch len(secParts[1]) {
case 1:
milliseconds *= 100
case 2:
milliseconds *= 10
}
}
default:
return model.Timestamp{}, fmt.Errorf("invalid timestamp format: %s", timeStr)
}
return model.Timestamp{
Hours: hours,
Minutes: minutes,
Seconds: seconds,
Milliseconds: milliseconds,
}, nil
}
// Generate generates an LRC file from a Lyrics struct
func Generate(lyrics model.Lyrics, filePath string) error {
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
// Write metadata
for key, value := range lyrics.Metadata {
fmt.Fprintf(file, "[%s:%s]\n", key, value)
}
// Write content with timestamps
for i, content := range lyrics.Content {
if i < len(lyrics.Timeline) {
timestamp := lyrics.Timeline[i]
fmt.Fprintf(file, "[%02d:%02d.%03d]%s\n",
timestamp.Minutes,
timestamp.Seconds,
timestamp.Milliseconds,
content)
} else {
fmt.Fprintln(file, content)
}
}
return nil
}
// Format formats an LRC file
func Format(filePath string) error {
lyrics, err := Parse(filePath)
if err != nil {
return err
}
return Generate(lyrics, filePath)
}

137
internal/format/srt/srt.go Normal file
View file

@ -0,0 +1,137 @@
package srt
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"time"
"sub-cli/internal/model"
)
// Parse parses an SRT file and returns a slice of SRTEntries
func Parse(filePath string) ([]model.SRTEntry, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
var entries []model.SRTEntry
var currentEntry model.SRTEntry
var isContent bool
var contentBuffer strings.Builder
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
if currentEntry.Number != 0 {
currentEntry.Content = contentBuffer.String()
entries = append(entries, currentEntry)
currentEntry = model.SRTEntry{}
isContent = false
contentBuffer.Reset()
}
continue
}
if currentEntry.Number == 0 {
currentEntry.Number, _ = strconv.Atoi(line)
} else if isEntryTimeStampUnset(currentEntry) {
times := strings.Split(line, " --> ")
if len(times) == 2 {
currentEntry.StartTime = parseSRTTimestamp(times[0])
currentEntry.EndTime = parseSRTTimestamp(times[1])
isContent = true
}
} else if isContent {
if contentBuffer.Len() > 0 {
contentBuffer.WriteString("\n")
}
contentBuffer.WriteString(line)
}
}
// Don't forget the last entry
if currentEntry.Number != 0 && contentBuffer.Len() > 0 {
currentEntry.Content = contentBuffer.String()
entries = append(entries, currentEntry)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return entries, nil
}
// isEntryTimeStampUnset checks if timestamp is unset
func isEntryTimeStampUnset(entry model.SRTEntry) bool {
return entry.StartTime.Hours == 0 &&
entry.StartTime.Minutes == 0 &&
entry.StartTime.Seconds == 0 &&
entry.StartTime.Milliseconds == 0
}
// parseSRTTimestamp parses an SRT timestamp string into a Timestamp struct
func parseSRTTimestamp(timeStr string) model.Timestamp {
timeStr = strings.Replace(timeStr, ",", ".", 1)
format := "15:04:05.000"
t, err := time.Parse(format, timeStr)
if err != nil {
return model.Timestamp{}
}
return model.Timestamp{
Hours: t.Hour(),
Minutes: t.Minute(),
Seconds: t.Second(),
Milliseconds: t.Nanosecond() / 1000000,
}
}
// Generate generates an SRT file from a slice of SRTEntries
func Generate(entries []model.SRTEntry, filePath string) error {
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
for _, entry := range entries {
fmt.Fprintf(file, "%d\n", entry.Number)
fmt.Fprintf(file, "%s --> %s\n",
formatSRTTimestamp(entry.StartTime),
formatSRTTimestamp(entry.EndTime))
fmt.Fprintf(file, "%s\n\n", entry.Content)
}
return nil
}
// formatSRTTimestamp formats a Timestamp struct as an SRT timestamp string
func formatSRTTimestamp(ts model.Timestamp) string {
return fmt.Sprintf("%02d:%02d:%02d,%03d",
ts.Hours,
ts.Minutes,
ts.Seconds,
ts.Milliseconds)
}
// ConvertToLyrics converts SRT entries to a Lyrics structure
func ConvertToLyrics(entries []model.SRTEntry) model.Lyrics {
lyrics := model.Lyrics{
Metadata: make(map[string]string),
}
for _, entry := range entries {
lyrics.Timeline = append(lyrics.Timeline, entry.StartTime)
lyrics.Content = append(lyrics.Content, entry.Content)
}
return lyrics
}