This repository has been archived by the owner on Jun 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathmake_compilation.py
183 lines (143 loc) · 6.27 KB
/
make_compilation.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
from moviepy.editor import VideoFileClip, concatenate_videoclips
from moviepy.video.fx.resize import resize
import os
from os.path import isfile, join
import random
import shutil
from collections import defaultdict
import json
from pyffmpeg import FFmpeg
ff = FFmpeg()
VideoFileClip.resize = resize
def extractAcc(filepath):
try:
s = filepath.split("/")[-1].split("-")
acc = "-".join(s[1:(2+(len(s) - 4))])
return acc
except:
return ""
# generateTimeRange converts float seconds to a range of form @MM:SS
def generateTimeRange(duration, clipDuration):
preHour = int(duration / 60)
preMin = int(duration % 60)
preTime = str(preHour // 10) + str(preHour % 10) + ":" + str(preMin // 10) + str(preMin % 10)
duration += clipDuration
postHour = int(duration / 60)
postMin = int(duration % 60)
postTime = str(postHour // 10) + str(postHour % 10) + ":" + str(postMin // 10) + str(postMin % 10)
#return "@" + preTime + " - " + "@" + postTime
return "@" + preTime
# makeCompilation takes videos in a folder and creates a compilation with max length totalVidLength
def makeCompilation(path = "./",
introName = '',
outroName = '',
wmark = '',
totalVidLength = 10,
maxClipLength = 20,
minClipLength = 5,
outputFile = "output.mp4",
video_source_meta = {},
videoDirectory = "",
description_meta = "",
modeAM = "A"):
downVideos = []
seenLengths = defaultdict(list)
#totalLength = 0
duration = 0
videos = []
# Add intro video if included
if introName != '':
introVid = VideoFileClip("./" + introName)
videos.append(introVid)
timeStamp = generateTimeRange(duration, introVid.duration)
duration += introVid.duration
for fileName in os.listdir(path):
filePath = join(path, fileName)
if isfile(filePath) and fileName.endswith(".mp4"):
if os.stat(filePath).st_size < 5000:
continue
# Destination path
print("[i] ", filePath)
clip = VideoFileClip(filePath)
clip = clip.resize(width=1920)
clip = clip.resize(height=1080)
duration = clip.duration
print("[i] " + fileName + " " + str(duration) + " Added")
# add_video in min&max range or ignore errors
def add_video(duration):
downVideos.append(clip)
seenLengths[duration].append(fileName)
duration += clip.duration
print("[i] ", duration, seenLengths, downVideos)
if modeAM == "A":
add_video(duration)
elif modeAM == "M":
if duration <= maxClipLength and duration >= minClipLength:
add_video(duration)
else:
ignore_error = input("[Q] Do you want to ignore Errors in min max Total Video Length?(Y/n)").strip()
if ignore_error != "n":
pass
else:
add_video(duration)
#Add automated description
for k in range(len(os.listdir(path))):
fileNameJ = fileName.split(".mp4")
fileNameJSON = ''.join(fileNameJ) + ".json"
acc = extractAcc(clip.filename)
timeStamp = generateTimeRange((duration - clip.duration), clip.duration)
video_source_meta[f"TimeStamps{k}"] = timeStamp + " : @" + acc + "\n"
video_source_meta[f"profile{k}"] = "Instagram profile:" + " instagram.com/" + acc +'\n'
#extract url & other information about video
f = open(f"{videoDirectory}{fileNameJSON}", "r")
json_d = json.loads(f.read())
f.close()
video_source_meta[f"vido_url{k}"] = "Video URL:" + "instagram.com/tv/" + json_d["shortcode"] + '\n'
video_source_meta[f"Caption{k}"] = json_d["edge_media_to_caption"]["edges"][0]["node"]["text"] + '\n'
description_meta = video_source_meta[f"TimeStamps{k}"] + video_source_meta[f"profile{k}"] + video_source_meta[f"vido_url{k}"] + video_source_meta[f"Caption{k}"] + '\n\n'
print("[i] ", description_meta)
with open(f"{videoDirectory}description.txt", 'a', encoding="utf-8") as dfile:
dfile.write(description_meta)
print("[i] Total Length: " + str(duration))
# Create videos
for clip in downVideos:
#duration += clip.duration
videos.append(clip)
if duration >= totalVidLength:
# Just make one video
break
# Add outro vid
if outroName != '':
outroVid = VideoFileClip("./" + outroName)
videos.append(outroVid)
# Used Moviepy
finalClip = concatenate_videoclips(videos, method="compose")
audio_path = "/tmp/temoaudiofile.m4a"
# Create compilation
finalClip.write_videofile(outputFile, threads=8, temp_audiofile=audio_path, remove_temp=True, codec="libx264", audio_codec="aac")
def watrmrk():
print("[i] Adding Watermark")
os.rename(outputFile, f"{outputFile}.tmp")
ff.options(f"-i {outputFile}.tmp -i {wmark} -filter_complex overlay=1500:10 {outputFile}")
os.remove(f"{outputFile}.tmp")
print("[i] Watermark added")
if modeAM == "M":
add_waterMark = input(f"[Q] Do you want to add watermark {wmark}(Y/n):").strip()
if add_waterMark.lower() == "n":
print("[i] No watermark added")
else:
watrmrk()
else:
watrmrk()
if __name__ == "__main__":
makeCompilation(path = "/home/kali/Documents/YOUTUBE/AutomatedChannel/Videos/Memes/",
introName = "intro_vid.mp4",
outroName = 'outro.mp4',
wmark = 'BotTuber.png',
totalVidLength = 10*60,
maxClipLength = 20,
outputFile = "outputseq.mp4",
video_source_meta = {},
videoDirectory = "",
description_meta = "",
modeAM = "A")