Spaces:
Sleeping
Sleeping
File size: 3,848 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 | 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 IdeaGenerationService : IIdeaGenerationService
{
private readonly IOpenAiClient _openAi;
private readonly IVideoIdeaRepository _ideaRepository;
private readonly ILogger<IdeaGenerationService> _logger;
public IdeaGenerationService(IOpenAiClient openAi, IVideoIdeaRepository ideaRepository, ILogger<IdeaGenerationService> logger)
{
_openAi = openAi;
_ideaRepository = ideaRepository;
_logger = logger;
}
public async Task<VideoIdea> GenerateIdeaAsync(string niche, string platform = "tiktok", CancellationToken ct = default)
{
var ideas = await GenerateBatchIdeasAsync(niche, 1, platform, ct);
return ideas.First();
}
public async Task<IReadOnlyList<VideoIdea>> GenerateBatchIdeasAsync(string niche, int count = 5, string platform = "tiktok", CancellationToken ct = default)
{
_logger.LogInformation("Generating {Count} video ideas for niche '{Niche}' on {Platform}", count, niche, platform);
var systemPrompt = @"Você é um estrategista de conteúdo viral especializado em TikTok/Reels/Shorts no Brasil.
REGRAS:
1. Cada ideia DEVE ser baseada em um FATO REAL, ESPECÍFICO e SURPREENDENTE
2. O título deve ser curto, impactante e gerar curiosidade IMEDIATA (estilo clickbait mas verdadeiro)
3. O hook deve ser uma frase que CHOCA nos primeiros 2 segundos - um fato que a pessoa não sabia
4. Use linguagem brasileira informal
Responda APENAS com um JSON array:
[{""topic"": ""tema específico e detalhado"", ""title"": ""título viral em português (max 50 chars)"", ""hook"": ""frase de abertura chocante em português"", ""targetAudience"": ""público alvo"", ""tags"": ""hashtags separadas por vírgula""}]";
var userPrompt = $@"Gere {count} ideias de vídeo VIRAL sobre: '{niche}'
Plataforma: {platform}
IMPORTANTE: Cada ideia deve revelar algo que 99% das pessoas NÃO sabem sobre o tema. Fatos de bastidores, polêmicas, números absurdos, coincidências malucas. Seja ESPECÍFICO.";
var response = await _openAi.GenerateChatCompletionAsync(systemPrompt, userPrompt, ct);
var jsonContent = ExtractJson(response);
var ideasData = JsonSerializer.Deserialize<List<IdeaDto>>(jsonContent, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}) ?? [];
var ideas = new List<VideoIdea>();
foreach (var dto in ideasData)
{
var idea = new VideoIdea
{
Topic = dto.Topic ?? niche,
Title = dto.Title ?? "Untitled",
Hook = dto.Hook ?? "",
TargetAudience = dto.TargetAudience ?? "general",
Platform = platform,
Niche = niche,
Tags = dto.Tags,
Status = "pending"
};
await _ideaRepository.AddAsync(idea, ct);
ideas.Add(idea);
}
_logger.LogInformation("Generated {Count} ideas successfully", ideas.Count);
return ideas;
}
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 IdeaDto(string? Topic, string? Title, string? Hook, string? TargetAudience, string? Tags);
}
|