File size: 6,856 Bytes
8fb6238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35a656e
56d8c4f
8fb6238
 
 
56d8c4f
 
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
using System.Text.Json;
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 VideoAssemblyService : IVideoAssemblyService
{
    private readonly IVideoScriptRepository _scriptRepository;
    private readonly IRepository<VoiceAsset> _voiceRepository;
    private readonly IVideoAssetRepository _videoAssetRepository;
    private readonly IFfmpegService _ffmpeg;
    private readonly IStockMediaService _stockMedia;
    private readonly ISubtitleService _subtitleService;
    private readonly StorageSettings _storage;
    private readonly ILogger<VideoAssemblyService> _logger;

    public VideoAssemblyService(
        IVideoScriptRepository scriptRepository,
        IRepository<VoiceAsset> voiceRepository,
        IVideoAssetRepository videoAssetRepository,
        IFfmpegService ffmpeg,
        IStockMediaService stockMedia,
        ISubtitleService subtitleService,
        IOptions<StorageSettings> storage,
        ILogger<VideoAssemblyService> logger)
    {
        _scriptRepository = scriptRepository;
        _voiceRepository = voiceRepository;
        _videoAssetRepository = videoAssetRepository;
        _ffmpeg = ffmpeg;
        _stockMedia = stockMedia;
        _subtitleService = subtitleService;
        _storage = storage.Value;
        _logger = logger;
    }

    public async Task<VideoAsset> AssembleVideoAsync(Guid scriptId, CancellationToken ct = default)
    {
        var script = await _scriptRepository.GetByIdAsync(scriptId, ct)
            ?? throw new InvalidOperationException($"Script {scriptId} not found");

        _logger.LogInformation("Starting video assembly for script {ScriptId}", scriptId);

        // Create video asset record
        var videoAsset = new VideoAsset
        {
            VideoScriptId = scriptId,
            Status = "processing"
        };
        await _videoAssetRepository.AddAsync(videoAsset, ct);

        try
        {
            // 1. Get voice asset (should already exist)
            var voiceAssets = await _voiceRepository.GetAllAsync(ct);
            var voiceAsset = voiceAssets.FirstOrDefault(v => v is VoiceAsset va && va.VideoScriptId == scriptId) as VoiceAsset
                ?? throw new InvalidOperationException($"Voice asset not found for script {scriptId}. Generate voice first.");

            // 2. Download background clips from YouTube
            var scenes = ParseScenes(script.Scenes);
            var tempDir = Path.Combine(_storage.BasePath, _storage.TempFolder, videoAsset.Id.ToString());
            Directory.CreateDirectory(tempDir);

            var backgroundClips = new List<string>();

            // Use the first 2 most specific scene descriptions as search queries
            var searchQueries = scenes.Take(4).ToList();
            
            foreach (var query in searchQueries)
            {
                if (backgroundClips.Count >= 12) break;
                var neededPerQuery = Math.Max(3, (12 - backgroundClips.Count));
                var clips = await _stockMedia.DownloadMultipleVideosAsync(query, neededPerQuery, tempDir, ct);
                backgroundClips.AddRange(clips);
            }

            // If still not enough, try a broader search with the topic
            if (backgroundClips.Count < 3)
            {
                var idea = await _scriptRepository.GetByIdAsync(scriptId, ct);
                var broadQuery = script.ScriptText[..Math.Min(60, script.ScriptText.Length)];
                var extras = await _stockMedia.DownloadMultipleVideosAsync(broadQuery, 4, tempDir, ct);
                backgroundClips.AddRange(extras);
            }

            if (backgroundClips.Count == 0)
                throw new InvalidOperationException("Could not download any background clips for the video.");

            // 3. Assemble video
            var videoDir = Path.Combine(_storage.BasePath, _storage.VideoFolder);
            Directory.CreateDirectory(videoDir);

            var rawVideoPath = Path.Combine(videoDir, $"{videoAsset.Id}_raw.mp4");
            await _ffmpeg.AssembleVerticalVideoAsync(voiceAsset.FilePath, backgroundClips, rawVideoPath, ct);

            // 4. Generate subtitles
            var duration = await _ffmpeg.GetMediaDurationAsync(rawVideoPath, ct);
            videoAsset.DurationSeconds = duration;
            await _videoAssetRepository.UpdateAsync(videoAsset, ct);

            var captionAsset = await _subtitleService.GenerateSubtitlesAsync(videoAsset.Id, ct);

            // 5. Burn subtitles into video
            var finalVideoPath = Path.Combine(videoDir, $"{videoAsset.Id}.mp4");
            await _ffmpeg.AddSubtitlesToVideoAsync(rawVideoPath, captionAsset.SrtFilePath, finalVideoPath, ct);

            // 6. Generate thumbnail
            var thumbDir = Path.Combine(_storage.BasePath, _storage.ThumbnailFolder);
            Directory.CreateDirectory(thumbDir);
            var thumbPath = Path.Combine(thumbDir, $"{videoAsset.Id}.jpg");
            await _ffmpeg.GenerateThumbnailAsync(finalVideoPath, thumbPath, ct: ct);

            // 7. Update video asset
            var fileInfo = new FileInfo(finalVideoPath);
            videoAsset.FilePath = finalVideoPath;
            videoAsset.ThumbnailPath = thumbPath;
            videoAsset.FileSizeBytes = fileInfo.Length;
            videoAsset.DurationSeconds = await _ffmpeg.GetMediaDurationAsync(finalVideoPath, ct);
            videoAsset.Status = "completed";
            await _videoAssetRepository.UpdateAsync(videoAsset, ct);

            // Cleanup raw video
            if (File.Exists(rawVideoPath))
                File.Delete(rawVideoPath);

            _logger.LogInformation("Video assembly completed: {FilePath}", finalVideoPath);
            return videoAsset;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Video assembly failed for script {ScriptId}", scriptId);
            videoAsset.Status = "failed";
            await _videoAssetRepository.UpdateAsync(videoAsset, ct);
            throw;
        }
    }

    private static List<string> ParseScenes(string scenesJson)
    {
        try
        {
            using var doc = JsonDocument.Parse(scenesJson);
            var scenes = new List<string>();
            foreach (var element in doc.RootElement.EnumerateArray())
            {
                if (element.TryGetProperty("description", out var desc))
                    scenes.Add(desc.GetString() ?? "nature");
            }
            return scenes.Count > 0 ? scenes : ["nature", "city", "technology"];
        }
        catch
        {
            return ["nature", "city", "technology"];
        }
    }
}