Hieucyber2208 commited on
Commit
2433c72
·
verified ·
1 Parent(s): cc85380

Update src/text_to_video.py

Browse files
Files changed (1) hide show
  1. src/text_to_video.py +112 -31
src/text_to_video.py CHANGED
@@ -58,49 +58,130 @@ def create_srt_from_time_and_text(duration_time, text_folder, output_srt):
58
  with open(output_srt, 'w', encoding='utf-8') as f:
59
  f.write(subtitle)
60
  def concatenate_audio_files(audio_folder, output_audio_path):
61
- # Lọc tất cả các file âm thanh .mp3 trong thư mục
62
- audio_clips = []
63
 
64
- for file in sorted(os.listdir(audio_folder)):
65
- if file.endswith('.mp3'):
66
- audio_path = os.path.join(audio_folder, file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  audio_clip = AudioFileClip(audio_path)
68
  audio_clips.append(audio_clip)
69
-
70
- # Ghép tất cả các audio clip lại với nhau
71
- final_audio = concatenate_audioclips(audio_clips)
72
-
73
- # Lưu kết quả vào file output
74
- final_audio.write_audiofile(output_audio_path, codec = 'libmp3lame')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- print(f"File audio đã được lưu tại: {output_audio_path}")
77
  def create_video_from_images(image_folder, audio_path, output_video_path):
78
- # Đọc file âm thanh để lấy thời lượng
79
- audio = AudioFileClip(audio_path)
80
- total_duration = audio.duration # Tổng thời lượng video bằng thời lượng audio
 
 
 
 
 
 
 
81
 
82
- # Đọc tất cả các file ảnh trong thư mục và sắp xếp theo tên
83
- image_files = [file for file in sorted(os.listdir(image_folder)) if file.endswith(".png")]
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
- if not image_files:
86
- raise ValueError("Không tìm thấy ảnh nào trong thư mục!")
 
87
 
88
- # Tính thời lượng hiển thị cho mỗi ảnh
89
- duration_per_image = total_duration / len(image_files)
 
90
 
91
- # Tạo danh sách các clip ảnh
92
- clips = [ImageClip(f"{img}").with_duration(duration_per_image).resized(width=1280) for img in image_files]
 
93
 
94
- # Ghép các clip ảnh l���i với nhau
95
- final_video = concatenate_videoclips(clips, method="chain")
96
-
97
- # Gán âm thanh vào video
98
- final_video .audio = audio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
- # Xuất video
101
- final_video.write_videofile(output_video_path, codec="libx264", audio_codec="aac", fps=30)
102
 
103
- print(f"Video đã được lưu tại: {output_video_path}")
 
104
  def wrap_text(text, max_width):
105
  """
106
  Tự động xuống dòng để vừa với chiều rộng max_width.
 
58
  with open(output_srt, 'w', encoding='utf-8') as f:
59
  f.write(subtitle)
60
  def concatenate_audio_files(audio_folder, output_audio_path):
61
+ """
62
+ Concatenate all .mp3 files in a folder into a single audio file.
63
 
64
+ Parameters:
65
+ audio_folder (str): The folder containing audio files.
66
+ output_audio_path (str): The path to save the concatenated audio.
67
+ """
68
+ print("\n[DEBUG] Function: concatenate_audio_files")
69
+ print(f"Received parameters -> audio_folder: {audio_folder}, output_audio_path: {output_audio_path}")
70
+
71
+ # Validate if the folder exists
72
+ if not os.path.isdir(audio_folder):
73
+ print(f"[ERROR] Directory does not exist: {audio_folder}")
74
+ return
75
+
76
+ audio_clips = []
77
+ audio_files = sorted([f for f in os.listdir(audio_folder) if f.endswith('.mp3')])
78
+
79
+ print(f"[DEBUG] Found audio files: {audio_files}")
80
+
81
+ if not audio_files:
82
+ print("[ERROR] No .mp3 files found in the directory!")
83
+ return
84
+
85
+ # Load audio clips
86
+ for file in audio_files:
87
+ audio_path = os.path.join(audio_folder, file)
88
+ try:
89
+ print(f"[DEBUG] Loading audio file: {audio_path}")
90
  audio_clip = AudioFileClip(audio_path)
91
  audio_clips.append(audio_clip)
92
+ except Exception as e:
93
+ print(f"[ERROR] Failed to load {file}: {e}")
94
+
95
+ # Ensure there are clips to concatenate
96
+ if not audio_clips:
97
+ print("[ERROR] No valid audio clips to concatenate!")
98
+ return
99
+
100
+ try:
101
+ print("[DEBUG] Concatenating audio clips...")
102
+ final_audio = concatenate_audioclips(audio_clips)
103
+
104
+ # Save the final concatenated audio
105
+ print(f"[DEBUG] Saving final audio to: {output_audio_path}")
106
+ final_audio.write_audiofile(output_audio_path, codec='libmp3lame')
107
+
108
+ print(f"✅ File audio has been saved at: {output_audio_path}")
109
+
110
+ except Exception as e:
111
+ print(f"[ERROR] Failed to concatenate and save audio: {e}")
112
+ import os
113
+ from moviepy.editor import ImageClip, AudioFileClip, concatenate_videoclips
114
 
 
115
  def create_video_from_images(image_folder, audio_path, output_video_path):
116
+ """
117
+ Create a video from images and an audio file.
118
+
119
+ Parameters:
120
+ image_folder (str): Folder containing images.
121
+ audio_path (str): Path to the background audio file.
122
+ output_video_path (str): Path to save the final video.
123
+ """
124
+ print("\n[DEBUG] Function: create_video_from_images")
125
+ print(f"Received parameters -> image_folder: {image_folder}, audio_path: {audio_path}, output_video_path: {output_video_path}")
126
 
127
+ # Validate input folder and file existence
128
+ if not os.path.isdir(image_folder):
129
+ print(f"[ERROR] Image folder does not exist: {image_folder}")
130
+ return
131
+ if not os.path.isfile(audio_path):
132
+ print(f"[ERROR] Audio file does not exist: {audio_path}")
133
+ return
134
+
135
+ try:
136
+ # Load audio file
137
+ print(f"[DEBUG] Loading audio file: {audio_path}")
138
+ audio = AudioFileClip(audio_path)
139
+ total_duration = audio.duration
140
+ print(f"[DEBUG] Audio duration: {total_duration:.2f} seconds")
141
 
142
+ # Get image files
143
+ image_files = sorted([file for file in os.listdir(image_folder) if file.endswith(".png")])
144
+ print(f"[DEBUG] Found image files: {image_files}")
145
 
146
+ if not image_files:
147
+ print("[ERROR] No images found in the directory!")
148
+ return
149
 
150
+ # Calculate duration per image
151
+ duration_per_image = total_duration / len(image_files)
152
+ print(f"[DEBUG] Duration per image: {duration_per_image:.2f} seconds")
153
 
154
+ # Create image clips
155
+ clips = []
156
+ for img in image_files:
157
+ img_path = os.path.join(image_folder, img)
158
+ try:
159
+ print(f"[DEBUG] Loading image: {img_path}")
160
+ clip = ImageClip(img_path).with_duration(duration_per_image).resize(width=1280)
161
+ clips.append(clip)
162
+ except Exception as e:
163
+ print(f"[ERROR] Failed to load image {img}: {e}")
164
+
165
+ if not clips:
166
+ print("[ERROR] No valid image clips to create video!")
167
+ return
168
+
169
+ # Concatenate image clips
170
+ print("[DEBUG] Concatenating image clips...")
171
+ final_video = concatenate_videoclips(clips, method="chain")
172
+
173
+ # Add audio to video
174
+ print("[DEBUG] Attaching audio to video...")
175
+ final_video.audio = audio
176
+
177
+ # Export video
178
+ print(f"[DEBUG] Saving final video to: {output_video_path}")
179
+ final_video.write_videofile(output_video_path, codec="libx264", audio_codec="aac", fps=30)
180
 
181
+ print(f"✅ Video has been saved at: {output_video_path}")
 
182
 
183
+ except Exception as e:
184
+ print(f"[ERROR] An error occurred: {e}")
185
  def wrap_text(text, max_width):
186
  """
187
  Tự động xuống dòng để vừa với chiều rộng max_width.