File size: 5,858 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
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
using System.Text.Json;
using ClipForge.Core.Entities;
using ClipForge.Core.Interfaces;
using ClipForge.Core.Interfaces.Services;
using Microsoft.Extensions.Logging;

namespace ClipForge.Infrastructure.Services;

public class ScriptGenerationService : IScriptGenerationService
{
    private readonly IOpenAiClient _openAi;
    private readonly IVideoIdeaRepository _ideaRepository;
    private readonly IVideoScriptRepository _scriptRepository;
    private readonly ILogger<ScriptGenerationService> _logger;

    public ScriptGenerationService(
        IOpenAiClient openAi,
        IVideoIdeaRepository ideaRepository,
        IVideoScriptRepository scriptRepository,
        ILogger<ScriptGenerationService> logger)
    {
        _openAi = openAi;
        _ideaRepository = ideaRepository;
        _scriptRepository = scriptRepository;
        _logger = logger;
    }

    public async Task<VideoScript> GenerateScriptAsync(Guid ideaId, CancellationToken ct = default)
    {
        var idea = await _ideaRepository.GetByIdAsync(ideaId, ct)
            ?? throw new InvalidOperationException($"Video idea {ideaId} not found");

        _logger.LogInformation("Generating script for idea: {Title}", idea.Title);

        var systemPrompt = @"Você é um roteirista de elite. Seus roteiros são usados em vídeos que viralizam com MILHÕES de views no TikTok.

Seu estilo é: IMPACTANTE, RÁPIDO, CHEIO DE INFORMAÇÃO BOMBÁSTICA, como se fosse um documentário da Netflix condensado em 60 segundos.

REGRAS INEGOCIÁVEIS:
1. O roteiro DEVE ter entre 200-300 palavras (50-70 segundos de narração)
2. PRIMEIRA FRASE: Uma bomba. Um fato tão absurdo que a pessoa PARA de rolar o feed. Exemplos: 'O sobrinho do Michael Jackson gastou 3 anos aprendendo a andar EXATAMENTE como o tio pra esse filme.' ou 'Hollywood gastou 150 MILHÕES de dólares pra recontar a vida do maior artista de todos os tempos.'
3. CADA FRASE deve conter um fato novo, um número, um nome, uma revelação. ZERO enrolação.
4. Use CONTRASTE e TENSÃO: 'Mas nem tudo foi fácil...', 'O que ninguém esperava era que...', 'E aqui vem a parte mais insana...'
5. Linguagem: como um narrador de documentário brasileiro falando com um amigo. Informal mas PODEROSO.
6. TERMINE com uma frase que OBRIGA a pessoa a comentar ou compartilhar.
7. NÃO use: 'é muito interessante', 'vale a pena', 'fique ligado', 'se inscreva'. Isso é LIXO.
8. CADA informação deve ser REAL e VERIFICÁVEL.

Para as cenas: gere termos de busca pro YouTube que retornem vídeos VISUAIS do tema (performances, trailers, entrevistas, clipes musicais). NÃO use termos que retornem vídeos de texto/podcast/reaction.

Responda APENAS com JSON:
{
  ""scriptText"": ""narração completa em português brasileiro"",
  ""scenes"": [{""description"": ""termo de busca YouTube"", ""duration"": 8}],
  ""estimatedDurationSeconds"": 55
}";

        var userPrompt = $@"Crie um roteiro NÍVEL HOLLYWOOD sobre:
Tema: {idea.Topic}
Título: {idea.Title}
Gancho: {idea.Hook}
Público: {idea.TargetAudience}
Plataforma: {idea.Platform}

EXIGÊNCIAS ABSOLUTAS:
- Mínimo 8 fatos REAIS e ESPECÍFICOS (nomes completos, datas, valores em dólares, bastidores)
- Primeira frase TÃO impactante que é impossível não assistir
- Ritmo de metralhadora: fato-fato-fato-fato sem pausa
- Linguagem de documentário Netflix narrado por brasileiro
- Cenas: use termos como 'Michael Jackson Thriller performance', 'Michael Jackson moonwalk live', 'Jaafar Jackson dancing' — termos que retornem VÍDEOS VISUAIS no YouTube, não podcasts ou textos
- Mínimo 7 cenas diferentes";

        var response = await _openAi.GenerateChatCompletionAsync(systemPrompt, userPrompt, ct);
        var jsonContent = ExtractJson(response);

        var scriptData = JsonSerializer.Deserialize<ScriptDto>(jsonContent, new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        }) ?? throw new InvalidOperationException("Failed to parse script response");

        var script = new VideoScript
        {
            VideoIdeaId = ideaId,
            ScriptText = scriptData.ScriptText ?? "",
            Scenes = scriptData.Scenes is not null ? JsonSerializer.Serialize(scriptData.Scenes) : "[]",
            EstimatedDurationSeconds = scriptData.EstimatedDurationSeconds > 0 ? scriptData.EstimatedDurationSeconds : 50,
            Tone = "engaging",
            Language = "pt-BR"
        };

        await _scriptRepository.AddAsync(script, ct);

        idea.Status = "scripted";
        await _ideaRepository.UpdateAsync(idea, ct);

        _logger.LogInformation("Script generated for idea {IdeaId}, duration: {Duration}s", ideaId, script.EstimatedDurationSeconds);
        return script;
    }

    public async Task<VideoScript> GenerateScriptFromTopicAsync(string topic, string tone = "engaging", string language = "pt-BR", CancellationToken ct = default)
    {
        var idea = new VideoIdea
        {
            Topic = topic,
            Title = topic,
            Hook = $"Você sabia que {topic}?",
            TargetAudience = "general",
            Platform = "tiktok",
            Status = "pending"
        };

        await _ideaRepository.AddAsync(idea, ct);
        return await GenerateScriptAsync(idea.Id, ct);
    }

    private static string ExtractJson(string response)
    {
        var trimmed = response.Trim();
        if (trimmed.StartsWith("```"))
        {
            var firstNewline = trimmed.IndexOf('\n');
            var lastBackticks = trimmed.LastIndexOf("```");
            if (firstNewline > 0 && lastBackticks > firstNewline)
            {
                trimmed = trimmed[(firstNewline + 1)..lastBackticks].Trim();
            }
        }
        return trimmed;
    }

    private record ScriptDto(string? ScriptText, JsonElement? Scenes, int EstimatedDurationSeconds);
}