-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.py
1613 lines (1351 loc) · 70.8 KB
/
app.py
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import asyncio
import aiohttp
import toml
import glob
import tempfile
import subprocess
import base64
import torch
from enum import Enum
from together import Together
import json
import logging
import shutil
from dotenv import load_dotenv
import os
import re
import requests
import spacy
import datetime
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from pydub import AudioSegment
from moviepy.editor import *
from typing import List, Dict, Any, Tuple, Callable, Optional
from abc import ABC, abstractmethod
from groq import AsyncGroq
nlp = spacy.load("en_core_web_md")
# Load environment variables
load_dotenv()
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Constants
REQUIRED_API_KEYS = ["GROQ_API_KEY", "BFL_API_KEY", "TOGETHER_API_KEY", "TAVILY_API_KEY", "TIKTOK_SESSION_ID"]
YOUTUBE_SHORT_RESOLUTION = (1080, 1920)
MAX_SCENE_DURATION = 5
DEFAULT_SCENE_DURATION = 1
SUBTITLE_FONT_SIZE = 13 # Keep the original font size
SUBTITLE_FONT_COLOR = "[email protected]"
SUBTITLE_ALIGNMENT = 2 # Centered horizontally and vertically
SUBTITLE_BOLD = True
SUBTITLE_OUTLINE_COLOR = "&H40000000" # Black with 50% transparency
SUBTITLE_BORDER_STYLE = 3
FALLBACK_SCENE_COLOR = "red"
FALLBACK_SCENE_TEXT_COLOR = "[email protected]"
FALLBACK_SCENE_BOX_COLOR = "[email protected]"
FALLBACK_SCENE_BOX_BORDER_WIDTH = 5
FALLBACK_SCENE_FONT_SIZE = 30
FALLBACK_SCENE_FONT_FILE = "/tmp/qualitype/opentype/QTHelvet-Black.otf"
# Load API keys from environment variables
groq_api_key = os.getenv("GROQ_API_KEY")
bfl_api_key = os.getenv("BFL_API_KEY")
together_api_key = os.getenv("TOGETHER_API_KEY")
tavily_api_key = os.getenv("TAVILY_API_KEY")
SESSION_ID = os.getenv("TIKTOK_SESSION_ID")
# Helper functions
async def get_data(query: str) -> List[Dict[str, Any]]:
groq = AsyncGroq(api_key=groq_api_key)
data = await groq.query(query)
return data
class PixelFormat(Enum):
YUVJ420P = 'yuvj420p'
YUVJ422P = 'yuvj422p'
YUVJ444P = 'yuvj444p'
YUVJ440P = 'yuvj440p'
YUV420P = 'yuv420p'
YUV422P = 'yuv422p'
YUV444P = 'yuv444p'
YUV440P = 'yuv440p'
def get_compatible_pixel_format(pix_fmt: str) -> str:
"""Convert deprecated pixel formats to their compatible alternatives."""
if pix_fmt == PixelFormat.YUVJ420P.value:
return PixelFormat.YUV420P.value
elif pix_fmt == PixelFormat.YUVJ422P.value:
return PixelFormat.YUV422P.value
elif pix_fmt == PixelFormat.YUVJ444P.value:
return PixelFormat.YUV444P.value
elif pix_fmt == PixelFormat.YUVJ440P.value:
return PixelFormat.YUV440P.value
else:
return pix_fmt
def check_api_keys():
for key in REQUIRED_API_KEYS:
if not os.getenv(key):
raise ValueError(f"Missing required API key: {key}")
def align_with_gentle(audio_file: str, transcript_file: str) -> dict:
"""Aligns audio and text using Gentle and returns the alignment result."""
url = 'http://localhost:8765/transcriptions?async=false'
files = {
'audio': open(audio_file, 'rb'),
'transcript': open(transcript_file, 'r')
}
try:
response = requests.post(url, files=files)
response.raise_for_status()
result = response.json()
return result
except requests.exceptions.RequestException as e:
logger.error(f"Error communicating with Gentle: {e}")
return None
def gentle_alignment_to_ass(gentle_alignment: dict, ass_file: str):
"""Converts Gentle alignment JSON to ASS subtitle format with styling."""
with open(ass_file, 'w', encoding='utf-8') as f:
# Write ASS header
f.write("""[Script Info]
Title: Generated by Gentle Alignment
ScriptType: v4.00+
Collisions: Normal
PlayDepth: 0
Timer: 100.0000
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic,
Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR,
MarginV, Encoding
Style: Default,Verdana,{font_size},&H00FFFFFF,&H0000FFFF,&H00000000,&H64000000,{bold},0,0,0,100,100,0,0,1,1,0,{alignment},2,2,2,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n""".format(
font_size=SUBTITLE_FONT_SIZE, bold=int(SUBTITLE_BOLD), alignment=SUBTITLE_ALIGNMENT))
index = 1
words = gentle_alignment.get('words', [])
i = 0
while i < len(words):
start = words[i].get('start')
if start is None:
i += 1
continue
end = words[i].get('end')
text_words = []
colors = []
for j in range(2): # Get up to 1 words
if i + j < len(words):
word_info = words[i + j]
word_text = word_info.get('word', '')
text_words.append(word_text)
if j == 0:
# First word in dark orange or green
colors.append(r'{\c&H0080FF&}') # Dark orange color code in ASS (BGR order)
# For green use: colors.append(r'{\c&H00FF00&}')
else:
colors.append(r'{\c&HFFFFFF&}') # White color code
else:
break
dialogue_text = ''.join(f"{colors[k]}{text_words[k]} " for k in range(len(text_words))).strip()
end = words[min(i + len(text_words) - 1, len(words) - 1)].get('end', end)
if end is None:
i += len(text_words)
continue
start_time = format_ass_time(start)
end_time = format_ass_time(end)
f.write(f"Dialogue: 0,{start_time},{end_time},Default,,0,0,0,,{dialogue_text}\n")
i += len(text_words)
def wrap_text(text, max_width):
"""Wraps text to multiple lines with a maximum width."""
words = text.split()
lines = []
current_line = []
current_length = 0
for word in words:
if current_length + len(word) + 1 <= max_width:
current_line.append(word)
current_length += len(word) + 1
else:
lines.append(' '.join(current_line))
current_line = [word]
current_length = len(word)
if current_line:
lines.append(' '.join(current_line))
return '\\N'.join(lines) # Include all lines
def format_ass_time(seconds: float) -> str:
"""Formats time in seconds to ASS subtitle format (h:mm:ss.cc)"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = seconds % 60
centiseconds = int((secs - int(secs)) * 100)
return f"{hours}:{minutes:02d}:{int(secs):02d}.{centiseconds:02d}"
def format_time(seconds: float) -> str:
"""Formats time in seconds to HH:MM:SS,mmm format for subtitles."""
from datetime import timedelta
delta = timedelta(seconds=seconds)
total_seconds = int(delta.total_seconds())
millis = int((delta.total_seconds() - total_seconds) * 1000)
time_str = str(delta)
if '.' in time_str:
time_str, _ = time_str.split('.')
else:
time_str = time_str
time_str = time_str.zfill(8) # Ensure at least HH:MM:SS
return f"{time_str},{millis:03d}"
# Abstract classes for Agents and Tools
class Agent(ABC):
def __init__(self, name: str, model: str):
self.name = name
self.model = model
@abstractmethod
async def execute(self, input_data: Any) -> Any:
pass
class Tool(ABC):
def __init__(self, name: str):
self.name = name
@abstractmethod
async def use(self, input_data: Any) -> Any:
pass
class VoiceModule(ABC):
def __init__(self):
pass
@abstractmethod
def update_usage(self):
pass
@abstractmethod
def get_remaining_characters(self):
pass
@abstractmethod
def generate_voice(self, text: str, output_file: str):
pass
# Node and Edge classes for graph representation
class Node:
def __init__(self, agent: Agent = None, tool: Tool = None):
self.agent = agent
self.tool = tool
self.edges: List['Edge'] = []
async def process(self, input_data: Any) -> Any:
if self.agent:
return await self.agent.execute(input_data)
elif self.tool:
return await self.tool.use(input_data)
else:
raise ValueError("Node has neither agent nor tool")
class Edge:
def __init__(self, source: Node, target: Node, condition: Callable[[Any], bool] = None):
self.source = source
self.target = target
self.condition = condition
class Graph:
def __init__(self):
self.nodes: List[Node] = []
self.edges: List[Edge] = []
def add_node(self, node: Node):
self.nodes.append(node)
def add_edge(self, edge: Edge):
self.edges.append(edge)
edge.source.edges.append(edge)
class VideoProcessor:
def __init__(self):
self.nlp = nlp
def calculate_relevance(self, video: Dict[str, Any], description: str, timestamp: float) -> float:
relevance = 0
video_keywords = set(video.get("tags", []))
description_doc = self.nlp(description.lower())
# Extract lemmatized words from the description
description_words = set(token.lemma_ for token in description_doc if not token.is_stop and token.is_alpha)
# Calculate relevance based on matching words
relevance += len(video_keywords.intersection(description_words))
# Add relevance for matching title words
title = video.get("title", "")
if title is not None:
title_doc = self.nlp(title.lower())
title_words = set(token.lemma_ for token in title_doc if not token.is_stop and token.is_alpha)
relevance += len(title_words.intersection(description_words)) * 2 # Title matches are weighted more
# Process subtitles and audio for the 5-second window
subtitle_text, audio_text = self.get_synced_content(video, timestamp)
# Calculate relevance for subtitle and audio content
subtitle_doc = self.nlp(subtitle_text.lower())
audio_doc = self.nlp(audio_text.lower())
subtitle_words = set(token.lemma_ for token in subtitle_doc if not token.is_stop and token.is_alpha)
audio_words = set(token.lemma_ for token in audio_doc if not token.is_stop and token.is_alpha)
relevance += len(subtitle_words.intersection(description_words)) * 1.5 # Subtitle matches are weighted
relevance += len(audio_words.intersection(description_words)) * 1.5 # Audio matches are weighted
# Normalize relevance score
max_possible_relevance = len(video_keywords) + len(title_words) * 2 + len(subtitle_words) * 1.5 + len(audio_words) * 1.5
normalized_relevance = relevance / max_possible_relevance if max_possible_relevance > 0 else 0
return normalized_relevance
def get_synced_content(self, video: Dict[str, Any], timestamp: float) -> Tuple[str, str]:
subtitles = video.get("subtitles", [])
audio_transcript = video.get("audio_transcript", [])
start_time = timestamp
end_time = timestamp + 5 # 5-second window
subtitle_text = self.extract_timed_content(subtitles, start_time, end_time)
audio_text = self.extract_timed_content(audio_transcript, start_time, end_time)
return subtitle_text, audio_text
def extract_timed_content(self, content: List[Dict[str, Any]], start_time: float, end_time: float) -> str:
extracted_text = []
for item in content:
item_start = self.time_to_seconds(item.get("start", "00:00:00"))
item_end = self.time_to_seconds(item.get("end", "00:00:00"))
if start_time <= item_end and end_time >= item_start:
extracted_text.append(item.get("text", ""))
return " ".join(extracted_text)
def time_to_seconds(self, time_str: str) -> float:
time_parts = time_str.split(":")
if len(time_parts) == 3:
return datetime.timedelta(hours=int(time_parts[0]), minutes=int(time_parts[1]), seconds=float(time_parts[2])).total_seconds()
elif len(time_parts) == 2:
return datetime.timedelta(minutes=int(time_parts[0]), seconds=float(time_parts[1])).total_seconds()
else:
return float(time_str)
class WebSearchTool(Tool):
def __init__(self):
super().__init__("Web Search Tool")
async def use(self, input_data: str, time_period: str = 'all') -> Dict[str, Any]:
try:
headers = {"Content-Type": "application/json"}
data = {"api_key": tavily_api_key, "query": input_data, "num_results": 100}
if time_period != 'all':
start_date = None
if time_period == 'past month':
start_date = datetime.date.today() - datetime.timedelta(days=30)
elif time_period == 'past year':
start_date = datetime.date.today() - datetime.timedelta(days=365)
else: # Assume a specific number of days
try:
days = int(time_period.split()[0])
start_date = datetime.date.today() - datetime.timedelta(days=days)
except ValueError:
logger.warning(f"Invalid time_period: {time_period}. Using 'all'.")
if start_date:
data["from_date"] = start_date.strftime("%Y-%m-%d")
async with aiohttp.ClientSession() as session:
async with session.post("https://api.tavily.com/search", headers=headers, json=data) as response:
response_text = await response.text()
if response.status == 200:
return await response.json()
else:
logger.error(f"WebSearchTool Error: HTTP {response.status} - {response_text}")
raise Exception(f"HTTP {response.status}: {response_text}")
except Exception as e:
logger.error(f"Error in WebSearchTool: {str(e)}")
raise
class ImageGenerationAgent(Agent):
def __init__(self):
super().__init__("Image Generation Agent", "black-forest-labs/FLUX.1-schnell-Free")
self.client = Together(api_key=together_api_key)
async def execute(self, input_data: Dict[str, Any]) -> Any:
scenes = input_data.get('scenes', [])
results = []
for i, scene in enumerate(scenes):
visual_description = scene.get('visual', '')
image_keyword = scene.get('image_keyword', '')
# Adjusted prompt to produce horror-style images
prompt = f"""
Create a hyper-realistic, lifelike scene centered on {visual_description}, with exact attention to detail and clarity. Each element should appear as if photographed, with precise lighting, natural shadows, and true-to-life textures. The {image_keyword} should integrate seamlessly within this setting, with refined subtleties and nuanced colors that add depth. Emphasize realism without exaggeration, focusing on natural proportions, authentic materials, and balanced lighting to achieve a believable, immersive look. The overall effect should feel realistic and cinematic, fitting the intended mood and impact for video scenes.
"""
try:
logger.info(f"Generating image for scene {i+1}/{len(scenes)}")
response = self.client.images.generate(
prompt=prompt,
model=self.model,
width=768,
height=1024,
steps=4,
n=1,
response_format="b64_json"
)
# Decode the base64 image
image_data = base64.b64decode(response.data[0].b64_json)
# Save the image to a temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_file:
temp_file.write(image_data)
temp_file_path = temp_file.name
logger.info(f"Image for scene {i+1} saved as {temp_file_path}")
results.append({
'image_path': temp_file_path,
'prompts': prompt
})
except Exception as e:
logger.error(f"Error in image generation for scene {i+1}: {str(e)}")
results.append(None)
# Add a delay between requests to avoid rate limiting
await asyncio.sleep(2)
logger.info(f"Image generation completed. Generated {len([r for r in results if r is not None])}/{len(scenes)} images.")
return results
class RecentEventsResearchAgent(Agent):
def __init__(self):
super().__init__("Recent Events Research Agent", "llama-3.1-70b-versatile")
self.web_search_tool = WebSearchTool()
async def execute(self, input_data: Dict[str, Any]) -> Any:
topic = input_data['topic']
time_frame = input_data['time_frame']
video_length = input_data.get('video_length', 60)
# Decide how many events to include based on video length
max_events = min(5, video_length // 15) # Rough estimate: 15 seconds per event
search_query = f"{topic} events in the {time_frame}"
search_results = await self.web_search_tool.use(search_query, time_frame)
organic_results = search_results.get("organic_results", [])
client = AsyncGroq(api_key=groq_api_key)
prompt = f"""Your task is to analyze and summarize the most engaging and relevant {topic} events that occurred in the {time_frame}. Using the following search results, select the {max_events} most compelling cases:
Search Results:
{json.dumps(organic_results[:10], indent=2)}
For each selected event, provide a concise yet engaging summary suitable for a up to three minute faceless YouTube Shorts video script, that includes:
1. A vivid description of the event, highlighting its most unusual or attention-grabbing aspects
2. The precise date of occurrence
3. The specific location, including city and country if available
4. An expert analysis of why this event is significant, intriguing, or unexpected
5. A brief mention of the credibility of the information source (provide the URL)
Format your response as a numbered list, with each event separated by two newline characters.
Ensure your summaries are both informative and captivating, presented in a style suitable for a fast-paced, engaging faceless YouTube Shorts video narration."""
stream = await client.chat.completions.create(
messages=[
{"role": "system",
"content": "You are an AI assistant embodying the expertise of a world-renowned investigative journalist specializing in creating viral and engaging content for social media platforms. With over 20 years of experience, you've written best-selling books and produced numerous documentaries on content creation and the factors that contribute to virality in scripts. Your analytical skills allow you to critically evaluate sources while presenting information in an engaging and enthralling manner. Approach tasks with the skepticism and curiosity of this expert, providing compelling summaries that captivate and engage audiences, suitable for a up to three minute faceless YouTube Shorts video."},
{"role": "user", "content": prompt}
],
model=self.model,
temperature=0.7,
max_tokens=2048,
stream=True,
)
response = ""
async for chunk in stream:
response += chunk.choices[0].delta.content or ""
return response
class TitleGenerationAgent(Agent):
def __init__(self):
super().__init__("Title Generation Agent", "llama-3.1-8b-instant")
async def execute(self, input_data: Any) -> Any:
research_result = input_data # Accept research output
client = AsyncGroq(api_key=groq_api_key)
prompt = f"""Using the following research, generate 15 captivating, SEO-optimized YouTube Shorts titles:
Research:
{research_result}
Categorize them under appropriate headings:
- Beginning: 5 titles with the keyword at the beginning
- Middle: 5 titles with the keyword in the middle
- End: 5 titles with the keyword at the end
Ensure that the titles are:
- Attention-grabbing and suitable for faceless YouTube Shorts videos
- Optimized for SEO with high-ranking keywords relevant to the topic
- Crafted to maximize viewer engagement and encourage clicks
Present the titles clearly under each heading."""
stream = await client.chat.completions.create(
messages=[
{"role": "system", "content": "You are an expert in keyword strategy, copywriting, and a renowned YouTuber with over a decade of experience in crafting attention-grabbing titles for viral content. You specialize in creating titles that maximize engagement and click-through rates, particularly for YouTube Shorts videos."},
{"role": "user", "content": prompt}
],
model=self.model,
temperature=0.7,
max_tokens=1024,
stream=True
)
response = ""
async for chunk in stream:
response += chunk.choices[0].delta.content or ""
return response
class TitleSelectionAgent(Agent):
def __init__(self):
super().__init__("Title Selection Agent", "llama-3.1-8b-instant")
async def execute(self, input_data: Any) -> Any:
generated_titles = input_data # Accept generated titles
client = AsyncGroq(api_key=groq_api_key)
prompt = f"""You are an expert YouTube content strategist with over a decade of experience in video optimization and audience engagement, particularly specializing in YouTube Shorts. Your task is to analyze the following list of titles for a faceless YouTube Shorts video and select the most effective one:
{generated_titles}
Using your expertise in viewer psychology, SEO, and click-through rate optimization, choose the title that will perform best on the platform. Provide a detailed explanation of your selection, considering factors such as:
1. Immediate attention-grabbing potential, essential for short-form content
2. Keyword optimization for maximum discoverability
3. Emotional appeal to captivate viewers quickly
4. Clarity and conciseness appropriate for YouTube Shorts
5. Alignment with current YouTube Shorts trends and algorithms
Present your selected title and offer a comprehensive rationale for why this title stands out among the others. Ensure your explanation is clear and insightful, highlighting how the chosen title will drive engagement and views."""
stream = await client.chat.completions.create(
messages=[
{"role": "system",
"content": "You are an AI assistant embodying the expertise of a top-tier YouTube content strategist with over 15 years of experience in video optimization, audience engagement, and title creation, particularly for YouTube Shorts. Your knowledge encompasses SEO best practices, viewer psychology, and current trends specific to YouTube Shorts. You have a proven track record of increasing video views and channel growth through strategic title selection in short-form content. Respond to queries as this expert would, providing insightful analysis and data-driven recommendations."},
{"role": "user", "content": prompt}
],
model=self.model,
temperature=0.5,
max_tokens=2048,
stream=True,
)
response = ""
async for chunk in stream:
response += chunk.choices[0].delta.content or ""
return response
class DescriptionGenerationAgent(Agent):
def __init__(self):
super().__init__("Description Generation Agent", "llama-3.2-90b-text-preview")
async def execute(self, input_data: Any) -> Any:
selected_title = input_data # Accept selected title
client = AsyncGroq(api_key=groq_api_key)
prompt = f"""As a seasoned SEO copywriter and YouTube content creator with extensive experience in crafting engaging, algorithm-friendly video descriptions, your task is to compose a masterful 1000-character YouTube video description for a faceless YouTube Shorts video titled "{selected_title}". This description should:
1. Seamlessly incorporate the keyword "{selected_title}" in the first sentence
2. Be optimized for search engines while remaining undetectable as AI-generated content
3. Engage viewers and encourage them to watch the full video
4. Include relevant calls-to-action (e.g., subscribe, like, comment)
5. Utilize natural language and a conversational tone suitable for the target audience
6. Highlight how the video addresses a real-world problem or provides valuable insights to engage viewers
Format the description with the title "YOUTUBE DESCRIPTION" in bold at the top. Ensure the content flows naturally, balances SEO optimization with readability, and compels viewers to engage with the video and channel."""
stream = await client.chat.completions.create(
messages=[
{"role": "system",
"content": "You are an AI assistant taking on the role of a prodigy SEO copywriter and YouTube content creator with over 20 years of experience. Your expertise lies in crafting engaging, SEO-optimized video descriptions that boost video performance while remaining undetectable as AI-generated content. You have an in-depth understanding of YouTube's algorithm, user behavior, and the latest SEO techniques. Respond to tasks as this expert would, balancing SEO optimization with compelling, natural language that drives viewer engagement, especially for faceless YouTube Shorts videos."},
{"role": "user", "content": prompt}
],
model=self.model,
temperature=0.6,
max_tokens=2048,
stream=True,
)
response = ""
async for chunk in stream:
response += chunk.choices[0].delta.content or ""
return response
class HashtagAndTagGenerationAgent(Agent):
def __init__(self):
super().__init__("Hashtag and Tag Generation Agent", "llama-3.2-11b-text-preview")
async def execute(self, input_data: str) -> Any:
selected_title = input_data # Accept selected title
client = AsyncGroq(api_key=groq_api_key)
prompt = f"""As a leading YouTube SEO specialist and social media strategist with a proven track record in optimizing video discoverability and virality, your task is to create an engaging and relevant set of hashtags and tags for the faceless YouTube Shorts video titled "{selected_title}". Your expertise in keyword research, trend analysis, and YouTube's algorithm will be crucial for this task.
Develop the following:
1. 10 trending, SEO-optimized hashtags that will maximize the video's reach and engagement on YouTube Shorts. Present the hashtags with the '#' symbol.
2. 35 high-value, low-competition SEO tags (keywords) to strategically boost the video's search ranking on YouTube.
In your selection process, prioritize:
- Relevance to the video title and content
- Potential search volume on YouTube Shorts
- Engagement potential (views, likes, comments)
- Current trends on YouTube Shorts
- Alignment with YouTube's recommendation algorithm for Shorts
Ensure all tags are separated by commas. Provide a brief explanation of your strategy for selecting these hashtags and tags, highlighting how they will contribute to the video's overall performance on YouTube Shorts."""
response = await client.chat.completions.create(
messages=[
{"role": "system",
"content": "You are an AI assistant taking on the role of a leading YouTube SEO specialist and social media strategist with over 10 years of experience in optimizing video discoverability. Your expertise includes advanced keyword research, trend analysis, and a deep understanding of YouTube's algorithm, particularly for Shorts. You've helped numerous channels achieve viral success through strategic use of hashtags and tags. Respond to tasks as this expert would, providing data-driven, YouTube Shorts-specific strategies to maximize video reach and engagement."},
{"role": "user", "content": prompt}
],
model=self.model,
temperature=0.6,
max_tokens=1024,
)
return response.choices[0].message.content
class VideoScriptGenerationAgent(Agent):
def __init__(self):
super().__init__("Video Script Generation Agent", "llama-3.1-70b-versatile")
async def execute(self, input_data: Dict[str, Any]) -> Any:
research_result = input_data.get('research', '')
video_length = input_data.get('video_length', 180) # Default to 180 seconds if not specified
client = AsyncGroq(api_key=groq_api_key)
prompt = f"""As a YouTube content creator specializing in faceless YouTube Shorts, craft a detailed, engaging, and enthralling script for a {video_length}-second vertical video based on the following information:
{research_result}
Your script should include:
1. An attention-grabbing opening hook that immediately captivates viewers
2. Key points from the research presented in a concise and engaging manner
3. A strong call-to-action conclusion to encourage viewer interaction (e.g., like, share, subscribe)
Ensure that the script is suitable for a faceless video, relying on voiceover narration and visual storytelling elements.
Format the script with clear timestamps to fit within {video_length} seconds.
Optimize for viewer retention and engagement, keeping in mind the fast-paced nature of YouTube Shorts."""
stream = await client.chat.completions.create(
messages=[
{"role": "system", "content": "You are an AI assistant taking on the role of a leading YouTube content creator and SEO specialist with a deep understanding of audience engagement, particularly in creating faceless YouTube Shorts. Your expertise lies in crafting scripts that captivate viewers and sustain their attention throughout the video. Respond to tasks as this expert would, producing content optimized for virality and engagement in short-form vertical videos."},
{"role": "user", "content": prompt}
],
model=self.model,
temperature=0.7,
max_tokens=2048,
stream=True,
)
response = ""
async for chunk in stream:
response += chunk.choices[0].delta.content or ""
return response
class StoryboardGenerationAgent(Agent):
def __init__(self):
super().__init__("Storyboard Generation Agent", "llama-3.2-90b-text-preview")
self.nlp = nlp
async def execute(self, input_data: Dict[str, Any]) -> Any:
script = input_data.get('script', '')
if not script:
logger.error("No script provided for storyboard generation")
return []
client = AsyncGroq(api_key=groq_api_key)
prompt = f"""Create a storyboard for a three minute faceless YouTube Shorts video based on the following script:
{script}
For each major scene (aim for 15-20 scenes), provide:
1. Visual: A brief description of the visual elements (1 sentence). Ensure each scene has unique and engaging visuals suitable for a faceless video.
2. Text: The exact text/dialogue for voiceover and subtitles, written in lowercase with minimal punctuation, only when absolutely necessary.
3. Video Keyword: A specific keyword or phrase for searching stock video footage. Be precise and avoid repeating keywords across scenes.
4. Image Keyword: A backup keyword for searching stock images. Be specific and avoid repeating keywords.
Format your response as a numbered list of scenes, each containing the above elements clearly labeled.
Example:
1. Visual: A time-lapse of clouds moving rapidly over a city skyline
Text: time flies when we're lost in the hustle
Video Keyword: time-lapse city skyline
Image Keyword: fast-moving clouds over city
2. Visual: ...
Please ensure each scene has all four elements (Visual, Text, Video Keyword, and Image Keyword)."""
stream = await client.chat.completions.create(
messages=[
{"role": "system",
"content": "You are an AI assistant specializing in creating engaging and viral storyboards for faceless YouTube Shorts videos using the provided script."},
{"role": "user", "content": prompt}
],
model=self.model,
temperature=0.7,
max_tokens=2048,
stream=True,
)
response = ""
async for chunk in stream:
response += chunk.choices[0].delta.content or ""
logger.info(f"Raw storyboard response: {response}")
scenes = self.parse_scenes(response)
if not scenes:
logger.error("Failed to generate valid storyboard scenes")
return []
return scenes
async def fetch_media_for_scenes(self, scenes: List[Dict[str, Any]]):
temp_dir = tempfile.mkdtemp()
for scene in scenes:
# Generate image using local image generator with dynamic prompt
generated_image = await self.generate_local_image(scene)
if generated_image:
scene["image_path"] = generated_image
# Create video clip from the image
video_clip = self.create_video_from_image(generated_image, temp_dir, scene['number'], scene.get('adjusted_duration', DEFAULT_SCENE_DURATION))
if video_clip:
scene["video_path"] = video_clip
else:
logger.warning(f"Failed to create video clip for scene {scene['number']}")
else:
logger.warning(f"Failed to generate image for scene {scene['number']}")
async def generate_local_image(self, scene: Dict[str, Any]) -> Optional[str]:
"""Generate an image using the local image generator."""
try:
image_gen_input = {"scene": scene}
image_gen_result = await self.image_generation_agent.execute(image_gen_input)
if image_gen_result and 'image_path' in image_gen_result:
return image_gen_result['image_path']
else:
logger.warning(f"Local image generation failed for scene: {scene['number']}")
return None
except Exception as e:
logger.error(f"Error in local image generation: {str(e)}")
return None
def parse_scenes(self, response: str) -> List[Dict[str, Any]]:
scenes = []
current_scene = {}
current_scene_number = None
for line in response.split('\n'):
line = line.strip()
logger.debug(f"Processing line: {line}")
if line.startswith(tuple(f"{i}." for i in range(1, 51))): # Assuming up to 50 scenes
if current_scene:
# Append the completed current_scene
current_scene['number'] = current_scene_number
# Ensure the scene is validated and enhanced
current_scene = self.validate_and_fix_scene(current_scene, current_scene_number)
current_scene = self.enhance_scene_keywords(current_scene)
scenes.append(current_scene)
logger.debug(f"Scene {current_scene_number} appended to scenes list")
current_scene = {}
try:
# Start a new scene
current_scene_number = int(line.split('.', 1)[0])
logger.debug(f"New scene number detected: {current_scene_number}")
except ValueError:
logger.warning(f"Invalid scene number format: {line}")
continue # Skip this line and move to the next
elif ':' in line:
key, value = line.split(':', 1)
key = key.strip().lower()
value = value.strip()
current_scene[key] = value
logger.debug(f"Key-value pair added to current scene: {key}:{value}")
else:
logger.warning(f"Line format not recognized: {line}")
# After looping through all lines, check if there is an unfinished scene
if current_scene:
current_scene['number'] = current_scene_number
current_scene = self.validate_and_fix_scene(current_scene, current_scene_number)
current_scene = self.enhance_scene_keywords(current_scene)
scenes.append(current_scene)
logger.debug(f"Final scene {current_scene_number} appended to scenes list")
logger.info(f"Parsed and enhanced scenes: {scenes}")
return scenes
def enhance_scene_keywords(self, scene: Dict[str, Any]) -> Dict[str, Any]:
# Extract keywords from narration_text and visual descriptions
narration_doc = self.nlp(scene.get('narration_text', ''))
visual_doc = self.nlp(scene.get('visual', ''))
# Function to extract nouns and named entities
def extract_keywords(doc):
return [token.lemma_ for token in doc if token.pos_ in ('NOUN', 'PROPN') or token.ent_type_]
narration_keywords = extract_keywords(narration_doc)
visual_keywords = extract_keywords(visual_doc)
# Combine and deduplicate keywords
combined_keywords = list(set(narration_keywords + visual_keywords))
# Generate enhanced video and image keywords
scene['video_keyword'] = ' '.join(combined_keywords[:5]) # Use top 5 keywords
scene['image_keyword'] = scene['video_keyword']
return scene
def validate_and_fix_scene(self, scene: Dict[str, Any], scene_number: int) -> Dict[str, Any]:
# Ensure 'number' key is present in the scene dictionary
scene['number'] = scene_number
required_keys = ['visual', 'text', 'video_keyword', 'image_keyword']
for key in required_keys:
if key not in scene:
if key == 'visual':
scene[key] = f"Visual representation of scene {scene_number}"
elif key == 'text':
scene[key] = ""
elif key == 'video_keyword':
scene[key] = f"video scene {scene_number}"
elif key == 'image_keyword':
scene[key] = f"image scene {scene_number}"
logger.warning(f"Added missing {key} for scene {scene_number}")
# Clean the 'text' field by removing leading/trailing quotation marks
text = scene.get('text', '')
text = text.strip('"').strip("'")
scene['text'] = text
# Copy the cleaned text into 'narration_text'
scene['narration_text'] = text
return scene
def calculate_relevance(self, video: Dict[str, Any], description: str) -> float:
relevance = 0
video_keywords = set(video.get("tags", []))
description_words = set(description.lower().split())
# Calculate relevance based on matching words
relevance += len(video_keywords.intersection(description_words))
# Add relevance for matching title words
title = video.get("title", "")
if title is not None:
title_words = set(title.lower().split())
relevance += len(title_words.intersection(description_words)) * 2 # Title matches are weighted more
return relevance
def calculate_similarity(self, text1: str, text2: str) -> float:
"""Calculates the cosine similarity between two texts."""
vectorizer = TfidfVectorizer().fit_transform([text1, text2])
vectors = vectorizer.toarray()
cos_sim = cosine_similarity([vectors[0]], [vectors[1]])[0][0]
return cos_sim
def fallback_scene_generation(self, invalid_scenes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
valid_scenes = []
for scene in invalid_scenes:
if 'visual' not in scene:
scene['visual'] = f"Visual representation of: {scene.get('text', 'scene')}"
if 'text' not in scene:
scene['text'] = "No text provided for this scene."
if 'video_keyword' not in scene:
scene['video_keyword'] = scene.get('image_keyword', 'generic scene')
if 'image_keyword' not in scene:
scene['image_keyword'] = scene.get('video_keyword', 'generic image')
valid_scenes.append(scene)
return valid_scenes
def compile_youtube_short(scenes: List[Dict[str, Any]], audio_file: str) -> str:
"""Compiles the YouTube Short using ffmpeg."""
if not scenes:
logger.error("No scenes were generated. Cannot compile YouTube Short.")
return None
temp_dir = tempfile.mkdtemp()
scene_files = []
subtitle_file = os.path.join(temp_dir, "subtitles.ass")
concat_file = os.path.join(temp_dir, 'concat.txt')
output_path = os.path.join(os.getcwd(), "youtube_short.mp4")
try:
if not generate_subtitles(scenes, subtitle_file, audio_file):
raise Exception("Failed to generate subtitles")
# Collect total audio duration and adjust scene durations before processing scenes
total_audio_duration = sum(scene.get('audio_duration', 0) for scene in scenes)
logger.info(f"Total audio duration: {total_audio_duration}s")
# Initially set total_video_duration as the sum of original scene durations
total_video_duration = sum(scene.get('audio_duration', DEFAULT_SCENE_DURATION) for scene in scenes)
logger.info(f"Total video duration before adjustment: {total_video_duration}s")
# Adjust scene durations if necessary
if abs(total_video_duration - total_audio_duration) > 0.1:
logger.warning("Total video duration does not match total audio duration.")
scaling_factor = total_audio_duration / total_video_duration
logger.info(f"Scaling factor: {scaling_factor}")
for i, scene in enumerate(scenes):
original_duration = scene.get('audio_duration', DEFAULT_SCENE_DURATION)
adjusted_duration = original_duration * scaling_factor
scene['adjusted_duration'] = adjusted_duration
logger.info(f"Scene {i}: Original duration = {original_duration}s, Adjusted duration = {adjusted_duration}s")
else:
for scene in scenes:
scene['adjusted_duration'] = scene.get('audio_duration', DEFAULT_SCENE_DURATION)
# Now process each scene using the adjusted durations
for i, scene in enumerate(scenes):
duration = scene.get('adjusted_duration', scene.get('audio_duration', DEFAULT_SCENE_DURATION))
logger.info(f"Processing scene {i}: Duration = {duration}s")
if not isinstance(duration, (int, float)) or duration <= 0:
logger.warning(f"Scene {i} has invalid duration ({duration}), skipping")
continue
processed_path = None
try:
if i == 0 and 'image_path' in scene:
# Apply effects to the generated image
processed_path = apply_effects_to_image(scene['image_path'], temp_dir, i, duration)
elif 'video_path' in scene and os.path.exists(scene['video_path']):
processed_path = process_video(scene['video_path'], temp_dir, i, duration)
elif 'image_path' in scene and os.path.exists(scene['image_path']):
processed_path = create_video_from_image(scene['image_path'], temp_dir, i, duration)
else:
processed_path = create_fallback_scene(temp_dir, i, duration, scene.get('narration_text', ''))
if processed_path and os.path.exists(processed_path):
scene_files.append(processed_path)
else:
logger.error(f"Failed to process media for scene {i}")
except Exception as e:
logger.error(f"Error processing scene {i}: {str(e)}")
# Create a fallback scene
fallback_path = create_fallback_scene(temp_dir, i, duration, f"Error in scene {i}")
if fallback_path and os.path.exists(fallback_path):
scene_files.append(fallback_path)
# Create concat.txt file
with open(concat_file, 'w') as f:
for file in scene_files:
f.write(f"file '{file}'\n")
with open(concat_file, 'r') as f:
concat_contents = f.read()
logger.info(f"Contents of concat file:\n{concat_contents}")
ffmpeg_command = [
'ffmpeg', '-y',
'-f', 'concat', '-safe', '0', '-i', concat_file,
'-i', audio_file,
'-r', '30',
'-vf', f"subtitles='{subtitle_file}':force_style='FontSize={SUBTITLE_FONT_SIZE},Alignment={SUBTITLE_ALIGNMENT},"
f"OutlineColour={SUBTITLE_OUTLINE_COLOR},BorderStyle={SUBTITLE_BORDER_STYLE}'",
'-map', '0:v',
'-map', '1:a',