File size: 3,918 Bytes
8fb6238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System.Text;
using ClipForge.Core.Entities;
using ClipForge.Core.Interfaces;
using ClipForge.Core.Interfaces.Services;
using ClipForge.Infrastructure.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace ClipForge.Infrastructure.Services;

public class SubtitleService : ISubtitleService
{
    private readonly IVideoAssetRepository _videoAssetRepository;
    private readonly IVideoScriptRepository _scriptRepository;
    private readonly IRepository<CaptionAsset> _captionRepository;
    private readonly StorageSettings _storage;
    private readonly ILogger<SubtitleService> _logger;

    public SubtitleService(
        IVideoAssetRepository videoAssetRepository,
        IVideoScriptRepository scriptRepository,
        IRepository<CaptionAsset> captionRepository,
        IOptions<StorageSettings> storage,
        ILogger<SubtitleService> logger)
    {
        _videoAssetRepository = videoAssetRepository;
        _scriptRepository = scriptRepository;
        _captionRepository = captionRepository;
        _storage = storage.Value;
        _logger = logger;
    }

    public async Task<CaptionAsset> GenerateSubtitlesAsync(Guid videoAssetId, CancellationToken ct = default)
    {
        var videoAsset = await _videoAssetRepository.GetByIdAsync(videoAssetId, ct)
            ?? throw new InvalidOperationException($"Video asset {videoAssetId} not found");

        var script = await _scriptRepository.GetByIdAsync(videoAsset.VideoScriptId, ct)
            ?? throw new InvalidOperationException($"Script not found for video asset {videoAssetId}");

        _logger.LogInformation("Generating subtitles for video asset {VideoAssetId}", videoAssetId);

        var srtContent = await GenerateSrtFromTextAsync(script.ScriptText, videoAsset.DurationSeconds, ct);

        // Save SRT file
        var subtitleDir = Path.Combine(_storage.BasePath, _storage.SubtitleFolder);
        Directory.CreateDirectory(subtitleDir);

        var srtPath = Path.Combine(subtitleDir, $"{videoAssetId}.srt");
        await File.WriteAllTextAsync(srtPath, srtContent, Encoding.UTF8, ct);

        var captionAsset = new CaptionAsset
        {
            VideoAssetId = videoAssetId,
            SrtFilePath = srtPath,
            CaptionStyle = "dynamic",
            FontFamily = "Montserrat",
            FontSize = 48,
            FontColor = "#FFFFFF",
            StrokeColor = "#000000",
            StrokeWidth = 2
        };

        await _captionRepository.AddAsync(captionAsset, ct);

        _logger.LogInformation("Subtitles generated: {SrtPath}", srtPath);
        return captionAsset;
    }

    public Task<string> GenerateSrtFromTextAsync(string text, double totalDuration, CancellationToken ct = default)
    {
        // Split text into segments of ~5-8 words for dynamic captions
        var words = text.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        var segments = new List<string>();
        var wordsPerSegment = 5;

        for (int i = 0; i < words.Length; i += wordsPerSegment)
        {
            var segment = string.Join(" ", words.Skip(i).Take(wordsPerSegment));
            segments.Add(segment);
        }

        var timePerSegment = totalDuration / segments.Count;
        var sb = new StringBuilder();

        for (int i = 0; i < segments.Count; i++)
        {
            var startTime = TimeSpan.FromSeconds(i * timePerSegment);
            var endTime = TimeSpan.FromSeconds((i + 1) * timePerSegment);

            sb.AppendLine((i + 1).ToString());
            sb.AppendLine($"{FormatSrtTime(startTime)} --> {FormatSrtTime(endTime)}");
            sb.AppendLine(segments[i]);
            sb.AppendLine();
        }

        return Task.FromResult(sb.ToString());
    }

    private static string FormatSrtTime(TimeSpan time)
        => $"{time.Hours:D2}:{time.Minutes:D2}:{time.Seconds:D2},{time.Milliseconds:D3}";
}