Spaces:
Sleeping
Sleeping
Download src/ClipForge.Infrastructure/Services/ScriptGenerationService.cs from clipeforge/app: direct link, hf CLI and curl.
- Browser
- Download file 5.86 kB
-
https://huggingface.co/spaces/clipeforge/app/resolve/main/src/ClipForge.Infrastructure/Services/ScriptGenerationService.cs
- Command line
-
hf download hf://spaces/clipeforge/app/src/ClipForge.Infrastructure/Services/ScriptGenerationService.cs
-
curl -L -o ScriptGenerationService.cs https://huggingface.co/spaces/clipeforge/app/resolve/main/src/ClipForge.Infrastructure/Services/ScriptGenerationService.cs
5.86 kB
| 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); | |
| } | |