File size: 7,065 Bytes
4fcacf9
bd1b97a
4fcacf9
 
 
 
f746763
7350c68
4fcacf9
1e23c4b
4fcacf9
2c5ffe4
 
 
a5481e4
 
 
 
 
 
c5adb9e
 
a5481e4
4fcacf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5ffe4
 
f746763
2c5ffe4
 
a5481e4
bd1b97a
a5481e4
bd1b97a
 
f746763
bd1b97a
f746763
2c5ffe4
 
 
f746763
 
 
 
c5adb9e
bd1b97a
 
c5adb9e
 
f746763
 
08ae9e1
1e23c4b
1c01c9c
1e23c4b
08ae9e1
f3595bc
 
 
 
 
 
 
2c5ffe4
c5adb9e
 
 
 
f3595bc
 
 
 
 
 
2c5ffe4
 
1e23c4b
08ae9e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e23c4b
08ae9e1
 
1e23c4b
08ae9e1
bd1b97a
 
 
 
08ae9e1
 
1e23c4b
08ae9e1
1e23c4b
08ae9e1
 
1e23c4b
 
 
 
 
 
08ae9e1
 
1e23c4b
 
2c5ffe4
 
 
1e23c4b
2c5ffe4
08ae9e1
 
 
 
cf030b8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import os
import mimetypes
import gradio as gr
from docx import Document
from content_generation import create_content, CONTENT_TYPES
from openai import OpenAI
from tts import generate_speech

# Khởi tạo client OpenAI với API key từ biến môi trường
client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))

# Đường dẫn đến thư mục chứa các file âm thanh
VOICES_DIR = "voices"

# Kiểm tra thư mục voices và các file trong đó
if not os.path.exists(VOICES_DIR):
    print(f"Thư mục {VOICES_DIR} không tồn tại.")
else:
    voice_files = [os.path.join(VOICES_DIR, f) for f in os.listdir(VOICES_DIR) if f.endswith(".wav")]
    print(f"Các file âm thanh trong thư mục {VOICES_DIR}: {voice_files}")
    if not voice_files:
        print(f"Không có file âm thanh nào trong thư mục {VOICES_DIR}.")

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 text_to_speech(content, voice_file):
    """
    Chuyển đổi nội dung thành giọng nói bằng hàm generate_speech từ tts.py.
    """
    try:
        print(f"Đường dẫn file âm thanh mẫu: {voice_file}")  # Log đường dẫn file
        if voice_file is None or not os.path.exists(voice_file):
            return f"Lỗi: File âm thanh mẫu không tồn tại hoặc không hợp lệ. Đường dẫn: {voice_file}"

        print(f"Chuyển đổi nội dung thành giọng nói: {content}")  # Log nội dung trước khi chuyển đổi
        output_audio = generate_speech(content, language="vi", speaker_wav=voice_file)
        print(f"File âm thanh đã được tạo: {output_audio}")  # Log file âm thanh
        return output_audio
    except Exception as e:
        return f"Lỗi khi chuyển đổi văn bản thành giọng nói: {str(e)}"

def convert_content_to_speech(content, voice_file):
    """
    Chuyển đổi nội dung thành giọng nói.
    """
    print(f"Giá trị của voice_file: {voice_file}")  # Log giá trị của voice_file
    if content is None or content.strip() == "":
        return "Lỗi: Nội dung trống hoặc không hợp lệ."
    if voice_file is None:
        return "Lỗi: Vui lòng chọn file âm thanh mẫu."
    return text_to_speech(content, voice_file)

def interface():
    with gr.Blocks() as app:
        gr.Markdown("# TTV@tdnm")

        with gr.Tab("Tạo Nội dung"):
            with gr.Row():
                with gr.Column():
                    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)  # Giá trị mặc định là không có gì được chọn
                    voice_files = [os.path.join(VOICES_DIR, f) for f in os.listdir(VOICES_DIR) if f.endswith(".wav")]
                    if voice_files:
                        voice_selector = gr.Dropdown(label="Chọn giọng đọc", choices=voice_files, value=voice_files[0])  # Đặt giá trị mặc định
                    else:
                        voice_selector = gr.Dropdown(label="Chọn giọng đọc", choices=[], value=None)  # Nếu không có file, để trống
                    content_button = gr.Button("Tạo Nội dung")
                
                with gr.Column():
                    content_output = gr.Textbox(label="Nội dung tạo ra", interactive=True)
                    download_docx = gr.File(label="Tải xuống file DOCX", interactive=False)
                    status_message = gr.Label(label="Trạng thái")
                    convert_to_speech_button = gr.Button("Chuyển đổi thành giọng nói")
                    audio_output = gr.Audio(label="Synthesised Audio", autoplay=True)  # Phát tự động

            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")
                    print(f"Nội dung từ LLM: {script_content}")  # Log nội dung từ LLM
                    if script_content is None:
                        raise ValueError("Nội dung từ LLM là None. Vui lòng kiểm tra lại hàm create_content.")

                    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)

            content_button.click(generate_content,
                                 inputs=[prompt, file_upload, content_type],
                                 outputs=[content_output, download_docx, status_message])

            convert_to_speech_button.click(convert_content_to_speech,
                                           inputs=[content_output, voice_selector],
                                           outputs=[audio_output])

    return app

# Khởi chạy ứng dụng
if __name__ == "__main__":
    app = interface()
    app.launch(share=True)