TDN-M commited on
Commit
08ae9e1
·
verified ·
1 Parent(s): 4aae87c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +225 -218
app.py CHANGED
@@ -1,219 +1,226 @@
1
- import asyncio
2
- import mimetypes
3
- import openai
4
- import os
5
- import tempfile
6
- import glob
7
- import fitz # PyMuPDF
8
- import random
9
- import gradio as gr
10
- from docx import Document
11
- from audio_processing import async_text_to_speech, text_to_speech
12
- from content_generation import create_content, CONTENT_TYPES
13
- from video_processing import create_video_func
14
- from moviepy.editor import AudioFileClip, VideoFileClip, CompositeAudioClip
15
- from utils import (combine_videos, get_pexels_video, get_bgm_file, download_video)
16
- from video_processing import create_video
17
- from content_generation import create_content, CONTENT_TYPES
18
-
19
- def create_docx(content, output_path):
20
- """
21
- Tạo file docx từ nội dung.
22
- """
23
- doc = Document()
24
- doc.add_paragraph(content)
25
- doc.save(output_path)
26
-
27
- def process_pdf(file_path):
28
- """
29
- Xử lý file PDF và trích xuất nội dung.
30
- """
31
- doc = fitz.open(file_path)
32
- text = ""
33
- for page in doc:
34
- text += page.get_text()
35
- return text
36
-
37
- def process_docx(file_path):
38
- """
39
- Xử lý file DOCX và trích xuất nội dung.
40
- """
41
- doc = Document(file_path)
42
- text = ""
43
- for para in doc.paragraphs:
44
- text += para.text
45
- return text
46
-
47
- def get_bgm_file_list():
48
- """
49
- Trả về danh sách các tệp nhạc nền.
50
- """
51
- # Giả sử bạn có một thư mục chứa các tệp nhạc nền
52
- song_dir = "/data/bg-music"
53
- return [os.path.basename(file) for file in glob.glob(os.path.join(song_dir, "*.mp3"))]
54
-
55
- # Lấy API key từ biến môi trường
56
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
57
-
58
- # Khởi tạo client OpenAI
59
- openai.api_key = OPENAI_API_KEY
60
-
61
- def extract_key_contents(script, num_contents=10):
62
- """
63
- Trích xuất các ý chính từ script.
64
- """
65
- try:
66
- response = openai.ChatCompletion.create(
67
- model="gpt-3.5-turbo",
68
- messages=[
69
- {"role": "system", "content": f"Bạn là một chuyên gia phân tích nội dung. Hãy trích xuất chính xác {num_contents} ý chính quan trọng nhất từ đoạn văn sau, mỗi ý không quá 20 từ."},
70
- {"role": "user", "content": script}
71
- ]
72
- )
73
- key_contents = response.choices[0].message.content.split('\n')
74
- return key_contents[:num_contents]
75
- except Exception as e:
76
- print(f"Lỗi khi trích xuất nội dung: {str(e)}")
77
- return []
78
-
79
- # Giao diện Gradio
80
- def interface():
81
- with gr.Blocks() as app:
82
- gr.Markdown("# Ứng dụng Tạo Nội dung và Video")
83
-
84
- with gr.Tab("Tạo Nội dung"):
85
- prompt = gr.Textbox(label="Nhập yêu cầu nội dung")
86
- file_upload = gr.File(label="Tải lên file kèm theo", type="filepath")
87
-
88
- # Sử dụng gr.Radio thay gr.CheckboxGroup
89
- content_type = gr.Radio(label="Chọn loại nội dung",
90
- choices=CONTENT_TYPES,
91
- value=None) # Giá trị mặc định là không có gì được chọn
92
-
93
- content_button = gr.Button("Tạo Nội dung")
94
- content_output = gr.Textbox(label="Nội dung tạo ra", interactive=True)
95
- confirm_button = gr.Button("Xác nhận nội dung")
96
- download_docx = gr.File(label="Tải xuống file DOCX", interactive=False)
97
- download_audio = gr.File(label="Tải xuống file âm thanh", interactive=False)
98
- status_message = gr.Label(label="Trạng thái")
99
-
100
- def generate_content(prompt, file, content_type):
101
- try:
102
- status = "Đang xử lý..."
103
- if file and os.path.exists(file):
104
- mime_type, _ = mimetypes.guess_type(file)
105
- if mime_type == "application/pdf":
106
- file_content = process_pdf(file)
107
- prompt = f"{prompt}\n\nDưới đây là nội dung của file tài liệu:\n\n{file_content}"
108
- elif mime_type in (
109
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
110
- "application/msword"):
111
- file_content = process_docx(file)
112
- prompt = f"{prompt}\n\nDưới đây là nội dung của file tài liệu:\n\n{file_content}"
113
- else:
114
- raise ValueError("Định dạng file không được hỗ trợ.")
115
-
116
- if not content_type:
117
- raise ValueError("Vui lòng chọn một loại nội dung")
118
-
119
- script_content = create_content(prompt, content_type, "Tiếng Việt")
120
- docx_path = "script.docx"
121
- create_docx(script_content, docx_path)
122
-
123
- status = "Đã tạo nội dung thành công!"
124
- return script_content, docx_path, status
125
- except Exception as e:
126
- status = f"Đã xảy ra lỗi: {str(e)}"
127
- return "", None, status
128
-
129
- async def confirm_content(content):
130
- docx_path = "script.docx"
131
- create_docx(content, docx_path)
132
-
133
- audio_path = await async_text_to_speech(content, "alloy", "Tiếng Việt")
134
- return docx_path, audio_path, "Nội dung đã được xác nhận và âm thanh đã được tạo!"
135
-
136
- content_button.click(generate_content,
137
- inputs=[prompt, file_upload, content_type],
138
- outputs=[content_output, download_docx, status_message])
139
-
140
- confirm_button.click(lambda x: asyncio.run(confirm_content(x)),
141
- inputs=[content_output],
142
- outputs=[download_docx, download_audio, status_message])
143
-
144
- # Định nghĩa danh sách giọng đọc
145
- VOICES = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
146
-
147
- with gr.Tab("Tạo Âm thanh"):
148
- text_input = gr.Textbox(label="Nhập văn bản để chuyển đổi")
149
- voice_select = gr.Dropdown(label="Chọn giọng đọc", choices=VOICES) # Dropdown cho voice_select
150
- audio_button = gr.Button("Tạo Âm thanh")
151
- audio_output = gr.Audio(label="Âm thanh tạo ra")
152
- download_audio = gr.File(label="Tải xuống file âm thanh", interactive=False)
153
-
154
- def text_to_speech_func(text, voice):
155
- try:
156
- audio_path = text_to_speech(text, voice, "Tiếng Việt")
157
- return audio_path, audio_path
158
- except Exception as e:
159
- print(f"Lỗi khi chuyển đổi văn bản thành giọng nói: {e}")
160
- return None, None
161
-
162
- audio_button.click(text_to_speech_func,
163
- inputs=[text_input, voice_select],
164
- outputs=[audio_output, download_audio])
165
-
166
- with gr.Tab("Tạo Video"):
167
- script_input = gr.Textbox(label="Nhập kịch bản")
168
- audio_file = gr.File(label="Chọn file âm thanh", type="filepath")
169
- keywords_output = gr.Textbox(label="Từ khóa", interactive=True)
170
- max_clip_duration = gr.Slider(minimum=2, maximum=5, step=1, label="Thời lượng tối đa mỗi video (giây)")
171
- join_order = gr.Checkbox(label="Ghép ngẫu nhiên", value=True)
172
- bgm_files = gr.Dropdown(choices=get_bgm_file_list(), label="Chọn nhạc nền")
173
- video_output = gr.Video(label="Video tạo ra")
174
- video_button = gr.Button("Tạo Video")
175
- status_message = gr.Label(label="Trạng thái") # Thêm thông báo trạng thái
176
-
177
- def create_video_func(script, audio_file, max_clip_duration, join_order, bgm_file):
178
- """ Tạo video từ các thông tin đầu vào. """
179
- try:
180
- status_message.update("Đang xử lý...") # Cập nhật trạng thái
181
-
182
- # 1. Tính toán thời lượng video
183
- audio_clip = AudioFileClip(audio_file)
184
- video_duration = audio_clip.duration
185
-
186
- # 2. Trích xuất từ khóa từ kịch bản
187
- keywords = extract_key_contents(script)
188
- video_paths = []
189
- for keyword in keywords:
190
- video_url = get_pexels_video(keyword.strip())
191
- if video_url:
192
- video_path = download_video(video_url)
193
- video_paths.append(video_path)
194
-
195
- # 3. Ghép video
196
- temp_dir = tempfile.mkdtemp()
197
- if join_order:
198
- random.shuffle(video_paths)
199
- combined_video_path = os.path.join(temp_dir, "combined_video.mp4")
200
- combine_videos(combined_video_path, video_paths, audio_file, max_clip_duration)
201
-
202
- # 4. Gộp audio và nhạc nền
203
- final_video_path = "final_video.mp4"
204
- bgm_clip = AudioFileClip(bgm_file)
205
- final_audio = CompositeAudioClip([audio_clip, bgm_clip])
206
- final_video = VideoFileClip(combined_video_path).set_audio(final_audio)
207
- final_video.write_videofile(final_video_path)
208
-
209
- status_message.update("Video đã được tạo thành công!") # Cập nhật trạng thái
210
- return final_video_path
211
- except Exception as e:
212
- status_message.update(f"Lỗi khi tạo video: {e}") # Cập nhật trạng thái
213
- return None
214
- return app
215
-
216
- # Khởi chạy ứng dụng
217
- if __name__ == "__main__":
218
- app = interface()
 
 
 
 
 
 
 
219
  app.launch()
 
1
+ import asyncio
2
+ import mimetypes
3
+ import openai
4
+ import os
5
+ import tempfile
6
+ import glob
7
+ import fitz # PyMuPDF
8
+ import random
9
+ import gradio as gr
10
+ from docx import Document
11
+ from audio_processing import async_text_to_speech, text_to_speech
12
+ from content_generation import create_content, CONTENT_TYPES
13
+ from video_processing import create_video_func
14
+ from moviepy.editor import AudioFileClip, VideoFileClip, CompositeAudioClip
15
+ from utils import (combine_videos, get_pexels_video, get_bgm_file, download_video)
16
+ from video_processing import create_video
17
+ from content_generation import create_content, CONTENT_TYPES
18
+
19
+ def create_docx(content, output_path):
20
+ """
21
+ Tạo file docx từ nội dung.
22
+ """
23
+ doc = Document()
24
+ doc.add_paragraph(content)
25
+ doc.save(output_path)
26
+
27
+ def process_pdf(file_path):
28
+ """
29
+ Xử lý file PDF và trích xuất nội dung.
30
+ """
31
+ doc = fitz.open(file_path)
32
+ text = ""
33
+ for page in doc:
34
+ text += page.get_text()
35
+ return text
36
+
37
+ def process_docx(file_path):
38
+ """
39
+ Xử lý file DOCX và trích xuất nội dung.
40
+ """
41
+ doc = Document(file_path)
42
+ text = ""
43
+ for para in doc.paragraphs:
44
+ text += para.text
45
+ return text
46
+
47
+ def get_bgm_file_list():
48
+ """
49
+ Trả về danh sách các tệp nhạc nền.
50
+ """
51
+ # Giả sử bạn có một thư mục chứa các tệp nhạc nền
52
+ song_dir = "/data/bg-music"
53
+ return [os.path.basename(file) for file in glob.glob(os.path.join(song_dir, "*.mp3"))]
54
+
55
+ # Lấy API key từ biến môi trường
56
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
57
+
58
+ # Khởi tạo client OpenAI
59
+ openai.api_key = OPENAI_API_KEY
60
+
61
+ def extract_key_contents(script, num_contents=10):
62
+ """
63
+ Trích xuất các ý chính từ script.
64
+ """
65
+ try:
66
+ response = openai.ChatCompletion.create(
67
+ model="gpt-3.5-turbo",
68
+ messages=[
69
+ {"role": "system", "content": f"Bạn là một chuyên gia phân tích nội dung. Hãy trích xuất chính xác {num_contents} ý chính quan trọng nhất từ đoạn văn sau, mỗi ý không quá 20 từ."},
70
+ {"role": "user", "content": script}
71
+ ]
72
+ )
73
+ key_contents = response.choices[0].message.content.split('\n')
74
+ return key_contents[:num_contents]
75
+ except Exception as e:
76
+ print(f"Lỗi khi trích xuất nội dung: {str(e)}")
77
+ return []
78
+
79
+ # ... existing imports and functions ...
80
+
81
+ # Giao diện Gradio
82
+ def interface():
83
+ with gr.Blocks() as app:
84
+ gr.Markdown("# Ứng dụng Tạo Nội dung và Video")
85
+
86
+ with gr.Tab("Tạo Nội dung"):
87
+ prompt = gr.Textbox(label="Nhập yêu cầu nội dung")
88
+ file_upload = gr.File(label="Tải lên file kèm theo", type="filepath")
89
+
90
+ # Sử dụng gr.Radio thay vì gr.CheckboxGroup
91
+ content_type = gr.Radio(label="Chọn loại nội dung",
92
+ choices=CONTENT_TYPES,
93
+ value=None) # Giá trị mặc định là không có gì được chọn
94
+
95
+ content_button = gr.Button("Tạo Nội dung")
96
+ content_output = gr.Textbox(label="Nội dung tạo ra", interactive=True)
97
+ confirm_button = gr.Button("Xác nhận nội dung")
98
+ download_docx = gr.File(label="Tải xuống file DOCX", interactive=False)
99
+ download_audio = gr.File(label="Tải xuống file âm thanh", interactive=False)
100
+ status_message = gr.Label(label="Trạng thái")
101
+
102
+ def generate_content(prompt, file, content_type):
103
+ try:
104
+ status = "Đang xử lý..."
105
+ if file and os.path.exists(file):
106
+ mime_type, _ = mimetypes.guess_type(file)
107
+ if mime_type == "application/pdf":
108
+ file_content = process_pdf(file)
109
+ prompt = f"{prompt}\n\nDưới đây là nội dung của file tài liệu:\n\n{file_content}"
110
+ elif mime_type in (
111
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
112
+ "application/msword"):
113
+ file_content = process_docx(file)
114
+ prompt = f"{prompt}\n\nDưới đây nội dung của file tài liệu:\n\n{file_content}"
115
+ else:
116
+ raise ValueError("Định dạng file không được hỗ trợ.")
117
+
118
+ if not content_type:
119
+ raise ValueError("Vui lòng chọn một loại nội dung")
120
+
121
+ script_content = create_content(prompt, content_type, "Tiếng Việt")
122
+ docx_path = "script.docx"
123
+ create_docx(script_content, docx_path)
124
+
125
+ status = "Đã tạo nội dung thành công!"
126
+ return script_content, docx_path, status
127
+ except Exception as e:
128
+ status = f"Đã xảy ra lỗi: {str(e)}"
129
+ return "", None, status
130
+
131
+ async def confirm_content(content):
132
+ docx_path = "script.docx"
133
+ create_docx(content, docx_path)
134
+
135
+ audio_path = await async_text_to_speech(content, "alloy", "Tiếng Việt")
136
+ return docx_path, audio_path, "Nội dung đã được xác nhận và âm thanh đã được tạo!"
137
+
138
+ content_button.click(generate_content,
139
+ inputs=[prompt, file_upload, content_type],
140
+ outputs=[content_output, download_docx, status_message])
141
+
142
+ confirm_button.click(lambda x: asyncio.run(confirm_content(x)),
143
+ inputs=[content_output],
144
+ outputs=[download_docx, download_audio, status_message])
145
+
146
+ # Định nghĩa danh sách giọng đọc
147
+ VOICES = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
148
+
149
+ with gr.Tab("Tạo Âm thanh"):
150
+ text_input = gr.Textbox(label="Nhập văn bản để chuyển đổi")
151
+ voice_select = gr.Dropdown(label="Chọn giọng đọc", choices=VOICES) # Dropdown cho voice_select
152
+ audio_button = gr.Button("Tạo Âm thanh")
153
+ audio_output = gr.Audio(label="Âm thanh tạo ra")
154
+ download_audio = gr.File(label="Tải xuống file âm thanh", interactive=False)
155
+
156
+ def text_to_speech_func(text, voice):
157
+ try:
158
+ audio_path = text_to_speech(text, voice, "Tiếng Việt")
159
+ return audio_path, audio_path
160
+ except Exception as e:
161
+ print(f"Lỗi khi chuyển đổi văn bản thành giọng nói: {e}")
162
+ return None, None
163
+
164
+ audio_button.click(text_to_speech_func,
165
+ inputs=[text_input, voice_select],
166
+ outputs=[audio_output, download_audio])
167
+
168
+ with gr.Tab("Tạo Video"):
169
+ script_input = gr.Textbox(label="Nhập kịch bản")
170
+ audio_file = gr.File(label="Chọn file âm thanh", type="filepath")
171
+ keywords_output = gr.Textbox(label="Từ khóa", interactive=True)
172
+ max_clip_duration = gr.Slider(minimum=2, maximum=5, step=1, label="Thời lượng tối đa mỗi video (giây)")
173
+ join_order = gr.Checkbox(label="Ghép ngẫu nhiên", value=True)
174
+ bgm_files = gr.Dropdown(choices=get_bgm_file_list(), label="Chọn nhạc nền")
175
+ video_output = gr.Video(label="Video tạo ra")
176
+ video_button = gr.Button("Tạo Video")
177
+ status_message = gr.Label(label="Trạng thái") # Thêm thông báo trạng thái
178
+
179
+ def create_video_func(script, audio_file, max_clip_duration, join_order, bgm_file):
180
+ """ Tạo video từ các thông tin đầu vào. """
181
+ try:
182
+ status_message.update("Đang xử lý...") # Cập nhật trạng thái
183
+
184
+ # 1. Tính toán thời lượng video
185
+ audio_clip = AudioFileClip(audio_file)
186
+ video_duration = audio_clip.duration
187
+
188
+ # 2. Trích xuất từ khóa từ kịch bản
189
+ keywords = extract_key_contents(script)
190
+ video_paths = []
191
+ for keyword in keywords:
192
+ video_url = get_pexels_video(keyword.strip())
193
+ if video_url:
194
+ video_path = download_video(video_url)
195
+ video_paths.append(video_path)
196
+
197
+ # 3. Ghép video
198
+ temp_dir = tempfile.mkdtemp()
199
+ if join_order:
200
+ random.shuffle(video_paths)
201
+ combined_video_path = os.path.join(temp_dir, "combined_video.mp4")
202
+ combine_videos(combined_video_path, video_paths, audio_file, max_clip_duration)
203
+
204
+ # 4. Gộp audio và nhạc nền
205
+ final_video_path = "final_video.mp4"
206
+ bgm_clip = AudioFileClip(bgm_file)
207
+ final_audio = CompositeAudioClip([audio_clip, bgm_clip])
208
+ final_video = VideoFileClip(combined_video_path).set_audio(final_audio)
209
+ final_video.write_videofile(final_video_path)
210
+
211
+ status_message.update("Video đã được tạo thành công!") # Cập nhật trạng thái
212
+ return final_video_path
213
+ except Exception as e:
214
+ status_message.update(f"Lỗi khi tạo video: {e}") # Cập nhật trạng thái
215
+ return None
216
+
217
+ video_button.click(create_video_func,
218
+ inputs=[script_input, audio_file, max_clip_duration, join_order, bgm_files],
219
+ outputs=[video_output, status_message])
220
+
221
+ return app
222
+
223
+ # Khởi chạy ứng dụng
224
+ if __name__ == "__main__":
225
+ app = interface()
226
  app.launch()