callmedougan

sraight dumo

Jun 13th, 2020 (edited)
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.41 KB | None | 0 0
  1. from contextlib import closing
  2. from PIL import Image
  3. import subprocess
  4. from audiotsm import phasevocoder
  5. from audiotsm.io.wav import WavReader, WavWriter
  6. from scipy.io import wavfile
  7. import numpy as np
  8. import re
  9. import math
  10. from shutil import copyfile, rmtree
  11. import os
  12. import argparse
  13. #from pytube3 import YouTube (2020.3.29 i added thr 3 to try & make python accept pytube3)
  14.  
  15. def downloadFile(url):
  16. name = YouTube(url).streams.first().download()
  17. newname = name.replace(' ','_')
  18. os.rename(name,newname)
  19. return newname
  20.  
  21. def getMaxVolume(s):
  22. maxv = float(np.max(s))
  23. minv = float(np.min(s))
  24. return max(maxv,-minv)
  25.  
  26. def copyFrame(inputFrame,outputFrame):
  27. src = TEMP_FOLDER+"/frame{:06d}".format(inputFrame+1)+".jpg"
  28. dst = TEMP_FOLDER+"/newFrame{:06d}".format(outputFrame+1)+".jpg"
  29. if not os.path.isfile(src):
  30. return False
  31. copyfile(src, dst)
  32. if outputFrame%20 == 19:
  33. print(str(outputFrame+1)+" time-altered frames saved.")
  34. return True
  35.  
  36. def inputToOutputFilename(filename):
  37. dotIndex = filename.rfind(".")
  38. return filename[:dotIndex]+"_ALTERED"+filename[dotIndex:]
  39.  
  40. def createPath(s):
  41. #assert (not os.path.exists(s)), "The filepath "+s+" already exists. Don't want to overwrite it. Aborting."
  42.  
  43. try:
  44. os.mkdir(s)
  45. except OSError:
  46. assert False, "Creation of the directory %s failed. (The TEMP folder may already exist. Delete or rename it, and try again.)"
  47.  
  48. def deletePath(s): # Dangerous! Watch out!
  49. try:
  50. rmtree(s,ignore_errors=False)
  51. except OSError:
  52. print ("Deletion of the directory %s failed" % s)
  53. print(OSError)
  54.  
  55. parser = argparse.ArgumentParser(description='Modifies a video file to play at different speeds when there is sound vs. silence.')
  56. parser.add_argument('--input_file', type=str, help='the video file you want modified')
  57. parser.add_argument('--url', type=str, help='A youtube url to download and process')
  58. parser.add_argument('--output_file', type=str, default="", help="the output file. (optional. if not included, it'll just modify the input file name)")
  59. parser.add_argument('--silent_threshold', type=float, default=0.03, help="the volume amount that frames' audio needs to surpass to be consider \"sounded\". It ranges from 0 (silence) to 1 (max volume)")
  60. parser.add_argument('--sounded_speed', type=float, default=1.00, help="the speed that sounded (spoken) frames should be played at. Typically 1.")
  61. parser.add_argument('--silent_speed', type=float, default=5.00, help="the speed that silent frames should be played at. 999999 for jumpcutting.")
  62. parser.add_argument('--frame_margin', type=float, default=1, help="some silent frames adjacent to sounded frames are included to provide context. How many frames on either the side of speech should be included? That's this variable.")
  63. parser.add_argument('--sample_rate', type=float, default=44100, help="sample rate of the input and output videos")
  64. parser.add_argument('--frame_rate', type=float, default=30, help="frame rate of the input and output videos. optional... I try to find it out myself, but it doesn't always work.")
  65. parser.add_argument('--frame_quality', type=int, default=3, help="quality of frames to be extracted from input video. 1 is highest, 31 is lowest, 3 is the default.")
  66.  
  67. args = parser.parse_args()
  68.  
  69.  
  70.  
  71. frameRate = args.frame_rate
  72. SAMPLE_RATE = args.sample_rate
  73. SILENT_THRESHOLD = args.silent_threshold
  74. FRAME_SPREADAGE = args.frame_margin
  75. NEW_SPEED = [args.silent_speed, args.sounded_speed]
  76. if args.url != None:
  77. INPUT_FILE = downloadFile(args.url)
  78. else:
  79. INPUT_FILE = args.input_file
  80. URL = args.url
  81. FRAME_QUALITY = args.frame_quality
  82.  
  83. assert INPUT_FILE != None , "why u put no input file, that dum"
  84.  
  85. if len(args.output_file) >= 1:
  86. OUTPUT_FILE = args.output_file
  87. else:
  88. OUTPUT_FILE = inputToOutputFilename(INPUT_FILE)
  89.  
  90. TEMP_FOLDER = "TEMP"
  91. AUDIO_FADE_ENVELOPE_SIZE = 400 # smooth out transitiion's audio by quickly fading in/out (arbitrary magic number whatever)
  92.  
  93. createPath(TEMP_FOLDER)
  94.  
  95. command = "ffmpeg -i "+INPUT_FILE+" -qscale:v "+str(FRAME_QUALITY)+" "+TEMP_FOLDER+"/frame%06d.jpg -hide_banner"
  96. subprocess.call(command, shell=True)
  97.  
  98. command = "ffmpeg -i "+INPUT_FILE+" -ab 160k -ac 2 -ar "+str(SAMPLE_RATE)+" -vn "+TEMP_FOLDER+"/track1audio.wav"
  99. #ffmpeg -i "Desktop 2020.03.12 - 22.34.34.01.mp4" -c:a libmp3lame -b:a 320k -map 0:2 cars2.mp3
  100.  
  101. subprocess.call(command, shell=True)
  102.  
  103. command = "ffmpeg -i "+TEMP_FOLDER+"/input.mp4 2>&1"
  104. f = open(TEMP_FOLDER+"/params.txt", "w")
  105. subprocess.call(command, shell=True, stdout=f)
  106.  
  107.  
  108.  
  109. #i changed the audio reference thus "audio.wav" wont work now
  110. sampleRate, audioData = wavfile.read(TEMP_FOLDER+"/audio.wav")
  111. audioSampleCount = audioData.shape[0]
  112. maxAudioVolume = getMaxVolume(audioData)
  113.  
  114. f = open(TEMP_FOLDER+"/params.txt", 'r+')
  115. pre_params = f.read()
  116. f.close()
  117. params = pre_params.split('\n')
  118. for line in params:
  119. m = re.search('Stream #.*Video.* ([0-9]*) fps',line)
  120. if m is not None:
  121. frameRate = float(m.group(1))
  122.  
  123. samplesPerFrame = sampleRate/frameRate
  124.  
  125. audioFrameCount = int(math.ceil(audioSampleCount/samplesPerFrame))
  126.  
  127. hasLoudAudio = np.zeros((audioFrameCount))
  128.  
  129.  
  130.  
  131. for i in range(audioFrameCount):
  132. start = int(i*samplesPerFrame)
  133. end = min(int((i+1)*samplesPerFrame),audioSampleCount)
  134. audiochunks = audioData[start:end]
  135. maxchunksVolume = float(getMaxVolume(audiochunks))/maxAudioVolume
  136. if maxchunksVolume >= SILENT_THRESHOLD:
  137. hasLoudAudio[i] = 1
  138.  
  139. chunks = [[0,0,0]]
  140. shouldIncludeFrame = np.zeros((audioFrameCount))
  141. for i in range(audioFrameCount):
  142. start = int(max(0,i-FRAME_SPREADAGE))
  143. end = int(min(audioFrameCount,i+1+FRAME_SPREADAGE))
  144. shouldIncludeFrame[i] = np.max(hasLoudAudio[start:end])
  145. if (i >= 1 and shouldIncludeFrame[i] != shouldIncludeFrame[i-1]): # Did we flip?
  146. chunks.append([chunks[-1][1],i,shouldIncludeFrame[i-1]])
  147.  
  148. chunks.append([chunks[-1][1],audioFrameCount,shouldIncludeFrame[i-1]])
  149. chunks = chunks[1:]
  150.  
  151. outputAudioData = np.zeros((0,audioData.shape[1]))
  152. outputPointer = 0
  153.  
  154. lastExistingFrame = None
  155. for chunk in chunks:
  156. audioChunk = audioData[int(chunk[0]*samplesPerFrame):int(chunk[1]*samplesPerFrame)]
  157.  
  158. sFile = TEMP_FOLDER+"/tempStart.wav"
  159. eFile = TEMP_FOLDER+"/tempEnd.wav"
  160. wavfile.write(sFile,SAMPLE_RATE,audioChunk)
  161. with WavReader(sFile) as reader:
  162. with WavWriter(eFile, reader.channels, reader.samplerate) as writer:
  163. tsm = phasevocoder(reader.channels, speed=NEW_SPEED[int(chunk[2])])
  164. tsm.run(reader, writer)
  165. _, alteredAudioData = wavfile.read(eFile)
  166. leng = alteredAudioData.shape[0]
  167. endPointer = outputPointer+leng
  168. outputAudioData = np.concatenate((outputAudioData,alteredAudioData/maxAudioVolume))
  169.  
  170. #outputAudioData[outputPointer:endPointer] = alteredAudioData/maxAudioVolume
  171.  
  172. # smooth out transitiion's audio by quickly fading in/out
  173.  
  174. if leng < AUDIO_FADE_ENVELOPE_SIZE:
  175. outputAudioData[outputPointer:endPointer] = 0 # audio is less than 0.01 sec, let's just remove it.
  176. else:
  177. premask = np.arange(AUDIO_FADE_ENVELOPE_SIZE)/AUDIO_FADE_ENVELOPE_SIZE
  178. mask = np.repeat(premask[:, np.newaxis],2,axis=1) # make the fade-envelope mask stereo
  179. outputAudioData[outputPointer:outputPointer+AUDIO_FADE_ENVELOPE_SIZE] *= mask
  180. outputAudioData[endPointer-AUDIO_FADE_ENVELOPE_SIZE:endPointer] *= 1-mask
  181.  
  182. startOutputFrame = int(math.ceil(outputPointer/samplesPerFrame))
  183. endOutputFrame = int(math.ceil(endPointer/samplesPerFrame))
  184. for outputFrame in range(startOutputFrame, endOutputFrame):
  185. inputFrame = int(chunk[0]+NEW_SPEED[int(chunk[2])]*(outputFrame-startOutputFrame))
  186. didItWork = copyFrame(inputFrame,outputFrame)
  187. if didItWork:
  188. lastExistingFrame = inputFrame
  189. else:
  190. copyFrame(lastExistingFrame,outputFrame)
  191.  
  192. outputPointer = endPointer
  193.  
  194. wavfile.write(TEMP_FOLDER+"/audioNew.wav",SAMPLE_RATE,outputAudioData)
  195.  
  196. '''
  197. outputFrame = math.ceil(outputPointer/samplesPerFrame)
  198. for endGap in range(outputFrame,audioFrameCount):
  199. copyFrame(int(audioSampleCount/samplesPerFrame)-1,endGap)
  200. '''
  201.  
  202. command = "ffmpeg -framerate "+str(frameRate)+" -i "+TEMP_FOLDER+"/newFrame%06d.jpg -i "+TEMP_FOLDER+"/audioNew.wav -strict -2 "+OUTPUT_FILE
  203. subprocess.call(command, shell=True)
  204.  
  205. # deletePath(TEMP_FOLDER)
  206. # this will delete the temp folder
Advertisement
Add Comment
Please, Sign In to add comment