File size: 13,709 Bytes
e62cec6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [],
   "source": [
    "from moviepy.video.io.VideoFileClip import VideoFileClip, AudioFileClip\n",
    "from moviepy.video.VideoClip import TextClip, ImageClip\n",
    "from moviepy.video.compositing.CompositeVideoClip import concatenate_videoclips, CompositeVideoClip\n",
    "from moviepy.audio.AudioClip import concatenate_audioclips\n",
    "from moviepy.video.tools.subtitles import SubtitlesClip\n",
    "from moviepy.video.VideoClip import ColorClip\n",
    "import os\n",
    "from tqdm import tqdm\n",
    "from itertools import accumulate\n",
    "import pysrt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "def format_time(seconds):\n",
    "    \"\"\"Chuyển đổi thời gian (giây) thành định dạng SRT hh:mm:ss,ms\"\"\"\n",
    "    mins, sec = divmod(seconds, 60)\n",
    "    hours, mins = divmod(mins, 60)\n",
    "    return f\"{int(hours):02}:{int(mins):02}:{int(sec):02},{int((sec % 1) * 1000):03}\"\n",
    "def get_audio_duration(audio_path):\n",
    "    # Lọc các file có đuôi .wav\n",
    "    audio_paths = os.listdir(audio_path)\n",
    "    audio_list = [file for file in audio_paths if file.endswith(\".wav\")]\n",
    "    \n",
    "    # Khởi tạo danh sách audio duration\n",
    "    duration_list = []\n",
    "    \n",
    "    for audio_path in audio_list:\n",
    "        # Mở file âm thanh và lấy thời gian\n",
    "        with AudioFileClip(f\"../data/audio/{audio_path}\") as audio:\n",
    "            duration_list.append(audio.duration)\n",
    "    # Tính tổng tích lũy thời gian\n",
    "    duration_list = [format_time(time) for time in list(accumulate(duration_list))]\n",
    "    return [format_time(0.0)] + duration_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "duration_time = get_audio_duration(\"../data/audio\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_srt_from_time_and_text(duration_time, text_folder, output_srt):\n",
    "    subtitle = \"\"\n",
    "    subtitle_index = 1\n",
    "    text_list = sorted([file for file in os.listdir(text_folder) if file.endswith('txt')])\n",
    "    # Duyệt qua các mốc thời gian và file text\n",
    "    for i in range(len(duration_time) - 1):\n",
    "        start_time = duration_time[i]\n",
    "        end_time = duration_time[i + 1]\n",
    "        \n",
    "        # Lấy tên file text tương ứng\n",
    "        text_file = text_list[i]  # Giả sử các file có tên như '1.txt', '2.txt', ...\n",
    "        \n",
    "        text_path = os.path.join(text_folder, text_file)\n",
    "        \n",
    "        if os.path.exists(text_path):\n",
    "            with open(text_path, 'r', encoding='utf-8') as f:\n",
    "                text = f.read().strip()\n",
    "                # Thêm phần subtitle vào chuỗi kết quả\n",
    "                subtitle += f\"{subtitle_index}\\n{start_time} --> {end_time}\\n{text}\\n\\n\"\n",
    "                subtitle_index += 1\n",
    "        else:\n",
    "            print(f\"File {text_file} không tồn tại!\")\n",
    "    \n",
    "    # Lưu vào file SRT\n",
    "    with open(output_srt, 'w', encoding='utf-8') as f:\n",
    "        f.write(subtitle)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "create_srt_from_time_and_text(duration_time, '../data/text', 'subtitle.srt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "def concatenate_audio_files(audio_folder, output_audio_path):\n",
    "    # Lọc tất cả các file âm thanh .wav trong thư mục\n",
    "    audio_clips = []\n",
    "    \n",
    "    for file in sorted(os.listdir(audio_folder)):\n",
    "        if file.endswith('.wav'):\n",
    "            audio_path = os.path.join(audio_folder, file)\n",
    "            audio_clip = AudioFileClip(audio_path)\n",
    "            audio_clips.append(audio_clip)\n",
    "    \n",
    "    # Ghép tất cả các audio clip lại với nhau\n",
    "    final_audio = concatenate_audioclips(audio_clips)\n",
    "    \n",
    "    # Lưu kết quả vào file output\n",
    "    final_audio.write_audiofile(output_audio_path, codec = 'pcm_s16le')\n",
    "\n",
    "    print(f\"File audio đã được lưu tại: {output_audio_path}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "chunk:   1%|          | 107/11954 [00:14<27:40,  7.14it/s, now=None]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Writing audio in final_audio.wav\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "chunk:   1%|          | 107/11954 [00:25<46:35,  4.24it/s, now=None]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Done.\n",
      "File audio đã được lưu tại: final_audio.wav\n"
     ]
    }
   ],
   "source": [
    "concatenate_audio_files(\"../data/audio\",\"final_audio.wav\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_video_from_images(image_folder, audio_path, output_video_path):\n",
    "    # Đọc file âm thanh để lấy thời lượng\n",
    "    audio = AudioFileClip(audio_path)\n",
    "    total_duration = audio.duration  # Tổng thời lượng video bằng thời lượng audio\n",
    "\n",
    "    # Đọc tất cả các file ảnh trong thư mục và sắp xếp theo tên\n",
    "    image_files = [file for file in sorted(os.listdir(image_folder))]\n",
    "    \n",
    "    if not image_files:\n",
    "        raise ValueError(\"Không tìm thấy ảnh nào trong thư mục!\")\n",
    "\n",
    "    # Tính thời lượng hiển thị cho mỗi ảnh\n",
    "    duration_per_image = total_duration / len(image_files)\n",
    "\n",
    "    # Tạo danh sách các clip ảnh\n",
    "    clips = [ImageClip(f\"../data/image/{img}\").with_duration(duration_per_image).resized(width=1280) for img in image_files]\n",
    "\n",
    "    # Ghép các clip ảnh lại với nhau\n",
    "    final_video = concatenate_videoclips(clips, method=\"chain\")\n",
    "    \n",
    "    # Gán âm thanh vào video\n",
    "    final_video .audio = audio\n",
    "\n",
    "    # Xuất video\n",
    "    final_video.write_videofile(output_video_path, codec=\"libx264\", audio_codec=\"pcm_s16le\", fps=24)\n",
    "\n",
    "    print(f\"Video đã được lưu tại: {output_video_path}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Building video output.mp4.\n",
      "MoviePy - Writing audio in outputTEMP_MPY_wvf_snd.wav\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "                                                                         \r"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Done.\n",
      "MoviePy - Writing video output.mp4\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "                                                                             \r"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Done !\n",
      "MoviePy - video ready output.mp4\n",
      "Video đã được lưu tại: output.mp4\n"
     ]
    }
   ],
   "source": [
    "create_video_from_images(\"../data/image\",\"final_audio.wav\",\"output.mp4\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [],
   "source": [
    "def wrap_text(text, max_width):\n",
    "    \"\"\"\n",
    "    Tự động xuống dòng để vừa với chiều rộng max_width.\n",
    "    \"\"\"\n",
    "    import textwrap\n",
    "    return \"\\n\".join(textwrap.wrap(text, width=max_width))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_subtitles_to_video(video_path, subtitle_path, output_video_path):\n",
    "    \"\"\"\n",
    "    Thêm phụ đề từ file .srt trực tiếp vào video.\n",
    "    \n",
    "    :param video_path: Đường dẫn video gốc\n",
    "    :param subtitle_path: Đường dẫn file .srt\n",
    "    :param output_video_path: Đường dẫn lưu video đầu ra\n",
    "    \"\"\"\n",
    "    \n",
    "    # Đọc file video\n",
    "    video = VideoFileClip(video_path)\n",
    "\n",
    "    # Đọc file .srt\n",
    "    subs = pysrt.open(subtitle_path)\n",
    "\n",
    "    subtitle_clips = []  # Danh sách các đoạn phụ đề\n",
    "\n",
    "    # Xử lý từng dòng phụ đề\n",
    "    for sub in subs:\n",
    "        # Chuyển thời gian thành giây\n",
    "        start_time = sub.start.ordinal / 1000  # Chuyển từ milliseconds sang giây\n",
    "        end_time = sub.end.ordinal / 1000\n",
    "        font = \"../BeVietnamPro-Light.ttf\"\n",
    "        # Tạo clip phụ đề\n",
    "        txt_clip = TextClip(font=font, text=wrap_text(sub.text, max_width=75), font_size=10, stroke_color=\"black\", stroke_width=3, color=\"#fff\")\n",
    "         \n",
    "        # Đặt vị trí hiển thị (giữa phía dưới video)\n",
    "        txt_clip = txt_clip.with_position(('center', 'bottom')).with_duration(end_time - start_time).with_start(start_time)\n",
    "        \n",
    "        subtitle_clips.append(txt_clip)\n",
    "\n",
    "    # Ghép phụ đề vào video\n",
    "    final_video = CompositeVideoClip([video] + subtitle_clips)\n",
    "\n",
    "    # Xuất video với phụ đề\n",
    "    final_video.write_videofile(output_video_path, fps=video.fps, codec='libx264', threads=4)\n",
    "\n",
    "    print(f\"Video với phụ đề đã được lưu tại: {output_video_path}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'video_found': True, 'audio_found': True, 'metadata': {'major_brand': 'isom', 'minor_version': '512', 'compatible_brands': 'isomiso2avc1mp41', 'encoder': 'Lavf61.7.100'}, 'inputs': [{'streams': [{'input_number': 0, 'stream_number': 0, 'stream_type': 'video', 'language': None, 'default': True, 'size': [400, 258], 'bitrate': 24, 'fps': 24.0, 'codec_name': 'h264', 'profile': '(High)', 'metadata': {'Metadata': '', 'handler_name': 'VideoHandler', 'vendor_id': '[0][0][0][0]', 'encoder': 'Lavc61.19.100 libx264'}}, {'input_number': 0, 'stream_number': 1, 'stream_type': 'audio', 'language': None, 'default': True, 'fps': 44100, 'bitrate': 127, 'metadata': {'Metadata': '', 'handler_name': 'SoundHandler', 'vendor_id': '[0][0][0][0]'}}], 'input_number': 0}], 'duration': 542.12, 'bitrate': 159, 'start': 0.0, 'default_video_input_number': 0, 'default_video_stream_number': 0, 'video_codec_name': 'h264', 'video_profile': '(High)', 'video_size': [400, 258], 'video_bitrate': 24, 'video_fps': 24.0, 'default_audio_input_number': 0, 'default_audio_stream_number': 1, 'audio_fps': 44100, 'audio_bitrate': 127, 'video_duration': 542.12, 'video_n_frames': 13010}\n",
      "/opt/anaconda3/lib/python3.12/site-packages/imageio_ffmpeg/binaries/ffmpeg-macos-aarch64-v7.1 -i output.mp4 -loglevel error -f image2pipe -vf scale=400:258 -sws_flags bicubic -pix_fmt rgb24 -vcodec rawvideo -\n",
      "MoviePy - Building video final_output.mp4.\n",
      "MoviePy - Writing audio in final_outputTEMP_MPY_wvf_snd.mp3\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "                                                                        \r"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Done.\n",
      "MoviePy - Writing video final_output.mp4\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "                                                                             "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MoviePy - Done !\n",
      "MoviePy - video ready final_output.mp4\n",
      "Video với phụ đề đã được lưu tại: final_output.mp4\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\r"
     ]
    }
   ],
   "source": [
    "add_subtitles_to_video(\"output.mp4\", \"subtitle.srt\", \"final_output.mp4\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}