def make(resolution=(3840, 2160), blur=0, debug_mode=False, gradient_opacity=1, file_name=''): # opens art, then adds blur, then blows up art_image = Image.open('lib/temp/art.png') art_image = art_image.filter(ImageFilter.GaussianBlur(radius=blur)) if (resolution > art_image.size): if debug_mode: print('Art smaller than background needed') art_image = art_image.resize( (math.ceil(resolution[0] * 1.05), math.ceil(resolution[0] * 1.05)), Image.ANTIALIAS) else: if debug_mode: print('Art larger than background needed') if debug_mode: print('Background size before crop: ' + str(art_image.size)) # cropping the blurred art width, height = art_image.size left = (width - resolution[0]) / 2 top = (height - resolution[1]) / 2 right = (width + resolution[0]) / 2 bottom = (height + resolution[1]) / 2 # crop art_image = art_image.crop((left, top, right, bottom)) art_image.save('lib/temp/' + file_name + '.png', 'PNG') art_image.close() # determines if the art is dark with is_dark if is_dark.calc(debug_mode=debug_mode): if debug_mode: print('Detected dark art; using white gradient') gradient_clip = ImageClip( 'themes/radio/gradient_white.png', transparent=True).set_opacity(gradient_opacity) else: # its light if debug_mode: print('Detected light art; using black gradient') gradient_clip = ImageClip( 'themes/radio/gradient_black.png', transparent=True).set_opacity(gradient_opacity) gradient_clip.resize(resolution) art_clip = ImageClip('lib/temp/' + file_name + '.png', transparent=True) transparent = ImageClip('lib/transparent.png').resize(resolution) # again, the transparent needs to go first, this is to force a given resolution background_clip = CompositeVideoClip( [transparent, art_clip, gradient_clip]) background_clip.save_frame('lib/temp/' + file_name + '.png')
def main(argv): inputFolder = None outputFolder = None videoFile = None videoEndFile = None imageFile = None imageEndFile = None imageTime = 3 cutFromBegining = 0 cutFromEnd = 0 codec = None fixedLength = None watermarkImage = None watermarkWidth = 100 watermarkDuration = None fadeDuration = 1 blackTop = 0 blackBottom = 0 cutUnitsPx = True cutUnitsStartPx = True cutUnitsEndPx = True watermarkX = "right" watermarkY = "top" watermarkStarts = None codecSuffix = None params = None resizeWithIntro = False resizeWithOutro = False mirrorVideo = False rotateVideo = None print_short_licence() try: opts, args = getopt.getopt(argv, "humf:v:i:t:s:e:o:c:l:w:r:", [ "help", "folder=", "output=", "video=", "video-end=", "image=", "image-end=", "image-time=", "cut-start=", "cut-end=", "licence", "watermark=", "black-top=", "black-bottom=", "cut-percent", "watermark-width=", "cut-percent-start", "cut-percent-end", "watermark-to-left", "watermark-to-bottom", "watermark-to-center", "watermark-duration=", "watermark-fade-duration=", "watermark-show-at=", "copy-codec=", "ffmpeg=", "suffix=", "resize-by-intro", "resize-by-outro", "mirror", "rotate=" ]) except getopt.GetoptError: print_help() sys.exit(2) for opt, arg in opts: if opt == '-h': print_help() sys.exit() if opt == '--licence': print_licence() sys.exit() elif opt in ("-f", "--folder"): inputFolder = arg elif opt in ("-o", "--output"): outputFolder = arg elif opt in ("-v", "--video"): videoFile = arg elif opt in ("-s", "--cut-start"): cutFromBegining = max(0, int(arg)) elif opt in ("-e", "--cut-end"): cutFromEnd = max(0, int(arg)) elif opt in ("-t", "--image-time"): imageTime = max(1, int(arg)) elif opt in ("-i", "--image"): imageFile = arg elif opt in ("--image-end"): imageEndFile = arg elif opt in ("--video-end"): videoEndFile = arg elif opt in ("-c"): codec = arg elif opt in ("-l"): fixedLength = int(arg) elif opt in ("-w", "--watermark"): watermarkImage = arg elif opt in ("--watermark-to-left"): watermarkX = "left" elif opt in ("--watermark-to-center"): watermarkX = "center" watermarkY = "center" elif opt in ("--watermark-to-bottom"): watermarkY = "bottom" elif opt in ("--watermark-duration"): watermarkDuration = int(arg) elif opt in ("--watermark-fade-duration"): fadeDuration = int(arg) elif opt in ("--watermark-show-at"): watermarkStarts = [int(a) for a in arg.split(',')] elif opt in ("--black-top"): blackTop = int(arg) elif opt in ("--black-bottom"): blackBottom = int(arg) elif opt in ("-u", "--cut-percent"): cutUnitsPx = False elif opt in ("--watermark-width"): watermarkWidth = max(0, int(arg)) elif opt in ("--cut-percent-start"): cutUnitsStartPx = False elif opt in ("--cut-percent-end"): cutUnitsEndPx = False elif opt in ("--copy-codec"): codec = 'copy' codecSuffix = arg elif opt in ("--suffix"): codecSuffix = arg elif opt in ("--ffmpeg"): params = arg.split(' ') elif opt in ("--resize-by-intro"): resizeWithIntro = True elif opt in ("--resize-by-outro"): resizeWithOutro = True elif opt in ("-m", "--mirror"): mirrorVideo = True elif opt in ("-r", "--rotate"): rotateVideo = int(arg) fileList = [] ffvideoFile = None ffvideoEndFile = None ffimageFile = None ffimageEndFile = None ffwatermark = None if not outputFolder: print( 'Output folder is not found, use -h or --help to show help message.' ) sys.exit(2) if not os.path.isdir(outputFolder): os.makedirs(outputFolder) if (videoFile and not os.path.isfile(videoFile)) or ( videoEndFile and not os.path.isfile(videoEndFile)): print( 'Input video file does not exists, use -h or --help to show help message.' ) sys.exit(2) if (imageFile and not os.path.isfile(imageFile)) or ( imageEndFile and not os.path.isfile(imageEndFile)): print( 'Input image file does not exists, use -h or --help to show help message.' ) sys.exit(2) if (watermarkImage and not os.path.isfile(watermarkImage)): print( 'Input watermark image does not exists, use -h or --help to show help message.' ) sys.exit(2) if codec is not None and not codecs.has_key(codec): print('Unknown codec, use -h or --help to show help message.') sys.exit(2) elif codec is not None and codecSuffix is None: codecSuffix = codecs[codec] if resizeWithIntro and not videoFile: print( 'No intro for resize found, use -h or --help to show help message.' ) sys.exit(2) if resizeWithIntro and not videoEndFile: print( 'No outro for resize found, use -h or --help to show help message.' ) sys.exit(2) if (videoFile): ffvideoFile = VideoFileClip(videoFile) if (videoEndFile): ffvideoEndFile = VideoFileClip(videoEndFile) if (imageFile): ffimageFile = ImageClip(imageFile, duration=imageTime) if (imageEndFile): ffimageEndFile = ImageClip(imageEndFile, duration=imageTime) if (watermarkImage): ffwatermark = ImageClip(watermarkImage) try: fileList = os.listdir(inputFolder) except: print('Input folder not found, use -h or --help to show help message.') sys.exit(2) for filename in fileList: try: if (os.path.isfile(os.path.join(inputFolder, filename))): video = VideoFileClip(os.path.join(inputFolder, filename)) if (resizeWithIntro and ffvideoFile): video = video.resize(ffvideoFile.size) if (resizeWithOutro and ffvideoEndFile): video = video.resize(ffvideoEndFile.size) beginingCut = cutFromBegining endingCut = -cutFromEnd if cutFromEnd > 0 else None if (not cutUnitsPx or not cutUnitsStartPx): beginingCut = (cutFromBegining * video.duration) / 100 if (not cutUnitsPx or not cutUnitsEndPx): endingCut = -(cutFromEnd * video.duration ) / 100 if cutFromEnd > 0 else None video = video.subclip(beginingCut, endingCut) width, height = video.size if (mirrorVideo): video = video.fx(vfx.mirror_x) if (rotateVideo is not None): video = video.rotate(rotateVideo) # video = (video # # .fx(vfx.mirror_x) # # .rotate(1) # # .fx(vfx.colorx, factor=1.4) # # .fx(vfx.painting, saturation=1.6, black=0.01) # ) if (fixedLength is not None): video = video.subclip(0, fixedLength) if (blackTop > 0): blackHeight = (blackTop * height) / 100 def top_filter(frame): frame[0:blackHeight, 0:width] = 0 return frame video = video.fl_image(top_filter) if (blackBottom > 0): blackHeight = (blackBottom * height) / 100 def bottom_filter(frame): frame[(height - blackHeight):height, 0:width] = 0 return frame video = video.fl_image(bottom_filter) if (ffwatermark is not None): wWidth = (watermarkWidth * width) / 100 duration = (watermarkDuration if watermarkDuration is not None else video.duration) logo = (ffwatermark.set_duration(duration).margin( left=0, right=0, bottom=0, top=0, opacity=0.6).resize(width=wWidth).set_pos( (watermarkX, watermarkY)).crossfadein( fadeDuration).crossfadeout(fadeDuration)) if (watermarkStarts is None): video = CompositeVideoClip([video, logo]) else: logos = [] for w in watermarkStarts: w_start = int(w * video.duration / 100) logos.append( logo.set_start(w_start).set_duration( min(video.duration - w_start, duration))) video = CompositeVideoClip([video] + logos) videos = [] if (ffvideoFile): videos.append(ffvideoFile.resize(video.size)) if (ffimageFile): videos.append(ffimageFile.resize(video.size)) videos.append(video) if (ffvideoEndFile): videos.append(ffvideoEndFile.resize(video.size)) if (ffimageEndFile): videos.append(ffimageEndFile.resize(video.size)) result = concatenate_videoclips(videos) translated_filename = filename if codecSuffix is None else os.path.splitext( filename)[0] + "." + codecSuffix result.write_videofile(os.path.join(outputFolder, translated_filename), codec=codec, ffmpeg_params=params) except Exception as e: print('Error while transfering file: ', filename) print('Original Error: ', str(e))
# print(zh_title) main_clip = VideoFileClip(r'./videos/{}'.format(mp4)) leader = VideoFileClip(r'./material/leader.mp4') leader = leader.resize(main_clip.size) # main_clip=main_clip.resize(leader.size) # leader.duration=3 # clip1=clip.fx(vfx.mirror_x) # clip2=clip.fx(vfx.mirror_y) # clip2=clip.resize(0.5) logo = ImageClip(r'./material/logo.png') logo.duration = main_clip.duration logo.resize((350, 150)) # logo_end_gif= concatenate = concatenate_videoclips([leader, main_clip]) if os.path.exists(r'./subtitle/{}.srt'.format(en_title)): with open(r'./subtitle/{}.srt'.format(en_title), 'rb') as f: pass # print(f.read()) # en_sub=f.read() # zh_sub=translat(en_sub) # zh_srt=open(r'./subtitle/translated/{}.srt'.format(en_title),'wb') # zh_srt.write(zh_sub) # zh_srt=translat_subtitle(f)
def create_overall_quality_video(request): trip_stats = process_user_stats() #load images image1 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image2 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image3 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image4 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image5 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image6 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image7 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image8 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image9 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image10 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') #calculate max width and height images = [] images.extend([image1, image2, image3, image4, image5, image6, image7, image8, image9, image10]) max_width = 0 max_height = 0 for img in images: if img.size[0] > max_width: max_width = img.size[0] if img.size[1] > max_height: max_height = img.size[1] #create blurred images image1 = CompositeVideoClip([image1.resize((max_width, max_height)).fl_image(blur), image1.resize(.95)]) image2 = CompositeVideoClip([image2.resize((max_width, max_height)).fl_image(blur), image2.resize(.95)]) image3 = CompositeVideoClip([image3.resize((max_width, max_height)).fl_image(blur), image3.resize(.95)]) image4 = CompositeVideoClip([image4.resize((max_width, max_height)).fl_image(blur), image4.resize(.95)]) image5 = CompositeVideoClip([image5.resize((max_width, max_height)).fl_image(blur), image5.resize(.95)]) image6 = CompositeVideoClip([image6.resize((max_width, max_height)).fl_image(blur), image6.resize(.95)]) image7 = CompositeVideoClip([image7.resize((max_width, max_height)).fl_image(blur), image7.resize(.95)]) image8 = CompositeVideoClip([image8.resize((max_width, max_height)).fl_image(blur), image8.resize(.95)]) image9 = CompositeVideoClip([image9.resize((max_width, max_height)).fl_image(blur), image9.resize(.95)]) image10 = CompositeVideoClip([image10.resize((max_width, max_height)).fl_image(blur), image10.resize(.95)]) #concatenate clips, play one clip after the other image_clips = concatenate_videoclips([image1.set_duration(2).fadein(.5).fadeout(.5), image2.set_duration(2).fadein(.5).fadeout(.5), image3.set_duration(2).fadein(.5).fadeout(.5), image4.set_duration(2).fadein(.5).fadeout(.5), image5.set_duration(2).fadein(.5).fadeout(.5), image6.set_duration(2).fadein(.5).fadeout(.5), image7.set_duration(2).fadein(.5).fadeout(.5), image8.set_duration(2).fadein(.5).fadeout(.5), image9.set_duration(2).fadein(.5).fadeout(.5), image10.set_duration(2).fadein(.5).fadeout(.5)]) title_clip = (TextClip("Just Back From...", fontsize=35, font="Century-Schoolbook-Roman", color="white", kerning=-2, interline=-1, bg_color='#e04400', method='caption', align='center', size=(max_width, max_height)) .margin(top=5, opacity=0) .set_duration(3).fadein(.5).fadeout(.5) .set_position(("center", "top"))) stats_clip = (TextClip("See Santi's recent trip of 1,836 round trip miles, with stops..", fontsize=35, font="Century-Schoolbook-Roman", color="white", kerning=-2, interline=-1, bg_color='#e04400', method='caption', align='center', size=(max_width, max_height)) .margin(top=5, opacity=0) .set_duration(4).fadein(.5).fadeout(.5) .set_position(("center", "top"))) final_clip = concatenate_videoclips([title_clip, image_clips, stats_clip], method="compose", padding=-1) audio_clip = AudioFileClip("media/music.aac").subclip(0, final_clip.duration) final_clip = final_clip.set_audio(audio_clip).afx(afx.audio_fadeout, 1.5) #write_videofile -> preset : #Sets the time that FFMPEG will spend optimizing the compression. # Choices are: ultrafast, superfast, fast, medium, slow, superslow. # Note that this does not impact the quality of the video, only the size of the video file. # So choose ultrafast when you are in a hurry and file size does not matter. final_clip.write_videofile('videos/overallQualityVideo.mp4', fps=23, codec='libx264', audio_bitrate='1000k', bitrate='4000k') #final_clip.write_gif('videos/overallQuality.gif', fps=23) html = "<html><body><div>Video successfully created<div><a href='http://localhost:8000'><button>Back</button></a></body></html>" return HttpResponse(html)
def func_edit(self): import os import os.path from moviepy.video import VideoClip from moviepy.editor import VideoFileClip, vfx, concatenate_videoclips, CompositeVideoClip, \ ImageClip, TextClip # from moviepy.video.compositing import CompositeVideoClip from moviepy.video.tools.subtitles import SubtitlesClip from googletrans import Translator def translat(text='no text is passed'): trans = Translator() result = trans.translate(text, dest='zh-CN', src='en').text # Translated(src=en, dest=zh-cn, text=你好, pronunciation=Nǐ hǎo, extra_data="{'translat...") # print(result.text) return result def translat_subtitle(file): for i, line in enumerate(file.readline()): print(i, line) translated_sub = open(r'/home/master/subtitle/translated/{}.srt'.format(en_title), 'w',encoding='utf-8') if i % 4 == 2 or i == 2: # doc='' # doc=doc+str(line) translated_line = translat(line) translated_sub.write(translated_line) else: translated_sub.write(line) return translated_sub for mp4 in os.listdir(r'/home/master/unvideos'): en_title = os.path.basename(mp4).split('.')[0] zh_title = translat(str(en_title)) print(zh_title) main_clip = VideoFileClip(r'/home/master/unvideos/{}'.format(mp4)) leader = VideoFileClip(r'./material/leader.mp4') main_clip=main_clip.resize(leader.size) # leader.duration=3 # clip1=clip.fx(vfx.mirror_x) # clip2=clip.fx(vfx.mirror_y) # clip2=clip.resize(0.5) concatenate = concatenate_videoclips([leader, main_clip]) logo = ImageClip(r'./material/logo.png') logo.duration = main_clip.duration logo.resize((350,150)) # logo_end_gif= if os.path.exists(r'/home/master/subtitle/{}.srt'.format(en_title)): with open(r'/home/master/subtitle/{}.srt'.format(en_title), 'rb') as f: pass # print(f.read()) # en_sub=f.read() # zh_sub=translat(en_sub) # zh_srt=open(r'./subtitle/translated/{}.srt'.format(en_title),'wb') # zh_srt.write(zh_sub) # zh_srt=translat_subtitle(f) font = "ArialUnicode" color = 'white' generator = lambda txt: TextClip(txt, font=font, fontsize=40, color=color) # sub=SubtitlesClip(r'./subtitle/translated/{}.srt'.format(en_title),'rb') sub = SubtitlesClip(r'/home/master/subtitle/{}.srt'.format(en_title), generator) # final=clips_array([[clip1,clip2]]) final = CompositeVideoClip([concatenate, sub.set_start(3).set_pos('bottom'), logo.set_start(3).set_pos((1400,100)).crossfadein(2)]) # final.write_videofile('add_subtitle.mp4',fps=clip.fps) final.write_videofile('/home/master/edited/{}.mp4'.format(en_title), fps=main_clip.fps) else: final = CompositeVideoClip([concatenate, logo.set_start(3).set_pos((1400,100)).crossfadein(2)]) final.write_videofile('/home/master/edited/{}.mp4'.format(en_title), fps=main_clip.fps,audio=True,verbose=True)
def compile_video(show_items, output_path='./manager/static/shows/', frame_rate=30): # items: {item 1, item 2, ...} print("Compiling Video...") name = "Show_%d.mp4" % (int(time.time())) print(name) if output_path.rindex('/') == len(output_path) - 1: showPath = "%s%s" % (output_path, name) else: showPath = "%s/%s" % (output_path, name) video_clips = [ ] # clip array, will use a SHIT LOAD of memory, you're editing a video... for item in show_items: if os.path.isfile(item.file): # debug params #print("file: ", item.file, "Exists") #print(os.listdir(item.file[0:item.file.rindex('/')+1])) if ".mp4" in item.file.lower(): # Use VideoFileClip class vclip = VideoFileClip(item.file) # resize the height to 1080p vclip = vclip.resize(height=1080) # then see if it is too wide (w, h) = vclip.size if w > 1920: vclip = vclip.resize(width=1920) print("resize width") video_clips.append(vclip) elif ".gif" in item.file.lower(): # Use VideoFileClip class vclip = VideoFileClip(item.file) # resize the height to 1080p vclip = vclip.resize(height=1080) # then see if it is too wide (w, h) = vclip.size if w > 1920: vclip = vclip.resize(width=1920) print("resize width") #vclip.set_fps(frame_rate) for gi in range(0, item.gifIteration): video_clips.append(vclip) elif ".png" or ".jpg" in item.file.lower(): # Use ImageClip class img = ImageClip(item.file) # resize the height to 1080p img = img.resize(height=1080) # then if it is too wide, resize to 1920 wide (w, h) = img.size if w > 1920: img = img.resize(width=1920) print("resize width") #img.resize(height=1080) img = img.set_end(int(item.displayTime)) #img.set_fps(frame_rate) video_clips.append(img) else: print("unsupported file type: ", item.file.lower()[item.file.rindex('.'):len(item.file)]) else: print("File: ", item.file, "Does Not Exist") #elif ".pdf" in item.file.lower(): # pdf are taken care of at upload # print("PDF: ", item.file) # pause last frame and fade out/in? final_clip = concatenate_videoclips(video_clips, method="compose") final_clip.resize(height=1080) final_clip.write_videofile(filename=showPath, fps=frame_rate, audio=False, threads=4) return showPath, name
from moviepy.editor import VideoFileClip, concatenate_videoclips, clips_array, CompositeVideoClip, ImageClip, AudioFileClip import sys import pathlib baseURL = pathlib.Path(__file__).parent.absolute() id = sys.argv[1] audio = sys.argv[2] foto = sys.argv[3] #Video clip1 = VideoFileClip(f"{baseURL}/video.mp4") #Audio audioclip = AudioFileClip(f"{baseURL}/{audio}.mp3") #Foto # fotoClip = ImageClip(f"{baseURL}/imagem.png", duration=13, transparent=True) fotoClip = ImageClip(foto, duration=13, transparent=True) fotoClip = fotoClip.set_audio(audioclip) fotoClip = fotoClip.resize(width=100, height=100) fotoClip = fotoClip.set_position((110, 150)) fotoClip = fotoClip.add_mask().rotate(40) fotoClip = fotoClip.set_start(65) final_clip = CompositeVideoClip([clip1, fotoClip]) final_clip.write_videofile(f"{baseURL}/../storage/app/videos/video_{id}.mp4")