Hieucyber2208 commited on
Commit
62cb98a
·
verified ·
1 Parent(s): 8adf349

Update src/text_to_video.py

Browse files
Files changed (1) hide show
  1. src/text_to_video.py +33 -111
src/text_to_video.py CHANGED
@@ -33,10 +33,10 @@ def create_srt_from_time_and_text(duration_time, text_folder, output_srt):
33
  subtitle = ""
34
  subtitle_index = 1
35
  text_list = sorted([file for file in os.listdir(text_folder) if file.endswith('.txt') and file != "text.txt" and file != "requirements.txt"])
36
- print(f"Accessing duration_time list:{duration_time} with lenght: {len(duration_time)}")
37
  # Duyệt qua các mốc thời gian và file text
38
  for i in range(len(duration_time) - 1):
39
- print(f"Accessing text_list list: {text_list} with length: {len(text_list)}")
40
  start_time = duration_time[i]
41
  end_time = duration_time[i + 1]
42
 
@@ -58,127 +58,49 @@ 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
- """
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
- def create_video_from_images(image_folder, audio_path, output_video_path):
113
- """
114
- Create a video from images and an audio file.
115
 
116
- Parameters:
117
- image_folder (str): Folder containing images.
118
- audio_path (str): Path to the background audio file.
119
- output_video_path (str): Path to save the final video.
120
- """
121
- print("\n[DEBUG] Function: create_video_from_images")
122
- print(f"Received parameters -> image_folder: {image_folder}, audio_path: {audio_path}, output_video_path: {output_video_path}")
123
-
124
- # Validate input folder and file existence
125
- if not os.path.isdir(image_folder):
126
- print(f"[ERROR] Image folder does not exist: {image_folder}")
127
- return
128
- if not os.path.isfile(audio_path):
129
- print(f"[ERROR] Audio file does not exist: {audio_path}")
130
- return
131
-
132
- try:
133
- # Load audio file
134
- print(f"[DEBUG] Loading audio file: {audio_path}")
135
- audio = AudioFileClip(audio_path)
136
- total_duration = audio.duration
137
- print(f"[DEBUG] Audio duration: {total_duration:.2f} seconds")
138
 
139
- # Get image files
140
- image_files = sorted([file for file in os.listdir(image_folder) if file.endswith(".png")])
141
- print(f"[DEBUG] Found image files: {image_files}")
142
-
143
- if not image_files:
144
- print("[ERROR] No images found in the directory!")
145
- return
146
-
147
- # Calculate duration per image
148
- duration_per_image = total_duration / len(image_files)
149
- print(f"[DEBUG] Duration per image: {duration_per_image:.2f} seconds")
150
 
151
- # Create image clips
152
- clips = []
153
- for img in image_files:
154
- img_path = os.path.join(image_folder, img)
155
- try:
156
- print(f"[DEBUG] Loading image: {img_path}")
157
- clip = ImageClip(img_path).with_duration(duration_per_image).resize(width=1280)
158
- clips.append(clip)
159
- except Exception as e:
160
- print(f"[ERROR] Failed to load image {img}: {e}")
161
 
162
- if not clips:
163
- print("[ERROR] No valid image clips to create video!")
164
- return
 
 
165
 
166
- # Concatenate image clips
167
- print("[DEBUG] Concatenating image clips...")
168
- final_video = concatenate_videoclips(clips, method="chain")
169
 
170
- # Add audio to video
171
- print("[DEBUG] Attaching audio to video...")
172
- final_video.audio = audio
173
 
174
- # Export video
175
- print(f"[DEBUG] Saving final video to: {output_video_path}")
176
- final_video.write_videofile(output_video_path, codec="libx264", audio_codec="aac", fps=30)
 
 
177
 
178
- print(f"✅ Video has been saved at: {output_video_path}")
 
179
 
180
- except Exception as e:
181
- print(f"[ERROR] An error occurred: {e}")
182
  def wrap_text(text, max_width):
183
  """
184
  Tự động xuống dòng để vừa với chiều rộng max_width.
 
33
  subtitle = ""
34
  subtitle_index = 1
35
  text_list = sorted([file for file in os.listdir(text_folder) if file.endswith('.txt') and file != "text.txt" and file != "requirements.txt"])
36
+ print(f"Accessing duration_time list: {len(text_list)} elements")
37
  # Duyệt qua các mốc thời gian và file text
38
  for i in range(len(duration_time) - 1):
39
+ print(f"Accessing text_list at index {i}, length of text_list: {len(text_list)}")
40
  start_time = duration_time[i]
41
  end_time = duration_time[i + 1]
42
 
 
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.