Ejemplo n.º 1
0
    def create_videoclip(self,
                         post_number,
                         is_comment=False,
                         comment_number=0):
        """
		Creates a video from the given details from the image and video paths.
		"""
        aud_path = f"audios/post_{post_number}.mp3"
        img_path = f"images/post_{post_number}.png"
        out_path = f"videos/post_{post_number}.mp4"
        if is_comment:
            aud_path = f"audios/post_{post_number}_comment_{comment_number}.mp3"
            img_path = f"images/post_{post_number}_comment_{comment_number}.png"
            out_path = f"videos/post_{post_number}_comment_{comment_number}.mp4"
        print(
            f"Creating video {out_path} from audio {aud_path} and image {img_path}\n"
        )
        aud_clip = AudioFileClip(aud_path)
        vid_clip = ImageClip(img_path)
        vid_clip = vid_clip.set_audio(aud_clip).set_duration(aud_clip.duration)
        vid_clip.write_videofile(out_path,
                                 preset="medium",
                                 temp_audiofile='temp-audio.m4a',
                                 remove_temp=True,
                                 codec="mpeg4",
                                 audio_codec="aac",
                                 fps=24)
Ejemplo n.º 2
0
def video_creation():

    # command line arguments [main.py, image, audio, min_length, movie_name]
    if len(sys.argv) < 5:
        arg_error('{0} args supplied but {1} args required.'.format(
            len(sys.argv) - 1, 4))

    location = ''  # default is no location, i.e., save video in working directory
    if len(sys.argv) > 5:
        if len(sys.argv[5]) > 0:  # allow empty path for future compatibility
            location = sys.argv[5]
            # append slash if required
            if location[-1] != '/' and location[-1] != '\\':
                location += '/'
            try:
                # create directory if needed (works recursively)
                pathlib.Path(location).mkdir(parents=True, exist_ok=True)
            except Exception as e:
                arg_error(
                    'problem with location \'{0}\'. Either it could not be found or it could not be created.'
                    .format(location), e)

    image_src = sys.argv[1]
    audio_src = sys.argv[2]

    try:
        min_length = int(
            str(sys.argv[3]).split(  # format: Minutes.Seconds
                '.')[0]) * 60 + int(str(
                    sys.argv[3]).split('.')[1])  # converted to seconds
    except Exception as e:
        arg_error(
            '[min_length] not parsable. \'{0}\' was supplied when the correct format is \'numbers.numbers\', e.g., \'123.59\'.'
            .format(sys.argv[3]), e)

    if min_length < 1:
        min_length = 1  # keep min_length no smaller than one second

    movie_name = sys.argv[4] + '.mp4'

    # beginning of moviepy functions
    image_clip = ImageClip(image_src)  # get image
    audio = AudioFileClip(audio_src)  # get audio

    # how many complete audio loops are needed to meet the min_length?
    loops_needed = int(min_length / audio.duration + 1)

    # loop our audio to meet the min_length
    audio = audio_loop.audio_loop(audio, nloops=loops_needed)

    # set up our clip
    image_clip = image_clip.set_audio(audio)
    image_clip.fps = 24
    image_clip.duration = audio.duration

    # render!
    image_clip.write_videofile(location + movie_name,
                               preset='ultrafast',
                               threads=multiprocessing.cpu_count())
Ejemplo n.º 3
0
def generate():
    """Genera los vídeos de finalización"""
    for png in Path('.').glob('end_*.png'):
        nombre = png.stem
        res = nombre.split('_')[1]
        clip = ImageClip(png.name).set_duration(NUM_SECONDS)
        clip.write_videofile('{}.mp4'.format(nombre, res), fps=24)
        print ("info: h: {}, w: {}".format(clip.h, clip.w))
        clip.close()
Ejemplo n.º 4
0
    def __make_image_video__(self, image_src, duration):
        file_path = "./tmp/{:s}.mp4".format(str(self.__next_index__()))
        clip = ImageClip(image_src, duration=duration)
        clip.write_videofile(file_path, fps=VIDEO_FPS)
        clip.close()

        file_path = self.__apply_transformation__(file_path, duration)

        return file_path
Ejemplo n.º 5
0
def outro():
    outroimg = pathlib.Path(RESOURCES + "/images/outputMoment.jpg")
    audio = AudioFileClip(pathlib.Path(RESOURCES + "/sounds/outroaud.wav"))
    music = AudioFileClip(pathlib.Path(RESOURCES + "/sounds/jazz_lounge.mp3"))
    final_audio = CompositeAudioClip([audio, music])
    outro = ImageClip(outroimg)
    outro = outro.set_fps(24)
    outro = outro.set_audio(final_audio)
    outro = outro.set_duration(30)
    outro.write_videofile(pathlib.Path(RESOURCES + "/vids/outro.mp4"))
Ejemplo n.º 6
0
def generate_leaderboard_clip(working_dir: WorkingDir,
                              duration: float = 5.0,
                              frames_per_second: int = 60):
    if working_dir.leaderboard.exists():
        clip = ImageClip(str(working_dir.leaderboard)).set_duration(duration)
        clip.write_videofile(str(working_dir.leaderboard_clip),
                             fps=frames_per_second)
        print('Successfully generated leaderboard clip.')

    else:
        print(f'No leaderboard has been generated yet.')
Ejemplo n.º 7
0
def convert(nombre):
    # Generamos la entradilla
    clip = ImageClip('{}.png'.format(nombre)).set_duration(5)
    clip.write_videofile('{}_start.mp4'.format(nombre), fps=24)
    clip.close()

    # Generamos vídeo final
    clip1 = VideoFileClip('{}_start.mp4'.format(nombre))
    clip2 = VideoFileClip('{}.mp4'.format(nombre))
    clip3 = VideoFileClip('video_end.mp4')

    final = concatenate_videoclips([clip1, clip2, clip3], method="compose")
    final.write_videofile('{}_final.mp4'.format(nombre))
    final.close()
Ejemplo n.º 8
0
def main(orientation, background_image_path):

    if orientation == "portrait":
        size = (1080, 1920)
    elif orientation == "landscape":
        size = (1920, 1080)

    background_image = ImageClip(
        os.path.join(background_image_path,
                     "background.png")).set_duration(1).resize(size)
    # fps = (1/math.ceil(raw_square_video.duration))
    # fps = 30
    background_image.write_videofile(os.path.join(background_image_path,
                                                  "background.mp4"),
                                     fps=60)
    background_image.close()

    return os.path.join(background_image_path, "background.mp4")
Ejemplo n.º 9
0
def write_output(audio_clip, output_filename, background=None, verbose=False):
    if verbose:
        print("Storing clip {} to {} (background={})".format(
            audio_clip, output_filename, background))

    if not background:
        audio_clip.write_audiofile(output_filename,
                                   fps=16000,
                                   nbytes=2,
                                   bitrate='16k',
                                   verbose=verbose)
    else:
        clip = ImageClip(background, duration=audio_clip.duration)
        clip = clip.set_audio(audio_clip)
        clip.write_videofile(output_filename,
                             fps=1,
                             audio_fps=16000,
                             audio_nbytes=2,
                             audio_bitrate='16k',
                             verbose=verbose)
Ejemplo n.º 10
0
def write_output(audio_clip, output_filename, background=None, verbose=False):

    if not background:
        audio_clip.write_audiofile(
            output_filename,
            fps=16000,
            nbytes=2,
            bitrate='16k',
            verbose=verbose
        )
    else:
        clip = ImageClip(background, duration=audio_clip.duration)
        clip = clip.set_audio(audio_clip)
        clip.write_videofile(
            output_filename,
            fps=1,
            audio_fps=16000,
            audio_nbytes=2,
            audio_bitrate='16k',
            verbose=verbose
        )
Ejemplo n.º 11
0
def generar_caratulas(num, clip_size):
    """generar_caratulas

        Genera y devuelve los vídeos de inicio y fin a partir
        de las imágnes de portada y finalización.

        (width, height)

    """
    inicio_mp4, fin_mp4 = None, None

    # generamos la imagen final
    out="end_{}.mp4".format(clip_size[1])
    if not Path(out).exists():
        im = Image.open('end_1440.png')
        im.resize(clip_size, Image.ANTIALIAS)
        name="end_{}.png".format(clip_size[0])
        im.save(name, "PNG")
        clip = ImageClip(name).set_duration(NUM_SECONDS)
        out="end_{}.mp4".format(clip_size[1])
        clip.write_videofile(out, fps=24)
        clip.close()
    fin_mp4 = Path(out)

    for png in Path('.').glob('{}-*_1440.png'.format(num)):
        im = Image.open(png.name)
        im.resize(clip_size, Image.ANTIALIAS)
        name_png="{}_{}_start.png".format(png.stem, clip_size[1])
        im.save(name_png, "PNG")

        clip = ImageClip(name_png).set_duration(NUM_SECONDS)
        name_mp4 = '{}_{}_start.mp4'.format(png.stem, clip_size[1])
        clip.write_videofile(name_mp4, fps=24)
        clip.close()
        inicio_mp4 = Path(name_mp4)
        break
    return inicio_mp4, fin_mp4
def generate_leaderboard(current_week,
                         extra=False,
                         background=True,
                         make_clip=False,
                         duration=5.0,
                         frames_per_second=60):
    """ Creates a leaderboard for league play.
    
    Arguments:
        current_week {int} -- Current week's number, e.g. 1, 2, 3, etc.
    
    Keyword Arguments:
        extra {bool} -- Whether to include the next 5 divisions. (default: {False})
        background {bool} -- Whether to use a background for the leaderboard. (default: {True})
        make_clip {bool} -- Whether to also make an mp4 clip. (default: {False})
        duration {float} -- Duration of the clip in seconds. (default: {5})
        frames_per_second {int} -- frames per second of the clip. (default: {60})
    """

    # ---------------------------------------------------------------

    # LOADING STANDINGS:

    # Getting previous week's standings from text file.
    previous_txt = open('previous_week.txt', 'r')
    previous = []
    for line in previous_txt:
        previous.append(line.strip())
    previous_txt.close()

    # Getting current week's standings from text file.
    current_txt = open('current_week.txt', 'r')
    current = []
    for line in current_txt:
        current.append(line.strip())
    current_txt.close

    # ---------------------------------------------------------------

    # SYMBOL SUBLISTS:

    # Creates lists to track which bots moved or which are new.
    new_bots = []
    moved_up = []
    moved_down = []

    # Loops through each bot in current standings.
    for bot in current:
        # Finds if the bot is new.
        if bot not in previous:
            new_bots.append(bot)

        else:
            # Finds whether the bot moved and whether up or down.
            if current.index(bot) < previous.index(bot):
                moved_up.append(bot)
            elif current.index(bot) > previous.index(bot):
                moved_down.append(bot)

    # Creates list for tracking who played last week.
    played = previous  # Since A and B are both playing in a single week no need to track this.
    '''
    # Takes current week's number and determines if it's odd or even.
    odd = current_week % 2 # 0 if week is even, 1 if week is odd.

    # Adds bots who played last week to list.
    for i in range(5):
        played += previous[i*8 + 4*odd : i*8 + 4*odd + 5]
    '''

    # ---------------------------------------------------------------

    # PARAMETERS FOR DRAWING:

    # Divisions
    divisions = ('Quantum', 'Overclocked', 'Processor', 'Circuit',
                 'Transistor', 'Abacus', 'Babbage', 'Colossus', 'Dragon',
                 'ENIAC', 'Ferranti')
    '''
    Each division has the origin at the top left corner of their emblem.

    Offsets:
        title offsets determine where the division title is drawn relative to the emblem.
        bot offsets determine where bot names are drawn relative to the emblem.
        sym offsets determine where the symbol is placed relative to the bot name.

    Increments:
        div increments are how much to move the origin between each division.
        bot increment is how much to move down for each bot name.

    '''

    # Start positions for drawing.
    start_x = 0
    start_y = 0

    # Division emblem offsets from the division name position.
    title_x_offset = 350
    title_y_offset = 85

    # Bot name offsets from the division name position.
    bot_x_offset = 200
    bot_y_offset = 300

    # Offsets for the symbols from the bot name position.
    sym_x_offset = 1295
    sym_y_offset = 5

    # Incremenets for x and y.
    div_x_incr = 1790
    div_y_incr = 790
    bot_y_incr = 140

    # ---------------------------------------------------------------

    # DRAWING:

    # Opening image for drawing.
    if background:
        if extra:
            leaderboard = Image.open('templates/Leaderboard_extra_empty.png')
        else:
            leaderboard = Image.open('templates/Leaderboard_empty.png')
    else:
        if extra:
            leaderboard = Image.open(
                'templates/Leaderboard_extra_no_background.png')
        else:
            leaderboard = Image.open('templates/Leaderboard_no_background.png')

    draw = ImageDraw.Draw(leaderboard)

    # Fonts for division titles and bot names.
    div_font = ImageFont.truetype('MontserratAlternates-Medium.ttf', 120)
    bot_font = ImageFont.truetype('MontserratAlternates-Medium.ttf', 80)

    # Bot name colour.
    bot_colour = (0, 0, 0)

    # For each divion, draw the division name, and each bot in the division.
    for i, div in enumerate(divisions):

        # Calculates position for the division.
        div_pos = (start_x + div_x_incr * (i // 5),
                   start_y + div_y_incr * (i % 5))

        # Draws the division emblem.
        try:
            # Opens the division emblem image.
            emblem = Image.open(f'emblems/{div}.png')
            # Pastes emblem onto image.
            leaderboard.paste(emblem, div_pos, emblem)
        except:
            # Sends warning message if it can't find the emblem.
            print(f'WARNING: Missing emblem for {div}.')

        # Draws the division title at an offset.
        title_pos = (div_pos[0] + title_x_offset, div_pos[1] + title_y_offset)
        draw.text(xy=title_pos, text=div, fill=palette[div][0], font=div_font)

        # Loops through the four bots in the division and draws each.
        bot_index = i * 4
        for ii, bot in enumerate(current[bot_index:bot_index + 4]):

            # Calculates position for the bot name and draws it.
            bot_pos = (div_pos[0] + bot_x_offset,
                       div_pos[1] + bot_y_offset + ii * bot_y_incr)
            draw.text(xy=bot_pos, text=bot, fill=bot_colour, font=bot_font)

            # Calculates symbol position.
            sym_pos = (bot_pos[0] + sym_x_offset, bot_pos[1] + sym_y_offset)

            # Pastes appropriate symbol
            if bot in new_bots:
                symbol = Image.open(f'symbols/{div}_new.png')
                leaderboard.paste(symbol, sym_pos, symbol)

            elif bot in moved_up:
                symbol = Image.open(f'symbols/{div}_up.png')
                leaderboard.paste(symbol, sym_pos, symbol)

            elif bot in moved_down:
                symbol = Image.open(f'symbols/{div}_down.png')
                leaderboard.paste(symbol, sym_pos, symbol)

            elif bot in played:
                symbol = Image.open(f'symbols/{div}_played.png')
                leaderboard.paste(symbol, sym_pos, symbol)

    # Shows and saves the image.
    leaderboard.show()
    leaderboard.save('Leaderboard.png', 'PNG')

    if make_clip:
        # Saves a clip of the image.
        clip = ImageClip('Leaderboard.png').set_duration(duration)
        clip.write_videofile("Leaderboard.mp4", fps=frames_per_second)
Ejemplo n.º 13
0
#!/usr/bin/env python

from moviepy.editor import AudioFileClip, ImageClip
from sys import argv

audio = AudioFileClip(argv[1])
clip = ImageClip(argv[2]).set_duration(audio.duration).set_audio(audio)
clip.write_videofile(argv[3], fps=24)