コード例 #1
0
ファイル: vaporiser.py プロジェクト: forkbabu/vaporiser
# Applying audio effects
fx(args.audio_input, audio_output)


def apply_sobel(image):
    # returns image with Sobel filter applied
    return sobel(image.astype(float))


# Create video if a GIF file is provided
if args.gif_file is None:
    # If no GIF is provided, exit here
    print("Script finished at", datetime.datetime.now().strftime('%H:%M:%S'))
    print("Vaporised MP3 file (audio):", audio_output)
    sys.exit()
else:
    # If a GIF is provided, loop it for the length of the vaporised audio file
    mp3_movedit = movedit.AudioFileClip(audio_output)
    gif_movedit = movedit.VideoFileClip(args.gif_file)
    number_of_loops = float(mp3_movedit.duration / gif_movedit.duration)
    gif_looped = gif_movedit.loop(number_of_loops)
    # Applies Sobel filter to looped GIF, if --sobel is used
    if args.sobel_filter:
        gif_looped = gif_looped.fl_image(apply_sobel)
    gif_looped_with_audio = gif_looped.set_audio(mp3_movedit)
    gif_looped_with_audio.write_videofile(video_output)
    print("Script finished at", datetime.datetime.now().strftime('%H:%M:%S'))
    print("Vaporised MP3 file (audio):", audio_output)
    print("Vaporised MP4 file (video):", video_output)
コード例 #2
0
ファイル: clip-aug.py プロジェクト: chfw/video-for-pyecharts
import os
import moviepy.editor as mp
from moviepy.audio.AudioClip import concatenate_audioclips
music = ["friends.mp3", "laugh1.mp3", "normal.mp3", "men1.mp3", "beyond.mp3"]
vclip = mp.VideoFileClip("gource.mp4")
audio = concatenate_audioclips([
    mp.AudioFileClip(os.path.join("music", file_name)) for file_name in music
])
vclip = vclip.set_audio(audio)
vclip.write_videofile('pyecharts.mp4')
コード例 #3
0
ファイル: reverse.py プロジェクト: Pupsen/photolab
def set_audio_to_video(video_path, audio_path):
    videoclip = mp.VideoFileClip(video_path)
    audioclip = mp.AudioFileClip(audio_path)
    videoclip.audio = audioclip
    return videoclip
コード例 #4
0
import gizeh
import math
import moviepy.editor as mpy
import os
import sys

if len(sys.argv)!=5:
    print('usage: python3 videoasm.py <imagedir> <audiofile> <omitseconds> <videooutfile>')
    raise SystemExit

# arg1 - image sequence directory
imgseqdir=sys.argv[1]
# arg2 - audio file for background
inaudfile=sys.argv[2]
# arg3 - audio first n seconds omit
omitseconds=sys.argv[3]
# arg4 - output video file name
outvidfnm=sys.argv[4]

imglist=os.listdir(imgseqdir)
imglist.sort()
imglist=[imgseqdir+'/'+x for x in imglist]

clip=mpy.ImageSequenceClip(imglist,fps=15)
if inaudfile != '_':
    auclip=mpy.AudioFileClip(inaudfile)
    if omitseconds != '_':
        auclip=auclip.fl_time(lambda: int(omitseconds)+t)
    clip=clip.set_audio(auclip)
clip.write_videofile(outvidfnm)
コード例 #5
0
ファイル: YT_MP3.py プロジェクト: Shalkith/yt_downloader
def processfile(filename):
    import requests
    import re, os
    import json
    from urllib.parse import parse_qs, unquote
    import csv
    import pytube
    import moviepy.editor as mp
    import string, random

    def get_random_string(length):
        letters = string.ascii_lowercase
        result_str = ''.join(random.choice(letters) for i in range(length))
        print("Random string of length", length, "is:", result_str)
        return result_str

    def zippem(filename, dir):
        import shutil
        shutil.make_archive(filename, 'zip', dir)

    def apply_descrambler(stream_data, key):
        """Apply various in-place transforms to YouTube's media stream data.
        Creates a ``list`` of dictionaries by string splitting on commas, then
        taking each list item, parsing it as a query string, converting it to a
        ``dict`` and unquoting the value.
        :param dict stream_data:
            Dictionary containing query string encoded values.
        :param str key:
            Name of the key in dictionary.
        **Example**:
        >>> d = {'foo': 'bar=1&var=test,em=5&t=url%20encoded'}
        >>> apply_descrambler(d, 'foo')
        >>> print(d)
        {'foo': [{'bar': '1', 'var': 'test'}, {'em': '5', 't': 'url encoded'}]}
        """
        otf_type = "FORMAT_STREAM_TYPE_OTF"

        if key == "url_encoded_fmt_stream_map" and not stream_data.get(
                "url_encoded_fmt_stream_map"):
            formats = json.loads(
                stream_data["player_response"])["streamingData"]["formats"]
            formats.extend(
                json.loads(stream_data["player_response"])["streamingData"]
                ["adaptiveFormats"])
            try:
                stream_data[key] = [{
                    "url":
                    format_item["url"],
                    "type":
                    format_item["mimeType"],
                    "quality":
                    format_item["quality"],
                    "itag":
                    format_item["itag"],
                    "bitrate":
                    format_item.get("bitrate"),
                    "is_otf": (format_item.get("type") == otf_type),
                } for format_item in formats]
            except KeyError:
                cipher_url = []
                for data in formats:
                    cipher = data.get("cipher") or data["signatureCipher"]
                    cipher_url.append(parse_qs(cipher))
                stream_data[key] = [{
                    "url":
                    cipher_url[i]["url"][0],
                    "s":
                    cipher_url[i]["s"][0],
                    "type":
                    format_item["mimeType"],
                    "quality":
                    format_item["quality"],
                    "itag":
                    format_item["itag"],
                    "bitrate":
                    format_item.get("bitrate"),
                    "is_otf": (format_item.get("type") == otf_type),
                } for i, format_item in enumerate(formats)]
        else:
            stream_data[key] = [{k: unquote(v)
                                 for k, v in parse_qsl(i)}
                                for i in stream_data[key].split(",")]

    try:
        pytube.__main__.apply_descrambler = apply_descrambler
        #filename = 'video_list.csv'

        with open(filename, 'r', encoding="latin1") as f:
            reader = csv.reader(f)
            #print(len(reader))
            videos = list(reader)

        for video in videos:
            y = pytube.YouTube(video[0])
            t = y.streams
            outfolder = r"output"
            randomfoldername = get_random_string(8)
            t[0].download(output_path=outfolder + '/' + randomfoldername)

        for file in [
                n for n in os.listdir(outfolder + '/' + randomfoldername)
                if re.search('mp4', n)
        ]:
            full_path = os.path.join(outfolder + '/' + randomfoldername, file)
            output_path = os.path.join(outfolder + '/' + randomfoldername,
                                       os.path.splitext(file)[0] + '.mp3')
            clip = mp.AudioFileClip(full_path).subclip(
                10, )  # disable if do not want any clipping
            clip.write_audiofile(output_path)
            os.remove(full_path)

        zippem(r'static/output/' + randomfoldername,
               outfolder + '/' + randomfoldername)

        for file in [
                n for n in os.listdir(outfolder + '/' + randomfoldername)
                if re.search('mp3', n)
        ]:
            full_path = os.path.join(outfolder + '/' + randomfoldername, file)
            os.remove(full_path)

        return r'static/output/' + randomfoldername
    except Exception as e:
        input(e)
コード例 #6
0
ファイル: views.py プロジェクト: SENG4920-wiaa/server
    def post(self, request, filename):
        # Parse JSON data
        if 'music' in request.data:
            music_url = request.data['music']['url']
            if 'start' in request.data['music']:
                music_start = request.data['music']['start']
            else:
                music_start = 0
            if 'volume' in request.data['music']:
                music_volume = request.data['music']['volume'] / 2
            else:
                music_volume = 1
        else:
            music_url = None
        effects = []
        if 'effects' in request.data:
            for n, e in enumerate(request.data['effects']):
                effect = {}
                effect['url'] = request.data['effects'][n]['url']
                if 'start' in request.data['effects'][n]:
                    effect['start'] = request.data['effects'][n]['start']
                else:
                    effect['start'] = 0
                if 'volume' in request.data['effects'][n]:
                    effect['volume'] = request.data['effects'][n]['volume'] / 2
                else:
                    effect['volume'] = 1
                effects.append(effect)

        # Find video file in uploaded files
        try:
            video_path = default_storage.path(filename)
            video = editor.VideoFileClip(video_path).fx(
                editor.afx.audio_normalize)
        except:
            return Response(
                'Video file not found. Plase upload using /upload/',
                status=status.HTTP_400_BAD_REQUEST)

        audio_clips = [video.audio] if video.audio else []

        # Process music
        if music_url:
            music_file = requests.get(music_url).content
            f = open('temp_music.mp3', 'wb')
            f.write(music_file)
            music = editor.AudioFileClip('temp_music.mp3')
            if music.duration > video.duration:
                if video.duration + music_start > music.duration:
                    music_start = music.duration - video.duration
                if music_start < 0: music_start = 0
                music = music.subclip(music_start,
                                      music_start + video.duration)
            music = music.volumex(music_volume)
            audio_clips.append(music)

        # Process effects
        def pad_effect(start, effect, duration):
            def pad_effect_frame(times, start=start, effect=effect):
                if type(times) == int: return [0, 0]
                return [
                    effect.get_frame(time - start)
                    if start < time < start + effect.duration else [0, 0]
                    for time in times
                ]

            return editor.AudioClip(pad_effect_frame, duration=duration)

        for e in effects:
            effect_file = requests.get(e['url']).content
            open('temp_audio.mp3', 'wb').write(effect_file)
            effect = editor.AudioFileClip('temp_audio.mp3')
            effect = effect.volumex(e['volume'])
            effect = pad_effect(e['start'], effect, video.duration)
            effect.fps = 44100
            # effect.write_audiofile('temp_audio.mp3', fps=44100)
            # effect = editor.AudioFileClip('temp_audio.mp3')
            audio_clips.append(effect)

        # Compose
        composed_audio = editor.CompositeAudioClip(audio_clips)
        composed_video = video.set_audio(composed_audio)
        composed_video.write_videofile('temp_video.mp4')

        response = FileResponse(open('temp_video.mp4', 'rb'))

        try:
            os.remove('temp_video.mp4')
        except:
            pass
        try:
            os.remove('temp_audio.mp3')
        except:
            pass
        try:
            os.remove('temp_music.mp3')
        except:
            pass

        return response
コード例 #7
0
ファイル: sul_tool.py プロジェクト: ddddwee1/TorchSUL
def combine_audio(vidname, audname, outname, fps=25):
	import moviepy.editor as mpe
	my_clip = mpe.VideoFileClip(vidname)
	audio_background = mpe.AudioFileClip(audname)
	final_clip = my_clip.set_audio(audio_background)
	final_clip.write_videofile(outname,fps=fps)
コード例 #8
0
def reformat_gif():
    song = mpy.AudioFileClip('chp_op31.wav')
    clip = mpy.VideoFileClip('test.gif')
    clip = clip.set_audio(song)

    clip.write_videofile('myvideo.mp4', codec='mpeg4')
コード例 #9
0
from pytube import YouTube
import moviepy.editor as mp
import re
import os

# Digite o link do vídeo e o local que deseja salvar o mp3 #
link = input("Digite o link do vídeo que deseja baixar:  ")
path = input("Digite o diretório que deseja salvar o vídeo:  ")
yt = YouTube(link)

# Começa o Download #
print("Baixando...")
ys = yt.streams.filter(only_audio=True).first().download(path)
print("Download completo!")

# Converte mp4 para mp3 #
print('Convertendo arquivo...')
for file in os.listdir(path):
    if re.search('mp4', file):
        mp4_path = os.path.join(path, file)
        mp3_path = os.path.join(path, os.path.splitext(file)[0]+'.mp3')
        new_file = mp.AudioFileClip(mp4_path)
        new_file.write_audiofile(mp3_path)
        os.remove(mp4_path)
print('Sucesso!')
コード例 #10
0
def save_video(x, fixed, path):
    np.save(x, path + ".mp4")
    my_clip = mpe.VideoFileClip(path + ".mp4")
    audio_background = mpe.AudioFileClip(fixed)
    final_audio = mpe.CompositeAudioClip([my_clip.audio, audio_background])
    final_clip = my_clip.set_audio(final_audio)
コード例 #11
0
ファイル: JTBCBot v1.3.py プロジェクト: MrPakoras/JoJoTBCfier
fileadd = input('Enter file address:   ')

file = str(fileadd[fileadd.rfind(r'\\|/'):len(fileadd)]
print('>> File "'+file+'" chosen.')

start_time = time.time()

v = mp.VideoFileClip('./videos/'+file)
final = v.duration-0.1 

song = './songs/roundabout_long.mp3'
riff_time = 44.944

start_song = final-riff_time
audioclip = mp.AudioFileClip(song)
audioclip = audioclip.set_start(t=start_song)

try:
    fa = mp.CompositeAudioClip([audioclip, v.audio])
except AttributeError:
    fa = mp.CompositeAudioClip([audioclip]) 

thumb = v.save_frame('thumbnail.jpg',t=final)
tg = Image.open('thumbnail.jpg').convert('L')
tinted = ImageOps.colorize(tg, black='#1e1a12', white='#bfb196')
tinted.save('thumbnail.jpg')

finalfr = mp.ImageClip('thumbnail.jpg', duration=(audioclip.duration-riff_time)).set_start(final)

tbcarrow = mp.ImageClip('tbcarrow.png')
コード例 #12
0
import re
import moviepy.editor as mp

tgt_folder = "/folder/contains/your/mp4"

for file in [n for n in os.listdir(tgt_folder) if re.search('mp4', n)]:
    full_path = os.path.join(tgt_folder, file)
    output_path = os.path.join(tgt_folder, os.path.splitext(file)[0] + '.mp3')
    clip = mp.AudioFileClip(full_path).subclip(
        10, )  # disable if do not want any clipping
    clip.write_audiofile(output_path)
コード例 #13
0
ファイル: main.py プロジェクト: Meep3278/VideoToAscii
frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
counter = 0
start = time.perf_counter()
last = start

while (cap.isOpened()):
    ret, frame = cap.read()

    if ret:
        ascii_frame = cvt_ascii(frame, 200, 0.43)
        out.write(ascii_frame)

        print(
            f"frame {counter} out of {frames}, {time.perf_counter() - last} seconds taken"
        )
        last = time.perf_counter()
        counter += 1
    else:
        break
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
out.release()
my_clip = mpe.VideoFileClip('output.avi')
audio = mpe.AudioFileClip('Rick_Astley_Never_Gonna_Give_You_Up.mp4')
final_clip = my_clip.set_audio(audio)
final_clip.write_videofile("Final_Output_200Color.mp4")
cv2.destroyAllWindows()
end = time.perf_counter()
print(f"Total Time Spent Converting: {end - start:0.4f} seconds.")
コード例 #14
0
def main(wav_file, output_file, duration=10, fps=30):
    view = pyrr.matrix44.create_look_at(eye=[0, 0, 120],
                                        target=[0, 0, 0],
                                        up=[0, 1, 0])
    projection = pyrr.matrix44.create_perspective_projection(fovy=15,
                                                             aspect=1,
                                                             near=10,
                                                             far=200)
    camera = svg3d.Camera(view, projection)

    style = dict(
        fill="white",
        fill_opacity="0.75",
        stroke="black",
        stroke_linejoin="round",
        stroke_width="0.0005",
    )

    video = cv2.VideoWriter("temp.avi", 0, fps, (512, 512))
    sr, wav_data = wavfile.read(wav_file)
    wav_data = np.mean(wav_data, axis=1)
    cqt_split, times = extract_bar_cqt(sr, wav_data)

    t = 0
    pointer = 0
    delta_r = 3.0 / fps
    R = 10
    r = 3
    start_flag = False
    while True:
        cqt = cqt_split[pointer]
        low_freq = np.mean(cqt[17])
        print(low_freq)
        print(t)
        if t >= times[0]:
            start_flag = True
        if t >= times[pointer]:
            delta_r *= -1.0
            pointer += 1

        if start_flag:
            r += delta_r

        shape = doughnut(R, r, (50, 20))
        faces = shape.transform(RandomNoise({"distortion": 15 / (np.abs(low_freq) ** 2)}))\
            .transforma(XRotation({"angle": t * 20}))\
            .get_faces(triangular=True)
        mesh = svg3d.Mesh(faces, shader=frontface_shader)
        view = svg3d.View(camera, svg3d.Scene([mesh]))
        svg3d.Engine([view]).render("temp.svg")
        cairosvg.svg2png(url="temp.svg", write_to="temp.png")
        image = cv2.imread("temp.png")
        video.write(image)
        t += 1 / fps
        if t >= duration:
            break

    cv2.destroyAllWindows()
    video.release()

    video_clip = mpe.VideoFileClip('temp.avi').set_duration(duration)
    audio_clip = mpe.AudioFileClip(wav_file).set_duration(duration)
    final_audio = mpe.CompositeAudioClip([audio_clip])
    final_clip = video_clip.set_audio(final_audio)
    final_clip.write_videofile(output_file, fps=fps)
    os.remove("temp.png")
    os.remove("temp.svg")
    os.remove("temp.avi")
コード例 #15
0
 def export(self, file_name="out.mp4"):
     background_music = mpe.AudioFileClip(self.audio)
     with_music = self.composite().set_audio(background_music)
     with_music.write_videofile(file_name)
コード例 #16
0
 def convert_to_audio(self, path):
     self.path_audio = os.path.join(self.current_directory, path,
                                    self.title + '.mp3')
     new_file = mp.AudioFileClip(self.path_video)
     new_file.write_audiofile(self.path_audio)
     os.remove(self.path_video)
コード例 #17
0
def start():
	browsebutton.config(state='disabled')
	mutebutton.config(state='disabled')
	mvar = 'JoJoTBCfying in progress. Please wait...'
	messvar.set(mvar)

	## JoJoTBCfier code:

	file = re.findall(r'.+(\/.+)$',filename)[0][1:]
	start_time = time.time()

	## Editing video

	# ~ Video clip ~
	
	v = mp.VideoFileClip(filename)
	final = v.duration-0.1 # Removes 0.1s from end of clip so that freeze frame doesnt loop to 1st frame



	# ~ Roundabout song ~	
	mvar = 'Adding roundabout.mp3...'
	messvar.set(mvar)
	
	song = 'roundabout.mp3'
	riff_time = 44.944

	start_song = final-riff_time
	audioclip = mp.AudioFileClip(song)
	audioclip = audioclip.set_start(t=start_song)  # Time at which song should start so riff is at end


	# ~ v1.2 edit - Adding Mute/No Audio function ~
	#v = v.set_audio('')
	global mute
	if mute.get() == 0: # If mute button not checked
		print('>> Not muting original audio')
		try:
		    fa = mp.CompositeAudioClip([audioclip, v.audio]) # If video contains audio, merge with song
		except AttributeError:
		    fa = mp.CompositeAudioClip([audioclip]) # Else just add audio
	elif mute.get() == 1: # If mute button checked
		print('>> Muting original audio')
		fa = mp.CompositeAudioClip([audioclip])



	# ~ Video Freeze Frame ~
	mvar = 'Creating freeze frame...'
	messvar.set(mvar)
	
	# Create Sepia image from last frame using PIL
	thumb = v.save_frame('thumbnail.jpg',t=final)
	tg = Image.open('thumbnail.jpg').convert('L') # Convert image to grayscale
	tinted = ImageOps.colorize(tg, black='#1e1a12', white='#bfb196') # Tinting sepia tones
	tinted.save('thumbnail.jpg')

	finalfr = mp.ImageClip('thumbnail.jpg', duration=(audioclip.duration-riff_time)).set_start(final) # Open tinted frame as freeze frame
	
	# TBC arrow slide in	
	mvar = 'Adding To Be Continued arrow...'
	messvar.set(mvar)

	tbcarrow = mp.ImageClip('tbcarrow.png')
	vidwid, vidhei = v.w, v.h
	print('>> WidthxHeight = '+str(vidwid)+'x'+str(vidhei))

	tbcarrow = tbcarrow.resize(width=(vidwid*0.4)) # Resizing arrow to 40% of video width


	#  ~ Exporting video ~
	mvar = 'Exporting video...'
	messvar.set(mvar)

	fv = mp.CompositeVideoClip([v, finalfr, tbcarrow.set_pos(('left','bottom')).set_start(final).set_duration(audioclip.duration-riff_time)]) #add tbc arrow
	fva = fv.set_audio(fa).set_end(fv.duration-0.1)
	fva = fva.set_fps(fps=30)

	extindex = file.rfind('.') # finding final . for extension	
	dt = time.strftime('%d-%m-%y_%H-%M-%S')
	file = f'{file[0:extindex]}_{dt}.mp4' # replacing extension with .mp4
	fpath = f'./jojofied/jojofied_{file}'

	fva.write_videofile(fpath)


	# ~ Log File ~ 	
	mvar = 'Writing log file...'
	messvar.set(mvar)
	

	lf = open('log.txt','a+')
	lf.write(f'\n\n{dt}\n>> File: {file}\n>> Location: {fpath}\n>> Video Length: {fva.duration}\n>> Time Taken: {time.time()-start_time}')
	lf.close()

	if len({fpath}) >= 45:
		mvar = f'Done. Video output at {fpath[:35]}...'
	else:
		mvar = f'Done. Video output at {fpath}'
	messvar.set(mvar)


	# ~ Resetting GUI ~
	#startbutton.config(state='disabled')
	browsebutton.config(state='normal')
	mutebutton.config(state='normal')
コード例 #18
0
        0, 2 * PI,
        N_SQUARES)[:-1]  ## Polar angles of the center of small squares

    ## Parametric n-gon equation for
    ## https://tpfto.wordpress.com/2011/09/15/parametric-equations-for-regular-and-reuleaux-polygons/
    r1 = np.cos(PI / N_GON) / (np.cos(a - (PI / N_GON) *
                                      (2 * np.floor((N_GON * a) /
                                                    (2 * PI)) + 1)))
    r2 = np.cos(PI / (N_GON + 2)) / (np.cos(a - (PI / (N_GON + 2)) *
                                            (2 * np.floor(((N_GON + 2) * a) /
                                                          (2 * PI)) + 1)))

    d1 = np.cumsum(np.sqrt(((r1[1:] - r1[:-1])**2)))
    d1 = [0] + list(d1 / (d1.max()) + 1e-10)
    d2 = np.cumsum(np.sqrt(((r2[1:] - r2[:-1])**2)))
    d2 = [0] + list(d2 / (d2.max()) + 1e-10)
    P1 = list(zip(r1, a, d1))
    P2 = list(zip(r2, a, d2))

    videoclip = mpe.VideoClip(make_frame=make_frame, duration=PSEUDO_DURATION)
    if EXTENSION == 'gif':
        videoclip.write_gif(output_file,
                            fps=FPS,
                            program='ImageMagick',
                            opt='OptimizePlus')
    else:
        _audioclip = mpe.AudioFileClip(AUDIO_FILE)
        audioclip = mpe.CompositeAudioClip([_audioclip])
        videoclip.audio = audioclip
        videoclip.write_videofile(output_file, fps=FPS)
        d = vid.duration
        print(d)
        clip = vid.subclip(0, d)
        clip.audio.write_audiofile(
            "C:\\Users\Sai Teja\Desktop\ELL888-CNN\\Spectrograms" + "\\" + p +
            str(d) + ".wav")
        subprocess.call([
            'ffmpeg', '-i',
            "C:\\Users\Sai Teja\Desktop\ELL888-CNN\\Spectrograms" + "\\" + p +
            str(d) + ".wav", '-af', "highpass=f=200, lowpass=f=3000",
            "C:\\Users\Sai Teja\Desktop\ELL888-CNN\\Spectrograms" + "\\" + p +
            str(d) + "denoise_audio.wav"
        ])
        clip.reader.close()
        audio = mp.AudioFileClip(
            "C:\\Users\Sai Teja\Desktop\ELL888-CNN\\Spectrograms" + "\\" + p +
            str(d) + "denoise_audio.wav")
        d = audio.duration
        print(d)
        i = 20
        while (i <= d - 25 and count < 394 and i < 420):

            clip = audio.subclip(i, i + 5)
            clip.write_audiofile(
                "C:\\Users\Sai Teja\Desktop\ELL888-CNN\\Spectrograms" + "\\" +
                "theaudio.wav")
            #clip.reader.close()

            i = i + 5
            print(i)
コード例 #20
0
ファイル: app.py プロジェクト: vuhaibang/youtube
def add_audio_in_videos(path_video, path_audio, path_output):
    my_clip = mpe.VideoFileClip(path_video)
    audio_background = mpe.AudioFileClip(path_audio)
    final_audio = my_clip.set_audio(audio_background)
    final_audio.write_videofile(path_output, fps=30, codec='libx264')
コード例 #21
0
def replyCommand(Msg, Chat):
    chat = Msg.content
    args = chat.split(' ')[1:]
    kpt = chat.lower().split(' ')[0].lower()
    chat_id = Msg.chat_id
    kpt = chat.lower().split(' ')[0].lower()
    jsObject = Msg.get_js_obj()
    ran = secrets.token_hex(7)
    if kpt == '#qrmaker':
        if len(kpt) == 1:
            Msg.reply_message('*salah*')
        else:
            pyqrcode.create(chat.replace(kpt + ' ', '')).png('cache/bar.png',
                                                             scale=6)
            driver.send_media('cache/bar.png', chat_id,
                              'text : %s' % (chat.replace(kpt, '')))
    elif kpt == "#igstalk":
        if args:
            Chat.send_message("Sedang Mencari 🔍")
            userProperty = igstalker(args[0].replace("@", ""))
            if userProperty:
                driver.wapi_functions.sendImage(
                    convert_to_base64(
                        BytesIO(requests.get(userProperty["pic"]).content)),
                    chat_id, "stalk.jpg", f'''
Nama Pengguna : {userProperty["username"]}
Mengikuti     : {userProperty["following"]}
Di Ikuti      : {userProperty["follower"]}
Jumlah Post   : {userProperty["post"]}
============BIO===========
{userProperty["bio"]}
''')
            else:
                Msg.reply_message("Nama Pengguna Tidak Ada ❌")
        else:
            Msg.reply_message("Masukan Nama Pengguna Yg Ingin Di Stalk")
    elif kpt == "#quote1":
        rep = GetRepMedia(Msg)
        if rep.type == "image":
            arg = chat[8:].split('|')
            for i in range(arg.count('')):
                arg.remove('')
            print(arg)
            print(len(arg))
            if len(arg) == 3:
                color = (0, 0, 0) if arg[2] == "1" else (255, 255, 255)
                wri = driver.download_media(rep)
                open("cache/%s.jpg" % ran, "wb").write(wri.read())
                desain("cache/%s.jpg" % ran,
                       katakata=arg[0],
                       author=arg[1],
                       col=color)
                driver.send_media("cache/%s.jpg" % ran, chat_id,
                                  "Apakah Kamu Suka")
            else:
                Msg.reply_message("Perintah Salah")
    elif kpt == '#qrreader':
        rep = GetRepMedia(Msg)
        if rep.type == "image":
            wri = driver.download_media(rep)
            img = decode(Image.open(wri))
            Msg.reply_message(
                'Text : %s\nType : %s' %
                (img[0][0].decode(), img[0][1])) if img else Msg.reply_message(
                    'Gambar Tidak Valid')
    elif kpt == "#wait":
        rep = GetRepMedia(Msg)
        if rep.type == "image":
            wri = driver.download_media(rep)
            open("cache/%s.jpg" % ran, "wb").write(wri.read())
            res = WhatAnimeIsThis("cache/%s.jpg" % ran)
            driver.wapi_functions.sendImage(
                convert_to_base64(BytesIO(
                    res["video"].content)), chat_id, "wait.mp4", res["hasil"]
            ) if res["status"] else Msg.reply_message("Gagal di cari")
            os.remove("cache/%s.jpg" % ran)
    elif kpt == "#grup":
        if '@g.us' in Msg.chat_id:
            cek = Change(Chat.id)
            driver.wapi_functions.sendImage(
                convert_to_base64(
                    BytesIO(driver.get_profile_pic_from_id(Chat.id))), chat_id,
                "Image.jpg",
                f"""Nama : {Chat.name}\nNsfw : {"Aktif" if cek.nsfwX() else "Nonaktif"}\nAntiToxic : {"Aktif" if cek.switch() else "Nonaktif"}\nMax : {cek.maxCount() if cek.switch() else "0"}"""
            )
        else:
            Msg.reply_message("Hanya Berlaku Di Dalam Grup")
    elif kpt == "#tulis":
        tulisan = tulis(chat[7:])
        for i in tulisan:
            ran = secrets.token_hex(7)
            i.save("cache/%s.jpg" % ran)
            driver.send_media("cache/%s.jpg" % ran, chat_id,
                              "Berhasil Ditulis 📝")
            os.remove("cache/%s.jpg" % ran)
    elif kpt == "#upimg":
        rep = GetRepMedia(Msg)
        if rep.type == "image":
            wri = driver.download_media(rep)
            Msg.reply_message(
                imgUploader(base64.b64encode(wri.read()).decode()))
    elif kpt == "#ocr":
        rep = GetRepMedia(Msg)
        if rep.type == "image":
            wri = driver.download_media(rep)
            open("%s.jpg" % ran, "wb").write(wri.read())
            Msg.reply_message(
                tesserocr.file_to_text("%s.jpg" % ran,
                                       lang="eng+ind+jap+chi").strip())
            os.remove("%s.jpg" % ran)
    elif kpt in ["#sticker", "#stiker"]:
        rep = GetRepMedia(Msg)
        if rep.type == "image":
            wri = driver.download_media(rep)
            open("cache/%s.png" % ran, "wb").write(wri.read())
            pasteLayer("cache/%s.png" % ran)
            driver.send_image_as_sticker("cache/%s.png" % ran, chat_id)
            os.remove("cache/%s.png" % ran)
    elif kpt == '#fb':
        link = fbvid(args[0])
        driver.wapi_functions.sendImage(
            convert_to_base64(BytesIO(requests.get(link["url"]).content)),
            chat_id, "fb.mp4", "") if link["status"] else Msg.reply_message(
                "Kemungkinan Link video salah/ video di privasikan")
    elif kpt == '#???':
        ksr = Kasar(chat_id)
        Msg.reply_message('You have said the harsh word %s times' %
                          (ksr.check()))
    elif kpt == '#intro':
        Msg.reply_message(
            '🙋‍♂Hallo Saya Chappie-Bot Saya Di Bangun 🛠️ Dengan Bahasa Python3.8 🐍 Dan Beberapa API🔥'
        )
    elif kpt in ['#menu', '#help']:
        Chat.send_message('''.    🛠️ TOOLS 🛠️
-> #
-> #sticker
-> #upimg
-> #ig
-> #igstalk [User]
-> #fb [Tautan Video]
-> #cari [Kata Kunci]
-> #qrmaker [Teks]
-> #qrreader
-> #? [Soal]
-> #wait
-> #tulis [Teks]
-> #ocr
-> #url2png [Tautan]
-> #run [Syntak]
-> #doujin [Kode Nuklir]
-> #film [Judul Film]
-> #kusonime [Judul Anime]
-> #otakudesu [Judul Anime]
-> #ts [cc] [text]
-> #tts [cc] [text]
-> #quotemaker|[quote]|[author]|[theme]
-> #yt2mp3 [Tautan Youtube]
-> #yt [Tautan Youtube]
-> #wiki [Kata Kunci]

     🕹️HIBURAN 🕹️
-> #dog
-> #neko
-> #quote
-> #kitsune
-> #gambar
-> # [chat]
-> #joke
-> #waifu
-> #bct [text]
    

     👁️‍🗨️   GRUP   👁️‍🗨️
-> #list-admin
-> #admin
-> #mentionall
-> #unadmin @tag
-> #delete @tag
-> #kick @tag
-> #add 62xxxx
-> #owner
-> #grup
-> #linkgroup
-> #revoke
-> #nsfw [1|0]
-> #notoxic [1|0] s/d

     🗣️  BANTUAN 🗣️
-> #cara-penggunaan

     ☕ DUKUNGAN ☕
-> #support
-> #intro

      & Author &
-> #bc [Teks]

''')
    elif kpt == '#joke':
        _help, dat = '''#joke <category> <flags>\ncategory:1:Programming\n         2:miscellaneous\n         3:dark\n         4:pun\nflags :1:nsfw\n       2:religious\n       3:political\n       4:racist\n       5:sexist''', {
            'flags': {
                '1': 'nsfw',
                '2': 'religious',
                '3': 'political',
                '4': 'racist',
                '5': 'sexist'
            },
            'category': {
                '1': 'Programming',
                '2': 'Miscellaneous',
                '3': 'Dark',
                '4': 'Pun'
            }
        }
        if (len(args) == 2 and args[0].isnumeric()) and (args[1].isnumeric()):
            try:
                global ffff
                ffff = json.loads(
                    requests.get(
                        'https://sv443.net/jokeapi/v2/joke/%s?blacklistFlags=%s'
                        % (dat['category'][args[0]],
                           dat['flags'][args[0]])).text)
            except:
                Msg.reply_message(_help)
            if ffff['error']:
                Msg.reply_message(_help)
            else:
                try:
                    Msg.reply_message(
                        tra.translate(text=ffff['joke'], dest='id').text)
                except KeyError:
                    Msg.reply_message(
                        tra.translate(text='%s\n%s' %
                                      (ffff['setup'], ffff['delivery']),
                                      dest='id').text)
        else:
            Msg.reply_message(_help)
    elif kpt == '#bct':
        try:
            Msg.reply_message(bacot(chat[5:]))
        except:
            Msg.reply_message('masukan Text')
    elif kpt == "#nsfw":
        if Msg.sender.id in [(x.id) for x in Chat.get_admins()]:
            if isAdmin(Chat.id):
                if args[0].isnumeric():
                    ns = Change(Chat.id)
                    if int(args[0]) == 1:
                        if ns.idGrup():
                            ns = Change(Chat.id, nsfw=1)
                            ns.nsfwEdit()
                            Chat.send_message("Mengaktifkan NSFW Berhasil")
                        else:
                            ns = Change(Chat.id, nsfw=1, switchInt=0)
                            ns.switchEdit()
                            ns.nsfwEdit()
                            Chat.send_message("Mengaktifkan NSFW Berhasil")
                    elif int(args[0]) == 0:
                        ns = Change(Chat.id, nsfw=0)
                        ns.nsfwEdit()
                        Chat.send_message("Menonaktifkan NSFW Berhasil")
                    else:
                        Chat.send_message(
                            "Masukan 1 untuk *mengaktifkan* dan 0 untuk *menonaktifkan*"
                        )
                else:
                    Chat.send_message(
                        "Masukan 1 untuk *mengaktifkan* dan 0 untuk *menonaktifkan*"
                    )
            else:
                Chat.send_message("Jadikan Saya Menjadi Admin Terlebih Dahulu")
        else:
            Msg.reply_message('Anda Bukan Admin Group')

    elif kpt == "#notoxic":
        if Msg.sender.id in [(x.id) for x in Chat.get_admins()]:
            if isAdmin(Chat.id):
                if int(args[0]) == 1:
                    if len(args) == 2:
                        if args[1].isnumeric():
                            alert = Change(Chat.id,
                                           maxint=int(args[1]),
                                           switchInt=1)
                            alert.switchEdit()
                            Chat.send_message(
                                f"Menyetel Anti Toxic dengan maksimal {args[1]} Peringatan Berhasil"
                            )
                        else:
                            Chat.send_message("Masukan Jumlah Max peringatan")
                    else:
                        Chat.send_message("Masukan Jumlah Max peringatan")
                elif int(args[0]) == 0:
                    alert = Change(Chat.id, switchInt=0)
                    alert.switchEdit()
                    Chat.send_message("Menonaktifkan Anti Toxic Berhasil")
                else:
                    Chat.send_message(
                        "Masukan 1 untuk *mengaktifkan* dan 0 untuk *menonaktifkan*"
                    )
            else:
                Chat.send_message("Jadikan Saya Menjadi Admin Terlebih Dahulu")
        else:
            Msg.reply_message('Anda Bukan Admin Group')
    elif kpt == '#kick':
        if "@g.us" in Msg.chat_id:
            for i in args:
                try:
                    if isAdmin(Chat.id):
                        (Chat.remove_participant_group(
                            i.replace('@', '') +
                            '@c.us') if len(args) == 1 else
                         Msg.reply_message('#kick @tag')) if Msg.sender.id in [
                             (x.id) for x in Chat.get_admins()
                         ] else Msg.reply_message(
                             'Anda Bukan Admin'
                         ) if '@g.us' in Msg.chat_id else Msg.reply_message(
                             "Hanya Berlaku Di Dalam Grup")
                    else:
                        Chat.send_message(
                            "Jadikan Saya Menjadi Admin Terlebih Dahulu")
                except Exception as e:
                    Msg.reply_message("Kick Gagal")
        else:
            Msg.reply_message("Hanya Berlaku Di Dalam Grup")
    elif kpt == "#delete":
        if "@g.us" in Msg.chat_id:
            if Msg._js_obj["quotedMsgObj"]:
                id_ = Msg._js_obj["quotedMsgObj"]["id"]
                chat_id = Msg.chat_id
                if Msg.sender.id in [(x.id)
                                     for x in Chat.get_admins()] + author:
                    if not driver.wapi_functions.deleteMessage(
                            chat_id, id_, True):
                        Msg.reply_message("Hanya Pesan Bot Yg Bisa Di Hapus")
                else:
                    Msg.reply_message("Anda Bukan Admin Grup")
            else:
                Msg.reply_message("Tag Pesan Bot Yg Ingin Di Hapus")
        else:
            Msg.reply_message("Hanya Berlaku Di Dalam Grup")

    elif kpt == '#admin':
        try:
            if '@g.us' in Msg.chat_id:
                if isAdmin(Chat.id):
                    (Chat.promove_participant_admin_group(
                        args[0].replace('@', '') +
                        '@c.us') if len(args) == 1 else
                     Msg.reply_message('#admin @tag')) if Msg.sender.id in [
                         (x.id) for x in Chat.get_admins()
                     ] else Msg.reply_message('Anda Bukan Admin Group')
                else:
                    Chat.send_message(
                        "Jadikan Saya Menjadi Admin Terlebih Dahulu")
            else:
                Msg.reply_message("Hanya Berlaku Di Dalam Grup")
        except Exception as e:
            Msg.reply_message('Terdapat Error\ndetail : %s' % (e))
    elif kpt == '#unadmin':
        try:
            if '@g.us' in Msg.chat_id:
                if isAdmin(Chat.id):
                    (Chat.demote_participant_admin_group(
                        args[0].replace('@', '') +
                        '@c.us') if len(args) == 1 else Msg.reply_message(
                            '#unadmin 62xxxxx')) if Msg.sender.id in [
                                (x.id) for x in Chat.get_admins()
                            ] else Msg.reply_message('Anda Bukan Admin Group')
                else:
                    Chat.send_message(
                        "Jadikan Saya Menjadi Admin Terlebih Dahulu")
            else:
                Msg.reply_message("Hanya Berlaku Di Dalam Grup")
        except Exception as e:
            Msg.reply_message("UnAdmin Gagal")
    elif kpt == '#revoke':
        try:
            if '@g.us' in Msg.chat_id:
                if isAdmin(Chat.id):
                    (Chat.send_message('Tautan Grup Berhasil Ditarik') if
                     driver.wapi_functions.revokeGroupInviteLink(Msg.chat_id)
                     else Chat.send_message('Tautan Grup Gagal Ditarik')
                     ) if Msg.sender.id in [
                         (x.id) for x in Chat.get_admins()
                     ] else Msg.reply_message('Anda Bukan Admin Group')
                else:
                    Chat.send_message(
                        "Jadikan Saya Menjadi Admin Terlebih Dahulu")
            else:
                Msg.reply_message("Hanya Berlaku Di Dalam Grup")
        except Exception as e:
            Chat.send_message("Menarik Tautan Gagal")
    elif kpt == '#add':
        try:
            if '@g.us' in Msg.chat_id:
                if isAdmin(Chat.id):
                    ((Msg.reply_message('Berhasil Ditambahkan')
                      if Chat.add_participant_group(args[0] + '@c.us') else
                      Msg.reply_message('Gagal Ditambahkan'))
                     if Msg.sender.id in [(x.id) for x in Chat.get_admins()]
                     else Msg.reply_message('Gagal Di Tambahkan'))
                else:
                    Chat.send_message(
                        "Jadikan Saya Menjadi Admin Terlebih Dahulu")
            else:
                Msg.reply_message("Hanya Berlaku Di Dalam Grup")
        except Exception as e:
            Msg.reply_message('#add 628xxxxxxx')
    if kpt == '#linkgroup':
        try:
            if '@g.us' in Msg.chat_id:
                if isAdmin(Chat.id):
                    Msg.reply_message(
                        driver.wapi_functions.getGroupInviteLink(Msg.chat_id))
                else:
                    Chat.send_message(
                        "Jadikan Saya Menjadi Admin Terlebih Dahulu")
            else:
                Msg.reply_message("Hanya Berlaku Di Dalam Grup")
        except:
            Msg.reply_message('Angkat Bot ini Menjadi Admin Dulu')
    elif kpt == '#list-admin':
        pesan = ''
        for i in Chat.get_admins():
            pesan += 'nama : @%s\n' % (i.id.replace('@c.us', ''))
        driver.wapi_functions.sendMessageWithMentions(Chat.id, pesan, '')
    elif kpt == '#owner':
        Msg.reply_message(
            Msg.get_js_obj()['chat']['groupMetadata']['owner'].replace(
                '@c.us', '')) if '@g.us' in Msg.chat_id else Msg.reply_message(
                    "Hanya Berlaku Di Dalam Grup")
    elif kpt == '#kitsune':
        driver.wapi_functions.sendImage(
            convert_to_base64(
                BytesIO(
                    requests.get(
                        json.loads(
                            requests.get('http://randomfox.ca/floof/').text)
                        ['image']).content)), chat_id, "kitsune.jpg",
            "What Is This")
    elif kpt == '#tts':
        try:
            gTTS(text=chat[8:], lang=chat[5:7]).save('cache/%s.mp3' % ran)
            driver.send_media('cache/%s.mp3' % ran, chat_id, '')
            os.remove("cache/%s.mp3" % ran)
        except:
            Msg.reply_message(
                "Masukan Perintah Dengan benar \n#tts [cc] [text]\nketik : #cc untuk melihat kode negara"
            )
    elif kpt == '#dog':
        driver.wapi_functions.sendImage(
            convert_to_base64(
                BytesIO(
                    requests.get("http" + literal_eval(
                        requests.get('http://shibe.online/api/shibes?count=1').
                        text)[0][5:]).content)), chat_id, "Dog.jpg",
            "What Is This")
    elif kpt == '#neko':
        driver.wapi_functions.sendImage(
            convert_to_base64(
                BytesIO(
                    requests.get(
                        json.loads(
                            requests.get(
                                'http://api.thecatapi.com/v1/images/search').
                            text)[0]['url']).content)), chat_id, "Neko.jpg",
            "What Is This")
    elif kpt == '#doujin':
        if "@g.us" in Msg.chat_id:
            if Change(Chat.id).nsfwX():
                doujin(
                    args[0], driver, chat_id,
                    Msg) if args else Msg.reply_message('Masukan Kode Nuklir')
            else:
                Msg.reply_message(
                    "Mode Nsfw Nonaktif Atau Anda Bisa Chat Pribadi Dengan Saya"
                )
        else:
            doujin(args[0], driver, chat_id,
                   Msg) if args else Msg.reply_message('Masukan Kode Nuklir')
    elif kpt == "#bc":
        if Msg.sender.id == author[0]:
            pesan = "[[ Chappi-Bot Broadcast ]]\n%s" % (chat[4:].strip())
            for i in driver.get_all_chat_ids():
                driver.wapi_functions.sendMessage(i, pesan)
        else:
            Msg.reply_message("Anda Bukan Author")
    elif kpt == '#quote':
        try:
            hasil = json.loads(
                requests.get(
                    'http://api.quotable.io/random', params={
                        'tags': args[0]
                    }).text) if args else json.loads(
                        requests.get('http://api.quotable.io/random').text)
            tags = ''
            for i in hasil['tags']:
                tags += ' ↦%s\n' % (i)
                pesan = '''author : %s
Tags :
%s[EN] : %s
[ID] : %s''' % (hasil['author'], tags, hasil['content'],
                tra.translate(text=hasil['content'], dest='id').text)
            Msg.reply_message(pesan)
        except:
            Msg.reply_message('Tags Tidak Ada')
    elif kpt == '#yt2mp3':
        if args:
            while True:
                has = yt2mp3(args[0])
                if not has["status"] == "ulang":
                    break
            if has["status"] == "Large":
                Msg.reply_message("Ukuran File Melebihi Batas Maksimal")
            elif has["status"] == True:
                aud = editor.AudioFileClip(has["url"])
                Chat.send_message("🛠️Sedang Mengkonversi Ke Audio 🛠️")
                aud.write_audiofile("cache/%s.mp3" % ran)
                Chat.send_message("🔖Menambahkan Metadata🔖")
                audio = MP3("cache/%s.mp3" % ran, ID3=ID3)
                audio["TIT2"] = TIT2(encoding=3, text=has["judul"])
                audio["APIC"] = APIC(mime="image/jpg",
                                     type=3,
                                     data=requests.get(has["thumb"]).content)
                audio.save()
                Chat.send_message("Sedang Mengunggah⏳")
                driver.wapi_functions.sendImage(
                    convert_to_base64(
                        BytesIO(requests.get(has["thumb"]).content)), chat_id,
                    "thumb.jpg", has["info"])
                driver.send_media("cache/%s.mp3" % ran, chat_id, "")
                os.remove("cache/%s.mp3" % ran)
            else:
                Msg.reply_message("Link Video Tidak Valid")
        else:
            Msg.reply_message("Masukan Url")
    elif kpt == '#yt':
        if len(args) == 2:
            if args[1].isnumeric():
                while True:
                    dow = Merger(args[0], int(args[1])).down()
                    if dow["status"] == True:
                        Chat.send_message("Merging 🛠️")
                        dow["result"].write_videofile("cache/%s.mp4" % ran)
                        Chat.send_message("Sedang Mengunggah⏳")
                        driver.send_media("cache/%s.mp4" % ran, chat_id, "")
                        os.remove("cache/%s.mp4" % ran)
                        break
                    elif dow["status"] == "L":
                        Msg.reply_message("Ukuran File Melebihi Batas")
                        break
                    elif dow["status"] == "url":
                        Msg.reply_message("Tautan Tidak Valid")
                        break
                    elif dow["status"] == "ulang":
                        print(dow)

            else:
                Msg.reply_message("Perintah Salah")
        else:
            if args:
                while True:
                    paser = Merger(args[0]).parser()
                    if not paser["status"] == "ulang":
                        Msg.reply_message(paser["result"])
                        break
                if paser["status"] == "url":
                    Msg.reply_message("Tautan Tidak Valid")
            else:
                Msg.reply_message("Masukan Tautan Video")
    elif kpt == '#gambar':
        driver.wapi_functions.sendImage(
            convert_to_base64(
                BytesIO(
                    requests.get(
                        'https://source.unsplash.com/1600x900/?%s' %
                        (args[0]) if args else
                        'https://source.unsplash.com/random').content)),
            chat_id, "Image.jpeg", "Apakah Kamu Suka ?")
    elif kpt == '#mentionall':
        if Msg.sender.id in [(x.id) for x in Chat.get_admins()
                             ] or Msg.sender.id == '*****@*****.**':
            semua = Chat.get_participants()
            pesan = ''
            for i in semua:
                pesan += '@%s ' % (i.id)
            driver.wapi_functions.sendMessageWithMentions(
                Chat.id, pesan.replace('@c.us', ''), '')
        else:
            Msg.reply_message('Anda Bukan Admin Group')
    elif kpt == '#?':
        if args:
            answers = ''
            isi = '''Soal    : %s\nMapel   : %s\nSekolah : %s\nTanggal : %s\n'''
            jum, soal = ((int(args[-1])),
                         chat[3:-len(args[-1])]) if args[-1].isnumeric() else (
                             1, chat[3:])
            Chat.send_message("Sedang Mencari 🔎")
            cari = gsearch('"%s" site:brainly.co.id' % soal)
            temp = []
            for i in cari:
                temp.append(
                    i) if 'google.com' not in i and 'tugas' in i else False
            if temp:
                for i in temp[:jum]:
                    try:
                        br = brainly(i)
                        Chat.send_message("%s\n%s" %
                                          (br.get("soal"), br.get("jawaban")))
                    except:
                        Msg.reply_message('❌ Gagal Mencari Jawaban ❌')
            else:
                Chat.send_message('❌ Mencari Jawaban *%s* Tidak Ada ❌' %
                                  (soal))
        else:
            Msg.reply_message('❌ Masukan Soal Yg Ingin Di Jawab ❌')
    elif kpt == '#cari':
        try:
            Chat.send_message("Sedang Mencari 🔎")
            hasil = wikipedia.search(chat.replace('#cari', ''))
            pesan = 'hasil pencarian : \n'
            for i in hasil:
                pesan += '↦ %s\n' % (i)
            Msg.reply_message(pesan)
        except:
            Msg.reply_message('Masukan Parameternya Bro')
    elif kpt == '#wiki':
        try:
            hasil = wikipedia.page(chat[6:])
            Msg.reply_message('title :%s\nsource: %s\n%s' %
                              (hasil.title, hasil.url, hasil.content))
        except:
            Msg.reply_message('❌ YG Anda Cari Tidak Ada ❌')
    elif kpt == '#quotemaker':
        '''
        #quotemaker |<kata>|<author>|<kategori>
        '''
        try:
            arg = chat[12:].split('|')
            for i in range(arg.count('')):
                arg.remove('')
            print(arg)
            hasil = json.loads(
                requests.get(
                    'https://terhambar.com/aw/qts/?kata=%s&author=%s&tipe=%s',
                    params={
                        'kata': arg[0],
                        'author': arg[1],
                        'tipe': arg[2]
                    }).text)
            driver.wapi_functions.sendImage(
                convert_to_base64(
                    BytesIO(requests.get(hasil['result']).content)), chat_id,
                "quotes.jpg", "Apakah Kamu Suka ?"
            ) if hasil['status'] else Msg.reply_message(
                '#quotemaker|<kata>|<author>|<kategori>')
        except:
            Msg.reply_message('#quotemaker|<kata>|<author>|<kategori>')
    elif kpt == '#cc':
        cc = json.loads(open('lib/ISO-639-1-language.json').read())
        pesan = ''
        for i in cc:
            pesan += '%s : %s\n' % (i['code'], i['name'])
        Msg.reply_message(pesan)
    elif kpt == '#ts':
        try:
            Msg.reply_message(
                tra.translate(text=chat[7:], dest=chat[4:6]).text)
        except:
            Msg.reply_message(
                '#ts [Target] [Text]\nContoh :\n #ts id good morning \nketik #cc untuk melihat kode negara'
            )
    elif kpt == '#run':
        Msg.reply_message('Hasil Eksekusi :\n%s' % (requests.get(
            'https://twilio-apis.herokuapp.com/', params={
                'cmd': chat[4:]
            }).text))
    elif kpt == '#waifu':
        hasil = waifu()
        driver.wapi_functions.sendImage(
            convert_to_base64(BytesIO(requests.get(hasil["image"]).content)),
            chat_id, "waifu.jpg", hasil["title"])
    elif kpt == '#url2png':
        if args:
            try:
                driver.wapi_functions.sendImage(
                    convert_to_base64(
                        BytesIO(requests.get(url2png(args[0])).content)),
                    chat_id, "url2png.png", "Link : %s" % args[0])
            except:
                False
        else:
            Msg.reply_message('masukan Url \n#url2png https://google.com')
    elif kpt == '#ig':
        ob = igdownload(args[0])
        if ob["status"]:
            for i in ob["result"]:
                if i["type"] == "image":
                    driver.wapi_functions.sendImage(
                        convert_to_base64(
                            BytesIO(requests.get(i["url"]).content)), chat_id,
                        "ig.jpg", "")
                elif i["type"] == "video":
                    driver.wapi_functions.sendImage(
                        convert_to_base64(
                            BytesIO(requests.get(i["url"]).content)), chat_id,
                        "ig.mp4", "")
        else:
            Msg.reply_message("Link Error")
    elif kpt == '#tts':
        try:
            gTTS(text=chat[8:], lang=chat[5:7]).save('cache/tts.mp3')
            driver.send_media('cache/%s.mp3' % ran, chat_id, '')
            os.remove("cache/%s.mp3" % ran)
        except:
            Msg.reply_message(
                "Masukan Perintah Dengan benar \n#tts [cc] [text]\nketik : #cc untuk melihat kode negara"
            )
    elif kpt == "#kusonime":
        try:
            result_scrap = scrap_kusonime(search_kusonime(chat[10:]))
            driver.wapi_functions.sendImage(
                convert_to_base64(
                    BytesIO(requests.get(result_scrap["thumb"]).content)),
                chat_id, "kusonime.jpg", result_scrap["info"])
            Msg.reply_message(
                "Sinopsis:\n %s\nLink Download:\n %s" %
                (result_scrap["sinopsis"], result_scrap["link_dl"]))
        except:
            Msg.reply("❌ Anime : %s Tidak Ada ❌" % (chat[7:]))
    elif kpt == "#otakudesu":
        try:
            result_scrap = scrap_otakudesu(search_otakudesu(chat[11:]))
            driver.wapi_functions.sendImage(
                convert_to_base64(
                    BytesIO(requests.get(result_scrap["thumb"]).content)),
                chat_id, "OtakuDesu.jpg", "%s\nSinopsis : %s" %
                (result_scrap["info"], result_scrap["sinopsis"]))
        except:
            Msg.reply_message("❌ Anime : %s Tidak Ada ❌" % (chat[11:]))
    elif kpt == '#film':
        Chat.send_message("Sedang Mencari 🔎")
        hasil = gsearch('"%s" site:sdmovie.fun' % chat[5:])
        h = 0
        for i in hasil:
            if ('sdmovie' in i and 'google' not in i):
                h += 1
                Link = ''
                hafun = fun(i)
                for o in hafun['video']:
                    Link += f"{o['url']} | {o['lewat']} | {o['sub']} | {o['res']} \n "
                pesan = '🎬 : %s\nrating: %s\nsinopsis : %s\n VIDEO :\n %s' % (
                    hafun['title'], hafun['rating'], hafun['sinopsis'], Link)
                driver.wapi_functions.sendImage(
                    convert_to_base64(
                        BytesIO(requests.get(hafun['cover']).content)),
                    chat_id, "sdmovie.jpg", hafun["title"])
                Chat.send_message(pesan)
        if h == 0:
            Msg.reply_message("❌ Film Yg Anda Cari Tidak Ditemukan ❌")
    elif hashlib.md5(
            kpt.encode()).hexdigest() == 'fe1538c21f7479f15103962373b2b841':
        driver.send_message_with_auto_preview(
            chat_id, "https://saweria.com/donate/KryptonByte",
            "📌Yuk Donasi Biar Bot Nya Aktif Terus Dan Mimin Nya Rajin Update & Fix Bug"
        )
    elif kpt == "#cara-penggunaan":
        Msg.reply_message('''*#help alat* -> menampilkan perintah alat
*#sticker* -> pembuat sticker
*#upimg* -> Upload Gambar Ke Img.bb
*#cari* -> cari query wikipedia
con : #cari hantu
*#qrmaker* -> pembuat qrcode
con : #qrmaker Sebuah qrcode
*#qrreader* -> pembaca qrcode
*#?* -> pencari jawaban langsung dari brainly.co.id
con : #? contoh soal matematika
con : #? contoh soal matematika 2
*#ocr* -> untuk mengambil teks di sebuah Gambar
*#url2png* -> mengubah url ke bentuk Gambar
con : #url2png https://www.google.com
*#run* -> python compiler Api
con : #run 
print("Hallo world")
*#doujin* -> Doujin Download
con : #doujin kode-nuklir
*#film* -> pencari film + link Download
con : #film chappie
*#ts* -> Translate
con : #ts en Hai
*#tts* -> text to speak
con : #tts id Hallo Saya Bot
*#cc* -> menampilkan Kode Negara
*#otakudesu* -> pencari anime
*#kusonime* -> pencari anime
*#wait* -> pencari judul Anime Menggunakan potongan scene
*#quotemaker* -> pembuat quotes
con : #quotemaker|Teks Kuotes|Penulis|happy
*#tulis* -> Menulis Text
con : #tulis Nama : Krypton-Byte
*#yt2mp3* -> pencari link download lagu dengan link youtube
con : #yt2mp3 #https://www.youtube.com/watch?v=FQQbRBs3nFY
*#yt2mp3* -> pencari download video dari youtube tidak termasuk audio
con : #yt https://www.youtube.com/watch?v=FQQbRBs3nFY
*#wiki* -> wikipedia
con : #wiki hantu
*#help grup* -> menampilkan perintah yg berlaku di dalam grup
*#list-admin* -> menampilkan admin grup
*#admin* -> mengadminkan seseorang
con : #admin @orang
con : #admin 6281234567890
*#unadmin* -> Mencopot sebagai admin
con : #unadmin @orang
con : #unadmin 6281234567890
*#kick* -> mengkick anggota grup
con : #kick @orang
con : #kick 6281234567890
*#add* -> menambah kan anggota grup
con : #add 6281234567890
atau anda bisa mengirim kartu kontak
*#owner* -> menampilkan owner grup
*#linkgroup* -> menampilkan tautan invite grup
*#revoke* -> menarik tautan invite grup
*#mentionall* -> menTag seluruh member grup
*#help bot* -> menampilkan perintah bot
*#* -> chat bot
#con : # Hai
*#help hiburan* -> menampilkan perintah yg bisa menghibur
*#dog* -> mengirimkan gambar anjing secara acak
*#neko* -> mengirimkan gambar kucing secara acak
*#kitsune* -> mengirimkan gambar rubah secra acak
*#gambar* -> mencari gambar
con : gambar cat
*#joke* -> menampilkan joke
con : #joke 1 1
con : #joke 1 3
*#waifu* -> Random Waifu 
*#bct* -> mengubah huruf semua huruf vokal ke huruf "i"
con : #bct Aku Saya kamu
*#help* -> menampilkan semua opsi help''')
    elif kpt == '#':
        if args:
            Msg.reply_message(chatbot(chat))
        else:
            Msg.reply_message('Mau Nanya apa ?')
コード例 #22
0
ファイル: app.py プロジェクト: vuhaibang/youtube
def gen_video_from_url_image(url_deses,
                             title_video,
                             intro,
                             screensize=(1920, 1080)):
    DICT = {
        "funpic": "Funny pics",
        "smile": "Smile pics",
        "dailyjoy": "Daily joy",
        "findingjoy": "Finding Joy",
        "happymonkey": "Happy Monkey",
        "strangerbanana": "Stranger Banana"
    }
    if os.path.isdir('/home/vuhaibangtk/'):
        audio_path = '/home/vuhaibangtk/youtube/audio'
        path_video_out_put = f'/home/vuhaibangtk/videos/{title_video}.mp4'
        path_intro = f'/home/vuhaibangtk/youtube/videos/intro/{intro}.mp4'
        bottom_path = "/home/vuhaibangtk/youtube/service/reup_videos/bottom.png"
        outtro_path = "/home/vuhaibangtk/youtube/videos/intro/outtro.jpg"
    elif os.path.isdir('/home/vhb/'):
        audio_path = '/home/vhb/PycharmProjects/Project/youtube/audio'
        path_video_out_put = f'/home/vhb/PycharmProjects/Project/videos/{title_video}.mp4'
        path_intro = f'/home/vhb/PycharmProjects/Project/youtube/videos/{intro}/fun_pic.mp4'
        bottom_path = "/home/vhb/PycharmProjects/Project/youtube/service/reup_videos/bottom.png"
    else:
        audio_path = 'C:/Project//youtube/audio'
        path_video_out_put = f'C:/Project/youtube/{title_video}.mp4'
        path_intro = f'C:/Project/youtube/videos/intro/{intro}.mp4'
        bottom_path = "C:/Project/youtube/service/reup_videos/bottom.png"

    clips = []
    for url, des in url_deses:
        duration = min(8.5, max(4.5, len(des) * 4.5 / 50))
        if len(des) < 1:
            des = DICT[intro]
        line_text, text = replace_space_in_text(des)
        size_text = int(screensize[0] / 33)

        try:
            main_image = mpe.ImageClip(url).set_position(
                ('center', 'center')).set_duration(duration)
            back_ground_image = mpe.ImageClip(url).resize(
                screensize).set_duration(duration).set_opacity(0.5)
            txt_mask = mpe.TextClip(text,
                                    font='Amiri-Bold',
                                    color='black',
                                    fontsize=size_text)
            bottom_image = mpe.ImageClip(bottom_path).resize((screensize[0], line_text * size_text + int(screensize[0]/80)))\
                .set_duration(duration).set_position("bottom", "center")
            txt_mask = txt_mask.set_duration(duration).set_position(
                ("center", screensize[1] - bottom_image.h + int(
                    (bottom_image.h - txt_mask.h) / 2)))
            main_image = main_image.resize(
                resize_center_image_in_video(main_image.w, main_image.h, screensize[0], screensize[1] - bottom_image.h))\
                .set_position(("center", "top"))
            clip = mpe.CompositeVideoClip(
                [back_ground_image, main_image, bottom_image, txt_mask])
        except:
            continue
        clips.append(clip)
    clips.append(mpe.ImageClip(outtro_path).set_duration(7))

    slided_clips = []
    for num, clip in enumerate(clips):
        if num + 1 < len(clips):
            slided_clips.append(
                mpe.CompositeVideoClip([
                    clips[num + 1].set_start(clip.duration - 1),
                    clip.fx(mpe.transfx.slide_out, 1, 'left')
                ]))
        else:
            slided_clips.append(clip)
    slided_clips.insert(0, mpe.VideoFileClip(path_intro))

    concat_clip = mpe.concatenate_videoclips(
        slided_clips, method="compose").resize(screensize)
    list_audio = os.listdir(audio_path)
    list_audio = [
        os.path.join(audio_path, l) for l in list_audio if l != 'money.wav'
    ]
    path_audio = random.choice(list_audio)
    money_audio_path = os.path.join(audio_path, 'money.wav')
    audio = mpe.AudioFileClip(path_audio)
    money_audio = mpe.AudioFileClip(money_audio_path)

    if intro == "dailyjoy":
        if concat_clip.duration > (mpe.VideoFileClip(path_intro).duration +
                                   money_audio.duration):
            audio = mpe.afx.audio_loop(audio,
                                       duration=concat_clip.duration -
                                       mpe.VideoFileClip(path_intro).duration -
                                       money_audio.duration)
            audio = mpe.CompositeAudioClip([
                mpe.VideoFileClip(path_intro).audio,
                audio.set_start(mpe.VideoFileClip(path_intro).duration),
                money_audio.set_start(
                    mpe.VideoFileClip(path_intro).duration + audio.duration)
            ])
        else:
            money_audio = money_audio.set_duration(
                concat_clip.duration - mpe.VideoFileClip(path_intro).duration)
            audio = mpe.CompositeAudioClip([
                mpe.VideoFileClip(path_intro).audio,
                money_audio.set_start(mpe.VideoFileClip(path_intro).duration)
            ])
    else:
        audio = mpe.afx.audio_loop(audio,
                                   duration=concat_clip.duration -
                                   mpe.VideoFileClip(path_intro).duration)
        audio = mpe.CompositeAudioClip([
            mpe.VideoFileClip(path_intro).audio,
            audio.set_start(mpe.VideoFileClip(path_intro).duration)
        ])
    print(audio.duration)
    print(concat_clip.duration)
    concat_clip = concat_clip.set_audio(audio)

    concat_clip.write_videofile(path_video_out_put,
                                fps=24,
                                codec='libx264',
                                threads=2)
コード例 #23
0
page_access_token = fb_config["access_token"]
facebook_page_id = fb_config["page_id"]
graph = facebook.GraphAPI(page_access_token)


# a random URL from the database is returned, and is passed to YoutubeDL for downloading and audio extraction
# the URL is also stored in a variable, so that it can be used as the video's description

title = download(db_access.get_url(rng.randint(0, db_access.get_max())), rng)
# renames every .mp3 file in the directory to audio.mp3, just to make sure that a valid file is passed
for files in glob.glob("*.mp3"):
    os.rename(files, "audio.mp3")

opDuration = rng.randint(45, 90)
lgth = MP3("audio.mp3").info.length
bgmusic = mpe.AudioFileClip("audio.mp3")

# the Bot would post the Evangelion ending on Sundays, and the opening on other days
if weekday=="Sun":
    # of course you change the file structure and relative paths however it suits you
    # although remember that if you plan to automate it (i.e. with cron), you should
    # uncomment line 11 and change it to the absolute path of this script
    originalOp = mpe.VideoFileClip("./FLYME/ED.mp4")
else:
    originalOp = mpe.VideoFileClip("./CRUAT/OP.mp4")

if lgth<45:
    # if the length of the audio source is shorter than the source video (i.e. 45 seconds), the audio plays from start to finish
    musicEnd=int(lgth)
    musicStart=0
コード例 #24
0
# installing video libraries
# this might take several minutes

# In[ ]:


# importing movie library
import moviepy.editor as mpe

# creating animation with sound - this takes literally forever! (expect 5 mins or more)
fig, ax = plt.subplots(1, 2,figsize=(18,6))
anim = animation.FuncAnimation(fig, animate_all, init_func=init_all, frames=frames, interval=1000/VIDEO_RATE, blit=False)
anim.save('animation.gif', fps=VIDEO_RATE)
my_clip = mpe.VideoFileClip('./animation.gif')
audio_background = mpe.AudioFileClip('./sound.wav')
final_audio = mpe.CompositeAudioClip([audio_background])
# this looks like a hack and it is.. it should be that "my_clip.fps==VIDEO_RATE"
# but for some reason it's not. Matplotlib isn't the best video saver..
# or moviepy isn't the best movie reader.. it's one or the other.
# basically when we're writing, we're setting fps to 24..
# but when we're reading, it's 25 fps all of a sudden
# Either this "anim.save('animation.gif', fps=VIDEO)" doesn't respect the FPS
# or this "mpe.VideoFileClip('./animation.gif')" doesn't read the file properly
# doesn't relly matter who... doing "speedx" does a "quick fix!"
final_clip = my_clip.speedx(VIDEO_RATE/my_clip.fps).set_audio(final_audio)
final_clip.write_videofile("./animation_with_sound.mp4")

# finally display produced animation
HTML("""
<div>