Skip to content

Instantly share code, notes, and snippets.

@Muratam
Last active December 14, 2016 11:38
Show Gist options
  • Save Muratam/c404aee2c4fe9e061ef9be3681ef1179 to your computer and use it in GitHub Desktop.
Save Muratam/c404aee2c4fe9e061ef9be3681ef1179 to your computer and use it in GitHub Desktop.
analyze_mp4.py
def analyze_mp4(filename, out_filename, comments, ok_time=3100):
"""
filename : 元となる動画ファイル名
out_filename : 生成した動画の保存ファイル名
comments : get_comments 関数で作成したコメント配列
ok_time : 3100 なら 31 * 100 で 開始31秒
"""
comments.sort(key=lambda x: x[1])
max_time = ok_time / 100.0
video = VideoFileClip(filename).subclip(0, max_time)
rangeses = [[], [], []]
def make_textclip(text, t, mail):
def check_dict(mail, dic, default):
for k, v in dic.items():
if k in mail:
return v
return default
# dicts
sizes = {"small": 15, "medium": 24, "big": 36}
colors = {
"white": "#FFFFFF", "red": "#FF0000", "pink": "#FF8080", "orange": "#FFC000",
"yellow": "#FFFF00", "green": "#00FF00", "cyan": "#00FFFF", "blue": "#0000FF",
"purple": "#C000FF", "black": "#000000",
"white2": "#CCCC99", "red2": "#CC0033", "pink2": "#FF33CC", "orange2": "#FF6600",
"yellow2": "#999900", "green2": "#00CC66", "cyan2": "#00CCCC", "blue2": "#3399FF",
"purple2": "#6633CC", "black2": "#666666",
}
poses = {"naka": 0, "ue": 1, "shita": 2}
# set parameter
color = check_dict(mail, colors, "#FFFFFF")
size = check_dict(mail, sizes, 24)
if size * len(text) > video.w:
size = int(video.w / len(text))
pos = check_dict(mail, poses, 0)
is_shita = pos == 2
t = t - 1 if pos == 0 else t
endtime = min(4, max_time - t)
textclip = (TextClip(text, font='./hiragino.ttc', fontsize=size,
color=color,
stroke_color="#000000",
stroke_width=0.5,
temptxt=text,
tempfilename="aatxt.png"
)
.set_start(t)
.subclip(0, endtime))
# search y
m_begin = max(0, t)
m_end = min(t + endtime, max_time)
margin = 4
y_max = video.h - size - margin
y = 0 if not is_shita else y_max
for r_begin, r_end, t_begin, t_end in rangeses[pos]:
if t_begin <= m_end and m_begin <= t_end:
y = r_end if not is_shita else r_begin - size - margin * 2
y += margin
if y > y_max or y < 0:
y = random.randrange(0, y_max)
y = max(0, min(y, y_max))
m_range = [y, y + size, m_begin, m_end]
rangeses[pos].append(m_range)
# set position
if pos == 0:
begin_x = video.w
end_x = -size * len(text)
textclip = textclip.set_pos(
lambda t: (begin_x + (end_x - begin_x) * (t / endtime), y))
else:
textclip = textclip.set_pos(("center", y))
return textclip
txt_clips = []
for text, t, date, mail in comments:
clip = make_textclip(text, t / 100.0, mail)
txt_clips.append(clip)
result = CompositeVideoClip([video] + txt_clips)
result.write_gif(out_filename + ".gif", fps=30)
result.save_frame(out_filename + ".png", 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment