Prudvireddy commited on
Commit
daf848e
·
verified ·
1 Parent(s): c762a72

Upload 7 files

Browse files
Files changed (7) hide show
  1. Montserrat-Bold.ttf +0 -0
  2. agents.py +171 -0
  3. app.py +78 -0
  4. demo.py +100 -0
  5. requirements.txt +18 -0
  6. streamlit_app.py +83 -0
  7. tools.py +410 -0
Montserrat-Bold.ttf ADDED
Binary file (29.6 kB). View file
 
agents.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from crewai import Agent, Task
2
+ from langchain_groq import ChatGroq
3
+ from tools import create_video_from_images_and_audio, image_generator, speech_generator, wiki_tool
4
+ import os
5
+
6
+ def get_agents_and_tasks(groq_api_key):
7
+ os.environ['GROQ_API_KEY'] = groq_api_key
8
+ llm = ChatGroq(model='llama3-70b-8192', temperature=0.6, max_tokens=1024, api_key=groq_api_key)
9
+
10
+ script_agent = Agent(
11
+ role='Senior Content Writer',
12
+ goal='Craft engaging, concise, and informative narrations for YouTube short videos',
13
+ backstory="""As a seasoned content writer, you excel at breaking down complex topics into captivating narratives that educate and entertain audiences. Your expertise lies in writing concise, attention-grabbing scripts for YouTube short videos.""",
14
+ verbose=True,
15
+ llm=llm,
16
+ allow_delegation=False
17
+ )
18
+
19
+ image_descriptive_agent = Agent(
20
+ role='Visual Storyteller',
21
+ goal='Design stunning, contextually relevant visual descriptions for YouTube short videos. The number of descriptions should not be greater than three',
22
+ backstory='With a keen eye for visual storytelling, you create compelling imagery that elevates the narrative and captivates the audience.',
23
+ verbose=True,
24
+ llm=llm,
25
+ allow_delegation=False
26
+ )
27
+
28
+ # img_speech_generating_agent = Agent(
29
+ # role='Multimedia Content Creator',
30
+ # goal='Generate high-quality images and speeches for YouTube short videos one after another based on provided descriptions.',
31
+ # backstory='As a multimedia expert, you excel at creating engaging multimedia content that brings stories to life.',
32
+ # verbose=True,
33
+ # llm=llm,
34
+ # allow_delegation=False
35
+ # )
36
+
37
+ img_speech_generating_agent = Agent(
38
+ role='Multimedia Content Creator',
39
+ goal='Generate high-quality images and speeches for YouTube short videos based on provided script',
40
+ backstory='As a multimedia expert, you excel at creating engaging multimedia content that brings stories to life.',
41
+ verbose=True,
42
+ llm=llm,
43
+ allow_delegation=False
44
+ )
45
+
46
+ editor = Agent(
47
+ role = 'Video editor',
48
+ goal = 'To make a video for YouTube shorts.',
49
+ backstory = "You are a video editor working for a YouTube creator",
50
+ verbose=True,
51
+ llm=llm,
52
+ allow_delegation = False,
53
+ tools = [create_video_from_images_and_audio]
54
+ )
55
+
56
+ content_generation_task = Task(
57
+ description='Generate engaging and informative content on the topic: {topic}. Use the provided tool, only if you have no idea about the given topic.',
58
+ expected_output="""Good corpus of text about: {topic}""",
59
+ agent=script_agent,
60
+ tools = [wiki_tool]
61
+ )
62
+
63
+ story_writing_task = Task(
64
+ description='Write an engaging narration for a YouTube short video on the topic: {topic}',
65
+ expected_output="""A short paragraph suitable for narrating in five seconds that provides an immersive experience to the audience. Follow the below example for output length and format.
66
+
67
+ **Example input:**
68
+ Ancient Wonders of the World
69
+
70
+ **Output format:**
71
+ Embark on a journey through time and marvel at the ancient wonders of the world!
72
+ From the majestic Great Pyramid of Giza, symbolizing the ingenuity of ancient Egypt,
73
+ to the Hanging Gardens of Babylon, an oasis of lush beauty amidst ancient Mesopotamia's arid landscape.
74
+ These remarkable structures continue to intrigue and inspire awe, reminding us of humanity's enduring quest for greatness.
75
+ """,
76
+ agent=script_agent
77
+ )
78
+
79
+
80
+ img_text_task = Task(
81
+ description='Given the narration, visually describe each sentence in the narration which will be used as a prompt for image generation.',
82
+ expected_output="""Sentences encoded in <narration> and <image> tags. Follow the example below for the output format.
83
+
84
+ **Example input:**
85
+ Embark on a journey through time and marvel at the ancient wonders of the world! From the majestic Great Pyramid of Giza, symbolizing the ingenuity of ancient Egypt, to the Hanging Gardens of Babylon, an oasis of lush beauty amidst ancient Mesopotamia's arid landscape. These remarkable structures continue to intrigue and inspire awe, reminding us of humanity's enduring quest for greatness.
86
+
87
+ **Output format:**
88
+
89
+ <narration>Embark on a journey through time and marvel at the ancient wonders of the world!</narration>
90
+ <image>A breathtaking view of various ancient wonders, showcasing their grandeur and mystery.</image>
91
+
92
+ <narration>From the majestic Great Pyramid of Giza, symbolizing the ingenuity of ancient Egypt,</narration>
93
+ <image>The majestic Great Pyramid of Giza, standing tall against the desert backdrop, a testament to ancient engineering.</image>
94
+
95
+ <narration>to the Hanging Gardens of Babylon, an oasis of lush beauty amidst ancient Mesopotamia's arid landscape,</narration>
96
+ <image>The Hanging Gardens of Babylon, lush greenery cascading from terraced gardens, amidst the arid Mesopotamian landscape.</image>
97
+
98
+ <narration>These remarkable structures continue to intrigue and inspire awe, reminding us of humanity's enduring quest for greatness.</narration>
99
+ <image>Visitors captivated by the beauty and historical significance of these ancient marvels, exploring and marveling.</image>
100
+ """,
101
+ agent=image_descriptive_agent,
102
+ context=[story_writing_task]
103
+ )
104
+
105
+
106
+
107
+ # process_script_task = Task(
108
+ # description="Extract text for image and speech generation from a provided script.",
109
+ # expected_output="A dictionary containing lists of texts for image generation and speech generation.",
110
+ # agent=ScriptSynthesizer
111
+ # )
112
+
113
+ # img_generation_task = Task(
114
+ # description='Given the input generate images for sequence of sentence enclosed in <image> tag.',
115
+ # expected_output="""Acknowledgement of image generation""",
116
+ # tools = [image_generator],
117
+ # context = [img_text_task],
118
+ # # async_execution=True,
119
+ # agent=img_speech_generating_agent
120
+ # )
121
+
122
+ # speech_generation_task = Task(
123
+ # description='Given the input generate speech for each sentence enclosed in <narration> tag.',
124
+ # expected_output="""Acknowledgement of speech generation""",
125
+ # tools = [speech_generator],
126
+ # context = [img_text_task],
127
+ # # async_execution=True,
128
+ # agent=img_speech_generating_agent
129
+ # )
130
+ img_generation_task = Task(
131
+ description='Given the script, use the given tool to generate images using {model}',
132
+ expected_output="""path of images folder""",
133
+ tools = [image_generator],
134
+ context = [img_text_task],
135
+ # async_execution=True,
136
+ agent=img_speech_generating_agent
137
+ )
138
+
139
+ speech_generation_task = Task(
140
+ description='Given the script, use the given tool to generate speech',
141
+ expected_output="""path of speeches folder""",
142
+ tools = [speech_generator],
143
+ context = [img_text_task],
144
+ # async_execution=True,
145
+ agent=img_speech_generating_agent
146
+ )
147
+
148
+ make_video_task = Task(
149
+ description = 'Create video using images and speeches from the forlders received from previous task.',
150
+ expected_output = "output video path",
151
+ agent=editor,
152
+ context = [img_generation_task, speech_generation_task]
153
+ )
154
+
155
+ agents = [
156
+ script_agent,
157
+ image_descriptive_agent,
158
+ img_speech_generating_agent,
159
+ editor
160
+ ]
161
+
162
+ tasks = [
163
+ content_generation_task,
164
+ story_writing_task,
165
+ img_text_task,
166
+ img_generation_task,
167
+ speech_generation_task,
168
+ make_video_task
169
+ ]
170
+
171
+ return agents, tasks
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+
4
+ from crewai import Crew, Process
5
+ from agents import get_agents_and_tasks
6
+
7
+
8
+ def generate_video(topic, openai_api_key, stabilityai_api_key):
9
+ # os.environ['STABILITY_AI_API_KEY'] = stability_ai_api_key
10
+ os.environ['OPENAI_API_KEY'] = openai_api_key
11
+ grow_api_key = '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'
12
+ agents, tasks = get_agents_and_tasks(grow_api_key)
13
+
14
+ crew = Crew(
15
+ agents = agents,
16
+ tasks = tasks,
17
+ process = Process.sequential,
18
+ memory=True,
19
+ verbose=2
20
+ )
21
+ result = crew.kickoff(inputs={'topic': topic})
22
+ return result
23
+
24
+ intro = """
25
+ <!DOCTYPE html>
26
+ <html lang="en">
27
+ <head>
28
+ <meta charset="UTF-8">
29
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
30
+ <title>Shorts Generator Page</title>
31
+ <style>
32
+ .heading {
33
+ font-size: 24px;
34
+ font-weight: bold;
35
+ text-align: center;
36
+ }
37
+ .subheading {
38
+ font-size: 18px;
39
+ font-weight: bold;
40
+ text-align: center;
41
+ margin-top: 10px;
42
+ }
43
+ .additional-text {
44
+ font-size: 16px;
45
+ text-align: center;
46
+ margin-top: 20px;
47
+ white-space: pre-line; /* Preserve line breaks */
48
+ }
49
+ </style>
50
+ </head>
51
+ <body>
52
+ <div class="heading">
53
+ YouTube Shorts Creator
54
+ </div>
55
+ <div class="subheading">
56
+ Generate stunning short videos with simple text input
57
+ </div>
58
+ </body>
59
+ </html>
60
+ """
61
+
62
+ with gr.Blocks(title='ShortsIn') as app:
63
+
64
+ gr.HTML(intro)
65
+
66
+ with gr.Row():
67
+ with gr.Column():
68
+ inp = gr.Textbox(label='Enter title here')
69
+ api = gr.Textbox(label='Enter your openai API key here')
70
+ btn = gr.Button('Generate', size='lg')
71
+
72
+ with gr.Column():
73
+ out = gr.Video(label='')
74
+
75
+
76
+ btn.click(fn=generate_video, inputs=[inp, api], outputs=out)
77
+
78
+ app.launch()
demo.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from crewai import Crew, Process
4
+ from agents import get_agents_and_tasks
5
+ from tools import send_mail
6
+
7
+ def generate_video(topic, openai_api_key, stabilityai_api_key, user_email):
8
+ os.environ['OPENAI_API_KEY'] = openai_api_key
9
+ grow_api_key = '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'
10
+ if stabilityai_api_key is not None:
11
+ os.environ['STABILITY_AI_API_KEY'] = stabilityai_api_key
12
+ model = 'Stability AI'
13
+ else:
14
+ model = 'Dalle-2'
15
+ agents, tasks = get_agents_and_tasks(grow_api_key)
16
+
17
+ crew = Crew(
18
+ agents=agents,
19
+ tasks=tasks,
20
+ process=Process.sequential,
21
+ memory=True,
22
+ verbose=2
23
+ )
24
+ result = crew.kickoff(inputs={'topic': topic, 'model' : model})
25
+ send_mail(user_email, result)
26
+ return result
27
+
28
+ # Custom CSS for styling
29
+ st.markdown(
30
+ """
31
+ <style>
32
+ .heading {
33
+ font-size: 24px;
34
+ font-weight: bold;
35
+ text-align: center;
36
+ }
37
+ .subheading {
38
+ font-size: 18px;
39
+ font-weight: bold;
40
+ text-align: center;
41
+ margin-top: 10px;
42
+ }
43
+ .example-video-container {
44
+ display: flex;
45
+ flex-wrap: wrap;
46
+ justify-content: flex-start;
47
+ }
48
+ .example-video {
49
+ margin: 10px;
50
+ }
51
+ </style>
52
+ """,
53
+ unsafe_allow_html=True,
54
+ )
55
+
56
+ # Main content area
57
+ st.markdown(
58
+ """
59
+ <div class="heading">
60
+ YouTube Shorts Creator
61
+ </div>
62
+ <div class="subheading">
63
+ Generate stunning short videos with simple prompt
64
+ </div>
65
+ """,
66
+ unsafe_allow_html=True,
67
+ )
68
+
69
+ # Space
70
+ st.text(" ")
71
+
72
+ # Main content for Input Details
73
+ st.markdown("## Input Details")
74
+ topic = st.text_input("Prompt")
75
+ openai_api_key = st.text_input("OpenAI API key")
76
+ size = st.selectbox('Size',
77
+ ('512 X 512', '1024 X 1024', '9:16'))
78
+ stabilityai_api_key = None
79
+ if size=='9:16':
80
+ st.text_input('Stability Ai API key')
81
+ user_email = st.text_input("Email address", placeholder='[email protected]')
82
+
83
+ if st.button("Mail Me!"):
84
+ st.text(f"Video will be sent to {user_email}")
85
+ result = generate_video(topic, openai_api_key, stabilityai_api_key, user_email)
86
+ #st.success(result)
87
+ # In a real scenario, you would send the generated video to the user's email here
88
+
89
+ # Sidebar for Example Videos
90
+ st.sidebar.markdown("### Example Videos")
91
+ example_paths = os.listdir('results')
92
+ examples = [os.path.join('results', i) for i in example_paths]
93
+
94
+ # Display videos in a row
95
+ st.sidebar.markdown('<div class="example-video-container">', unsafe_allow_html=True)
96
+ for video_url in examples:
97
+ title = video_url.split('\\')[1].split('.')[0]
98
+ st.sidebar.text(f"input: {title}")
99
+ st.sidebar.video(video_url, format="video/mp4", start_time=0)
100
+ st.sidebar.markdown("</div>", unsafe_allow_html=True)
requirements.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ gradio
3
+ ffmpeg
4
+ pysqlite3-binary
5
+ embedchain
6
+ crewai
7
+ crewai-tools
8
+ langchain_groq
9
+ langchain
10
+ langchain_community
11
+ moviepy
12
+ opencv-python-headless
13
+ opencv-python
14
+ gradio
15
+ wikipedia
16
+ gtts
17
+ openai
18
+ pydub
streamlit_app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from crewai import Crew, Process
4
+ from agents import get_agents_and_tasks
5
+ from tools import send_mail
6
+
7
+ def generate_video(topic, openai_api_key, stabilityai_api_key, user_mail):
8
+ os.environ['OPENAI_API_KEY'] = openai_api_key
9
+ grow_api_key = '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'
10
+ if stabilityai_api_key is not None:
11
+ os.environ['STABILITY_AI_API_KEY'] = stabilityai_api_key
12
+ model = 'Stability AI'
13
+ else:
14
+ model = 'Dalle-2'
15
+ agents, tasks = get_agents_and_tasks(grow_api_key)
16
+
17
+ crew = Crew(
18
+ agents=agents,
19
+ tasks=tasks,
20
+ process=Process.sequential,
21
+ memory=True,
22
+ verbose=2
23
+ )
24
+ result = crew.kickoff(inputs={'topic': topic, 'model' : model})
25
+ send_mail(user_mail, result)
26
+ return result
27
+
28
+ st.markdown("""
29
+ <style>
30
+ .heading {
31
+ font-size: 24px;
32
+ font-weight: bold;
33
+ text-align: center;
34
+ }
35
+ .subheading {
36
+ font-size: 18px;
37
+ font-weight: bold;
38
+ text-align: center;
39
+ margin-top: 10px;
40
+ }
41
+ </style>
42
+ """, unsafe_allow_html=True)
43
+
44
+ st.markdown("""
45
+ <div class="heading">
46
+ YouTube Shorts Creator
47
+ </div>
48
+ <div class="subheading">
49
+ Generate stunning short videos with simple text input
50
+ </div>
51
+ """, unsafe_allow_html=True)
52
+
53
+ st.text(" ")
54
+
55
+ topic = st.text_input('Enter title here')
56
+ openai_api_key = st.text_input('Enter your OpenAI API key here')
57
+ size = st.selectbox('Size',
58
+ ('512 X 512', '1024 X 1024', '9:16'))
59
+ stabilityai_api_key = None
60
+ if size=='9:16':
61
+ stabilityai_api_key = st.text_input('Enter your stability ai API key here')
62
+ mail = st.text_input('Enter you email address')
63
+
64
+ if st.button('Generate'):
65
+ st.text(f"Video will be sent to {mail}")
66
+ result = generate_video(topic, openai_api_key, stabilityai_api_key, mail)
67
+ # with open(result, 'rb') as video_file:
68
+ # video_data = video_file.read()
69
+ # st.video(video_data)
70
+
71
+ # Sidebar for Example Videos
72
+ st.sidebar.markdown("### Example Videos")
73
+ example_paths = os.listdir('results')
74
+ examples = [os.path.join('results', i) for i in example_paths]
75
+
76
+ # Display videos in a row
77
+ st.sidebar.markdown('<div class="example-video-container">', unsafe_allow_html=True)
78
+ for video_url in examples:
79
+ title = video_url.split('\\')[1].split('.')[0]
80
+ st.sidebar.text(f"input: {title}")
81
+ st.sidebar.video(video_url, format="video/mp4", start_time=0)
82
+ st.sidebar.markdown("</div>", unsafe_allow_html=True)
83
+
tools.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from crewai import Task, Agent, Crew, Process
2
+ from langchain.tools import tool, Tool
3
+ import re
4
+ import os
5
+ from langchain_groq import ChatGroq
6
+ # llm = ChatGroq(model='mixtral-8x7b-32768', temperature=0.6, max_tokens=2048)
7
+ llm = ChatGroq(model='llama3-70b-8192', temperature=0.6, max_tokens=1024, api_key='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')
8
+ from langchain_community.tools import WikipediaQueryRun
9
+ from langchain_community.utilities import WikipediaAPIWrapper
10
+ from langchain_core.pydantic_v1 import BaseModel, Field
11
+ import requests
12
+ # import pyttsx3
13
+ import io
14
+ import tempfile
15
+ from gtts import gTTS
16
+ from pydub import AudioSegment
17
+ from groq import Groq
18
+ import cv2
19
+ import numpy as np
20
+ from PIL import Image, ImageDraw, ImageFont
21
+ from moviepy.editor import VideoFileClip, AudioFileClip, concatenate_videoclips, ImageClip
22
+ from openai import OpenAI
23
+
24
+ def split_text_into_chunks(text, chunk_size):
25
+ words = text.split()
26
+ return [' '.join(words[i:i + chunk_size]) for i in range(0, len(words), chunk_size)]
27
+
28
+ def add_text_to_video(input_video, text, duration=1, fontsize=40, fontcolor=(255, 255, 255),
29
+ outline_thickness=2, outline_color=(0, 0, 0), delay_between_chunks=0.3,
30
+ font_path='Montserrat-Bold.ttf'):
31
+ temp_output_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
32
+ output_video = temp_output_file.name
33
+
34
+ chunks = split_text_into_chunks(text, 3) # Adjust chunk size as needed
35
+
36
+ cap = cv2.VideoCapture(input_video)
37
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
38
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
39
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
40
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
41
+ out = cv2.VideoWriter(output_video, fourcc, fps, (width, height))
42
+
43
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
44
+ chunk_duration_frames = duration * fps
45
+ delay_frames = int(delay_between_chunks * fps)
46
+
47
+ font = ImageFont.truetype(font_path, fontsize)
48
+
49
+ current_frame = 0
50
+
51
+ while cap.isOpened():
52
+ ret, frame = cap.read()
53
+ if not ret:
54
+ break
55
+
56
+ frame_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
57
+ draw = ImageDraw.Draw(frame_pil)
58
+
59
+ chunk_index = current_frame // (chunk_duration_frames + delay_frames)
60
+
61
+ if current_frame % (chunk_duration_frames + delay_frames) < chunk_duration_frames and chunk_index < len(chunks):
62
+ chunk = chunks[chunk_index]
63
+ text_bbox = draw.textbbox((0, 0), chunk, font=font)
64
+ text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
65
+ text_x = (width - text_width) // 2
66
+ text_y = height - 400 # Position text at the bottom
67
+
68
+ if text_width > width:
69
+ words = chunk.split()
70
+ half = len(words) // 2
71
+ line1 = ' '.join(words[:half])
72
+ line2 = ' '.join(words[half:])
73
+
74
+ text_size_line1 = draw.textsize(line1, font=font)
75
+ text_size_line2 = draw.textsize(line2, font=font)
76
+ text_x_line1 = (width - text_size_line1[0]) // 2
77
+ text_x_line2 = (width - text_size_line2[0]) // 2
78
+ text_y = height - 250 - text_size_line1[1] # Adjust vertical position for two lines
79
+
80
+ for dx in range(-outline_thickness, outline_thickness + 1):
81
+ for dy in range(-outline_thickness, outline_thickness + 1):
82
+ if dx != 0 or dy != 0:
83
+ draw.text((text_x_line1 + dx, text_y + dy), line1, font=font, fill=outline_color)
84
+ draw.text((text_x_line2 + dx, text_y + text_size_line1[1] + dy), line2, font=font, fill=outline_color)
85
+
86
+ draw.text((text_x_line1, text_y), line1, font=font, fill=fontcolor)
87
+ draw.text((text_x_line2, text_y + text_size_line1[1]), line2, font=fontcolor)
88
+
89
+ else:
90
+ for dx in range(-outline_thickness, outline_thickness + 1):
91
+ for dy in range(-outline_thickness, outline_thickness + 1):
92
+ if dx != 0 or dy != 0:
93
+ draw.text((text_x + dx, text_y + dy), chunk, font=font, fill=outline_color)
94
+
95
+ draw.text((text_x, text_y), chunk, font=font, fill=fontcolor)
96
+
97
+ frame = cv2.cvtColor(np.array(frame_pil), cv2.COLOR_RGB2BGR)
98
+
99
+ out.write(frame)
100
+ current_frame += 1
101
+
102
+ # Ensure loop breaks after processing all frames
103
+ if current_frame >= frame_count:
104
+ break
105
+
106
+ cap.release()
107
+ out.release()
108
+ cv2.destroyAllWindows()
109
+
110
+ return output_video
111
+
112
+ def apply_zoom_in_effect(clip, zoom_factor=1.2):
113
+ width, height = clip.size
114
+ duration = clip.duration
115
+
116
+ def zoom_in_effect(get_frame, t):
117
+ frame = get_frame(t)
118
+ zoom = 1 + (zoom_factor - 1) * (t / duration)
119
+ new_width, new_height = int(width * zoom), int(height * zoom)
120
+ resized_frame = cv2.resize(frame, (new_width, new_height))
121
+
122
+ x_start = (new_width - width) // 2
123
+ y_start = (new_height - height) // 2
124
+ cropped_frame = resized_frame[y_start:y_start + height, x_start:x_start + width]
125
+
126
+ return cropped_frame
127
+
128
+ return clip.fl(zoom_in_effect, apply_to=['mask'])
129
+
130
+ @tool
131
+ def create_video_from_images_and_audio(images_dir, speeches_dir, zoom_factor=1.2):
132
+ """Creates video using images and audios.
133
+ Args:
134
+ images_dir: path to images folder
135
+ speeches_dir: path to speeches folder"""
136
+ client = Groq(api_key='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')
137
+ # images_paths = sorted(os.listdir(images_dir))
138
+ # audio_paths = sorted(os.listdir(speeches_dir))
139
+ images_paths = sorted([os.path.join(images_dir, img) for img in os.listdir(images_dir) if img.endswith('.png') or img.endswith('.jpg')])
140
+ audio_paths = sorted([os.path.join(speeches_dir, speech) for speech in os.listdir(speeches_dir) if speech.endswith('.mp3')])
141
+ clips = []
142
+ temp_files = []
143
+
144
+ for i in range(min(len(images_paths), len(audio_paths))):
145
+ img_clip = ImageClip(os.path.join(images_dir, images_paths[i]))
146
+ audioclip = AudioFileClip(os.path.join(speeches_dir, audio_paths[i]))
147
+ videoclip = img_clip.set_duration(audioclip.duration)
148
+ zoomed_clip = apply_zoom_in_effect(videoclip, zoom_factor)
149
+
150
+ with open(os.path.join(speeches_dir, audio_paths[i]), "rb") as file:
151
+ transcription = client.audio.transcriptions.create(
152
+ file=(audio_paths[i], file.read()),
153
+ model="whisper-large-v3",
154
+ response_format="verbose_json",
155
+ )
156
+ caption = transcription.text
157
+ temp_video_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name
158
+ zoomed_clip.write_videofile(temp_video_path, codec='libx264', fps=24)
159
+ temp_files.append(temp_video_path)
160
+
161
+ final_video_path = add_text_to_video(temp_video_path, caption, duration=1, fontsize=60)
162
+ temp_files.append(final_video_path)
163
+
164
+ final_clip = VideoFileClip(final_video_path)
165
+ final_clip = final_clip.set_audio(audioclip)
166
+
167
+ print(f'create small video {i}')
168
+ clips.append(final_clip)
169
+
170
+ final_clip = concatenate_videoclips(clips)
171
+ temp_final_video = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name
172
+ final_clip.write_videofile(temp_final_video, codec='libx264', fps=24)
173
+
174
+ # Close all video files properly
175
+ for clip in clips:
176
+ clip.close()
177
+
178
+ # Remove all temporary files
179
+ for temp_file in temp_files:
180
+ try:
181
+ os.remove(temp_file)
182
+ except Exception as e:
183
+ print(f"Error removing file {temp_file}: {e}")
184
+
185
+ return temp_final_video
186
+
187
+ from langchain.pydantic_v1 import BaseModel, Field
188
+ from langchain_community.tools import WikipediaQueryRun
189
+ from langchain_community.utilities import WikipediaAPIWrapper
190
+
191
+ class WikiInputs(BaseModel):
192
+ """Inputs to the wikipedia tool."""
193
+ query: str = Field(description="query to look up in Wikipedia, should be 3 or less words")
194
+
195
+ api_wrapper = WikipediaAPIWrapper(top_k_results=2)#, doc_content_chars_max=100)
196
+
197
+ wiki_tool = WikipediaQueryRun(
198
+ name="wiki-tool",
199
+ description="{query:'input here'}",
200
+ args_schema=WikiInputs,
201
+ api_wrapper=api_wrapper,
202
+ return_direct=True,
203
+ )
204
+
205
+ wiki = Tool(
206
+ name = 'wikipedia',
207
+ func = wiki_tool.run,
208
+ description= "{query:'input here'}"
209
+ )
210
+
211
+ def process_script(script):
212
+ """Used to process the script into dictionary format"""
213
+ dict = {}
214
+ text_for_image_generation = re.findall(r'<image>(.*?)</?image>', script, re.DOTALL)
215
+ text_for_speech_generation = re.findall(r'<narration>(.*?)</?narration>', script, re.DOTALL)
216
+ dict['text_for_image_generation'] = text_for_image_generation
217
+ dict['text_for_speech_generation'] = text_for_speech_generation
218
+ return dict
219
+
220
+ def generate_speech(text, lang='en', speed=1.15, num=0):
221
+ """
222
+ Generates speech for the given script using gTTS and adjusts the speed.
223
+ """
224
+ temp_speech_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
225
+ temp_speech_path = temp_speech_file.name
226
+
227
+ tts = gTTS(text=text, lang=lang)
228
+ tts.save(temp_speech_path)
229
+
230
+ sound = AudioSegment.from_file(temp_speech_path)
231
+ if speed != 1.0:
232
+ sound_with_altered_speed = sound._spawn(sound.raw_data, overrides={
233
+ "frame_rate": int(sound.frame_rate * speed)
234
+ }).set_frame_rate(sound.frame_rate)
235
+ sound_with_altered_speed.export(temp_speech_path, format="mp3")
236
+ else:
237
+ sound.export(temp_speech_path, format="mp3")
238
+
239
+ temp_speech_file.close()
240
+ return temp_speech_path
241
+
242
+ @tool
243
+ def image_generator(script, model):
244
+ """Generates images for the given script.
245
+ Saves it to a temporary directory and returns the path.
246
+ Args:
247
+ script: a complete script containing narrations and image descriptions.
248
+ model: image generation model used to generate images, can be 'Stability' or 'Dalle-2'"""
249
+
250
+ remove_temp_files('/tmp')
251
+
252
+ images_dir = tempfile.mkdtemp()
253
+ dict = process_script(script)
254
+
255
+ if model == 'Stability':
256
+
257
+ for i, text in enumerate(dict['text_for_image_generation']):
258
+ try:
259
+ response = requests.post(
260
+ f"https://api.stability.ai/v2beta/stable-image/generate/core",
261
+ headers={
262
+ "authorization": os.environ.get('STABILITY_AI_API_KEY'),
263
+ "accept": "image/*"
264
+ },
265
+ files={"none": ''},
266
+ data={
267
+ "prompt": text,
268
+ "output_format": "png",
269
+ 'aspect_ratio': "9:16",
270
+ },
271
+ )
272
+ print(f'image {i} generated')
273
+ if response.status_code == 200:
274
+ with open(os.path.join(images_dir, f'image_{i}.png'), 'wb') as file:
275
+ file.write(response.content)
276
+ else:
277
+ raise Exception(str(response.json()))
278
+ except Exception as e:
279
+ raise Exception(f"Image generation failed: {e}")
280
+
281
+ elif model == 'Dalle-2':
282
+ client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
283
+ for i, text in enumerate(dict['text_for_image_generation']):
284
+ try:
285
+ response = client.images.generate(
286
+ model="dall-e-2",
287
+ prompt=text,
288
+ size="1024x1024",
289
+ quality="standard",
290
+ n=1
291
+ )
292
+ image_url = response.data[0].url
293
+
294
+ print(f'image {i} generated')
295
+ # Download the image
296
+ image_response = requests.get(image_url)
297
+ if image_response.status_code == 200:
298
+ with open(os.path.join(images_dir, f'image_{i}.png'), 'wb') as file:
299
+ file.write(image_response.content)
300
+ else:
301
+ raise Exception(f"Failed to download image with status code {image_response.status_code} and message: {image_response.text}")
302
+
303
+ except Exception as e:
304
+ raise Exception(f"Image generation failed: {e}")
305
+
306
+ return f'images are stored in {images_dir} directory'
307
+
308
+ @tool
309
+ def speech_generator(script):
310
+ """
311
+ Generates speech files for the given script using gTTS.
312
+ Saves them to a temporary directory and returns the path.
313
+ Args:
314
+ script: a complete script containing narrations and image descriptions.
315
+ """
316
+ speeches_dir = tempfile.mkdtemp()
317
+
318
+ dict = process_script(script)
319
+ for i, text in enumerate(dict['text_for_speech_generation']):
320
+ speech_path = generate_speech(text, num=i)
321
+ print(f'speech {i} generated')
322
+ os.rename(speech_path, os.path.join(speeches_dir, f'speech_{i}.mp3'))
323
+
324
+ return f'images are stored in {speeches_dir} directory'
325
+
326
+ def find_temp_files(directory):
327
+ temp_files = []
328
+
329
+ for root, dirs, files in os.walk(directory):
330
+ for file in files:
331
+ file_path = os.path.join(root, file)
332
+ if os.path.isfile(file_path) and file_path.startswith('/tmp'):
333
+ temp_files.append(file_path)
334
+
335
+ return temp_files
336
+
337
+ def remove_temp_files(directory):
338
+ temp_files = find_temp_files(directory)
339
+
340
+ for temp_file in temp_files:
341
+ try:
342
+ os.remove(temp_file)
343
+ print(f"Removed temp file: {temp_file}")
344
+ except Exception as e:
345
+ print(f"Error removing temp file {temp_file}: {e}")
346
+
347
+ # # Example usage
348
+ # remove_temp_files('/tmp')
349
+
350
+ import smtplib
351
+ from email.mime.text import MIMEText
352
+ from email.mime.multipart import MIMEMultipart
353
+ from email.mime.base import MIMEBase
354
+ from email import encoders
355
+
356
+ def send_mail(user_mail, video_path):
357
+ # Email configuration
358
+ sender_email = '[email protected]'
359
+ receiver_email = user_mail
360
+ password = 'pzxb drfj aebj ypuv' # Normally, you should store sensitive information like passwords securely.
361
+
362
+ # Create message container - the correct MIME type is multipart/alternative.
363
+ msg = MIMEMultipart('alternative')
364
+ msg['Subject'] = 'From ShortsIn'
365
+ msg['From'] = sender_email
366
+ msg['To'] = receiver_email
367
+
368
+ # Create the plain-text and HTML version of your message
369
+ text = "Hello,"
370
+ html = """\
371
+ <html>
372
+ <body>
373
+ <p>Hello,<br>
374
+ Thankyou for using ShortsIn.
375
+ </p>
376
+ </body>
377
+ </html>
378
+ """
379
+
380
+ # Attach parts into message container
381
+ part1 = MIMEText(text, 'plain')
382
+ part2 = MIMEText(html, 'html')
383
+
384
+ msg.attach(part1)
385
+ msg.attach(part2)
386
+
387
+ if os.path.isfile(video_path):
388
+ with open(video_path, 'rb') as attachment:
389
+ part = MIMEBase('application', 'octet-stream')
390
+ part.set_payload(attachment.read())
391
+ encoders.encode_base64(part)
392
+ part.add_header(
393
+ 'Content-Disposition',
394
+ f'attachment; filename= {os.path.basename(video_path)}',
395
+ )
396
+ msg.attach(part)
397
+ else:
398
+ print(f"Error: The file {video_path} does not exist.")
399
+
400
+ # Connect to the SMTP server
401
+ try:
402
+ server = smtplib.SMTP('smtp.gmail.com', 587) # Example SMTP server and port
403
+ server.starttls() # Secure the connection
404
+ server.login(sender_email, password)
405
+ server.sendmail(sender_email, receiver_email, msg.as_string())
406
+ print('Email sent successfully!')
407
+ except Exception as e:
408
+ print(f'Error sending email: {str(e)}')
409
+ finally:
410
+ server.quit()