ogeti siva satyanarayana commited on
Commit
e079ab1
·
1 Parent(s): 3155cc9

Create video_enhancer.py

Browse files
Files changed (1) hide show
  1. video_enhancer.py +47 -0
video_enhancer.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # video_enhancer.py
2
+
3
+ from moviepy.editor import TextClip, CompositeVideoClip, AudioFileClip, VideoFileClip
4
+ from moviepy.video.tools.subtitles import SubtitlesClip
5
+ from gtts import gTTS
6
+ from datetime import timedelta
7
+ import os
8
+
9
+ # Constants
10
+ FONT = "Arial"
11
+ FONT_SIZE = 36
12
+ FONT_COLOR = "white"
13
+ BG_COLOR = "black"
14
+ BGM_PATH = "default_bgm.mp3" # bundled with your repo
15
+
16
+ def generate_srt_from_text(text, output_srt_path, duration_per_line=4):
17
+ """Generate .srt subtitles file from multi-line text."""
18
+ lines = text.strip().split("\n")
19
+ with open(output_srt_path, "w", encoding="utf-8") as f:
20
+ for i, line in enumerate(lines):
21
+ start_time = timedelta(seconds=i * duration_per_line)
22
+ end_time = timedelta(seconds=(i + 1) * duration_per_line)
23
+ f.write(f"{i+1}\n")
24
+ f.write(f"{str(start_time)[:-3].replace('.', ',')} --> {str(end_time)[:-3].replace('.', ',')}\n")
25
+ f.write(f"{line}\n\n")
26
+
27
+ def create_subtitle_clips_from_srt(srt_path):
28
+ """Convert .srt to a SubtitlesClip usable in moviepy."""
29
+ generator = lambda txt: TextClip(txt, font=FONT, fontsize=FONT_SIZE, color=FONT_COLOR, bg_color=BG_COLOR)
30
+ return SubtitlesClip(srt_path, generator)
31
+
32
+ def enhance_video_with_subtitles_and_bgm(input_video_path, output_video_path, srt_path, bgm_path=BGM_PATH):
33
+ video = VideoFileClip(input_video_path)
34
+ subs = create_subtitle_clips_from_srt(srt_path)
35
+ video = CompositeVideoClip([video, subs.set_position(('center','bottom'))])
36
+
37
+ if os.path.exists(bgm_path):
38
+ bgm = AudioFileClip(bgm_path).volumex(0.2)
39
+ bgm = bgm.set_duration(video.duration)
40
+ video = video.set_audio(bgm)
41
+
42
+ video.write_videofile(output_video_path, codec="libx264", audio_codec="aac")
43
+
44
+ # Example usage:
45
+ # text = """Hello there\nThis is an AI-generated video\nThank you for watching"""
46
+ # generate_srt_from_text(text, "output.srt")
47
+ # enhance_video_with_subtitles_and_bgm("input.mp4", "final_output.mp4", "output.srt")