Files
prepare/prepare.py

126 lines
4.7 KiB
Python
Executable File

#!/usr/bin/python3
import random
import os
import pathlib
import moviepy.editor
import threading
import time
import logging
import argparse
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
from pymediainfo import MediaInfo
logging.basicConfig(filename='prepare.log', filemode='w', format='%(asctime)s \t %(threadName)s \t %(levelname)s \t '
'%(message)s', level=logging.INFO)
class Args:
parser = ArgumentParser = argparse.ArgumentParser(
description='Extracting mediainfo, sample and screens from random timecodes from video')
parser.add_argument('-s', action='store_true', dest='screens', help="create screenshots")
parser.add_argument('-c', action='store_true', dest='sample', help="extract sample")
parser.add_argument('-m', action='store_true', dest='mediainfo', help='create mediainfo')
parser.add_argument('-n', action='store', dest="count", default=10,
help="number of screenshots, default 10", type=int)
parser.add_argument('-i', action='store', dest='input', help="input file", required=True)
args = parser.parse_args()
logging.info(' '.join(f'{k}={v}' for k, v in vars(args).items()))
class Head:
"""
Creates mediainfo, screenshots and sample from file
"""
def __init__(self):
procs = []
bname: str
bname = moviepy.editor.os.path.basename(Args.args.input)
fname = moviepy.editor.os.path.splitext(bname)[0]
exname = moviepy.editor.os.path.splitext(bname)[1]
fold = str(pathlib.Path.home()) + "/samples/" + fname
logging.info("Filename is %s" % bname)
if os.path.isdir(fold):
logging.info("Directory %s is exist" % fold)
else:
try:
moviepy.editor.os.makedirs(fold)
except OSError:
logging.error("Creation of the directory %s failed" % fold)
else:
logging.info("Successfully created the directory %s " % fold)
logging.info("Files will be located at %s" % fold)
media_info = MediaInfo.parse(Args.args.input, output="", parse_speed=2)
mi = MediaInfo.parse(Args.args.input)
mfile = fold + "/mediainfo.txt"
duration = mi.tracks[0]
max_time = duration.duration / 1000
if Args.args.sample:
thread = threading.Thread(name="sample",
target=Head.sample, args=(fold, exname, max_time,))
procs.append(thread)
thread.start()
time.sleep(1)
if Args.args.screens:
max_time = round(max_time)
logging.info("Rounded duration %ss" % max_time)
logging.info("Creating %s screenshots" % Args.args.count)
mintimescr = round(max_time * 0.05)
maxtimescr = round(max_time * 0.95)
for i in range(Args.args.count):
thread = threading.Thread(name="screens",
target=Head.screens, args=(fold, mintimescr, maxtimescr, i,))
procs.append(thread)
thread.start()
time.sleep(1)
if Args.args.mediainfo:
thread = threading.Thread(name="mediainfo",
target=Head.info, args=(mfile, media_info,))
procs.append(thread)
thread.start()
time.sleep(1)
for proc in procs:
proc.join()
def sample(fold, exname, max_time):
"""
Create sample with duration 2m if file longer then 6m
"""
sam = fold + "/sample" + exname
if max_time <= 360:
logging.info(f"Creating Sample with duration {(max_time * 2 / 3) - (max_time / 3)}s")
ffmpeg_extract_subclip(Args.args.input, max_time / 3, max_time * 2 / 3, targetname=sam)
else:
logging.info(f"Creating Sample with duration {(max_time / 2 + 60) - (max_time / 2 - 60)}s")
ffmpeg_extract_subclip(Args.args.input, max_time / 2 - 60, max_time / 2 + 60, targetname=sam)
def info(file, media_info):
logging.info(f"Creating MediaInfo at {file}")
f = open(file, "w")
f.write(str(media_info))
f.close()
logging.info("Created MediaInfo")
def screens(fold, mintimescr, maxtimescr, num_screen):
sec = random.randint(mintimescr, maxtimescr)
imgname = fold + "/" + str(sec) + ".png"
logging.info(f"{num_screen + 1}st screen time {sec}s\tthread is {threading.get_ident()}")
screen_create = moviepy.editor.VideoFileClip(Args.args.input)
screen_create.save_frame(imgname, t=sec)
screen_create.audio.reader.close_proc()
screen_create.reader.close()
if __name__ == '__main__':
Head()