yt-clipper-new / clipper.py
yasvanthkumar's picture
Create clipper.py
77cac6a verified
raw
history blame
2.18 kB
import os
import yt_dlp
from moviepy.editor import VideoFileClip, vfx
import tempfile
from pydub import AudioSegment
import numpy as np
def download_youtube(url, out_dir="downloads"):
os.makedirs(out_dir, exist_ok=True)
ydl_opts = {
"format": "bestvideo+bestaudio/best",
"outtmpl": os.path.join(out_dir, "%(id)s.%(ext)s"),
"merge_output_format": "mp4",
"quiet": True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
filename = ydl.prepare_filename(info)
if not filename.endswith(".mp4"):
filename = filename.rsplit(".", 1)[0] + ".mp4"
return filename
def detect_highlights_simple(video_path):
clip = VideoFileClip(video_path)
tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
tmp.close()
clip.audio.write_audiofile(tmp.name, logger=None)
audio = AudioSegment.from_wav(tmp.name)
os.unlink(tmp.name)
window = 1000
energies = [audio[i:i+window].rms for i in range(0, len(audio), window)]
energies = np.array(energies)
best = energies.argsort()[-3:][::-1]
clips = []
for idx in best:
start = int(idx)
end = start + 10
if end > clip.duration:
end = int(clip.duration)
clips.append((start, end))
clip.close()
return clips
def make_vertical_clip(video_path, start, end):
clip = VideoFileClip(video_path).subclip(start, end)
out_path = f"outputs/clip_{start}.mp4"
w, h = clip.size
target_w, target_h = 1080, 1920
scale = max(target_h / h, target_w / w)
clip = clip.resize(scale)
clip = clip.crop(x_center=clip.w/2, y_center=clip.h/2, width=target_w, height=target_h)
clip.write_videofile(out_path, fps=24, audio_codec="aac", logger=None)
clip.close()
return out_path
def process_youtube_link(url):
video = download_youtube(url)
return process_uploaded_file(video)
def process_uploaded_file(video_path):
highlights = detect_highlights_simple(video_path)
final = []
for start, end in highlights:
final.append(make_vertical_clip(video_path, start, end))
return final