|
import asyncio
|
|
import mimetypes
|
|
import openai
|
|
import os
|
|
import tempfile
|
|
import glob
|
|
import fitz
|
|
import random
|
|
import gradio as gr
|
|
from docx import Document
|
|
from audio_processing import async_text_to_speech, text_to_speech
|
|
from content_generation import create_content, CONTENT_TYPES
|
|
from video_processing import create_video_func
|
|
from moviepy.editor import AudioFileClip, VideoFileClip, CompositeAudioClip
|
|
from utils import (combine_videos, get_pexels_video, get_bgm_file, download_video)
|
|
from video_processing import create_video
|
|
from content_generation import create_content, CONTENT_TYPES
|
|
|
|
def create_docx(content, output_path):
|
|
"""
|
|
Tạo file docx từ nội dung.
|
|
"""
|
|
doc = Document()
|
|
doc.add_paragraph(content)
|
|
doc.save(output_path)
|
|
|
|
def process_pdf(file_path):
|
|
"""
|
|
Xử lý file PDF và trích xuất nội dung.
|
|
"""
|
|
doc = fitz.open(file_path)
|
|
text = ""
|
|
for page in doc:
|
|
text += page.get_text()
|
|
return text
|
|
|
|
def process_docx(file_path):
|
|
"""
|
|
Xử lý file DOCX và trích xuất nội dung.
|
|
"""
|
|
doc = Document(file_path)
|
|
text = ""
|
|
for para in doc.paragraphs:
|
|
text += para.text
|
|
return text
|
|
|
|
def get_bgm_file_list():
|
|
"""
|
|
Trả về danh sách các tệp nhạc nền.
|
|
"""
|
|
|
|
song_dir = "/data/bg-music"
|
|
return [os.path.basename(file) for file in glob.glob(os.path.join(song_dir, "*.mp3"))]
|
|
|
|
|
|
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
|
|
|
|
|
openai.api_key = OPENAI_API_KEY
|
|
|
|
def extract_key_contents(script, num_contents=10):
|
|
"""
|
|
Trích xuất các ý chính từ script.
|
|
"""
|
|
try:
|
|
response = openai.ChatCompletion.create(
|
|
model="gpt-3.5-turbo",
|
|
messages=[
|
|
{"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ừ."},
|
|
{"role": "user", "content": script}
|
|
]
|
|
)
|
|
key_contents = response.choices[0].message.content.split('\n')
|
|
return key_contents[:num_contents]
|
|
except Exception as e:
|
|
print(f"Lỗi khi trích xuất nội dung: {str(e)}")
|
|
return []
|
|
|
|
|
|
def interface():
|
|
with gr.Blocks() as app:
|
|
gr.Markdown("# Ứng dụng Tạo Nội dung và Video")
|
|
|
|
with gr.Tab("Tạo Nội dung"):
|
|
prompt = gr.Textbox(label="Nhập yêu cầu nội dung")
|
|
file_upload = gr.File(label="Tải lên file kèm theo", type="filepath")
|
|
|
|
|
|
content_type = gr.Radio(label="Chọn loại nội dung",
|
|
choices=CONTENT_TYPES,
|
|
value=None)
|
|
|
|
content_button = gr.Button("Tạo Nội dung")
|
|
content_output = gr.Textbox(label="Nội dung tạo ra", interactive=True)
|
|
confirm_button = gr.Button("Xác nhận nội dung")
|
|
download_docx = gr.File(label="Tải xuống file DOCX", interactive=False)
|
|
download_audio = gr.File(label="Tải xuống file âm thanh", interactive=False)
|
|
status_message = gr.Label(label="Trạng thái")
|
|
|
|
def generate_content(prompt, file, content_type):
|
|
try:
|
|
status = "Đang xử lý..."
|
|
if file and os.path.exists(file):
|
|
mime_type, _ = mimetypes.guess_type(file)
|
|
if mime_type == "application/pdf":
|
|
file_content = process_pdf(file)
|
|
prompt = f"{prompt}\n\nDưới đây là nội dung của file tài liệu:\n\n{file_content}"
|
|
elif mime_type in (
|
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
"application/msword"):
|
|
file_content = process_docx(file)
|
|
prompt = f"{prompt}\n\nDưới đây là nội dung của file tài liệu:\n\n{file_content}"
|
|
else:
|
|
raise ValueError("Định dạng file không được hỗ trợ.")
|
|
|
|
if not content_type:
|
|
raise ValueError("Vui lòng chọn một loại nội dung")
|
|
|
|
script_content = create_content(prompt, content_type, "Tiếng Việt")
|
|
docx_path = "script.docx"
|
|
create_docx(script_content, docx_path)
|
|
|
|
status = "Đã tạo nội dung thành công!"
|
|
return script_content, docx_path, status
|
|
except Exception as e:
|
|
status = f"Đã xảy ra lỗi: {str(e)}"
|
|
return "", None, status
|
|
|
|
async def confirm_content(content):
|
|
docx_path = "script.docx"
|
|
create_docx(content, docx_path)
|
|
|
|
audio_path = await async_text_to_speech(content, "alloy", "Tiếng Việt")
|
|
return docx_path, audio_path, "Nội dung đã được xác nhận và âm thanh đã được tạo!"
|
|
|
|
content_button.click(generate_content,
|
|
inputs=[prompt, file_upload, content_type],
|
|
outputs=[content_output, download_docx, status_message])
|
|
|
|
confirm_button.click(lambda x: asyncio.run(confirm_content(x)),
|
|
inputs=[content_output],
|
|
outputs=[download_docx, download_audio, status_message])
|
|
|
|
|
|
VOICES = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
|
|
|
|
with gr.Tab("Tạo Âm thanh"):
|
|
text_input = gr.Textbox(label="Nhập văn bản để chuyển đổi")
|
|
voice_select = gr.Dropdown(label="Chọn giọng đọc", choices=VOICES)
|
|
audio_button = gr.Button("Tạo Âm thanh")
|
|
audio_output = gr.Audio(label="Âm thanh tạo ra")
|
|
download_audio = gr.File(label="Tải xuống file âm thanh", interactive=False)
|
|
|
|
def text_to_speech_func(text, voice):
|
|
try:
|
|
audio_path = text_to_speech(text, voice, "Tiếng Việt")
|
|
return audio_path, audio_path
|
|
except Exception as e:
|
|
print(f"Lỗi khi chuyển đổi văn bản thành giọng nói: {e}")
|
|
return None, None
|
|
|
|
audio_button.click(text_to_speech_func,
|
|
inputs=[text_input, voice_select],
|
|
outputs=[audio_output, download_audio])
|
|
|
|
with gr.Tab("Tạo Video"):
|
|
script_input = gr.Textbox(label="Nhập kịch bản")
|
|
audio_file = gr.File(label="Chọn file âm thanh", type="filepath")
|
|
keywords_output = gr.Textbox(label="Từ khóa", interactive=True)
|
|
max_clip_duration = gr.Slider(minimum=2, maximum=5, step=1, label="Thời lượng tối đa mỗi video (giây)")
|
|
join_order = gr.Checkbox(label="Ghép ngẫu nhiên", value=True)
|
|
bgm_files = gr.Dropdown(choices=get_bgm_file_list(), label="Chọn nhạc nền")
|
|
video_output = gr.Video(label="Video tạo ra")
|
|
video_button = gr.Button("Tạo Video")
|
|
status_message = gr.Label(label="Trạng thái")
|
|
|
|
def create_video_func(script, audio_file, max_clip_duration, join_order, bgm_file):
|
|
""" Tạo video từ các thông tin đầu vào. """
|
|
try:
|
|
status_message.update("Đang xử lý...")
|
|
|
|
|
|
audio_clip = AudioFileClip(audio_file)
|
|
video_duration = audio_clip.duration
|
|
|
|
|
|
keywords = extract_key_contents(script)
|
|
video_paths = []
|
|
for keyword in keywords:
|
|
video_url = get_pexels_video(keyword.strip())
|
|
if video_url:
|
|
video_path = download_video(video_url)
|
|
video_paths.append(video_path)
|
|
|
|
|
|
temp_dir = tempfile.mkdtemp()
|
|
if join_order:
|
|
random.shuffle(video_paths)
|
|
combined_video_path = os.path.join(temp_dir, "combined_video.mp4")
|
|
combine_videos(combined_video_path, video_paths, audio_file, max_clip_duration)
|
|
|
|
|
|
final_video_path = "final_video.mp4"
|
|
bgm_clip = AudioFileClip(bgm_file)
|
|
final_audio = CompositeAudioClip([audio_clip, bgm_clip])
|
|
final_video = VideoFileClip(combined_video_path).set_audio(final_audio)
|
|
final_video.write_videofile(final_video_path)
|
|
|
|
status_message.update("Video đã được tạo thành công!")
|
|
return final_video_path
|
|
except Exception as e:
|
|
status_message.update(f"Lỗi khi tạo video: {e}")
|
|
return None
|
|
return app
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app = interface()
|
|
app.launch() |