File size: 9,900 Bytes
dfecb3b
 
 
 
 
 
 
 
 
 
 
03bb32f
dfecb3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acf3a0a
dfecb3b
03bb32f
 
 
 
 
 
 
 
 
 
 
 
dfecb3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03bb32f
dfecb3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03bb32f
 
 
 
 
 
 
 
 
 
 
 
dfecb3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03bb32f
 
 
 
 
 
 
 
 
dfecb3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54ac269
dfecb3b
 
 
 
03bb32f
 
 
 
dfecb3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
from argparse import ArgumentParser
import gradio as gr
import mdtex2html
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation import GenerationConfig
import os
import webbrowser
import asyncio
import edge_tts
import base64
import time

# 获取当前脚本所在的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取当前目录的上一级目录
parent_dir = os.path.dirname(current_dir)
# 定义默认的检查点路径
DEFAULT_CKPT_PATH = os.path.join(parent_dir, 'INFJ')

# 创建wav_output文件夹路径
wav_output_dir = os.path.join(parent_dir, 'wav_output')
if not os.path.exists(wav_output_dir):
    os.makedirs(wav_output_dir)

# TTS参数
VOICE = "zh-CN-YunyangNeural"
RATE = "-1%"  # 降低语速
VOLUME = "-10%"  # 降低音量10%
OUTPUT_FILE = os.path.join(wav_output_dir, "input_audio.wav")  # 音频文件名

#创建default_video文件夹路径
default_video_dir = os.path.join(parent_dir, 'default_video')
if not os.path.exists(default_video_dir):
    os.makedirs(default_video_dir)
OUTPUT_DEFAULT_VIDEO=os.path.join(default_video_dir, "default.mp4")  # 默认视频文件名

# 待播放视频的路径
response_video_dir = os.path.join(parent_dir, 'response')
if not os.path.exists(response_video_dir):
    os.makedirs(response_video_dir)
RESPONSE_VIDEO=os.path.join(response_video_dir, "output.mp4")  # 生成视频文件名


def _get_args():
    parser = ArgumentParser()
    parser.add_argument("-c", "--checkpoint-path", type=str, default=DEFAULT_CKPT_PATH,
                        help="检查点名称或路径,默认为 %(default)r")
    parser.add_argument("--cpu-only", action="store_true", help="仅使用 CPU 运行演示")
    parser.add_argument("--share", action="store_true", default=True, help="为界面创建一个可公开分享的链接")
    parser.add_argument("--inbrowser", action="store_true", default=False, help="在默认浏览器的新标签页中自动启动界面")
    parser.add_argument("--server-port", type=int, default=8000, help="演示服务器端口")
    parser.add_argument("--server-name", type=str, default="127.0.0.1", help="演示服务器名称")
    args = parser.parse_args()
    return args

def _load_model_tokenizer(args):
    tokenizer = AutoTokenizer.from_pretrained(
        args.checkpoint_path, trust_remote_code=True, resume_download=False,
    )

    device_map = "cpu" if args.cpu_only else "auto"

    model = AutoModelForCausalLM.from_pretrained(
        args.checkpoint_path,
        device_map=device_map,
        trust_remote_code=True,
        resume_download=False,
    ).eval()

    config = GenerationConfig.from_pretrained(
        args.checkpoint_path, trust_remote_code=True, resume_download=False,
    )

    webbrowser.open(f"http://{args.server_name}:{args.server_port}")

    return model, tokenizer, config

def postprocess(self, y):
    if y is None:
        return []
    for i, (message, response) in enumerate(y):
        y[i] = (
            None if message is None else mdtex2html.convert(message),
            None if response is None else mdtex2html.convert(response),
        )
    return y

gr.Chatbot.postprocess = postprocess

def _parse_text(text):
    lines = text.split("\n")
    lines = [line for line in lines if line != ""]
    count = 0
    for i, line in enumerate(lines):
        if "```" in line:
            count += 1
            items = line.split("`")
            if count % 2 == 1:
                lines[i] = f'<pre><code class="language-{items[-1]}">'
            else:
                lines[i] = f"<br></code></pre>"
        else:
            if i > 0:
                if count % 2 == 1:
                    line = line.replace("`", r"\`")
                    line = line.replace("<", "&lt;")
                    line = line.replace(">", "&gt;")
                    line = line.replace(" ", "&nbsp;")
                    line = line.replace("*", "&ast;")
                    line = line.replace("_", "&lowbar;")
                    line = line.replace("-", "&#45;")
                    line = line.replace(".", "&#46;")
                    line = line.replace("!", "&#33;")
                    line = line.replace("(", "&#40;")
                    line = line.replace(")", "&#41;")
                    line = line.replace("$", "&#36;")
                lines[i] = "<br>" + line
    text = "".join(lines)
    return text

def _gc():
    import gc
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()

my_css = """
body {
    background: linear-gradient(to right, #ece9e6, #ffffff); /* 背景渐变 */
    font-family: 'Arial Rounded MT Bold', sans-serif; /* 字体 */
}

#qwen-chat-container {
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
    transition: 0.3s;
    border-radius: 5px;
    background-color: #f9f9f9;
    padding: 10px;
}
.gr-button {
    border-radius: 20px;
    padding: 10px 20px;
    font-size: 16px;
    color: white;
    background-color: #007BFF;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s, transform 0.2s;
}

.gr-button:hover {
    background-color: #0056b3;
    transform: scale(1.05);
}

textarea.gr-textbox {
    font-family: 'Arial Rounded MT Bold', sans-serif;
}

.gr-row {
    justify-content: space-evenly;
}

#header-img {
    height: 80px;
    animation: fadeIn 2s ease-in-out;
}

#header-text {
    font-size: 40px;
    font-family: 'Arial Rounded MT Bold', sans-serif;
    color: #007BFF;
    font-weight: bold;
    text-shadow: 2px 2px 8px rgba(0, 123, 255, 0.5);
    animation: popIn 2s ease;
}

#video-container {
    display: flex;
    justify-content: center;
}

#default-video {
    width: 450px;
    height: 800px;
    display: block;
    margin: auto;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes popIn {
    0% { transform: scale(0.5); opacity: 0; }
    60% { transform: scale(1.1); opacity: 1; }
    100% { transform: scale(1); }
}
"""

async def _generate_audio(text, output_path):
    communicate = edge_tts.Communicate(
        text=text,
        voice=VOICE,
        rate=RATE,
        volume=VOLUME
    )
    await communicate.save(output_path)
    return output_path


def encode_audio_to_base64(audio_file_path):
    with open(audio_file_path, "rb") as audio_file:
        audio_data = audio_file.read()
        encoded_audio = base64.b64encode(audio_data).decode("utf-8")
    return encoded_audio

def _launch_demo(args, model, tokenizer, config):
    def predict(_query, _chatbot, _task_history):
        
        global new_video_path
        # 在处理用户输入的同时生成或更新新视频文件路径
        # 假设视频生成逻辑在这里执行,并且生成视频存储在 new_video_path
        #new_video_path = "output.mp4"  # 您的生成新视频逻辑
        #video.update(value=new_video_path)
        
        
        
        _chatbot.append((_parse_text(_query), ""))
        full_response = ""

        for response in model.chat_stream(tokenizer, _query, history=_task_history, generation_config=config):
            _chatbot[-1] = (_parse_text(_query), _parse_text(response))
            yield _chatbot
            full_response = _parse_text(response)

        _task_history.append((_query, full_response))
        
        # 生成音频文件,并编码为Base64
        asyncio.run(_generate_audio(full_response, OUTPUT_FILE))
        
        encoded_audio = encode_audio_to_base64(OUTPUT_FILE)
        
        # 在聊天框中添加Base64编码的音频播放按钮
        audio_button_html = f"""
            <audio controls>
                <source src="data:audio/wav;base64,{encoded_audio}" type="audio/wav">
                Your browser does not support the audio element.
            </audio>
        """
        _chatbot[-1] = (_parse_text(_query), _parse_text(full_response) + audio_button_html)
        yield _chatbot

    def regenerate(_chatbot, _task_history):
        if not _task_history:
            yield _chatbot
            return
        item = _task_history.pop(-1)
        _chatbot.pop(-1)
        yield from predict(item[0], _chatbot, _task_history)

    def reset_user_input():
        return gr.update(value="")

    def reset_state(_chatbot, _task_history):
        _task_history.clear()
        _chatbot.clear()
        _gc()
        return _chatbot

    with gr.Blocks(css=my_css) as demo:
        gr.Markdown("""
        <center>
            <span id="header-text">
                InsightCompanion
            </span>
        </center>
        """)

        # 添加视频播放组件
        video = gr.Video(value=OUTPUT_DEFAULT_VIDEO, format="mp4", label="默认视频", elem_id="default-video")
        
        chatbot = gr.Chatbot(label='Qwen-Chat', elem_id="qwen-chat-container",height=180)
        query = gr.Textbox(lines=2, label='请输入您的问题', placeholder="开始对话...")
        task_history = gr.State([])

        with gr.Row():
            empty_btn = gr.Button("刷新", elem_classes="gr-button")
            submit_btn = gr.Button("发送", elem_classes="gr-button")
            regen_btn = gr.Button("重试", elem_classes="gr-button")

        submit_btn.click(predict, [query, chatbot, task_history], [chatbot], show_progress=True)
        submit_btn.click(reset_user_input, [], [query])
        empty_btn.click(reset_state, [chatbot, task_history], outputs=[chatbot], show_progress=True)
        regen_btn.click(regenerate, [chatbot, task_history], [chatbot], show_progress=True)

    demo.queue().launch(
        share=args.share,
        inbrowser=args.inbrowser,
        server_port=args.server_port,
        server_name=args.server_name,
    )

def main():
    args = _get_args()
    model, tokenizer, config = _load_model_tokenizer(args)
    _launch_demo(args, model, tokenizer, config)

if __name__ == '__main__':
    main()