Spaces:
Sleeping
Sleeping
File size: 22,463 Bytes
36d488d | 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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 | const { Logger } = require('../utils/logger');
const geminiService = require('../utils/gemini-service');
class ScriptWriterAgent {
constructor(db, credentials) {
this.db = db;
this.credentials = credentials;
this.logger = new Logger('ScriptWriter');
this.templates = this.loadTemplates();
this.useGemini = !!process.env.GEMINI_API_KEY;
}
async initialize() {
this.logger.info('Initializing Script Writer Agent...');
if (this.useGemini) {
this.logger.info(' ✨ Gemini AI Scripting enabled');
}
return true;
}
loadTemplates() {
return {
tutorial: {
structure: ['hook', 'introduction', 'problem', 'solution_steps', 'demonstration', 'recap', 'cta'],
tone: 'educational',
pacing: 'moderate'
},
explainer: {
structure: ['hook', 'question', 'background', 'explanation', 'examples', 'implications', 'summary', 'cta'],
tone: 'informative',
pacing: 'steady'
},
list: {
structure: ['hook', 'introduction', 'list_items', 'bonus_item', 'summary', 'cta'],
tone: 'engaging',
pacing: 'quick'
},
review: {
structure: ['hook', 'introduction', 'overview', 'pros', 'cons', 'comparison', 'verdict', 'cta'],
tone: 'analytical',
pacing: 'detailed'
},
story: {
structure: ['hook', 'setup', 'conflict', 'journey', 'climax', 'resolution', 'lesson', 'cta'],
tone: 'narrative',
pacing: 'dynamic'
}
};
}
async generateScript(strategy) {
try {
this.logger.info(`Generating script for: ${strategy.topic}`);
if (this.useGemini) {
this.logger.info(' 🚀 Using Gemini AI for script generation...');
// Use the specialized Shorts generator if it's a Short
if (strategy.contentType === 'Shorts' || strategy.isShort) {
const shortsScript = await geminiService.generateShortsScript(
strategy.topic,
strategy.niche || 'interesting facts',
60 // Shorts target
);
// Map to project's script format
const script = {
...shortsScript,
fullScript: this.formatShortsScript(shortsScript),
duration: '0:60',
keywords: strategy.keywords || [],
metadata: {
strategy: strategy,
generatedAt: new Date().toISOString(),
isGemini: true,
isShort: true
}
};
await this.db.saveScript(script);
this.logger.info(` ✅ AI Shorts Script generated: ${script.title}`);
return script;
}
// Long-form Gemini script generation (custom prompt)
const ai = await geminiService.getClient();
const prompt = `Write a high-quality YouTube video script about: "${strategy.topic}"
Niche: ${strategy.niche || 'general'}
Content Type: ${strategy.contentType}
Angle: ${strategy.angle}
Keywords: ${strategy.keywords?.join(', ')}
Please structure the script with:
1. Catchy Title
2. Engaging Hook
3. Introduction
4. Main Body with several detailed sections
5. Conclusion
6. Call to Action
Format your response as a clear, ready-to-read script. Include [VISUALS: ...] descriptions for each section.`;
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash-preview-05-20',
contents: prompt
});
const text = response.text || response.candidates?.[0]?.content?.parts?.[0]?.text;
const script = {
title: strategy.topic,
fullScript: text,
duration: '5:00', // Estimate
keywords: strategy.keywords || [],
metadata: {
strategy: strategy,
generatedAt: new Date().toISOString(),
isGemini: true
}
};
await this.db.saveScript(script);
this.logger.info(` ✅ AI Script generated: ${script.title}`);
return script;
}
// Fallback to legacy template system
this.logger.info(' ⚠️ Gemini not available, using template system');
const template = this.templates[strategy.contentType.toLowerCase()] || this.templates.explainer;
const hook = await this.generateHook(strategy);
const introduction = await this.generateIntroduction(strategy);
const mainContent = await this.generateMainContent(strategy, template);
const conclusion = await this.generateConclusion(strategy);
const cta = await this.generateCTA(strategy);
const script = {
title: await this.generateTitle(strategy),
hook,
introduction,
mainContent,
conclusion,
callToAction: cta,
duration: this.estimateDuration(mainContent),
tone: template.tone,
pacing: template.pacing,
keywords: strategy.keywords,
metadata: {
strategy: strategy,
generatedAt: new Date().toISOString(),
version: '1.0'
}
};
script.fullScript = this.formatFullScript(script);
await this.db.saveScript(script);
this.logger.info(`Script generated: ${script.title}`);
return script;
} catch (error) {
this.logger.error('Failed to generate script:', error);
throw error;
}
}
formatShortsScript(script) {
let out = `TITLE: ${script.title}\n`;
out += `HASHTAGS: ${script.hashtags.join(' ')}\n\n`;
out += `HOOK: ${script.hook}\n\n`;
out += `FULL NARRATION:\n${script.script}\n\n`;
out += `SCENE BREAKDOWN:\n`;
script.scenes.forEach(s => {
out += `[${s.durationSec}s] ${s.narration}\n`;
out += `🎬 VISUAL: ${s.visualPrompt}\n\n`;
});
return out;
}
async generateTitle(strategy) {
const templates = [
`${strategy.angle}`,
`${strategy.topic}: The Complete Guide`,
`Everything You Need to Know About ${strategy.topic}`,
`${strategy.topic} in ${new Date().getFullYear()}: What's Changed?`,
`The Truth About ${strategy.topic} (Shocking Results)`,
`How to Master ${strategy.topic} in 30 Days`,
`${strategy.topic}: Beginner to Expert Guide`
];
// Select based on content type
if (strategy.contentType === 'Tutorial') {
return `How to ${strategy.topic}: Step-by-Step Guide`;
} else if (strategy.contentType === 'List') {
return `Top 10 ${strategy.topic} Tips You Need to Know`;
} else if (strategy.contentType === 'Review') {
return `${strategy.topic} Review: Is It Worth It?`;
}
return templates[Math.floor(Math.random() * templates.length)];
}
async generateHook(strategy) {
const hooks = [
{
type: 'question',
text: `Have you ever wondered ${this.generateQuestionAbout(strategy.topic)}?`
},
{
type: 'statistic',
text: `Did you know that ${this.generateStatistic(strategy.topic)}?`
},
{
type: 'statement',
text: `${strategy.topic} is about to change everything, and here's why...`
},
{
type: 'challenge',
text: `Most people think they understand ${strategy.topic}, but they're completely wrong.`
},
{
type: 'promise',
text: `In the next few minutes, you'll learn exactly how to master ${strategy.topic}.`
}
];
const selected = hooks[Math.floor(Math.random() * hooks.length)];
return {
type: selected.type,
text: selected.text,
duration: '0:00-0:05'
};
}
generateQuestionAbout(topic) {
const questions = [
`why ${topic} is becoming so important`,
`how ${topic} actually works`,
`what makes ${topic} different from everything else`,
`why experts are talking about ${topic}`,
`how ${topic} could change your life`
];
return questions[Math.floor(Math.random() * questions.length)];
}
generateStatistic(topic) {
const stats = [
`90% of people don't understand ${topic} correctly`,
`${topic} has grown by 300% in the last year alone`,
`experts predict ${topic} will be worth billions by 2030`,
`only 1 in 10 people are using ${topic} effectively`,
`${topic} can save you hours every single day`
];
return stats[Math.floor(Math.random() * stats.length)];
}
async generateIntroduction(strategy) {
return {
greeting: "Hey everyone, welcome back to the channel!",
topicIntro: `Today, we're diving deep into ${strategy.topic}.`,
valueProposition: `By the end of this video, you'll understand exactly ${this.getValueProposition(strategy)}.`,
credibility: this.getCredibilityStatement(strategy),
duration: '0:05-0:20'
};
}
getValueProposition(strategy) {
const propositions = {
'Tutorial': `how to implement ${strategy.topic} step by step`,
'Explainer': `what ${strategy.topic} is and why it matters`,
'List': `the most important things about ${strategy.topic}`,
'Review': `whether ${strategy.topic} is right for you`,
'Story': `the incredible journey of ${strategy.topic}`
};
return propositions[strategy.contentType] || `everything about ${strategy.topic}`;
}
getCredibilityStatement(strategy) {
const statements = [
"I've spent months researching this topic",
"After working with hundreds of people on this",
"Based on the latest research and data",
"Drawing from real-world experience",
"Using proven methods and strategies"
];
return statements[Math.floor(Math.random() * statements.length)];
}
async generateMainContent(strategy, template) {
const sections = [];
for (const section of template.structure) {
if (!['hook', 'introduction', 'cta'].includes(section)) {
sections.push(await this.generateSection(section, strategy));
}
}
return {
sections,
totalDuration: this.calculateSectionsDuration(sections)
};
}
async generateSection(sectionType, strategy) {
const sectionGenerators = {
problem: () => this.generateProblemSection(strategy),
solution_steps: () => this.generateSolutionSteps(strategy),
demonstration: () => this.generateDemonstration(strategy),
explanation: () => this.generateExplanation(strategy),
examples: () => this.generateExamples(strategy),
list_items: () => this.generateListItems(strategy),
pros: () => this.generatePros(strategy),
cons: () => this.generateCons(strategy),
comparison: () => this.generateComparison(strategy),
implications: () => this.generateImplications(strategy)
};
const generator = sectionGenerators[sectionType];
if (generator) {
return await generator();
}
return this.generateGenericSection(sectionType, strategy);
}
async generateProblemSection(strategy) {
return {
type: 'problem',
title: 'The Challenge',
content: [
`Many people struggle with ${strategy.topic}.`,
`The main issues are:`,
`1. Lack of clear information`,
`2. Complexity and confusion`,
`3. Not knowing where to start`,
`But don't worry, we're going to solve all of these today.`
],
visuals: ['Problem illustration', 'Statistics graphic'],
duration: 30
};
}
async generateSolutionSteps(strategy) {
const steps = [];
const numSteps = 3 + Math.floor(Math.random() * 3); // 3-5 steps
for (let i = 1; i <= numSteps; i++) {
steps.push({
number: i,
title: `Step ${i}: ${this.generateStepTitle(strategy.topic, i)}`,
description: this.generateStepDescription(strategy.topic, i),
tip: this.generateProTip(strategy.topic)
});
}
return {
type: 'solution_steps',
title: 'The Solution',
steps,
duration: steps.length * 45
};
}
generateStepTitle(topic, stepNumber) {
const titles = [
'Research and Preparation',
'Setting Up the Foundation',
'Implementation and Execution',
'Testing and Optimization',
'Scaling and Automation'
];
return titles[stepNumber - 1] || `Advanced ${topic} Techniques`;
}
generateStepDescription(topic, stepNumber) {
return `This step involves understanding the key aspects of ${topic} and how to apply them effectively. Pay special attention to the details here, as they make all the difference.`;
}
generateProTip(topic) {
const tips = [
`Pro tip: Start small and scale gradually`,
`Remember: Consistency is more important than perfection`,
`Quick tip: Document everything as you go`,
`Expert advice: Focus on one aspect at a time`,
`Insider secret: This works best when combined with regular practice`
];
return tips[Math.floor(Math.random() * tips.length)];
}
async generateDemonstration(strategy) {
return {
type: 'demonstration',
title: 'Live Demo',
content: [
`Now let me show you exactly how this works.`,
`[Screen recording or visual demonstration]`,
`As you can see, the process is straightforward once you understand the basics.`,
`The key is to follow the steps exactly as shown.`
],
visuals: ['Screen recording', 'Step-by-step graphics'],
duration: 120
};
}
async generateExplanation(strategy) {
return {
type: 'explanation',
title: 'Deep Dive',
content: [
`Let's break down ${strategy.topic} into its core components.`,
`First, we need to understand the fundamental principles.`,
`The science behind this is fascinating...`,
`[Detailed explanation with visuals]`,
`This is why ${strategy.topic} works so effectively.`
],
visuals: ['Diagrams', 'Infographics', 'Charts'],
duration: 90
};
}
async generateExamples(strategy) {
return {
type: 'examples',
title: 'Real-World Examples',
content: [
`Let's look at some real examples of ${strategy.topic} in action.`,
`Example 1: [Specific case study]`,
`Example 2: [Another relevant example]`,
`Example 3: [Third compelling example]`,
`These examples show the versatility and power of ${strategy.topic}.`
],
visuals: ['Case study graphics', 'Before/after comparisons'],
duration: 75
};
}
async generateListItems(strategy) {
const items = [];
const numItems = 5 + Math.floor(Math.random() * 6); // 5-10 items
for (let i = 1; i <= numItems; i++) {
items.push({
number: numItems - i + 1, // Countdown for engagement
title: this.generateListItemTitle(strategy.topic, i),
description: this.generateListItemDescription(strategy.topic),
impact: this.generateImpactStatement()
});
}
return {
type: 'list_items',
title: `Top ${numItems} Things About ${strategy.topic}`,
items,
duration: items.length * 30
};
}
generateListItemTitle(topic, index) {
const titles = [
`The Hidden Power of ${topic}`,
`Why ${topic} Matters More Than You Think`,
`The Surprising Truth About ${topic}`,
`How ${topic} Can Transform Your Approach`,
`The ${topic} Secret Nobody Talks About`,
`Mastering ${topic} in Record Time`,
`The Ultimate ${topic} Hack`,
`${topic}: The Game Changer`,
`Breaking Down ${topic} Myths`,
`The Future of ${topic}`
];
return titles[index - 1] || `Advanced ${topic} Technique #${index}`;
}
generateListItemDescription(topic) {
return `This aspect of ${topic} is crucial because it fundamentally changes how we approach the subject. Understanding this will give you a significant advantage.`;
}
generateImpactStatement() {
const impacts = [
'This alone can save you hours',
'Game-changing for beginners',
'Essential for long-term success',
'Often overlooked but critical',
'The difference between success and failure'
];
return impacts[Math.floor(Math.random() * impacts.length)];
}
async generatePros(strategy) {
return {
type: 'pros',
title: 'The Benefits',
points: [
'Easy to get started',
'Cost-effective solution',
'Proven results',
'Scalable approach',
'Community support'
],
duration: 45
};
}
async generateCons(strategy) {
return {
type: 'cons',
title: 'Things to Consider',
points: [
'Learning curve at the beginning',
'Requires consistent effort',
'Results may vary',
'Some technical knowledge helpful'
],
duration: 30
};
}
async generateComparison(strategy) {
return {
type: 'comparison',
title: 'How It Compares',
content: `Compared to alternatives, ${strategy.topic} stands out because of its unique approach and proven effectiveness.`,
comparisonPoints: [
'More efficient than traditional methods',
'Better ROI than competitors',
'Easier to implement',
'More sustainable long-term'
],
duration: 60
};
}
async generateImplications(strategy) {
return {
type: 'implications',
title: 'What This Means',
content: [
`The implications of ${strategy.topic} are far-reaching.`,
'This will change how we think about the industry.',
'Early adopters will have a significant advantage.',
'The potential for growth is enormous.'
],
duration: 45
};
}
generateGenericSection(sectionType, strategy) {
return {
type: sectionType,
title: sectionType.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),
content: `This section covers important aspects of ${strategy.topic} that you need to know.`,
duration: 60
};
}
async generateConclusion(strategy) {
return {
type: 'conclusion',
title: 'Wrapping Up',
recap: [
`So that's everything you need to know about ${strategy.topic}.`,
'We covered the key points:',
'- The fundamentals and why they matter',
'- Practical steps to get started',
'- Real-world applications and examples',
'- Tips for long-term success'
],
finalThought: `Remember, ${strategy.topic} is a journey, not a destination. Keep learning and improving!`,
duration: '30 seconds'
};
}
async generateCTA(strategy) {
return {
type: 'call_to_action',
subscribe: "If you found this helpful, make sure to subscribe and hit the notification bell!",
like: "Give this video a thumbs up if you learned something new.",
comment: `Let me know in the comments: What's your experience with ${strategy.topic}?`,
nextVideo: "Check out this related video for more insights.",
duration: '15 seconds'
};
}
formatFullScript(script) {
let fullScript = '';
// Title
fullScript += `TITLE: ${script.title}\n\n`;
fullScript += '═'.repeat(50) + '\n\n';
// Hook
fullScript += `[${script.hook.duration}] HOOK\n`;
fullScript += `${script.hook.text}\n\n`;
// Introduction
fullScript += `[${script.introduction.duration}] INTRODUCTION\n`;
fullScript += `${script.introduction.greeting}\n`;
fullScript += `${script.introduction.topicIntro}\n`;
fullScript += `${script.introduction.valueProposition}\n`;
fullScript += `${script.introduction.credibility}\n\n`;
// Main Content
fullScript += 'MAIN CONTENT\n';
fullScript += '─'.repeat(30) + '\n\n';
for (const section of script.mainContent.sections) {
fullScript += `[${this.formatDuration(section.duration)}] ${section.title.toUpperCase()}\n`;
if (Array.isArray(section.content)) {
section.content.forEach(line => {
fullScript += `${line}\n`;
});
} else if (section.steps) {
section.steps.forEach(step => {
fullScript += `\n${step.title}\n`;
fullScript += `${step.description}\n`;
fullScript += `💡 ${step.tip}\n`;
});
} else if (section.items) {
section.items.forEach(item => {
fullScript += `\n#${item.number}: ${item.title}\n`;
fullScript += `${item.description}\n`;
fullScript += `Impact: ${item.impact}\n`;
});
} else if (section.points) {
section.points.forEach(point => {
fullScript += `• ${point}\n`;
});
} else {
fullScript += `${section.content}\n`;
}
if (section.visuals) {
fullScript += `\n[VISUALS: ${section.visuals.join(', ')}]\n`;
}
fullScript += '\n';
}
// Conclusion
fullScript += `[${script.conclusion.duration}] CONCLUSION\n`;
script.conclusion.recap.forEach(line => {
fullScript += `${line}\n`;
});
fullScript += `\n${script.conclusion.finalThought}\n\n`;
// Call to Action
fullScript += `[${script.callToAction.duration}] CALL TO ACTION\n`;
fullScript += `${script.callToAction.subscribe}\n`;
fullScript += `${script.callToAction.like}\n`;
fullScript += `${script.callToAction.comment}\n`;
fullScript += `${script.callToAction.nextVideo}\n\n`;
// Metadata
fullScript += '═'.repeat(50) + '\n';
fullScript += `ESTIMATED DURATION: ${script.duration}\n`;
fullScript += `TONE: ${script.tone}\n`;
fullScript += `PACING: ${script.pacing}\n`;
fullScript += `KEYWORDS: ${script.keywords.join(', ')}\n`;
return fullScript;
}
estimateDuration(mainContent) {
const totalSeconds = mainContent.sections.reduce((total, section) => {
return total + (section.duration || 60);
}, 0);
// Add hook, intro, conclusion, CTA
const fullDuration = totalSeconds + 5 + 15 + 30 + 15;
return this.formatDuration(fullDuration);
}
formatDuration(seconds) {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}
calculateSectionsDuration(sections) {
return sections.reduce((total, section) => total + (section.duration || 60), 0);
}
}
module.exports = { ScriptWriterAgent }; |