TDN-M commited on
Commit
cbfa1a4
·
verified ·
1 Parent(s): ef7948b

Delete video_processing.py

Browse files
Files changed (1) hide show
  1. video_processing.py +0 -191
video_processing.py DELETED
@@ -1,191 +0,0 @@
1
- import os
2
- import random
3
- import glob
4
- import shutil
5
- import tempfile
6
- from concurrent.futures import ThreadPoolExecutor
7
- from moviepy.editor import (
8
- AudioFileClip,
9
- CompositeVideoClip,
10
- ImageClip,
11
- VideoFileClip,
12
- concatenate_videoclips,
13
- vfx,
14
- )
15
- from moviepy.video.tools.subtitles import SubtitlesClip
16
- import tqdm
17
-
18
- from sentence_transformers import SentenceTransformer, util
19
-
20
- # Khởi tạo model sentence transformer
21
- model = SentenceTransformer('all-MiniLM-L6-v2')
22
-
23
- # Tăng số lượng ảnh lên 30
24
- NUM_IMAGES = 30
25
-
26
- def add_transitions(clips, transition_duration=1):
27
- """
28
- Thêm hiệu ứng chuyển cảnh giữa các clip.
29
- """
30
- final_clips = []
31
- for i, clip in enumerate(clips):
32
- start_time = i * (clip.duration - transition_duration)
33
- end_time = start_time + clip.duration
34
-
35
- if i > 0:
36
- # Tạo hiệu ứng fade in
37
- fade_in = clip.fx(vfx.fadeout, duration=transition_duration)
38
- fade_in = fade_in.set_start(start_time)
39
- final_clips.append(fade_in)
40
-
41
- if i < len(clips) - 1:
42
- # Tạo hiệu ứng fade out
43
- fade_out = clip.fx(vfx.fadein, duration=transition_duration)
44
- fade_out = fade_out.set_end(end_time)
45
- final_clips.append(fade_out)
46
-
47
- # Thêm clip gốc
48
- final_clips.append(clip.set_start(start_time).set_end(end_time))
49
-
50
- return CompositeVideoClip(final_clips)
51
-
52
- def create_video(sentences, audio_files, video_files, output_path="output_video.mp4"):
53
- """
54
- Tạo video từ các câu, file âm thanh và file video.
55
- """
56
- clips = []
57
- for sentence, audio_path, video_path in tqdm.tqdm(zip(sentences, audio_files, video_files), desc="Tạo video"):
58
- audio = AudioFileClip(audio_path)
59
- video = VideoFileClip(video_path).set_duration(audio.duration)
60
- video = video.set_audio(audio)
61
- clips.append(video)
62
-
63
- final_video = concatenate_videoclips(clips, method="compose")
64
- final_video.write_videofile(output_path, fps=24)
65
- print(f"Đã tạo video: {output_path}")
66
- return output_path
67
-
68
- def process_images_parallel(image_patch, clip_duration):
69
- """
70
- Xử lý song song các hình ảnh.
71
- """
72
- with ThreadPoolExecutor() as executor:
73
- futures = []
74
- for content, image_path in image_patch:
75
- if image_path:
76
- future = executor.submit(ImageClip, image_path)
77
- futures.append((future, clip_duration))
78
-
79
- clips = []
80
- for future, duration in futures:
81
- clip = future.result().set_duration(duration)
82
- clips.append(clip)
83
-
84
- return clips
85
-
86
- # Định nghĩa hàm extract_key_contents
87
- def extract_key_contents(script: str) -> list[str]:
88
- """
89
- Hàm này dùng để trích xuất các ý chính từ một đoạn script.
90
-
91
- Tham số:
92
- - script (str): Đoạn văn bản cần xử lý để trích xuất các ý chính.
93
-
94
- Trả về:
95
- - list[str]: Danh sách các câu được tách ra từ đoạn script.
96
-
97
- Logic xử lý:
98
- - Đầu tiên, đoạn script được tách thành các câu dựa trên dấu chấm ('.').
99
- - Mỗi câu được xem như một ý chính và được thêm vào danh sách kết quả.
100
- """
101
- # Kiểm tra nếu script là chuỗi rỗng
102
- if not script:
103
- return []
104
-
105
- # Tách đoạn script thành các câu dựa trên dấu chấm
106
- sentences = script.split('.')
107
-
108
- # Loại bỏ các khoảng trắng thừa và các câu rỗng
109
- sentences = [sentence.strip() for sentence in sentences if sentence.strip()]
110
-
111
- # Trả về danh sách các câu
112
- return sentences
113
-
114
-
115
- def process_script_for_video(script, dataset_path, use_dataset):
116
- """
117
- Xử lý script để tạo video.
118
- """
119
- sentences = extract_key_contents(script)
120
- return sentences
121
-
122
- def create_video_func(script, audio_path, dataset_path, use_dataset):
123
- """
124
- Hàm chính để tạo video.
125
- """
126
- try:
127
- sentences = process_script_for_video(script, dataset_path, use_dataset)
128
-
129
- # Tạo thư mục tạm thời để lưu các file âm thanh tách biệt
130
- temp_dir = tempfile.mkdtemp()
131
-
132
- # Tách file âm thanh thành các đoạn nhỏ
133
- audio_clips = split_audio(audio_path, len(sentences), temp_dir)
134
-
135
- # Lấy đường dẫn của các video từ dataset
136
- video_files = glob.glob(os.path.join(dataset_path, "*.mp4")) if use_dataset else []
137
-
138
- # Đảm bảo số lượng câu, âm thanh và video là bằng nhau
139
- min_length = min(len(sentences), len(audio_clips), len(video_files))
140
- sentences = sentences[:min_length]
141
- audio_clips = audio_clips[:min_length]
142
- video_files = video_files[:min_length]
143
-
144
- output_path = "output_video.mp4"
145
- create_video(sentences, audio_clips, video_files, output_path)
146
-
147
- return output_path
148
- except Exception as e:
149
- print(f"Lỗi khi tạo video: {e}")
150
- return None
151
- finally:
152
- # Xóa thư mục tạm thời
153
- shutil.rmtree(temp_dir)
154
-
155
- def split_audio(audio_path, num_segments, output_dir):
156
- """
157
- Chia file âm thanh thành các đoạn nhỏ.
158
- """
159
- audio = AudioFileClip(audio_path)
160
- duration = audio.duration
161
- segment_duration = duration / num_segments
162
-
163
- audio_clips = []
164
- for i in range(num_segments):
165
- start = i * segment_duration
166
- end = (i + 1) * segment_duration
167
- segment = audio.subclip(start, end)
168
- output_path = os.path.join(output_dir, f"segment_{i}.mp3")
169
- segment.write_audiofile(output_path)
170
- audio_clips.append(output_path)
171
-
172
- return audio_clips
173
-
174
- def find_matching_image(prompt, dataset_path, threshold=0.5):
175
- """
176
- Tìm kiếm hình ảnh phù hợp với prompt trong dataset.
177
- """
178
- prompt_embedding = model.encode(prompt, convert_to_tensor=True)
179
- best_match = None
180
- best_score = -1
181
-
182
- for filename in os.listdir(dataset_path):
183
- if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
184
- image_path = os.path.join(dataset_path, filename)
185
- image_name = os.path.splitext(filename)[0].replace('_', ' ')
186
- image_embedding = model.encode(image_name, convert_to_tensor=True)
187
- cosine_score = util.pytorch_cos_sim(prompt_embedding, image_embedding).item()
188
- if cosine_score > best_score and cosine_score >= threshold:
189
- best_score = cosine_score
190
- best_match = image_path
191
- return best_match