-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheditor.py
294 lines (275 loc) · 10.4 KB
/
editor.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
import datetime
import ffmpeg
import inspect
import json
import os
import sys
if os.name == 'nt':
delimeter = '\\'
else:
delimeter = '/'
try:
if (sys.argv[1] == "--debug"):
lineEnd = "\n"
else:
lineEnd = "\r"
except:
lineEnd = "\r"
def line(): #get line number
line = inspect.currentframe().f_back.f_lineno
line = '%03d' % line
return line
def clearline(): #clear line for reprinting on same line
print("\t\t\t\t\t\t\t\t\t\t\t\t\t",end='\r')
def textline(line,text,endLine=lineEnd): #print to terminal including timestamp and line number
if(endLine==lineEnd):
clearline()
print(datetime.datetime.now().strftime("%H:%M:%S")+": "+str(line)+" - " + text,end=endLine)
def convert(seconds):
min, sec = divmod(seconds, 60)
hour, min = divmod(min, 60)
return "%d:%02d:%02d" % (hour, min, sec)
def selectFile(k):
fileSelection = input(">:")
try:
fileSelection = int(fileSelection)
except ValueError:
print("Enter a Number Between 1 and "+str(k-1)+":")
fileSelection = input(">:")
while fileSelection >= int(k):
print("Enter a Number Between 1 and "+str(k-1)+":")
fileSelection = input(">:")
try:
fileSelection = int(fileSelection)
except ValueError:
fileSelection = k
return fileSelection
def formatDuration(file):
fileProbe = ffmpeg.probe(file)
lengthSplit = fileProbe['format']['duration'].split('.')
lengthSeconds = int(lengthSplit[0])
lengthFormatted = convert(lengthSeconds)
return lengthFormatted
def secondsDuration(file):
fileProbe = ffmpeg.probe(file)
lengthSeconds = fileProbe['format']['duration']
return lengthSeconds
def getFrameRate(file):
frameRate = ""
try:
fileProbe = ffmpeg.probe(file)
avgFrameRate = fileProbe['streams'][1]['avg_frame_rate'].split('/')
except:
frameRate = "N/A"
if frameRate != "N/A":
try:
frameRate = round(int(avgFrameRate[0])/int(avgFrameRate[1]),2)
except ZeroDivisionError as err:
print("Framerate Detection Error")
frameRate = 0
return frameRate
def selectDirectory(delimeter):
print("Enter the directory path to scan")
workingDir = os.getcwd()
print("Press Enter to use "+workingDir)
path = input(">:")
if path == "":
path = workingDir
if path[-1] != delimeter:
path = path + delimeter
return path
def selectJSON(path):
dirContents = os.scandir(path)
dirDict = {}
k = 1
for entry in dirContents:
if entry.name[-4:].lower() in 'json':
dirDict[k] = entry.name
print(str(k)+": "+entry.name)
k = k + 1
fileSelection = selectFile(k)
print("\nJSON FILE SELECTED")
print(path+dirDict[fileSelection])
cont = input("\nContinue with this file? (Y/N) >:")
yn = ['y','Y','Yes','YES','yes','N','n','No','NO','no']
yes = ['y','Y','Yes','YES','yes']
no = ['N','n','No','NO','no']
while cont not in yn:
print("INVALID ENTRY")
cont = input("Continue with this file? (Y/N) >:")
while cont in no:
print("Enter a Number Between 1 and "+str(k-1)+":")
fileSelection = selectFile(k)
print("FILE SELECTED")
print(dirDict[fileSelection])
cont = input("\nContinue with this file? (Y/N) >:")
print("CONFIRMED!")
return dirDict[fileSelection]
def selectVideoFile(path, ext):
dirContents = os.scandir(path)
dirDict = {}
k = 1
for entry in dirContents:
if entry.name[-3:] in ext:
dirDict[k] = entry.name
try:
lengthFormatted = formatDuration(entry.name)
except:
lengthFormatted = "N/A"
print(str(k)+": "+entry.name+" ------ "+lengthFormatted)
k = k + 1
fileSelection = selectFile(k)
print("\nFILE SELECTED")
print(path+dirDict[fileSelection])
try:
lengthFormatted = formatDuration(dirDict[fileSelection])
except:
lengthFormatted = "N/A"
print("DURATION = "+lengthFormatted)
try:
frameRate = getFrameRate(dirDict[fileSelection])
except:
frameRate = "N/A"
print("FRAME RATE = "+str(frameRate)+" FPS")
cont = input("\nContinue with this file? (Y/N) >:")
yn = ['y','Y','Yes','YES','yes','N','n','No','NO','no']
yes = ['y','Y','Yes','YES','yes']
no = ['N','n','No','NO','no']
while cont not in yn:
print("INVALID ENTRY")
cont = input("Continue with this file? (Y/N) >:")
while cont in no:
print("Enter a Number Between 1 and "+str(k-1)+":")
fileSelection = selectFile(k)
print("FILE SELECTED")
print(dirDict[fileSelection])
lengthFormatted = formatDuration(dirDict[fileSelection])
print("DURATION = "+lengthFormatted)
frameRate = getFrameRate(dirDict[fileSelection])
print("FRAME RATE = "+str(frameRate)+" FPS")
cont = input("\nContinue with this file? (Y/N) >:")
print("CONFIRMED!")
return dirDict[fileSelection]
def splitVideo(entry,startSplit,endSplit,outputName,path):
prevOutputName = ""
filename = os.path.join(path,entry)
#do the split
print("Creating "+outputName+" from "+entry)
try:
(
ffmpeg
.input(filename, ss=startSplit, to=endSplit)
.output(os.path.join(path,outputName), c='copy', loglevel="error")
.run(quiet=True, capture_stderr=True)
)
except Exception as e:
print("[ERROR] ffmpeg command failed with the following error:")
print(e.stderr.decode('utf-8'))
return
x = 1
prevOutputName = ""
def overlayVideo(inFile,overlayFile,xAxis,yAxis,outputName,overlayStart=None,overlayEnd=None,start=0,end=1):
clearline()
if overlayStart != None and overlayEnd != None:
overlay_file = ffmpeg.input(overlayFile,ss=overlayStart,to=overlayEnd)
elif overlayStart != None and overlayEnd == None:
overlay_file = ffmpeg.input(overlayFile,ss=overlayStart)
elif overlayStart == None and overlayEnd != None:
overlay_file = ffmpeg.input(overlayFile,to=overlayEnd)
else:
overlay_file = ffmpeg.input(overlayFile)
overlayEnable = 'between(t,'+str(start)+','+str(end)+')'
(
ffmpeg
.input(inFile)
.overlay(overlay_file,x=xAxis,y=yAxis,eof_action="pass",repeatlast=0,enable=overlayEnable, loglevel="quiet")
.output(outputName, map='0:a', vcodec='libx264', acodec='aac')
.run()
)
def overlayImage(inFile,overlayFile,xAxis=30,yAxis=870,outputName="video-output",start=0,end=1):
clearline()
overlay_file = ffmpeg.input(overlayFile,ss=start,to=end)
overlayEnable = 'between(t,'+str(start)+','+str(end)+')'
(
ffmpeg
.input(inFile)
.overlay(overlay_file,x=xAxis,y=yAxis,eof_action="pass",repeatlast=0,enable=overlayEnable,loglevel="quiet")
.output(outputName, map='0:a', vcodec='libx264', acodec='aac')
.run()
)
def mergeVideos(inFiles,outputName, path):
inFiles = inFiles.split(',')
try:
f = open(os.path.join(path,"merge.tmp"),"x",encoding='utf8')
except:
os.remove(os.path.join(path,"merge.tmp"))
f = open(os.path.join(path,"merge.tmp"),"x",encoding='utf8')
f.close()
for file in inFiles:
clearline()
textline(line(),"PREPARING "+file+" FOR MERGE")
f = open(os.path.join(path,"merge.tmp"),"a",encoding='utf8')
f.write("file \'"+os.path.join(path,file)+"\'\n")
f.close()
textline(line(),"MERGING FILES")
try:
(
ffmpeg
.input(os.path.join(path,"merge.tmp"), format='concat', safe=0)
.output(os.path.join(path,outputName), vcodec='libx264', loglevel="quiet", preset='fast', crf=11, acodec='aac')
.run()
)
except ffmpeg._run.Error as e:
if e.stderr is not None:
print(e.stderr.decode())
else:
print("Unknown error occurred during ffmpeg execution.")
os.remove(os.path.join(path,"merge.tmp"))
def processJSON(JSONfile=None, path=None):
if path == None:
path = selectDirectory(delimeter)
if JSONfile == None:
JSONfile = selectJSON(path)
j = open(os.path.join(path,JSONfile),)
jsonData = json.load(j)
#print(jsonData)
try:
for d in jsonData['split']:
#do the splits
splitVideo(d['input'],d['inTime'],d['outTime'],d['output'],path)
except:
pass
try:
for d in jsonData['merge']:
#merge together
print(d['input'])
print(d['output'])
mergeVideos(d['input'],d['output'],path)
except Exception as e:
print(e)
pass
try:
for d in jsonData['overlayVideo']:
#video overlay
if d['overlayStart'] != None and d['overlayEnd'] != None:
overlayVideo(d['input'],d['overlay'],d['xAxis'],d['yAxis'],d['output'],d['overlayStart'],d['overlayEnd'],d['start'],d['end'])
elif d['overlayStart'] != None and d['overlayEnd'] == None:
overlayVideo(d['input'],d['overlay'],d['xAxis'],d['yAxis'],d['output'],d['overlayStart'],d['overlayEnd'],d['start'],None)
elif d['overlayStart'] == None and d['overlayEnd'] != None:
overlayVideo(d['input'],d['overlay'],d['xAxis'],d['yAxis'],d['output'],d['overlayStart'],d['overlayEnd'],None,d['end'])
else:
overlayVideo(d['input'],d['overlay'],d['xAxis'],d['yAxis'],d['output'],d['overlayStart'],d['overlayEnd'],None,None)
except:
pass
try:
for d in jsonData['overlayImage']:
#image overlay
overlayImage(d['input'],d['overlay'],d['xAxis'],d['yAxis'],d['output'],d['start'],d['end'])
except:
pass
try:
for d in jsonData['processVideo']:
#full video processing
processVideo(d['input'],d['inTime'],d['outTime'],d['regions'],d['intro'],d['endscreens'],d['startEndscreen'],d['xAxisRating'],d['yAxisRating'],d['endRating'],d['startIntro'],d['endIntro'],d['videoFadeIn'],d['videoFadeOut'],d['audioFadeIn'],d['audioFadeOut'],d['output'])
except:
pass