Spaces:
Sleeping
Sleeping
Commit
·
e62cec6
1
Parent(s):
1973060
"LOL"
Browse files- .gitignore +13 -0
- LICENSE +201 -0
- README.md +42 -13
- app.py +113 -0
- data/BeVietnamPro-Light.ttf +0 -0
- main.py +24 -0
- notebook/image_gen.ipynb +190 -0
- notebook/text_preprocessing.ipynb +247 -0
- notebook/text_to_speech.ipynb +224 -0
- notebook/text_to_video.ipynb +0 -0
- src/image_gen.py +126 -0
- src/text_processing.py +151 -0
- src/text_to_speech.py +52 -0
- src/text_to_video.py +153 -0
- test/test.ipynb +391 -0
.gitignore
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.venv/
|
2 |
+
__pycache__/
|
3 |
+
*.mp4
|
4 |
+
*.wav
|
5 |
+
.data
|
6 |
+
.env
|
7 |
+
*.txt
|
8 |
+
.streamlit
|
9 |
+
.vercel
|
10 |
+
.DS_Store
|
11 |
+
*.png
|
12 |
+
*.srt
|
13 |
+
*.pdf
|
LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright [yyyy] [name of copyright owner]
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
README.md
CHANGED
@@ -1,14 +1,43 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# KnowFlow - Chuyển Bài Giảng Thành Video
|
2 |
+
|
3 |
+
KnowFlow là một ứng dụng giúp chuyển đổi file bài giảng (PDF, DOCX) thành video có giọng đọc và hình ảnh minh họa. Dự án sử dụng các công nghệ AI hiện đại để phân tích nội dung, sinh lời giảng, tạo ảnh và dựng video tự động.
|
4 |
+
|
5 |
+
## 🚀 Tính năng chính
|
6 |
+
- **Semantic Chunking & Text Analysis**: Sử dụng `gemini-pro` của Google để chia nhỏ văn bản và tạo lời giảng tự động.
|
7 |
+
- **Text-to-Speech (TTS)**: Sử dụng `mms-tts-vie` của Facebook để tạo giọng đọc tiếng Việt tự nhiên.
|
8 |
+
- **Image Generation**: Sử dụng `stable-diffusion-3.5-large` của Stability AI để tạo hình ảnh minh họa.
|
9 |
+
- **Video Generation**: Sử dụng `moviepy` để tạo video từ giọng đọc và hình ảnh.
|
10 |
+
- **Triển khai dễ dàng**: Chạy trên `Streamlit` với giao diện đơn giản, hỗ trợ tải file và xem video đầu ra.
|
11 |
+
|
12 |
+
## 🛠️ Công nghệ sử dụng
|
13 |
+
- **Google Gemini-Pro** - Semantic chunking & text generation
|
14 |
+
- **Facebook MMS-TTS-VIE** - Chuyển văn bản thành giọng nói
|
15 |
+
- **Stability AI Stable Diffusion 3.5 Large** - Tạo hình ảnh minh họa
|
16 |
+
- **MoviePy** - Dựng video từ giọng đọc và hình ảnh
|
17 |
+
- **Streamlit** - Giao diện web để tải file và xem kết quả
|
18 |
+
|
19 |
+
## 📥 Cài đặt
|
20 |
+
Yêu cầu Python 3.8+ và pip.
|
21 |
|
22 |
+
```bash
|
23 |
+
# Clone repo
|
24 |
+
git clone https://github.com/hieunguyen-cyber/knowflow.git
|
25 |
+
cd knowflow
|
26 |
+
|
27 |
+
# Cài đặt các thư viện cần thiết
|
28 |
+
pip install -r requirements.txt
|
29 |
+
```
|
30 |
+
## ▶️ Chạy ứng dụng
|
31 |
+
```bash
|
32 |
+
streamlit run app.py
|
33 |
+
```
|
34 |
+
Sau khi chạy lệnh trên, mở trình duyệt và truy cập `http://localhost:8501` để sử dụng.
|
35 |
+
|
36 |
+
## 📸 Hình ảnh minh họa
|
37 |
+

|
38 |
+
|
39 |
+
## 📜 Giấy phép
|
40 |
+
Dự án được phát hành dưới giấy phép Apache.
|
41 |
+
|
42 |
+
---
|
43 |
+
_Tác giả: Nguyễn Trung Hiếu_
|
app.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import asyncio
|
2 |
+
|
3 |
+
try:
|
4 |
+
asyncio.get_running_loop()
|
5 |
+
except RuntimeError:
|
6 |
+
asyncio.run(asyncio.sleep(0)) # Ensures an event loop is created before Streamlit starts
|
7 |
+
|
8 |
+
import streamlit as st
|
9 |
+
from main import main
|
10 |
+
import os
|
11 |
+
import subprocess
|
12 |
+
from huggingface_hub import InferenceClient
|
13 |
+
import google.generativeai as genai
|
14 |
+
|
15 |
+
HF_TOKEN = st.secrets["secrets"]["HF_TOKEN"]
|
16 |
+
GOOGLE_API_KEY = st.secrets["secrets"]["GOOGLE_API_KEY"]
|
17 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
18 |
+
client = InferenceClient(provider="hf-inference", api_key=HF_TOKEN)
|
19 |
+
|
20 |
+
# Định nghĩa đường dẫn video đầu ra
|
21 |
+
OUTPUT_VIDEO_PATH = "./data/output/final_output.mp4"
|
22 |
+
OUTPUT_VIDEO_FIXED_PATH = "./data/output/final_output_fixed.mp4"
|
23 |
+
|
24 |
+
# Tiêu đề ứng dụng
|
25 |
+
st.set_page_config(page_title="KnowFlow", page_icon="📖")
|
26 |
+
st.markdown("<h1 style='text-align: center;'>📖 KnowFlow 🌊</h1>", unsafe_allow_html=True)
|
27 |
+
st.markdown("<h4 style='text-align: center;'>Convert documents into videos with AI-powered storytelling</h4>", unsafe_allow_html=True)
|
28 |
+
|
29 |
+
# Thông tin tác giả
|
30 |
+
st.markdown("---")
|
31 |
+
st.markdown("👨💻 **Author:** Nguyễn Trung Hiếu")
|
32 |
+
st.markdown("🔗 [GitHub Repository](https://github.com/hieunguyen-cyber/KnowFlow.git)")
|
33 |
+
st.markdown("---")
|
34 |
+
|
35 |
+
# Upload file PDF
|
36 |
+
uploaded_file = st.file_uploader("📂 Upload your document (PDF)", type=["pdf","docx"])
|
37 |
+
|
38 |
+
# Nếu có file, lưu vào thư mục tạm và lấy đường dẫn
|
39 |
+
file_path = None
|
40 |
+
if uploaded_file:
|
41 |
+
file_path = f"./data/input/{uploaded_file.name}"
|
42 |
+
with open(file_path, "wb") as f:
|
43 |
+
f.write(uploaded_file.getbuffer()) # Lưu file thực tế
|
44 |
+
number_of_images = st.slider("🖼️ Nhập số ảnh",1,10,3)
|
45 |
+
# Cấu hình đầu vào
|
46 |
+
gender = st.radio("🗣️ Select Voice Gender", options=["female", "male"])
|
47 |
+
|
48 |
+
# Nếu chọn giọng nam, vô hiệu hóa tốc độ (chỉ cho phép "normal")
|
49 |
+
if gender == "male":
|
50 |
+
speed = st.radio("⚡ Speech Speed (Male voice supports only normal)", options=["normal"], disabled=True)
|
51 |
+
else:
|
52 |
+
speed = st.radio("⚡ Speech Speed", options=["fast", "normal", "slow"])
|
53 |
+
analysis_level = st.radio("Analysis Level", options=["basic", "detailed"])
|
54 |
+
writting_style = st.radio("Writting Style", options = ["academic","popular","creative","humorous"])
|
55 |
+
|
56 |
+
# Tạo thanh trượt với giá trị từ 50 đến 250, bước nhảy 50
|
57 |
+
word_lower_limit, word_upper_limit = st.slider(
|
58 |
+
"Chọn khoảng độ dài văn bản:",
|
59 |
+
min_value=50,
|
60 |
+
max_value=250,
|
61 |
+
value=(50, 250), # Giá trị mặc định
|
62 |
+
step=50
|
63 |
+
)
|
64 |
+
|
65 |
+
st.write(f"Giới hạn độ dài văn bản từ **{word_lower_limit}** đến **{word_upper_limit}** ký tự.")
|
66 |
+
detail_level = st.radio("📖 Detail Level of Image Description", options=["short", "detailed"])
|
67 |
+
perspective = st.radio("🔎 Perspective", options=["subjective", "neutral"])
|
68 |
+
emotion = st.text_input("🎭 Emotion", placeholder="Example: mysterious, romantic,...")
|
69 |
+
time_setting = st.text_input("⏳ Time Setting", placeholder="Example: modern, medieval,...")
|
70 |
+
art_style = st.text_input("🖌️ Image Description Style", placeholder="Example: realistic, abstract,...")
|
71 |
+
style = st.text_input("🎨 Image Style", placeholder="Example: realistic, anime,...")
|
72 |
+
color_palette = st.text_input("🌈 Color Palette", placeholder="Example: vibrant, monochrome,...")
|
73 |
+
|
74 |
+
def convert_audio_format(video_input, video_output):
|
75 |
+
"""Chuyển đổi định dạng âm thanh của video sang AAC."""
|
76 |
+
if not os.path.exists(video_input):
|
77 |
+
raise FileNotFoundError(f"File '{video_input}' không tồn tại!")
|
78 |
+
|
79 |
+
command = [
|
80 |
+
"ffmpeg", "-i", video_input,
|
81 |
+
"-c:v", "copy", "-c:a", "aac", "-b:a", "192k",
|
82 |
+
"-y", # Ghi đè nếu file output đã tồn tại
|
83 |
+
video_output
|
84 |
+
]
|
85 |
+
|
86 |
+
try:
|
87 |
+
subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
88 |
+
print(f"✅ Chuyển đổi thành công: {video_output}")
|
89 |
+
except subprocess.CalledProcessError as e:
|
90 |
+
print(f"❌ Lỗi khi chuyển đổi video: {e.stderr.decode()}")
|
91 |
+
|
92 |
+
# Nút chạy pipeline
|
93 |
+
if st.button("🚀 Generate Video"):
|
94 |
+
if file_path and os.path.exists(file_path):
|
95 |
+
st.success("⏳ Processing started...")
|
96 |
+
main(file_path, analysis_level, writting_style, word_lower_limit, word_upper_limit, gender, speed, number_of_images, detail_level, perspective, emotion, time_setting, art_style, style, color_palette)
|
97 |
+
|
98 |
+
# Kiểm tra xem video đã được tạo chưa
|
99 |
+
if os.path.exists(OUTPUT_VIDEO_PATH):
|
100 |
+
st.success("🎉 Video generated successfully!")
|
101 |
+
|
102 |
+
# Chuyển đổi định dạng âm thanh
|
103 |
+
convert_audio_format(OUTPUT_VIDEO_PATH, OUTPUT_VIDEO_FIXED_PATH)
|
104 |
+
|
105 |
+
st.video(OUTPUT_VIDEO_FIXED_PATH) # Trình chiếu video
|
106 |
+
|
107 |
+
# Tạo link tải về
|
108 |
+
with open(OUTPUT_VIDEO_FIXED_PATH, "rb") as video_file:
|
109 |
+
st.download_button(label="📥 Download Video", data=video_file, file_name="final_output_fixed.mp4", mime="video/mp4")
|
110 |
+
else:
|
111 |
+
st.error("⚠️ Video generation failed. Please check the logs.")
|
112 |
+
else:
|
113 |
+
st.error("⚠️ Please upload a valid PDF file.")
|
data/BeVietnamPro-Light.ttf
ADDED
Binary file (135 kB). View file
|
|
main.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from src.text_processing import text_processing
|
2 |
+
from src.text_to_speech import text_to_speech
|
3 |
+
from src.image_gen import image_gen
|
4 |
+
from src.text_to_video import text_to_video
|
5 |
+
import os
|
6 |
+
def remove_cache(folder_path):
|
7 |
+
if not os.path.exists(folder_path):
|
8 |
+
os.makedirs(folder_path) # Tạo thư mục nếu chưa tồn tại
|
9 |
+
for file_name in os.listdir(folder_path):
|
10 |
+
file_path = os.path.join(folder_path, file_name)
|
11 |
+
if os.path.isfile(file_path): # Kiểm tra nếu là file
|
12 |
+
os.remove(file_path)
|
13 |
+
def main(file_path = "./data/input/sample.pdf", analysis_level='basic', writting_style='academic', word_lower_limit=100, word_upper_limit = 150, gender = "female", speed = "fast", number_of_images = 3, detail_level="short", perspective="neutral", emotion="sad", time_setting="classic", art_style="realistic", style="anime", color_palette="monochrome"):
|
14 |
+
remove_cache("./data/audio")
|
15 |
+
remove_cache("./data/image")
|
16 |
+
remove_cache("./data/text")
|
17 |
+
remove_cache("./data/output")
|
18 |
+
text_processing(file_path = file_path, analysis_level=analysis_level, writting_style=writting_style, word_lower_limit = word_lower_limit, word_upper_limit=word_upper_limit )
|
19 |
+
text_to_speech(gender = gender, speed = speed)
|
20 |
+
image_gen(number_of_images = number_of_images, detail_level=detail_level, perspective=perspective, emotion=emotion, time_setting=time_setting, art_style=art_style, style=style, color_palette=color_palette)
|
21 |
+
text_to_video()
|
22 |
+
|
23 |
+
if __name__ == "__main__":
|
24 |
+
main(file_path="./data/input/sample_2.pdf")
|
notebook/image_gen.ipynb
ADDED
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": null,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [],
|
8 |
+
"source": [
|
9 |
+
"from huggingface_hub import InferenceClient\n",
|
10 |
+
"import os\n",
|
11 |
+
"import glob\n",
|
12 |
+
"from collections import defaultdict\n",
|
13 |
+
"import google.generativeai as genai\n",
|
14 |
+
"from tqdm import tqdm\n",
|
15 |
+
"from huggingface_hub.utils import HfHubHTTPError\n",
|
16 |
+
"import random\n",
|
17 |
+
"from dotenv import load_dotenv\n",
|
18 |
+
"import time\n",
|
19 |
+
"\n",
|
20 |
+
"\n",
|
21 |
+
"load_dotenv()\n",
|
22 |
+
"HF_API_KEY = os.getenv(\"HUGGINGFACE_API_KEY\")\n",
|
23 |
+
"GOOGLE_API_KEY = os.getenv(\"GOOGLE_API_KEY\")\n",
|
24 |
+
"genai.configure(api_key=GOOGLE_API_KEY)\n",
|
25 |
+
"client = InferenceClient(provider=\"hf-inference\", api_key=HF_API_KEY)\n",
|
26 |
+
"import time"
|
27 |
+
]
|
28 |
+
},
|
29 |
+
{
|
30 |
+
"cell_type": "code",
|
31 |
+
"execution_count": null,
|
32 |
+
"metadata": {},
|
33 |
+
"outputs": [],
|
34 |
+
"source": [
|
35 |
+
"def split_text_by_semantics(number_of_images):\n",
|
36 |
+
" with open(\"../data/text/text.txt\", \"r\", encoding=\"utf-8\") as file:\n",
|
37 |
+
" text = file.read()\n",
|
38 |
+
" prompt = f\"\"\"\n",
|
39 |
+
" Bạn là một chuyên gia xử lý văn bản. Hãy chia văn bản sau thành {number_of_images} đoạn có ý nghĩa sao cho mỗi đoạn vừa đủ để giải thích trong khoảng 3 đến 5 câu.\n",
|
40 |
+
"\n",
|
41 |
+
" Văn bản:\n",
|
42 |
+
" {text}\n",
|
43 |
+
"\n",
|
44 |
+
" Định dạng đầu ra:\n",
|
45 |
+
" - Phần 1: [Nội dung]\n",
|
46 |
+
" - Phần 2: [Nội dung]\n",
|
47 |
+
" - Phần 3: [Nội dung]\n",
|
48 |
+
" \"\"\"\n",
|
49 |
+
"\n",
|
50 |
+
" try:\n",
|
51 |
+
" model = genai.GenerativeModel(\"gemini-pro\")\n",
|
52 |
+
" response = model.generate_content(prompt)\n",
|
53 |
+
" result_text = response.text.strip()\n",
|
54 |
+
"\n",
|
55 |
+
" chunks = result_text.split(\"- Phần \")\n",
|
56 |
+
" chunks = [chunk.strip() for chunk in chunks if chunk]\n",
|
57 |
+
" return chunks\n",
|
58 |
+
" except Exception as e:\n",
|
59 |
+
" print(f\"Lỗi khi gọi API Gemini: {e}\")\n",
|
60 |
+
" return []"
|
61 |
+
]
|
62 |
+
},
|
63 |
+
{
|
64 |
+
"cell_type": "code",
|
65 |
+
"execution_count": null,
|
66 |
+
"metadata": {},
|
67 |
+
"outputs": [],
|
68 |
+
"source": [
|
69 |
+
"def describe_image(description, detail_level=\"short\", perspective=\"neutral\", emotion=None, time_setting=None, art_style=None):\n",
|
70 |
+
" \"\"\"\n",
|
71 |
+
" Nhận một đoạn văn mô tả chi tiết và trả về một câu mô tả hình ảnh theo các tùy chỉnh.\n",
|
72 |
+
"\n",
|
73 |
+
" Args:\n",
|
74 |
+
" description (str): Đoạn văn mô tả chi tiết.\n",
|
75 |
+
" detail_level (str): Mức độ chi tiết (\"short\" hoặc \"detailed\").\n",
|
76 |
+
" perspective (str): Góc nhìn (\"subjective\" hoặc \"neutral\").\n",
|
77 |
+
" emotion (str, optional): Cảm xúc chủ đạo (nếu có, ví dụ: \"mysterious\", \"romantic\").\n",
|
78 |
+
" time_setting (str, optional): Bối cảnh thời gian (ví dụ: \"modern\", \"medieval\", \"futuristic\").\n",
|
79 |
+
" art_style (str, optional): Phong cách nghệ thuật (ví dụ: \"realistic\", \"abstract\", \"sketch\").\n",
|
80 |
+
"\n",
|
81 |
+
" Returns:\n",
|
82 |
+
" str: Một câu mô tả hình ảnh theo yêu cầu.\n",
|
83 |
+
" \"\"\"\n",
|
84 |
+
" \n",
|
85 |
+
" prompt = f\"\"\"\n",
|
86 |
+
" Bạn là chuyên gia mô tả hình ảnh. Hãy đọc đoạn mô tả dưới đây và tạo một mô tả hình ảnh theo các tiêu chí sau:\n",
|
87 |
+
" - Mức độ chi tiết: {\"Ngắn gọn\" if detail_level == \"short\" else \"Chi tiết\"}.\n",
|
88 |
+
" - Góc nhìn: {\"Chủ quan\" if perspective == \"subjective\" else \"Trung lập\"}.\n",
|
89 |
+
" {f\"- Cảm xúc chủ đạo: {emotion}.\" if emotion else \"\"}\n",
|
90 |
+
" {f\"- Bối cảnh thời gian: {time_setting}.\" if time_setting else \"\"}\n",
|
91 |
+
" {f\"- Phong cách nghệ thuật: {art_style}.\" if art_style else \"\"}\n",
|
92 |
+
"\n",
|
93 |
+
" Đoạn mô tả:\n",
|
94 |
+
" {description}\n",
|
95 |
+
"\n",
|
96 |
+
" Hãy tạo một mô tả hình ảnh phù hợp với yêu cầu trên bằng Tiếng Anh.\n",
|
97 |
+
" \"\"\"\n",
|
98 |
+
"\n",
|
99 |
+
" try:\n",
|
100 |
+
" model = genai.GenerativeModel(\"gemini-pro\")\n",
|
101 |
+
" response = model.generate_content(prompt)\n",
|
102 |
+
" return response.text.strip()\n",
|
103 |
+
" except Exception as e:\n",
|
104 |
+
" print(f\"Lỗi khi gọi API Gemini: {e}\")\n",
|
105 |
+
" return \"\"\n"
|
106 |
+
]
|
107 |
+
},
|
108 |
+
{
|
109 |
+
"cell_type": "code",
|
110 |
+
"execution_count": null,
|
111 |
+
"metadata": {},
|
112 |
+
"outputs": [],
|
113 |
+
"source": [
|
114 |
+
"def generate_image(prompt, output_path, model=\"stabilityai/stable-diffusion-3.5-large\", resolution=(512, 512), style=None, color_palette=None):\n",
|
115 |
+
" \"\"\"\n",
|
116 |
+
" Tạo hình ảnh từ mô tả văn bản với các tùy chỉnh linh hoạt.\n",
|
117 |
+
" \n",
|
118 |
+
" :param prompt: Mô tả hình ảnh đầu vào.\n",
|
119 |
+
" :param output_path: Đường dẫn lưu ảnh đầu ra.\n",
|
120 |
+
" :param model: Mô hình AI sử dụng để tạo ảnh.\n",
|
121 |
+
" :param style: Phong cách hình ảnh (nếu có, ví dụ: 'realistic', 'anime', 'cyberpunk').\n",
|
122 |
+
" :param color_palette: Bảng màu ưu tiên (nếu có, ví dụ: 'vibrant', 'monochrome').\n",
|
123 |
+
" \"\"\"\n",
|
124 |
+
" \n",
|
125 |
+
" custom_prompt = prompt\n",
|
126 |
+
" \n",
|
127 |
+
" if style:\n",
|
128 |
+
" custom_prompt += f\" in {style} style\"\n",
|
129 |
+
" if color_palette:\n",
|
130 |
+
" custom_prompt += f\" with {color_palette} color scheme\"\n",
|
131 |
+
" \n",
|
132 |
+
" image = client.text_to_image(custom_prompt, model=model, resolution=resolution)\n",
|
133 |
+
" image.save(output_path)\n"
|
134 |
+
]
|
135 |
+
},
|
136 |
+
{
|
137 |
+
"cell_type": "code",
|
138 |
+
"execution_count": null,
|
139 |
+
"metadata": {},
|
140 |
+
"outputs": [],
|
141 |
+
"source": [
|
142 |
+
"texts = split_text_by_semantics(number_of_images=3)\n",
|
143 |
+
"index = 0\n",
|
144 |
+
"for merged_text in tqdm(texts, desc=\"Processing\", unit=\"image\"):\n",
|
145 |
+
" output_path = f\"../data/image/{index}.png\"\n",
|
146 |
+
" prompt = describe_image(merged_text)\n",
|
147 |
+
" print(prompt)\n",
|
148 |
+
"\n",
|
149 |
+
" # Cơ chế retry với backoff\n",
|
150 |
+
" max_retries = 5\n",
|
151 |
+
" retry_count = 0\n",
|
152 |
+
"\n",
|
153 |
+
" while retry_count < max_retries:\n",
|
154 |
+
" try:\n",
|
155 |
+
" generate_image(prompt, output_path)\n",
|
156 |
+
" time.sleep(60) # Chờ sau khi tạo ảnh thành công\n",
|
157 |
+
" break # Nếu thành công thì thoát khỏi vòng lặp retry\n",
|
158 |
+
" except HfHubHTTPError as e:\n",
|
159 |
+
" print(f\"Lỗi khi gọi API: {e}\")\n",
|
160 |
+
" retry_count += 1\n",
|
161 |
+
" wait_time = 2 ** retry_count + random.uniform(0, 1) # Exponential backoff\n",
|
162 |
+
" print(f\"Thử lại sau {wait_time:.2f} giây...\")\n",
|
163 |
+
" time.sleep(wait_time)\n",
|
164 |
+
"\n",
|
165 |
+
" index += 1"
|
166 |
+
]
|
167 |
+
}
|
168 |
+
],
|
169 |
+
"metadata": {
|
170 |
+
"kernelspec": {
|
171 |
+
"display_name": "base",
|
172 |
+
"language": "python",
|
173 |
+
"name": "python3"
|
174 |
+
},
|
175 |
+
"language_info": {
|
176 |
+
"codemirror_mode": {
|
177 |
+
"name": "ipython",
|
178 |
+
"version": 3
|
179 |
+
},
|
180 |
+
"file_extension": ".py",
|
181 |
+
"mimetype": "text/x-python",
|
182 |
+
"name": "python",
|
183 |
+
"nbconvert_exporter": "python",
|
184 |
+
"pygments_lexer": "ipython3",
|
185 |
+
"version": "3.12.7"
|
186 |
+
}
|
187 |
+
},
|
188 |
+
"nbformat": 4,
|
189 |
+
"nbformat_minor": 2
|
190 |
+
}
|
notebook/text_preprocessing.ipynb
ADDED
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {},
|
6 |
+
"source": [
|
7 |
+
"# Cài đặt thư viện\n",
|
8 |
+
"API Free của Gemini nên không cần private"
|
9 |
+
]
|
10 |
+
},
|
11 |
+
{
|
12 |
+
"cell_type": "code",
|
13 |
+
"execution_count": 1,
|
14 |
+
"metadata": {},
|
15 |
+
"outputs": [],
|
16 |
+
"source": [
|
17 |
+
"import os\n",
|
18 |
+
"import fitz # PyMuPDF\n",
|
19 |
+
"from docx import Document\n",
|
20 |
+
"import google.generativeai as genai\n",
|
21 |
+
"from dotenv import load_dotenv\n",
|
22 |
+
"\n",
|
23 |
+
"# Load biến môi trường từ .env\n",
|
24 |
+
"load_dotenv()\n",
|
25 |
+
"GOOGLE_API_KEY = os.getenv(\"GOOGLE_API_KEY\")\n",
|
26 |
+
"genai.configure(api_key=GOOGLE_API_KEY)"
|
27 |
+
]
|
28 |
+
},
|
29 |
+
{
|
30 |
+
"cell_type": "markdown",
|
31 |
+
"metadata": {},
|
32 |
+
"source": [
|
33 |
+
"# Thiết lập hàm đọc file\n",
|
34 |
+
"Chấp nhận hai định dạng là .doc và .pdf. Đảm bảo file bài giảng nhiều chữ."
|
35 |
+
]
|
36 |
+
},
|
37 |
+
{
|
38 |
+
"cell_type": "code",
|
39 |
+
"execution_count": 2,
|
40 |
+
"metadata": {},
|
41 |
+
"outputs": [],
|
42 |
+
"source": [
|
43 |
+
"def extract_text_from_pdf(pdf_path):\n",
|
44 |
+
" # Mở file PDF\n",
|
45 |
+
" doc = fitz.open(pdf_path)\n",
|
46 |
+
" text = \"\"\n",
|
47 |
+
" for page_num in range(doc.page_count):\n",
|
48 |
+
" page = doc.load_page(page_num)\n",
|
49 |
+
" text += page.get_text()\n",
|
50 |
+
" return text\n",
|
51 |
+
"\n",
|
52 |
+
"def extract_text_from_docx(docx_path):\n",
|
53 |
+
" # Mở file DOCX\n",
|
54 |
+
" doc = Document(docx_path)\n",
|
55 |
+
" text = \"\"\n",
|
56 |
+
" for para in doc.paragraphs:\n",
|
57 |
+
" text += para.text + \"\\n\"\n",
|
58 |
+
" return text\n",
|
59 |
+
"\n",
|
60 |
+
"def extract_text_from_file(file_path):\n",
|
61 |
+
" # Kiểm tra loại file và gọi hàm tương ứng\n",
|
62 |
+
" file_extension = os.path.splitext(file_path)[1].lower()\n",
|
63 |
+
"\n",
|
64 |
+
" if file_extension == '.pdf':\n",
|
65 |
+
" return extract_text_from_pdf(file_path)\n",
|
66 |
+
" elif file_extension == '.docx':\n",
|
67 |
+
" return extract_text_from_docx(file_path)\n",
|
68 |
+
" else:\n",
|
69 |
+
" raise ValueError(\"Unsupported file format. Only PDF and DOCX are supported.\")"
|
70 |
+
]
|
71 |
+
},
|
72 |
+
{
|
73 |
+
"cell_type": "code",
|
74 |
+
"execution_count": 4,
|
75 |
+
"metadata": {},
|
76 |
+
"outputs": [],
|
77 |
+
"source": [
|
78 |
+
"text = extract_text_from_file(\"../data/input/sample.pdf\")\n",
|
79 |
+
"with open(\"../data/text/text.txt\", \"w\", encoding=\"utf-8\") as f:\n",
|
80 |
+
" f.write(text) "
|
81 |
+
]
|
82 |
+
},
|
83 |
+
{
|
84 |
+
"cell_type": "markdown",
|
85 |
+
"metadata": {},
|
86 |
+
"source": [
|
87 |
+
"# Gọi API tiến hành chia đoạn và phân tích tóm tắt\n",
|
88 |
+
"Đưa ra phân tích và lưu lại file"
|
89 |
+
]
|
90 |
+
},
|
91 |
+
{
|
92 |
+
"cell_type": "code",
|
93 |
+
"execution_count": null,
|
94 |
+
"metadata": {},
|
95 |
+
"outputs": [],
|
96 |
+
"source": [
|
97 |
+
"def split_text_by_semantics(text, number_of_chunks):\n",
|
98 |
+
" prompt = f\"\"\"\n",
|
99 |
+
" Bạn là một chuyên gia xử lý văn bản. Hãy chia văn bản sau thành {number_of_chunks} đoạn có ý nghĩa sao cho mỗi đoạn vừa đủ để giải thích trong khoảng 3 đến 5 câu.\n",
|
100 |
+
"\n",
|
101 |
+
" Văn bản:\n",
|
102 |
+
" {text}\n",
|
103 |
+
"\n",
|
104 |
+
" Định dạng đầu ra:\n",
|
105 |
+
" - Phần 1: [Nội dung]\n",
|
106 |
+
" - Phần 2: [Nội dung]\n",
|
107 |
+
" - Phần 3: [Nội dung]\n",
|
108 |
+
" \"\"\"\n",
|
109 |
+
"\n",
|
110 |
+
" try:\n",
|
111 |
+
" model = genai.GenerativeModel(\"gemini-pro\")\n",
|
112 |
+
" response = model.generate_content(prompt)\n",
|
113 |
+
" result_text = response.text.strip()\n",
|
114 |
+
"\n",
|
115 |
+
" chunks = result_text.split(\"- Phần \")\n",
|
116 |
+
" chunks = [chunk.strip() for chunk in chunks if chunk]\n",
|
117 |
+
" return chunks\n",
|
118 |
+
" except Exception as e:\n",
|
119 |
+
" print(f\"Lỗi khi gọi API Gemini: {e}\")\n",
|
120 |
+
" return []"
|
121 |
+
]
|
122 |
+
},
|
123 |
+
{
|
124 |
+
"cell_type": "code",
|
125 |
+
"execution_count": null,
|
126 |
+
"metadata": {},
|
127 |
+
"outputs": [],
|
128 |
+
"source": [
|
129 |
+
"def generate_explaination_for_chunks(chunks, analysis_level='basic', style='academic', word_limit=100):\n",
|
130 |
+
" \"\"\"\n",
|
131 |
+
" Phân tích nội dung của văn bản theo mức độ và phong cách mong muốn.\n",
|
132 |
+
" \n",
|
133 |
+
" :param chunks: Danh sách các đoạn văn bản cần phân tích.\n",
|
134 |
+
" :param text: Toàn bộ văn bản gốc.\n",
|
135 |
+
" :param analysis_level: Mức độ phân tích ('basic' hoặc 'detailed').\n",
|
136 |
+
" :param style: Phong cách phân tích ('academic', 'popular', 'creative', 'humorous').\n",
|
137 |
+
" :param word_limit: Số từ ước lượng cho mỗi phần tóm tắt.\n",
|
138 |
+
" :return: Danh sách các phân tích tương ứng với từng đoạn.\n",
|
139 |
+
" \"\"\"\n",
|
140 |
+
" \n",
|
141 |
+
" level_prompts = {\n",
|
142 |
+
" 'basic': \"Hãy đưa ra một bản tóm tắt ngắn gọn, tập trung vào nội dung chính.\",\n",
|
143 |
+
" 'detailed': \"Hãy phân tích chuyên sâu từng phần, làm rõ ý nghĩa, ngữ cảnh và các yếu tố quan trọng.\"\n",
|
144 |
+
" }\n",
|
145 |
+
" \n",
|
146 |
+
" style_prompts = {\n",
|
147 |
+
" 'academic': \"Phân tích theo phong cách học thuật, sử dụng ngôn ngữ chuyên sâu và lập luận chặt chẽ.\",\n",
|
148 |
+
" 'popular': \"Trình bày theo phong cách phổ thông, dễ hiểu và phù hợp với nhiều đối tượng.\",\n",
|
149 |
+
" 'creative': \"Giải thích một cách sáng tạo, sử dụng hình ảnh ẩn dụ và cách diễn đạt thú vị.\",\n",
|
150 |
+
" 'humorous': \"Phân tích theo phong cách hài hước, thêm vào yếu tố vui nhộn và bất ngờ.\"\n",
|
151 |
+
" }\n",
|
152 |
+
" \n",
|
153 |
+
" overview_prompt = f\"\"\"\n",
|
154 |
+
" Đây là một văn bản có nội dung quan trọng. Bạn sẽ phân tích từng phần theo mức độ '{analysis_level}' và phong cách '{style}'.\n",
|
155 |
+
" Văn bản gồm các phần sau: {', '.join([f'Phần {i+1}' for i in range(len(chunks))])}.\n",
|
156 |
+
" {level_prompts[analysis_level]}\n",
|
157 |
+
" {style_prompts[style]}\n",
|
158 |
+
" Mỗi phần không vượt quá {word_limit} từ.\n",
|
159 |
+
" \"\"\"\n",
|
160 |
+
" \n",
|
161 |
+
" try:\n",
|
162 |
+
" model = genai.GenerativeModel(\"gemini-pro\")\n",
|
163 |
+
" response = model.generate_content(overview_prompt)\n",
|
164 |
+
" overview_text = response.text.strip()\n",
|
165 |
+
" \n",
|
166 |
+
" explanations = []\n",
|
167 |
+
" for idx, chunk in enumerate(chunks, start=1):\n",
|
168 |
+
" part_prompt = f\"\"\"\n",
|
169 |
+
" Phân tích phần {idx} của văn bản.\n",
|
170 |
+
" {level_prompts[analysis_level]}\n",
|
171 |
+
" {style_prompts[style]}\n",
|
172 |
+
" Nội dung phần này:\n",
|
173 |
+
" {chunk}\n",
|
174 |
+
" Hãy đảm bảo phần tóm tắt không vượt quá {word_limit} từ.\n",
|
175 |
+
" \"\"\"\n",
|
176 |
+
" \n",
|
177 |
+
" part_response = model.generate_content(part_prompt)\n",
|
178 |
+
" explanations.append(part_response.text.strip())\n",
|
179 |
+
" \n",
|
180 |
+
" return explanations\n",
|
181 |
+
" \n",
|
182 |
+
" except Exception as e:\n",
|
183 |
+
" print(f\"Lỗi khi gọi API Gemini: {e}\")\n",
|
184 |
+
" return []"
|
185 |
+
]
|
186 |
+
},
|
187 |
+
{
|
188 |
+
"cell_type": "code",
|
189 |
+
"execution_count": null,
|
190 |
+
"metadata": {},
|
191 |
+
"outputs": [],
|
192 |
+
"source": [
|
193 |
+
"# Tách văn bản theo ngữ nghĩa sử dụng API Gemini\n",
|
194 |
+
"semantic_chunks = split_text_by_semantics(text, number_of_chunks=3)\n",
|
195 |
+
"\n",
|
196 |
+
"# Tạo thuyết minh cho từng phần semantic chunk\n",
|
197 |
+
"explainations = generate_explaination_for_chunks(semantic_chunks)\n",
|
198 |
+
"\n",
|
199 |
+
"# In kết quả\n",
|
200 |
+
"for idx, explaination in enumerate(explainations, start=1):\n",
|
201 |
+
" print(f\"Giải thích cho Phần {idx}:\\n{explaination}\\n\")"
|
202 |
+
]
|
203 |
+
},
|
204 |
+
{
|
205 |
+
"cell_type": "code",
|
206 |
+
"execution_count": null,
|
207 |
+
"metadata": {},
|
208 |
+
"outputs": [],
|
209 |
+
"source": [
|
210 |
+
"# Lưu từng câu vào tệp riêng biệt\n",
|
211 |
+
"for idx, explaination in enumerate(explainations, start=1):\n",
|
212 |
+
" # Tách đoạn văn bản thành các câu dựa trên dấu chấm\n",
|
213 |
+
" sentences = explaination.split('.')\n",
|
214 |
+
" \n",
|
215 |
+
" # Lưu từng câu vào tệp riêng biệt\n",
|
216 |
+
" for sentence_idx, sentence in enumerate(sentences, start=1):\n",
|
217 |
+
" sentence = sentence.strip() # Loại bỏ khoảng trắng thừa\n",
|
218 |
+
" if sentence: # Kiểm tra nếu câu không rỗng\n",
|
219 |
+
" output_file = f\"../data/text/{idx}_{sentence_idx}.txt\" # Tên tệp theo định dạng x_y.txt\n",
|
220 |
+
" with open(output_file, \"w\", encoding=\"utf-8\") as f:\n",
|
221 |
+
" f.write(f\"'{sentence}'\") # Ghi câu trong dấu nháy đơn\n",
|
222 |
+
" print(f\"Đã lưu: {output_file}\")"
|
223 |
+
]
|
224 |
+
}
|
225 |
+
],
|
226 |
+
"metadata": {
|
227 |
+
"kernelspec": {
|
228 |
+
"display_name": "base",
|
229 |
+
"language": "python",
|
230 |
+
"name": "python3"
|
231 |
+
},
|
232 |
+
"language_info": {
|
233 |
+
"codemirror_mode": {
|
234 |
+
"name": "ipython",
|
235 |
+
"version": 3
|
236 |
+
},
|
237 |
+
"file_extension": ".py",
|
238 |
+
"mimetype": "text/x-python",
|
239 |
+
"name": "python",
|
240 |
+
"nbconvert_exporter": "python",
|
241 |
+
"pygments_lexer": "ipython3",
|
242 |
+
"version": "3.12.7"
|
243 |
+
}
|
244 |
+
},
|
245 |
+
"nbformat": 4,
|
246 |
+
"nbformat_minor": 2
|
247 |
+
}
|
notebook/text_to_speech.ipynb
ADDED
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 6,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [],
|
8 |
+
"source": [
|
9 |
+
"import torch\n",
|
10 |
+
"from transformers import VitsModel, AutoTokenizer\n",
|
11 |
+
"import torchaudio\n",
|
12 |
+
"import numpy as np\n",
|
13 |
+
"import os\n",
|
14 |
+
"from gtts import gTTS"
|
15 |
+
]
|
16 |
+
},
|
17 |
+
{
|
18 |
+
"cell_type": "code",
|
19 |
+
"execution_count": 11,
|
20 |
+
"metadata": {},
|
21 |
+
"outputs": [],
|
22 |
+
"source": [
|
23 |
+
"# Đọc và load danh sách từ các file .txt trong thư mục ../data/text\n",
|
24 |
+
"text_folder = \"../data/text\"\n",
|
25 |
+
"text_files = sorted([f for f in os.listdir(text_folder) if f.endswith('.txt')]) # Lọc các file .txt trong thư mục"
|
26 |
+
]
|
27 |
+
},
|
28 |
+
{
|
29 |
+
"cell_type": "code",
|
30 |
+
"execution_count": 9,
|
31 |
+
"metadata": {},
|
32 |
+
"outputs": [
|
33 |
+
{
|
34 |
+
"name": "stdout",
|
35 |
+
"output_type": "stream",
|
36 |
+
"text": [
|
37 |
+
"✅ Audio saved as hello.mp3 (gTTS - Female)\n"
|
38 |
+
]
|
39 |
+
}
|
40 |
+
],
|
41 |
+
"source": [
|
42 |
+
"def text_to_speech(text, filename=\"output.mp3\", gender=\"female\", speed=\"normal\"):\n",
|
43 |
+
" \"\"\"\n",
|
44 |
+
" Convert text to speech and save it as an audio file.\n",
|
45 |
+
" \n",
|
46 |
+
" Parameters:\n",
|
47 |
+
" text (str): The text to convert.\n",
|
48 |
+
" filename (str): The output file name.\n",
|
49 |
+
" gender (str): \"male\" (use MMS-TTS) or \"female\" (use gTTS).\n",
|
50 |
+
" speed (str): \"slow\", \"normal\", or \"fast\" (only for gTTS).\n",
|
51 |
+
" \"\"\"\n",
|
52 |
+
" lang = \"vi\"\n",
|
53 |
+
" \n",
|
54 |
+
" if gender.lower() == \"female\":\n",
|
55 |
+
" # gTTS chỉ có giọng nữ\n",
|
56 |
+
" speed_mapping = {\"slow\": True, \"normal\": False, \"fast\": False}\n",
|
57 |
+
" slow = speed_mapping.get(speed.lower(), False)\n",
|
58 |
+
" \n",
|
59 |
+
" tts = gTTS(text=text, lang=lang, slow=slow)\n",
|
60 |
+
" tts.save(filename)\n",
|
61 |
+
" print(f\"✅ Audio saved as {filename}\")\n",
|
62 |
+
" \n",
|
63 |
+
" elif gender.lower() == \"male\":\n",
|
64 |
+
" # MMS-TTS cho giọng nam\n",
|
65 |
+
" model = VitsModel.from_pretrained(\"facebook/mms-tts-vie\")\n",
|
66 |
+
" tokenizer = AutoTokenizer.from_pretrained(\"facebook/mms-tts-vie\")\n",
|
67 |
+
" \n",
|
68 |
+
" inputs = tokenizer(text, return_tensors=\"pt\")\n",
|
69 |
+
" with torch.no_grad():\n",
|
70 |
+
" output = model(**inputs).waveform\n",
|
71 |
+
" \n",
|
72 |
+
" # Lưu file âm thanh\n",
|
73 |
+
" torchaudio.save(filename, output, 24000)\n",
|
74 |
+
" print(f\"✅ Audio saved as {filename}\")\n",
|
75 |
+
" \n",
|
76 |
+
" else:\n",
|
77 |
+
" print(\"⚠️ Giọng không hợp lệ! Chỉ hỗ trợ 'male' hoặc 'female'.\")"
|
78 |
+
]
|
79 |
+
},
|
80 |
+
{
|
81 |
+
"cell_type": "code",
|
82 |
+
"execution_count": 12,
|
83 |
+
"metadata": {},
|
84 |
+
"outputs": [
|
85 |
+
{
|
86 |
+
"name": "stdout",
|
87 |
+
"output_type": "stream",
|
88 |
+
"text": [
|
89 |
+
"✅ Audio saved as 1_1.wav (gTTS - Female)\n",
|
90 |
+
"Đã lưu 1_1.wav\n",
|
91 |
+
"✅ Audio saved as 1_10.wav (gTTS - Female)\n",
|
92 |
+
"Đã lưu 1_10.wav\n",
|
93 |
+
"✅ Audio saved as 1_11.wav (gTTS - Female)\n",
|
94 |
+
"Đã lưu 1_11.wav\n",
|
95 |
+
"✅ Audio saved as 1_12.wav (gTTS - Female)\n",
|
96 |
+
"Đã lưu 1_12.wav\n",
|
97 |
+
"✅ Audio saved as 1_13.wav (gTTS - Female)\n",
|
98 |
+
"Đã lưu 1_13.wav\n",
|
99 |
+
"✅ Audio saved as 1_14.wav (gTTS - Female)\n",
|
100 |
+
"Đã lưu 1_14.wav\n",
|
101 |
+
"✅ Audio saved as 1_15.wav (gTTS - Female)\n",
|
102 |
+
"Đã lưu 1_15.wav\n",
|
103 |
+
"✅ Audio saved as 1_16.wav (gTTS - Female)\n",
|
104 |
+
"Đã lưu 1_16.wav\n",
|
105 |
+
"✅ Audio saved as 1_17.wav (gTTS - Female)\n",
|
106 |
+
"Đã lưu 1_17.wav\n",
|
107 |
+
"✅ Audio saved as 1_2.wav (gTTS - Female)\n",
|
108 |
+
"Đã lưu 1_2.wav\n",
|
109 |
+
"✅ Audio saved as 1_3.wav (gTTS - Female)\n",
|
110 |
+
"Đã lưu 1_3.wav\n",
|
111 |
+
"✅ Audio saved as 1_4.wav (gTTS - Female)\n",
|
112 |
+
"Đã lưu 1_4.wav\n",
|
113 |
+
"✅ Audio saved as 1_5.wav (gTTS - Female)\n",
|
114 |
+
"Đã lưu 1_5.wav\n",
|
115 |
+
"✅ Audio saved as 1_6.wav (gTTS - Female)\n",
|
116 |
+
"Đã lưu 1_6.wav\n",
|
117 |
+
"✅ Audio saved as 1_7.wav (gTTS - Female)\n",
|
118 |
+
"Đã lưu 1_7.wav\n",
|
119 |
+
"✅ Audio saved as 1_8.wav (gTTS - Female)\n",
|
120 |
+
"Đã lưu 1_8.wav\n",
|
121 |
+
"✅ Audio saved as 1_9.wav (gTTS - Female)\n",
|
122 |
+
"Đã lưu 1_9.wav\n",
|
123 |
+
"✅ Audio saved as 2_1.wav (gTTS - Female)\n",
|
124 |
+
"Đã lưu 2_1.wav\n",
|
125 |
+
"✅ Audio saved as 2_10.wav (gTTS - Female)\n",
|
126 |
+
"Đã lưu 2_10.wav\n",
|
127 |
+
"✅ Audio saved as 2_11.wav (gTTS - Female)\n",
|
128 |
+
"Đã lưu 2_11.wav\n",
|
129 |
+
"✅ Audio saved as 2_12.wav (gTTS - Female)\n",
|
130 |
+
"Đã lưu 2_12.wav\n",
|
131 |
+
"✅ Audio saved as 2_13.wav (gTTS - Female)\n",
|
132 |
+
"Đã lưu 2_13.wav\n",
|
133 |
+
"✅ Audio saved as 2_14.wav (gTTS - Female)\n",
|
134 |
+
"Đã lưu 2_14.wav\n",
|
135 |
+
"✅ Audio saved as 2_15.wav (gTTS - Female)\n",
|
136 |
+
"Đã lưu 2_15.wav\n",
|
137 |
+
"✅ Audio saved as 2_16.wav (gTTS - Female)\n",
|
138 |
+
"Đã lưu 2_16.wav\n",
|
139 |
+
"✅ Audio saved as 2_17.wav (gTTS - Female)\n",
|
140 |
+
"Đã lưu 2_17.wav\n",
|
141 |
+
"✅ Audio saved as 2_18.wav (gTTS - Female)\n",
|
142 |
+
"Đã lưu 2_18.wav\n",
|
143 |
+
"✅ Audio saved as 2_2.wav (gTTS - Female)\n",
|
144 |
+
"Đã lưu 2_2.wav\n",
|
145 |
+
"✅ Audio saved as 2_3.wav (gTTS - Female)\n",
|
146 |
+
"Đã lưu 2_3.wav\n",
|
147 |
+
"✅ Audio saved as 2_4.wav (gTTS - Female)\n",
|
148 |
+
"Đã lưu 2_4.wav\n",
|
149 |
+
"✅ Audio saved as 2_5.wav (gTTS - Female)\n",
|
150 |
+
"Đã lưu 2_5.wav\n",
|
151 |
+
"✅ Audio saved as 2_6.wav (gTTS - Female)\n",
|
152 |
+
"Đã lưu 2_6.wav\n",
|
153 |
+
"✅ Audio saved as 2_7.wav (gTTS - Female)\n",
|
154 |
+
"Đã lưu 2_7.wav\n",
|
155 |
+
"✅ Audio saved as 2_8.wav (gTTS - Female)\n",
|
156 |
+
"Đã lưu 2_8.wav\n",
|
157 |
+
"✅ Audio saved as 2_9.wav (gTTS - Female)\n",
|
158 |
+
"Đã lưu 2_9.wav\n",
|
159 |
+
"✅ Audio saved as 3_1.wav (gTTS - Female)\n",
|
160 |
+
"Đã lưu 3_1.wav\n",
|
161 |
+
"✅ Audio saved as 3_10.wav (gTTS - Female)\n",
|
162 |
+
"Đã lưu 3_10.wav\n",
|
163 |
+
"✅ Audio saved as 3_11.wav (gTTS - Female)\n",
|
164 |
+
"Đã lưu 3_11.wav\n",
|
165 |
+
"✅ Audio saved as 3_12.wav (gTTS - Female)\n",
|
166 |
+
"Đã lưu 3_12.wav\n",
|
167 |
+
"✅ Audio saved as 3_14.wav (gTTS - Female)\n",
|
168 |
+
"Đã lưu 3_14.wav\n",
|
169 |
+
"✅ Audio saved as 3_17.wav (gTTS - Female)\n",
|
170 |
+
"Đã lưu 3_17.wav\n",
|
171 |
+
"✅ Audio saved as 3_18.wav (gTTS - Female)\n",
|
172 |
+
"Đã lưu 3_18.wav\n",
|
173 |
+
"✅ Audio saved as 3_19.wav (gTTS - Female)\n",
|
174 |
+
"Đã lưu 3_19.wav\n",
|
175 |
+
"✅ Audio saved as 3_2.wav (gTTS - Female)\n",
|
176 |
+
"Đã lưu 3_2.wav\n",
|
177 |
+
"✅ Audio saved as 3_3.wav (gTTS - Female)\n",
|
178 |
+
"Đã lưu 3_3.wav\n",
|
179 |
+
"✅ Audio saved as 3_4.wav (gTTS - Female)\n",
|
180 |
+
"Đã lưu 3_4.wav\n",
|
181 |
+
"✅ Audio saved as 3_5.wav (gTTS - Female)\n",
|
182 |
+
"Đã lưu 3_5.wav\n",
|
183 |
+
"✅ Audio saved as 3_6.wav (gTTS - Female)\n",
|
184 |
+
"Đã lưu 3_6.wav\n",
|
185 |
+
"✅ Audio saved as 3_7.wav (gTTS - Female)\n",
|
186 |
+
"Đã lưu 3_7.wav\n",
|
187 |
+
"✅ Audio saved as 3_8.wav (gTTS - Female)\n",
|
188 |
+
"Đã lưu 3_8.wav\n",
|
189 |
+
"✅ Audio saved as 3_9.wav (gTTS - Female)\n",
|
190 |
+
"Đã lưu 3_9.wav\n"
|
191 |
+
]
|
192 |
+
}
|
193 |
+
],
|
194 |
+
"source": [
|
195 |
+
"for text_file in text_files:\n",
|
196 |
+
" with open(f\"../data/text/{text_file}\", \"r\", encoding=\"utf-8\") as file:\n",
|
197 |
+
" content = file.read()\n",
|
198 |
+
" audio_file = text_file.replace(\"txt\",\"wav\")\n",
|
199 |
+
" text_to_speech(content, audio_file)"
|
200 |
+
]
|
201 |
+
}
|
202 |
+
],
|
203 |
+
"metadata": {
|
204 |
+
"kernelspec": {
|
205 |
+
"display_name": "base",
|
206 |
+
"language": "python",
|
207 |
+
"name": "python3"
|
208 |
+
},
|
209 |
+
"language_info": {
|
210 |
+
"codemirror_mode": {
|
211 |
+
"name": "ipython",
|
212 |
+
"version": 3
|
213 |
+
},
|
214 |
+
"file_extension": ".py",
|
215 |
+
"mimetype": "text/x-python",
|
216 |
+
"name": "python",
|
217 |
+
"nbconvert_exporter": "python",
|
218 |
+
"pygments_lexer": "ipython3",
|
219 |
+
"version": "3.12.7"
|
220 |
+
}
|
221 |
+
},
|
222 |
+
"nbformat": 4,
|
223 |
+
"nbformat_minor": 2
|
224 |
+
}
|
notebook/text_to_video.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
src/image_gen.py
ADDED
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from huggingface_hub import InferenceClient
|
2 |
+
import os
|
3 |
+
import glob
|
4 |
+
from collections import defaultdict
|
5 |
+
import google.generativeai as genai
|
6 |
+
from tqdm import tqdm
|
7 |
+
from huggingface_hub.utils import HfHubHTTPError
|
8 |
+
import random
|
9 |
+
import time
|
10 |
+
from dotenv import load_dotenv
|
11 |
+
|
12 |
+
load_dotenv()
|
13 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
14 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
15 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
16 |
+
client = InferenceClient(provider="hf-inference", api_key=HF_TOKEN)
|
17 |
+
|
18 |
+
def split_text_for_images(number_of_images):
|
19 |
+
with open("./data/text/text.txt", "r", encoding="utf-8") as file:
|
20 |
+
text = file.read().strip()
|
21 |
+
|
22 |
+
total_length = len(text)
|
23 |
+
chunk_size = total_length // number_of_images # Độ dài trung bình của mỗi đoạn
|
24 |
+
|
25 |
+
chunks = []
|
26 |
+
start = 0
|
27 |
+
|
28 |
+
for i in range(number_of_images):
|
29 |
+
# Xác định điểm kết thúc gần nhất tại dấu câu (nếu có)
|
30 |
+
end = start + chunk_size
|
31 |
+
if i < number_of_images - 1:
|
32 |
+
while end < total_length and text[end] not in ".!?":
|
33 |
+
end += 1 # Mở rộng đến dấu câu gần nhất để tránh cắt ngang câu
|
34 |
+
if end < total_length - 1:
|
35 |
+
end += 1 # Bao gồm cả dấu câu vào đoạn
|
36 |
+
|
37 |
+
chunk = text[start:end].strip()
|
38 |
+
chunks.append(chunk)
|
39 |
+
start = end # Bắt đầu đoạn tiếp theo từ đây
|
40 |
+
|
41 |
+
return chunks
|
42 |
+
def describe_image(description, detail_level="short", perspective="neutral", emotion=None, time_setting=None, art_style=None):
|
43 |
+
"""
|
44 |
+
Nhận một đoạn văn mô tả chi tiết và trả về một câu mô tả hình ảnh theo các tùy chỉnh.
|
45 |
+
|
46 |
+
Args:
|
47 |
+
description (str): Đoạn văn mô tả chi tiết.
|
48 |
+
detail_level (str): Mức độ chi tiết ("short" hoặc "detailed").
|
49 |
+
perspective (str): Góc nhìn ("subjective" hoặc "neutral").
|
50 |
+
emotion (str, optional): Cảm xúc chủ đạo (nếu có, ví dụ: "mysterious", "romantic").
|
51 |
+
time_setting (str, optional): Bối cảnh thời gian (ví dụ: "modern", "medieval", "futuristic").
|
52 |
+
art_style (str, optional): Phong cách nghệ thuật (ví dụ: "realistic", "abstract", "sketch").
|
53 |
+
|
54 |
+
Returns:
|
55 |
+
str: Một câu mô tả hình ảnh theo yêu cầu.
|
56 |
+
"""
|
57 |
+
|
58 |
+
prompt = f"""
|
59 |
+
Bạn là chuyên gia mô tả hình ảnh. Hãy đọc đoạn mô tả dưới đây và tạo một mô tả hình ảnh theo các tiêu chí sau:
|
60 |
+
- Mức độ chi tiết: {"Ngắn gọn" if detail_level == "short" else "Chi tiết"}.
|
61 |
+
- Góc nhìn: {"Chủ quan" if perspective == "subjective" else "Trung lập"}.
|
62 |
+
{f"- Cảm xúc chủ đạo: {emotion}." if emotion else ""}
|
63 |
+
{f"- Bối cảnh thời gian: {time_setting}." if time_setting else ""}
|
64 |
+
{f"- Phong cách nghệ thuật: {art_style}." if art_style else ""}
|
65 |
+
|
66 |
+
Đoạn mô tả:
|
67 |
+
{description}
|
68 |
+
|
69 |
+
Hãy tạo một mô tả hình ảnh phù hợp với yêu cầu trên bằng Tiếng Anh.
|
70 |
+
"""
|
71 |
+
|
72 |
+
try:
|
73 |
+
model = genai.GenerativeModel("gemini-pro")
|
74 |
+
response = model.generate_content(prompt)
|
75 |
+
return response.text.strip()
|
76 |
+
except Exception as e:
|
77 |
+
print(f"Lỗi khi gọi API Gemini: {e}")
|
78 |
+
return ""
|
79 |
+
def generate_image(prompt, output_path, style=None, color_palette=None):
|
80 |
+
model="stabilityai/stable-diffusion-3.5-large"
|
81 |
+
"""
|
82 |
+
Tạo hình ảnh từ mô tả văn bản với các tùy chỉnh linh hoạt.
|
83 |
+
|
84 |
+
:param prompt: Mô tả hình ảnh đầu vào.
|
85 |
+
:param output_path: Đường dẫn lưu ảnh đầu ra.
|
86 |
+
:param model: Mô hình AI sử dụng để tạo ảnh.
|
87 |
+
:param style: Phong cách hình ảnh (nếu có, ví dụ: 'realistic', 'anime', 'cyberpunk').
|
88 |
+
:param color_palette: Bảng màu ưu tiên (nếu có, ví dụ: 'vibrant', 'monochrome').
|
89 |
+
"""
|
90 |
+
custom_prompt = prompt
|
91 |
+
|
92 |
+
if style:
|
93 |
+
custom_prompt += f" in {style} style"
|
94 |
+
if color_palette:
|
95 |
+
custom_prompt += f" with {color_palette} color scheme"
|
96 |
+
|
97 |
+
image = client.text_to_image(custom_prompt, model=model)
|
98 |
+
image.save(output_path)
|
99 |
+
print(f"✅Image saved at {output_path}")
|
100 |
+
def image_gen(number_of_images = 3,detail_level = "short", perspective="neutral", emotion=None, time_setting=None, art_style=None, style=None, color_palette=None):
|
101 |
+
texts = split_text_for_images(number_of_images)
|
102 |
+
index = 0
|
103 |
+
for text in tqdm(texts, desc="Processing", unit="image"):
|
104 |
+
output_path = f"./data/image/{index}.png"
|
105 |
+
prompt = describe_image(text, detail_level, perspective, emotion, time_setting, art_style)
|
106 |
+
print(prompt)
|
107 |
+
|
108 |
+
# Cơ chế retry với backoff
|
109 |
+
max_retries = 5
|
110 |
+
retry_count = 0
|
111 |
+
|
112 |
+
while retry_count < max_retries:
|
113 |
+
try:
|
114 |
+
generate_image(prompt, output_path, style, color_palette)
|
115 |
+
time.sleep(60) # Chờ sau khi tạo ảnh thành công
|
116 |
+
break # Nếu thành công thì thoát khỏi vòng lặp retry
|
117 |
+
except HfHubHTTPError as e:
|
118 |
+
print(f"Lỗi khi gọi API: {e}")
|
119 |
+
retry_count += 1
|
120 |
+
wait_time = 2 ** retry_count + random.uniform(0, 1) # Exponential backoff
|
121 |
+
print(f"Thử lại sau {wait_time:.2f} giây...")
|
122 |
+
time.sleep(wait_time)
|
123 |
+
index += 1
|
124 |
+
os.remove("./data/text/text.txt")
|
125 |
+
if __name__ == "__main__":
|
126 |
+
image_gen(number_of_images = 3, detail_level="short", perspective="neutral", emotion="sad", time_setting="classic", art_style="realistic", style="anime", color_palette="monochrome")
|
src/text_processing.py
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import fitz
|
3 |
+
from docx import Document
|
4 |
+
import google.generativeai as genai
|
5 |
+
from dotenv import load_dotenv
|
6 |
+
|
7 |
+
load_dotenv()
|
8 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
9 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
10 |
+
|
11 |
+
####################### - TEXT EXTRACTION - #######################
|
12 |
+
def extract_text_from_pdf(pdf_path):
|
13 |
+
# Mở file PDF
|
14 |
+
doc = fitz.open(pdf_path)
|
15 |
+
text = ""
|
16 |
+
for page_num in range(doc.page_count):
|
17 |
+
page = doc.load_page(page_num)
|
18 |
+
text += page.get_text()
|
19 |
+
return text
|
20 |
+
|
21 |
+
def extract_text_from_docx(docx_path):
|
22 |
+
# Mở file DOCX
|
23 |
+
doc = Document(docx_path)
|
24 |
+
text = ""
|
25 |
+
for para in doc.paragraphs:
|
26 |
+
text += para.text + "\n"
|
27 |
+
return text
|
28 |
+
|
29 |
+
def extract_text_from_file(file_path):
|
30 |
+
# Kiểm tra loại file và gọi hàm tương ứng
|
31 |
+
file_extension = os.path.splitext(file_path)[1].lower()
|
32 |
+
|
33 |
+
if file_extension == '.pdf':
|
34 |
+
return extract_text_from_pdf(file_path)
|
35 |
+
elif file_extension == '.docx':
|
36 |
+
return extract_text_from_docx(file_path)
|
37 |
+
else:
|
38 |
+
raise ValueError("Unsupported file format. Only PDF and DOCX are supported.")
|
39 |
+
####################### - SEMANTIC CHUNKING - #######################
|
40 |
+
def split_text_by_semantics(text):
|
41 |
+
prompt = f"""
|
42 |
+
Bạn là một chuyên gia xử lý văn bản. Hãy chia văn bản sau thành một số đoạn có ý nghĩa sao cho mỗi đoạn vừa đủ để giải thích trong khoảng 3 đến 5 câu.
|
43 |
+
|
44 |
+
Văn bản:
|
45 |
+
{text}
|
46 |
+
|
47 |
+
Định dạng đầu ra:
|
48 |
+
- Phần 1: [Nội dung]
|
49 |
+
- Phần 2: [Nội dung]
|
50 |
+
- Phần 3: [Nội dung]
|
51 |
+
"""
|
52 |
+
|
53 |
+
try:
|
54 |
+
model = genai.GenerativeModel("gemini-pro")
|
55 |
+
response = model.generate_content(prompt)
|
56 |
+
result_text = response.text.strip()
|
57 |
+
|
58 |
+
chunks = result_text.split("- Phần ")
|
59 |
+
chunks = [chunk.strip() for chunk in chunks if chunk]
|
60 |
+
return chunks
|
61 |
+
except Exception as e:
|
62 |
+
print(f"Lỗi khi gọi API Gemini: {e}")
|
63 |
+
return []
|
64 |
+
|
65 |
+
####################### - CONTENT GENERATION - #######################
|
66 |
+
def generate_explaination_for_chunks(chunks, analysis_level='basic', writting_style='academic', word_lower_limit=100, word_upper_limit=150):
|
67 |
+
"""
|
68 |
+
Phân tích nội dung của văn bản theo mức độ và phong cách mong muốn.
|
69 |
+
|
70 |
+
:param chunks: Danh sách các đoạn văn bản cần phân tích.
|
71 |
+
:param text: Toàn bộ văn bản gốc.
|
72 |
+
:param analysis_level: Mức độ phân tích ('basic' hoặc 'detailed').
|
73 |
+
:param writting_style: Phong cách phân tích ('academic', 'popular', 'creative', 'humorous').
|
74 |
+
:param word_limit: Số từ ước lượng cho mỗi phần tóm tắt.
|
75 |
+
:return: Danh sách các phân tích tương ứng với từng đoạn.
|
76 |
+
"""
|
77 |
+
|
78 |
+
level_prompts = {
|
79 |
+
'basic': "Hãy đưa ra một bản tóm tắt ngắn gọn, tập trung vào nội dung chính.",
|
80 |
+
'detailed': "Hãy phân tích chuyên sâu từng phần, làm rõ ý nghĩa, ngữ cảnh và các yếu tố quan trọng."
|
81 |
+
}
|
82 |
+
|
83 |
+
writting_style_prompts = {
|
84 |
+
'academic': "Phân tích theo phong cách học thuật, sử dụng ngôn ngữ chuyên sâu và lập luận chặt chẽ.",
|
85 |
+
'popular': "Trình bày theo phong cách phổ thông, dễ hiểu và phù hợp với nhiều đối tượng.",
|
86 |
+
'creative': "Giải thích một cách sáng tạo, sử dụng hình ảnh ẩn dụ và cách diễn đạt thú vị.",
|
87 |
+
'humorous': "Phân tích theo phong cách hài hước, thêm vào yếu tố vui nhộn và bất ngờ."
|
88 |
+
}
|
89 |
+
|
90 |
+
overview_prompt = f"""
|
91 |
+
Đây là một văn bản có nội dung quan trọng. Bạn sẽ phân tích từng phần theo mức độ '{analysis_level}' và phong cách '{writting_style}'.
|
92 |
+
Văn bản gồm các phần sau: {', '.join([f'Phần {i+1}' for i in range(len(chunks))])}.
|
93 |
+
{level_prompts[analysis_level]}
|
94 |
+
{writting_style_prompts[writting_style]}
|
95 |
+
Mỗi phần không vượt quá {word_upper_limit} từ và không ít hơn {word_lower_limit} từ.
|
96 |
+
"""
|
97 |
+
|
98 |
+
try:
|
99 |
+
model = genai.GenerativeModel("gemini-pro")
|
100 |
+
response = model.generate_content(overview_prompt)
|
101 |
+
overview_text = response.text.strip()
|
102 |
+
|
103 |
+
explanations = []
|
104 |
+
for idx, chunk in enumerate(chunks, start=1):
|
105 |
+
part_prompt = f"""
|
106 |
+
Phân tích phần {idx} của văn bản.
|
107 |
+
{level_prompts[analysis_level]}
|
108 |
+
{writting_style_prompts[writting_style]}
|
109 |
+
Nội dung phần này:
|
110 |
+
{chunk}
|
111 |
+
Hãy đảm bảo phần tóm tắt không vượt quá {word_upper_limit} từ và không ít hơn {word_lower_limit}.
|
112 |
+
"""
|
113 |
+
|
114 |
+
part_response = model.generate_content(part_prompt)
|
115 |
+
explanations.append(part_response.text.strip())
|
116 |
+
|
117 |
+
return explanations
|
118 |
+
|
119 |
+
except Exception as e:
|
120 |
+
print(f"Lỗi khi gọi API Gemini: {e}")
|
121 |
+
return []
|
122 |
+
def text_processing(file_path, analysis_level='basic', writting_style='academic', word_lower_limit = 100, word_upper_limit = 150):
|
123 |
+
# Trích xuất văn bản từ file PDF
|
124 |
+
text = extract_text_from_file(file_path=file_path)
|
125 |
+
with open("./data/text/text.txt", "w", encoding="utf-8") as f:
|
126 |
+
f.write(text)
|
127 |
+
# Tách văn bản theo ngữ nghĩa
|
128 |
+
semantic_chunks = split_text_by_semantics(text)
|
129 |
+
|
130 |
+
# Tạo thuyết minh cho từng phần semantic chunk
|
131 |
+
explanations = generate_explaination_for_chunks(semantic_chunks, analysis_level=analysis_level, writting_style = writting_style, word_lower_limit = word_lower_limit, word_upper_limit=word_upper_limit)
|
132 |
+
|
133 |
+
# Tạo thư mục nếu chưa tồn tại
|
134 |
+
output_dir = "./data/text/"
|
135 |
+
os.makedirs(output_dir, exist_ok=True)
|
136 |
+
|
137 |
+
# Lưu từng câu vào file riêng biệt
|
138 |
+
for chunk_idx, explanation in enumerate(explanations, start=1):
|
139 |
+
# Tách đoạn phân tích thành các câu
|
140 |
+
sentences = explanation.split('.')
|
141 |
+
|
142 |
+
for sentence_idx, sentence in enumerate(sentences, start=1):
|
143 |
+
sentence = sentence.strip() # Loại bỏ khoảng trắng thừa
|
144 |
+
if sentence: # Kiểm tra nếu câu không rỗng
|
145 |
+
output_file = os.path.join(output_dir, f"{chunk_idx}_{sentence_idx}.txt") # Tên file dạng "chunkID_sentenceID.txt"
|
146 |
+
with open(output_file, "w", encoding="utf-8") as f:
|
147 |
+
f.write(sentence.replace("*","") + ".") # Giữ dấu chấm cuối câu
|
148 |
+
print(f"Đã lưu: {output_file}")
|
149 |
+
####################### - MAIN CODE - #######################
|
150 |
+
if __name__ == "__main__":
|
151 |
+
text_processing(file_path = "./data/input/sample_3.pdf")
|
src/text_to_speech.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from transformers import VitsModel, AutoTokenizer
|
3 |
+
import torchaudio
|
4 |
+
import os
|
5 |
+
from gtts import gTTS
|
6 |
+
|
7 |
+
def generate_audio(text, filename="output.mp3", gender="female", speed="normal"):
|
8 |
+
"""
|
9 |
+
Convert text to speech and save it as an audio file.
|
10 |
+
|
11 |
+
Parameters:
|
12 |
+
text (str): The text to convert.
|
13 |
+
filename (str): The output file name.
|
14 |
+
gender (str): "male" (use MMS-TTS) or "female" (use gTTS).
|
15 |
+
speed (str): "slow", "normal", or "fast" (only for gTTS).
|
16 |
+
"""
|
17 |
+
lang = "vi"
|
18 |
+
|
19 |
+
if gender.lower() == "female":
|
20 |
+
# gTTS chỉ có giọng nữ
|
21 |
+
speed_mapping = {"slow": True, "normal": False, "fast": False}
|
22 |
+
slow = speed_mapping.get(speed.lower(), False)
|
23 |
+
|
24 |
+
tts = gTTS(text=text, lang=lang, slow=slow)
|
25 |
+
tts.save(filename)
|
26 |
+
print(f"✅ Audio saved as {filename}")
|
27 |
+
|
28 |
+
elif gender.lower() == "male":
|
29 |
+
# MMS-TTS cho giọng nam
|
30 |
+
model = VitsModel.from_pretrained("facebook/mms-tts-vie")
|
31 |
+
tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-vie")
|
32 |
+
|
33 |
+
inputs = tokenizer(text, return_tensors="pt")
|
34 |
+
with torch.no_grad():
|
35 |
+
output = model(**inputs).waveform
|
36 |
+
|
37 |
+
# Lưu file âm thanh
|
38 |
+
torchaudio.save(filename, output, 24000, backend="sox_io")
|
39 |
+
print(f"✅ Audio saved as {filename}")
|
40 |
+
|
41 |
+
else:
|
42 |
+
print("⚠️ Giọng không hợp lệ! Chỉ hỗ trợ 'male' hoặc 'female'.")
|
43 |
+
def text_to_speech(gender, speed):
|
44 |
+
text_folder = "./data/text"
|
45 |
+
text_files = sorted([f for f in os.listdir(text_folder) if f.endswith('.txt') and f != "text.txt"])
|
46 |
+
for text_file in text_files:
|
47 |
+
with open(f"./data/text/{text_file}", "r", encoding="utf-8") as file:
|
48 |
+
content = file.read()
|
49 |
+
audio_file = text_file.replace("txt","wav")
|
50 |
+
generate_audio(content, f"./data/audio/{audio_file}", gender=gender, speed=speed)
|
51 |
+
if __name__ == "__main__":
|
52 |
+
text_to_speech(gender = "female", speed = "fast")
|
src/text_to_video.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from moviepy.video.io.VideoFileClip import VideoFileClip, AudioFileClip
|
2 |
+
from moviepy.video.VideoClip import TextClip, ImageClip
|
3 |
+
from moviepy.video.compositing.CompositeVideoClip import concatenate_videoclips, CompositeVideoClip
|
4 |
+
from moviepy.audio.AudioClip import concatenate_audioclips
|
5 |
+
from moviepy.video.tools.subtitles import SubtitlesClip
|
6 |
+
from moviepy.video.VideoClip import ColorClip
|
7 |
+
import os
|
8 |
+
from itertools import accumulate
|
9 |
+
import pysrt
|
10 |
+
|
11 |
+
|
12 |
+
def format_time(seconds):
|
13 |
+
"""Chuyển đổi thời gian (giây) thành định dạng SRT hh:mm:ss,ms"""
|
14 |
+
mins, sec = divmod(seconds, 60)
|
15 |
+
hours, mins = divmod(mins, 60)
|
16 |
+
return f"{int(hours):02}:{int(mins):02}:{int(sec):02},{int((sec % 1) * 1000):03}"
|
17 |
+
def get_audio_duration(audio_path):
|
18 |
+
# Lọc các file có đuôi .wav
|
19 |
+
audio_paths = os.listdir(audio_path)
|
20 |
+
audio_list = [file for file in audio_paths if file.endswith(".wav")]
|
21 |
+
|
22 |
+
# Khởi tạo danh sách audio duration
|
23 |
+
duration_list = []
|
24 |
+
|
25 |
+
for audio_path in audio_list:
|
26 |
+
# Mở file âm thanh và lấy thời gian
|
27 |
+
with AudioFileClip(f"./data/audio/{audio_path}") as audio:
|
28 |
+
duration_list.append(audio.duration)
|
29 |
+
# Tính tổng tích lũy thời gian
|
30 |
+
duration_list = [format_time(time) for time in list(accumulate(duration_list))]
|
31 |
+
return [format_time(0.0)] + duration_list
|
32 |
+
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')])
|
36 |
+
# Duyệt qua các mốc thời gian và file text
|
37 |
+
for i in range(len(duration_time) - 1):
|
38 |
+
start_time = duration_time[i]
|
39 |
+
end_time = duration_time[i + 1]
|
40 |
+
|
41 |
+
# Lấy tên file text tương ứng
|
42 |
+
text_file = text_list[i]
|
43 |
+
|
44 |
+
text_path = os.path.join(text_folder, text_file)
|
45 |
+
|
46 |
+
if os.path.exists(text_path):
|
47 |
+
with open(text_path, 'r', encoding='utf-8') as f:
|
48 |
+
text = f.read().strip()
|
49 |
+
# Thêm phần subtitle vào chuỗi kết quả
|
50 |
+
subtitle += f"{subtitle_index}\n{start_time} --> {end_time}\n{text}\n\n"
|
51 |
+
subtitle_index += 1
|
52 |
+
else:
|
53 |
+
print(f"File {text_file} không tồn tại!")
|
54 |
+
|
55 |
+
# Lưu vào file SRT
|
56 |
+
with open(output_srt, 'w', encoding='utf-8') as f:
|
57 |
+
f.write(subtitle)
|
58 |
+
def concatenate_audio_files(audio_folder, output_audio_path):
|
59 |
+
# Lọc tất cả các file âm thanh .wav trong thư mục
|
60 |
+
audio_clips = []
|
61 |
+
|
62 |
+
for file in sorted(os.listdir(audio_folder)):
|
63 |
+
if file.endswith('.wav'):
|
64 |
+
audio_path = os.path.join(audio_folder, file)
|
65 |
+
audio_clip = AudioFileClip(audio_path)
|
66 |
+
audio_clips.append(audio_clip)
|
67 |
+
|
68 |
+
# Ghép tất cả các audio clip lại với nhau
|
69 |
+
final_audio = concatenate_audioclips(audio_clips)
|
70 |
+
|
71 |
+
# Lưu kết quả vào file output
|
72 |
+
final_audio.write_audiofile(output_audio_path, codec = 'pcm_s16le')
|
73 |
+
|
74 |
+
print(f"File audio đã được lưu tại: {output_audio_path}")
|
75 |
+
def create_video_from_images(image_folder, audio_path, output_video_path):
|
76 |
+
# Đọc file âm thanh để lấy thời lượng
|
77 |
+
audio = AudioFileClip(audio_path)
|
78 |
+
total_duration = audio.duration # Tổng thời lượng video bằng thời lượng audio
|
79 |
+
|
80 |
+
# Đọc tất cả các file ảnh trong thư mục và sắp xếp theo tên
|
81 |
+
image_files = [file for file in sorted(os.listdir(image_folder)) if file.endswith("png")]
|
82 |
+
|
83 |
+
if not image_files:
|
84 |
+
raise ValueError("Không tìm thấy ảnh nào trong thư mục!")
|
85 |
+
|
86 |
+
# Tính thời lượng hiển thị cho mỗi ảnh
|
87 |
+
duration_per_image = total_duration / len(image_files)
|
88 |
+
|
89 |
+
# Tạo danh sách các clip ảnh
|
90 |
+
clips = [ImageClip(f"./data/image/{img}").with_duration(duration_per_image).resized(width=1280) for img in image_files]
|
91 |
+
|
92 |
+
# Ghép các clip ảnh lại với nhau
|
93 |
+
final_video = concatenate_videoclips(clips, method="chain")
|
94 |
+
|
95 |
+
# Gán âm thanh vào video
|
96 |
+
final_video .audio = audio
|
97 |
+
|
98 |
+
# Xuất video
|
99 |
+
final_video.write_videofile(output_video_path, codec="libx264", audio_codec="pcm_s16le", fps=24)
|
100 |
+
|
101 |
+
print(f"Video đã được lưu tại: {output_video_path}")
|
102 |
+
def wrap_text(text, max_width):
|
103 |
+
"""
|
104 |
+
Tự động xuống dòng để vừa với chiều rộng max_width.
|
105 |
+
"""
|
106 |
+
import textwrap
|
107 |
+
return "\n".join(textwrap.wrap(text, width=max_width))
|
108 |
+
def add_subtitles_to_video(video_path, subtitle_path, output_video_path):
|
109 |
+
"""
|
110 |
+
Thêm phụ đề từ file .srt trực tiếp vào video.
|
111 |
+
|
112 |
+
:param video_path: Đường dẫn video gốc
|
113 |
+
:param subtitle_path: Đường dẫn file .srt
|
114 |
+
:param output_video_path: Đường dẫn lưu video đầu ra
|
115 |
+
"""
|
116 |
+
|
117 |
+
# Đọc file video
|
118 |
+
video = VideoFileClip(video_path)
|
119 |
+
|
120 |
+
# Đọc file .srt
|
121 |
+
subs = pysrt.open(subtitle_path)
|
122 |
+
|
123 |
+
subtitle_clips = [] # Danh sách các đoạn phụ đề
|
124 |
+
|
125 |
+
# Xử lý từng dòng phụ đề
|
126 |
+
for sub in subs:
|
127 |
+
# Chuyển thời gian thành giây
|
128 |
+
start_time = sub.start.ordinal / 1000 # Chuyển từ milliseconds sang giây
|
129 |
+
end_time = sub.end.ordinal / 1000
|
130 |
+
font = "./data/BeVietnamPro-Light.ttf"
|
131 |
+
# Tạo clip phụ đề
|
132 |
+
txt_clip = TextClip(font=font, text=wrap_text(sub.text, max_width=85), font_size=30, stroke_color="black", stroke_width=3, color="#fff")
|
133 |
+
|
134 |
+
# Đặt vị trí hiển thị (giữa phía dưới video)
|
135 |
+
txt_clip = txt_clip.with_position(('center', 'bottom')).with_duration(end_time - start_time).with_start(start_time)
|
136 |
+
|
137 |
+
subtitle_clips.append(txt_clip)
|
138 |
+
|
139 |
+
# Ghép phụ đề vào video
|
140 |
+
final_video = CompositeVideoClip([video] + subtitle_clips)
|
141 |
+
|
142 |
+
# Xuất video với phụ đề
|
143 |
+
final_video.write_videofile(output_video_path, fps=video.fps, codec='libx264', threads=4)
|
144 |
+
|
145 |
+
print(f"Video với phụ đề đã được lưu tại: {output_video_path}")
|
146 |
+
def text_to_video():
|
147 |
+
duration_time = get_audio_duration("./data/audio")
|
148 |
+
create_srt_from_time_and_text(duration_time, './data/text', './data/output/subtitle.srt')
|
149 |
+
concatenate_audio_files("./data/audio","./data/output/final_audio.wav")
|
150 |
+
create_video_from_images("./data/image","./data/output/final_audio.wav","./data/output/output.mp4")
|
151 |
+
add_subtitles_to_video("./data/output/output.mp4", "./data/output/subtitle.srt", "./data/output/final_output.mp4")
|
152 |
+
if __name__ == "__main__":
|
153 |
+
text_to_video()
|
test/test.ipynb
ADDED
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 70,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [],
|
8 |
+
"source": [
|
9 |
+
"from moviepy.video.io.VideoFileClip import VideoFileClip, AudioFileClip\n",
|
10 |
+
"from moviepy.video.VideoClip import TextClip, ImageClip\n",
|
11 |
+
"from moviepy.video.compositing.CompositeVideoClip import concatenate_videoclips, CompositeVideoClip\n",
|
12 |
+
"from moviepy.audio.AudioClip import concatenate_audioclips\n",
|
13 |
+
"from moviepy.video.tools.subtitles import SubtitlesClip\n",
|
14 |
+
"from moviepy.video.VideoClip import ColorClip\n",
|
15 |
+
"import os\n",
|
16 |
+
"from tqdm import tqdm\n",
|
17 |
+
"from itertools import accumulate\n",
|
18 |
+
"import pysrt"
|
19 |
+
]
|
20 |
+
},
|
21 |
+
{
|
22 |
+
"cell_type": "code",
|
23 |
+
"execution_count": 29,
|
24 |
+
"metadata": {},
|
25 |
+
"outputs": [],
|
26 |
+
"source": [
|
27 |
+
"def format_time(seconds):\n",
|
28 |
+
" \"\"\"Chuyển đổi thời gian (giây) thành định dạng SRT hh:mm:ss,ms\"\"\"\n",
|
29 |
+
" mins, sec = divmod(seconds, 60)\n",
|
30 |
+
" hours, mins = divmod(mins, 60)\n",
|
31 |
+
" return f\"{int(hours):02}:{int(mins):02}:{int(sec):02},{int((sec % 1) * 1000):03}\"\n",
|
32 |
+
"def get_audio_duration(audio_path):\n",
|
33 |
+
" # Lọc các file có đuôi .wav\n",
|
34 |
+
" audio_paths = os.listdir(audio_path)\n",
|
35 |
+
" audio_list = [file for file in audio_paths if file.endswith(\".wav\")]\n",
|
36 |
+
" \n",
|
37 |
+
" # Khởi tạo danh sách audio duration\n",
|
38 |
+
" duration_list = []\n",
|
39 |
+
" \n",
|
40 |
+
" for audio_path in audio_list:\n",
|
41 |
+
" # Mở file âm thanh và lấy thời gian\n",
|
42 |
+
" with AudioFileClip(f\"../data/audio/{audio_path}\") as audio:\n",
|
43 |
+
" duration_list.append(audio.duration)\n",
|
44 |
+
" # Tính tổng tích lũy thời gian\n",
|
45 |
+
" duration_list = [format_time(time) for time in list(accumulate(duration_list))]\n",
|
46 |
+
" return [format_time(0.0)] + duration_list"
|
47 |
+
]
|
48 |
+
},
|
49 |
+
{
|
50 |
+
"cell_type": "code",
|
51 |
+
"execution_count": 31,
|
52 |
+
"metadata": {},
|
53 |
+
"outputs": [],
|
54 |
+
"source": [
|
55 |
+
"duration_time = get_audio_duration(\"../data/audio\")"
|
56 |
+
]
|
57 |
+
},
|
58 |
+
{
|
59 |
+
"cell_type": "code",
|
60 |
+
"execution_count": 43,
|
61 |
+
"metadata": {},
|
62 |
+
"outputs": [],
|
63 |
+
"source": [
|
64 |
+
"def create_srt_from_time_and_text(duration_time, text_folder, output_srt):\n",
|
65 |
+
" subtitle = \"\"\n",
|
66 |
+
" subtitle_index = 1\n",
|
67 |
+
" text_list = sorted([file for file in os.listdir(text_folder) if file.endswith('txt')])\n",
|
68 |
+
" # Duyệt qua các mốc thời gian và file text\n",
|
69 |
+
" for i in range(len(duration_time) - 1):\n",
|
70 |
+
" start_time = duration_time[i]\n",
|
71 |
+
" end_time = duration_time[i + 1]\n",
|
72 |
+
" \n",
|
73 |
+
" # Lấy tên file text tương ứng\n",
|
74 |
+
" text_file = text_list[i] # Giả sử các file có tên như '1.txt', '2.txt', ...\n",
|
75 |
+
" \n",
|
76 |
+
" text_path = os.path.join(text_folder, text_file)\n",
|
77 |
+
" \n",
|
78 |
+
" if os.path.exists(text_path):\n",
|
79 |
+
" with open(text_path, 'r', encoding='utf-8') as f:\n",
|
80 |
+
" text = f.read().strip()\n",
|
81 |
+
" # Thêm phần subtitle vào chuỗi kết quả\n",
|
82 |
+
" subtitle += f\"{subtitle_index}\\n{start_time} --> {end_time}\\n{text}\\n\\n\"\n",
|
83 |
+
" subtitle_index += 1\n",
|
84 |
+
" else:\n",
|
85 |
+
" print(f\"File {text_file} không tồn tại!\")\n",
|
86 |
+
" \n",
|
87 |
+
" # Lưu vào file SRT\n",
|
88 |
+
" with open(output_srt, 'w', encoding='utf-8') as f:\n",
|
89 |
+
" f.write(subtitle)"
|
90 |
+
]
|
91 |
+
},
|
92 |
+
{
|
93 |
+
"cell_type": "code",
|
94 |
+
"execution_count": 44,
|
95 |
+
"metadata": {},
|
96 |
+
"outputs": [],
|
97 |
+
"source": [
|
98 |
+
"create_srt_from_time_and_text(duration_time, '../data/text', 'subtitle.srt')"
|
99 |
+
]
|
100 |
+
},
|
101 |
+
{
|
102 |
+
"cell_type": "code",
|
103 |
+
"execution_count": 56,
|
104 |
+
"metadata": {},
|
105 |
+
"outputs": [],
|
106 |
+
"source": [
|
107 |
+
"def concatenate_audio_files(audio_folder, output_audio_path):\n",
|
108 |
+
" # Lọc tất cả các file âm thanh .wav trong thư mục\n",
|
109 |
+
" audio_clips = []\n",
|
110 |
+
" \n",
|
111 |
+
" for file in sorted(os.listdir(audio_folder)):\n",
|
112 |
+
" if file.endswith('.wav'):\n",
|
113 |
+
" audio_path = os.path.join(audio_folder, file)\n",
|
114 |
+
" audio_clip = AudioFileClip(audio_path)\n",
|
115 |
+
" audio_clips.append(audio_clip)\n",
|
116 |
+
" \n",
|
117 |
+
" # Ghép tất cả các audio clip lại với nhau\n",
|
118 |
+
" final_audio = concatenate_audioclips(audio_clips)\n",
|
119 |
+
" \n",
|
120 |
+
" # Lưu kết quả vào file output\n",
|
121 |
+
" final_audio.write_audiofile(output_audio_path, codec = 'pcm_s16le')\n",
|
122 |
+
"\n",
|
123 |
+
" print(f\"File audio đã được lưu tại: {output_audio_path}\")"
|
124 |
+
]
|
125 |
+
},
|
126 |
+
{
|
127 |
+
"cell_type": "code",
|
128 |
+
"execution_count": 58,
|
129 |
+
"metadata": {},
|
130 |
+
"outputs": [
|
131 |
+
{
|
132 |
+
"name": "stderr",
|
133 |
+
"output_type": "stream",
|
134 |
+
"text": [
|
135 |
+
"chunk: 1%| | 107/11954 [00:14<27:40, 7.14it/s, now=None]"
|
136 |
+
]
|
137 |
+
},
|
138 |
+
{
|
139 |
+
"name": "stdout",
|
140 |
+
"output_type": "stream",
|
141 |
+
"text": [
|
142 |
+
"MoviePy - Writing audio in final_audio.wav\n"
|
143 |
+
]
|
144 |
+
},
|
145 |
+
{
|
146 |
+
"name": "stderr",
|
147 |
+
"output_type": "stream",
|
148 |
+
"text": [
|
149 |
+
"chunk: 1%| | 107/11954 [00:25<46:35, 4.24it/s, now=None]"
|
150 |
+
]
|
151 |
+
},
|
152 |
+
{
|
153 |
+
"name": "stdout",
|
154 |
+
"output_type": "stream",
|
155 |
+
"text": [
|
156 |
+
"MoviePy - Done.\n",
|
157 |
+
"File audio đã được lưu tại: final_audio.wav\n"
|
158 |
+
]
|
159 |
+
}
|
160 |
+
],
|
161 |
+
"source": [
|
162 |
+
"concatenate_audio_files(\"../data/audio\",\"final_audio.wav\")"
|
163 |
+
]
|
164 |
+
},
|
165 |
+
{
|
166 |
+
"cell_type": "code",
|
167 |
+
"execution_count": 111,
|
168 |
+
"metadata": {},
|
169 |
+
"outputs": [],
|
170 |
+
"source": [
|
171 |
+
"def create_video_from_images(image_folder, audio_path, output_video_path):\n",
|
172 |
+
" # Đọc file âm thanh để lấy thời lượng\n",
|
173 |
+
" audio = AudioFileClip(audio_path)\n",
|
174 |
+
" total_duration = audio.duration # Tổng thời lượng video bằng thời lượng audio\n",
|
175 |
+
"\n",
|
176 |
+
" # Đọc tất cả các file ảnh trong thư mục và sắp xếp theo tên\n",
|
177 |
+
" image_files = [file for file in sorted(os.listdir(image_folder))]\n",
|
178 |
+
" \n",
|
179 |
+
" if not image_files:\n",
|
180 |
+
" raise ValueError(\"Không tìm thấy ảnh nào trong thư mục!\")\n",
|
181 |
+
"\n",
|
182 |
+
" # Tính thời lượng hiển thị cho mỗi ảnh\n",
|
183 |
+
" duration_per_image = total_duration / len(image_files)\n",
|
184 |
+
"\n",
|
185 |
+
" # Tạo danh sách các clip ảnh\n",
|
186 |
+
" clips = [ImageClip(f\"../data/image/{img}\").with_duration(duration_per_image).resized(width=1280) for img in image_files]\n",
|
187 |
+
"\n",
|
188 |
+
" # Ghép các clip ảnh lại với nhau\n",
|
189 |
+
" final_video = concatenate_videoclips(clips, method=\"chain\")\n",
|
190 |
+
" \n",
|
191 |
+
" # Gán âm thanh vào video\n",
|
192 |
+
" final_video .audio = audio\n",
|
193 |
+
"\n",
|
194 |
+
" # Xuất video\n",
|
195 |
+
" final_video.write_videofile(output_video_path, codec=\"libx264\", audio_codec=\"pcm_s16le\", fps=24)\n",
|
196 |
+
"\n",
|
197 |
+
" print(f\"Video đã được lưu tại: {output_video_path}\")"
|
198 |
+
]
|
199 |
+
},
|
200 |
+
{
|
201 |
+
"cell_type": "code",
|
202 |
+
"execution_count": 112,
|
203 |
+
"metadata": {},
|
204 |
+
"outputs": [
|
205 |
+
{
|
206 |
+
"name": "stdout",
|
207 |
+
"output_type": "stream",
|
208 |
+
"text": [
|
209 |
+
"MoviePy - Building video output.mp4.\n",
|
210 |
+
"MoviePy - Writing audio in outputTEMP_MPY_wvf_snd.wav\n"
|
211 |
+
]
|
212 |
+
},
|
213 |
+
{
|
214 |
+
"name": "stderr",
|
215 |
+
"output_type": "stream",
|
216 |
+
"text": [
|
217 |
+
" \r"
|
218 |
+
]
|
219 |
+
},
|
220 |
+
{
|
221 |
+
"name": "stdout",
|
222 |
+
"output_type": "stream",
|
223 |
+
"text": [
|
224 |
+
"MoviePy - Done.\n",
|
225 |
+
"MoviePy - Writing video output.mp4\n",
|
226 |
+
"\n"
|
227 |
+
]
|
228 |
+
},
|
229 |
+
{
|
230 |
+
"name": "stderr",
|
231 |
+
"output_type": "stream",
|
232 |
+
"text": [
|
233 |
+
" \r"
|
234 |
+
]
|
235 |
+
},
|
236 |
+
{
|
237 |
+
"name": "stdout",
|
238 |
+
"output_type": "stream",
|
239 |
+
"text": [
|
240 |
+
"MoviePy - Done !\n",
|
241 |
+
"MoviePy - video ready output.mp4\n",
|
242 |
+
"Video đã được lưu tại: output.mp4\n"
|
243 |
+
]
|
244 |
+
}
|
245 |
+
],
|
246 |
+
"source": [
|
247 |
+
"create_video_from_images(\"../data/image\",\"final_audio.wav\",\"output.mp4\")"
|
248 |
+
]
|
249 |
+
},
|
250 |
+
{
|
251 |
+
"cell_type": "code",
|
252 |
+
"execution_count": 91,
|
253 |
+
"metadata": {},
|
254 |
+
"outputs": [],
|
255 |
+
"source": [
|
256 |
+
"def wrap_text(text, max_width):\n",
|
257 |
+
" \"\"\"\n",
|
258 |
+
" Tự động xuống dòng để vừa với chiều rộng max_width.\n",
|
259 |
+
" \"\"\"\n",
|
260 |
+
" import textwrap\n",
|
261 |
+
" return \"\\n\".join(textwrap.wrap(text, width=max_width))"
|
262 |
+
]
|
263 |
+
},
|
264 |
+
{
|
265 |
+
"cell_type": "code",
|
266 |
+
"execution_count": 96,
|
267 |
+
"metadata": {},
|
268 |
+
"outputs": [],
|
269 |
+
"source": [
|
270 |
+
"def add_subtitles_to_video(video_path, subtitle_path, output_video_path):\n",
|
271 |
+
" \"\"\"\n",
|
272 |
+
" Thêm phụ đề từ file .srt trực tiếp vào video.\n",
|
273 |
+
" \n",
|
274 |
+
" :param video_path: Đường dẫn video gốc\n",
|
275 |
+
" :param subtitle_path: Đường dẫn file .srt\n",
|
276 |
+
" :param output_video_path: Đường dẫn lưu video đầu ra\n",
|
277 |
+
" \"\"\"\n",
|
278 |
+
" \n",
|
279 |
+
" # Đọc file video\n",
|
280 |
+
" video = VideoFileClip(video_path)\n",
|
281 |
+
"\n",
|
282 |
+
" # Đọc file .srt\n",
|
283 |
+
" subs = pysrt.open(subtitle_path)\n",
|
284 |
+
"\n",
|
285 |
+
" subtitle_clips = [] # Danh sách các đoạn phụ đề\n",
|
286 |
+
"\n",
|
287 |
+
" # Xử lý từng dòng phụ đề\n",
|
288 |
+
" for sub in subs:\n",
|
289 |
+
" # Chuyển thời gian thành giây\n",
|
290 |
+
" start_time = sub.start.ordinal / 1000 # Chuyển từ milliseconds sang giây\n",
|
291 |
+
" end_time = sub.end.ordinal / 1000\n",
|
292 |
+
" font = \"../BeVietnamPro-Light.ttf\"\n",
|
293 |
+
" # Tạo clip phụ đề\n",
|
294 |
+
" 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",
|
295 |
+
" \n",
|
296 |
+
" # Đặt vị trí hiển thị (giữa phía dưới video)\n",
|
297 |
+
" txt_clip = txt_clip.with_position(('center', 'bottom')).with_duration(end_time - start_time).with_start(start_time)\n",
|
298 |
+
" \n",
|
299 |
+
" subtitle_clips.append(txt_clip)\n",
|
300 |
+
"\n",
|
301 |
+
" # Ghép phụ đề vào video\n",
|
302 |
+
" final_video = CompositeVideoClip([video] + subtitle_clips)\n",
|
303 |
+
"\n",
|
304 |
+
" # Xuất video với phụ đề\n",
|
305 |
+
" final_video.write_videofile(output_video_path, fps=video.fps, codec='libx264', threads=4)\n",
|
306 |
+
"\n",
|
307 |
+
" print(f\"Video với phụ đề đã được lưu tại: {output_video_path}\")"
|
308 |
+
]
|
309 |
+
},
|
310 |
+
{
|
311 |
+
"cell_type": "code",
|
312 |
+
"execution_count": 97,
|
313 |
+
"metadata": {},
|
314 |
+
"outputs": [
|
315 |
+
{
|
316 |
+
"name": "stdout",
|
317 |
+
"output_type": "stream",
|
318 |
+
"text": [
|
319 |
+
"{'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",
|
320 |
+
"/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",
|
321 |
+
"MoviePy - Building video final_output.mp4.\n",
|
322 |
+
"MoviePy - Writing audio in final_outputTEMP_MPY_wvf_snd.mp3\n"
|
323 |
+
]
|
324 |
+
},
|
325 |
+
{
|
326 |
+
"name": "stderr",
|
327 |
+
"output_type": "stream",
|
328 |
+
"text": [
|
329 |
+
" \r"
|
330 |
+
]
|
331 |
+
},
|
332 |
+
{
|
333 |
+
"name": "stdout",
|
334 |
+
"output_type": "stream",
|
335 |
+
"text": [
|
336 |
+
"MoviePy - Done.\n",
|
337 |
+
"MoviePy - Writing video final_output.mp4\n",
|
338 |
+
"\n"
|
339 |
+
]
|
340 |
+
},
|
341 |
+
{
|
342 |
+
"name": "stderr",
|
343 |
+
"output_type": "stream",
|
344 |
+
"text": [
|
345 |
+
" "
|
346 |
+
]
|
347 |
+
},
|
348 |
+
{
|
349 |
+
"name": "stdout",
|
350 |
+
"output_type": "stream",
|
351 |
+
"text": [
|
352 |
+
"MoviePy - Done !\n",
|
353 |
+
"MoviePy - video ready final_output.mp4\n",
|
354 |
+
"Video với phụ đề đã được lưu tại: final_output.mp4\n"
|
355 |
+
]
|
356 |
+
},
|
357 |
+
{
|
358 |
+
"name": "stderr",
|
359 |
+
"output_type": "stream",
|
360 |
+
"text": [
|
361 |
+
"\r"
|
362 |
+
]
|
363 |
+
}
|
364 |
+
],
|
365 |
+
"source": [
|
366 |
+
"add_subtitles_to_video(\"output.mp4\", \"subtitle.srt\", \"final_output.mp4\")"
|
367 |
+
]
|
368 |
+
}
|
369 |
+
],
|
370 |
+
"metadata": {
|
371 |
+
"kernelspec": {
|
372 |
+
"display_name": "base",
|
373 |
+
"language": "python",
|
374 |
+
"name": "python3"
|
375 |
+
},
|
376 |
+
"language_info": {
|
377 |
+
"codemirror_mode": {
|
378 |
+
"name": "ipython",
|
379 |
+
"version": 3
|
380 |
+
},
|
381 |
+
"file_extension": ".py",
|
382 |
+
"mimetype": "text/x-python",
|
383 |
+
"name": "python",
|
384 |
+
"nbconvert_exporter": "python",
|
385 |
+
"pygments_lexer": "ipython3",
|
386 |
+
"version": "3.12.7"
|
387 |
+
}
|
388 |
+
},
|
389 |
+
"nbformat": 4,
|
390 |
+
"nbformat_minor": 2
|
391 |
+
}
|