Spaces:
Sleeping
Sleeping
File size: 7,277 Bytes
e62cec6 927e529 e62cec6 552f457 e62cec6 552f457 e62cec6 8773ee1 e62cec6 5997829 62cb98a e62cec6 62cb98a e62cec6 62cb98a 2433c72 62cb98a e62cec6 2433c72 62cb98a e62cec6 62cb98a e62cec6 62cb98a 8f9dd80 26d40d8 8f9dd80 e62cec6 8f9dd80 e62cec6 8f9dd80 e62cec6 8f9dd80 e62cec6 f87ca8b 8f9dd80 f87ca8b 8f9dd80 f902400 e62cec6 8f9dd80 927e529 e62cec6 8773ee1 3b616a4 8531f55 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
from moviepy.video.io.VideoFileClip import VideoFileClip, AudioFileClip
from moviepy.video.VideoClip import TextClip, ImageClip
from moviepy.video.compositing.CompositeVideoClip import concatenate_videoclips, CompositeVideoClip
from moviepy.audio.AudioClip import concatenate_audioclips
import os
from itertools import accumulate
import pysrt
import subprocess
def format_time(seconds):
"""Chuyển đổi thời gian (giây) thành định dạng SRT hh:mm:ss,ms"""
mins, sec = divmod(seconds, 60)
hours, mins = divmod(mins, 60)
return f"{int(hours):02}:{int(mins):02}:{int(sec):02},{int((sec % 1) * 1000):03}"
def get_audio_duration(audio_path):
# Lọc các file có đuôi .mp3
audio_paths = os.listdir(audio_path)
audio_list = [file for file in audio_paths if file.endswith(".mp3")]
# Khởi tạo danh sách audio duration
duration_list = []
for audio_path in audio_list:
# Mở file âm thanh và lấy thời gian
with AudioFileClip(f"{audio_path}") as audio:
duration_list.append(audio.duration)
# Tính tổng tích lũy thời gian
duration_list = [format_time(time) for time in list(accumulate(duration_list))]
return [format_time(0.0)] + duration_list
def create_srt_from_time_and_text(duration_time, text_folder, output_srt):
subtitle = ""
subtitle_index = 1
text_list = sorted([file for file in os.listdir(text_folder) if file.endswith('.txt') and file != "text.txt" and file != "requirements.txt"])
print(f"Accessing duration_time list: {len(text_list)} elements")
# Duyệt qua các mốc thời gian và file text
for i in range(len(duration_time) - 1):
print(f"Accessing text_list at index {i}, length of text_list: {len(text_list)}")
start_time = duration_time[i]
end_time = duration_time[i + 1]
# Lấy tên file text tương ứng
text_file = text_list[i]
text_path = os.path.join(text_folder, text_file)
if os.path.exists(text_path):
with open(text_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
# Thêm phần subtitle vào chuỗi kết quả
subtitle += f"{subtitle_index}\n{start_time} --> {end_time}\n{text}\n\n"
subtitle_index += 1
else:
print(f"File {text_file} không tồn tại!")
# Lưu vào file SRT
with open(output_srt, 'w', encoding='utf-8') as f:
f.write(subtitle)
def concatenate_audio_files(audio_folder, output_audio_path):
# Lọc tất cả các file âm thanh .mp3 trong thư mục
audio_clips = []
for file in sorted(os.listdir(audio_folder)):
if file.endswith('.mp3'):
audio_path = os.path.join(audio_folder, file)
audio_clip = AudioFileClip(audio_path)
audio_clips.append(audio_clip)
# Ghép tất cả các audio clip lại với nhau
final_audio = concatenate_audioclips(audio_clips)
# Lưu kết quả vào file output
final_audio.write_audiofile(output_audio_path, codec = 'libmp3lame')
print(f"File audio đã được lưu tại: {output_audio_path}")
def create_video_from_images(image_folder, audio_path, output_video_path):
# Đọc file âm thanh để lấy thời lượng
audio = AudioFileClip(audio_path)
total_duration = audio.duration # Tổng thời lượng video bằng thời lượng audio
# Đọc tất cả các file ảnh trong thư mục và sắp xếp theo tên
image_files = [file for file in sorted(os.listdir(image_folder)) if file.endswith(".png")]
if not image_files:
raise ValueError("Không tìm thấy ảnh nào trong thư mục!")
# Tính thời lượng hiển thị cho mỗi ảnh
duration_per_image = total_duration / len(image_files)
# Tạo danh sách các clip ảnh
clips = [ImageClip(f"{img}").with_duration(duration_per_image).resized(width=1280) for img in image_files]
# Ghép các clip ảnh lại với nhau
final_video = concatenate_videoclips(clips, method="chain")
# Gán âm thanh vào video
final_video .audio = audio
# Xuất video
final_video.write_videofile(output_video_path, codec="libx264", audio_codec="aac", fps=1)
print(f"Video đã được lưu tại: {output_video_path}")
def wrap_text(text, max_width):
"""
Tự động xuống dòng để vừa với chiều rộng max_width.
"""
import textwrap
return "\n".join(textwrap.wrap(text, width=max_width))
def add_subtitles_to_video(video_path, subtitle_path, output_video_path):
"""
Thêm phụ đề từ file .srt trực tiếp vào video.
:param video_path: Đường dẫn video gốc
:param subtitle_path: Đường dẫn file .srt
:param output_video_path: Đường dẫn lưu video đầu ra
"""
# Đọc file video
video = VideoFileClip(video_path)
# Đọc file .srt
subs = pysrt.open(subtitle_path)
subtitle_clips = [] # Danh sách các đoạn phụ đề
# Xử lý từng dòng phụ đề
for sub in subs:
# Chuyển thời gian thành giây
start_time = sub.start.ordinal / 1000 # Chuyển từ milliseconds sang giây
end_time = sub.end.ordinal / 1000
font = "BeVietnamPro-Light.ttf"
# Tạo clip phụ đề
txt_clip = TextClip(font=font, text=wrap_text(sub.text, max_width=85), font_size=30, stroke_color="black", stroke_width=3, color="#fff")
# Đặt vị trí hiển thị (giữa phía dưới video)
txt_clip = txt_clip.with_position(('center', 'bottom')).with_duration(end_time - start_time).with_start(start_time)
subtitle_clips.append(txt_clip)
# Ghép phụ đề vào video
final_video = CompositeVideoClip([video] + subtitle_clips)
# Xuất video với phụ đề
final_video.write_videofile(output_video_path, fps=1, codec='libx264', threads=8)
print(f"Video với phụ đề đã được lưu tại: {output_video_path}")
def convert_audio_format(video_input, video_output):
"""Chuyển đổi định dạng âm thanh của video sang AAC."""
if not os.path.exists(video_input):
raise FileNotFoundError(f"File '{video_input}' không tồn tại!")
command = [
"ffmpeg", "-i", video_input,
"-c:v", "copy", "-c:a", "aac", "-b:a", "192k",
"-y", # Ghi đè nếu file output đã tồn tại
video_output
]
try:
subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"✅ Chuyển đổi thành công: {video_output}")
except subprocess.CalledProcessError as e:
print(f"❌ Lỗi khi chuyển đổi video: {e.stderr.decode()}")
def text_to_video():
duration_time = get_audio_duration("./")
create_srt_from_time_and_text(duration_time, './', 'subtitle.srt')
concatenate_audio_files("./","final_audio.mp3")
create_video_from_images("./","final_audio.mp3","output.mp4")
add_subtitles_to_video("output.mp4", "subtitle.srt", "final_output.mp4")
convert_audio_format("final_output.mp4","final_fixed_output.mp4") |