Update Qwen/test.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294from 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
# 获取当前脚本所在的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取当前目录的上一级目录
parent_dir = os.path.dirname(current_dir)
# 定义默认的检查点路径
DEFAULT_CKPT_PATH = os.path.join(parent_dir, 'Qwen-1_8B-Chat')
# 创建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, "response.wav") # 音频文件名
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("<", "<")
line = line.replace(">", ">")
line = line.replace(" ", " ")
line = line.replace("*", "*")
line = line.replace("_", "_")
line = line.replace("-", "-")
line = line.replace(".", ".")
line = line.replace("!", "!")
line = line.replace("(", "(")
line = line.replace(")", ")")
line = line.replace("$", "$")
lines[i] = "<br>" + line
text = "".join(lines)
return text
def _gc():
import gc
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
cheetah = os.path.join(os.path.dirname(__file__), "42.png")
my_css = """
body {
background: linear-gradient(to right, #ece9e6, #ffffff); /* 背景渐变 */
font-family: 'Arial Rounded MT Bold', sans-serif; /* 字体 */
}
#healthy_img {
width: 1032px;
height: 480px;
transition: transform 0.5s;
display: block;
margin-left: auto;
margin-right: auto;
margin-top: 0;
}
#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: 20px;
}
.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);
}
.control-height {
min-height: 500px;
}
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;
}
@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):
_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">
济卫士——你的智能健康顾问
</span>
</center>
""")
chatbot = gr.Chatbot(label='Qwen-Chat', elem_id="qwen-chat-container")
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)
gr.Image(type="pil", value=cheetah, elem_id="healthy_img")
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()
from argparse import ArgumentParserimport gradio as grimport mdtex2htmlimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom transformers.generation import GenerationConfigimport osimport webbrowserimport asyncioimport edge_ttsimport base64
# 获取当前脚本所在的目录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, "response.wav") # 音频文件名
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("<", "<") line = line.replace(">", ">") line = line.replace(" ", " ") line = line.replace("*", "*") line = line.replace("_", "_") line = line.replace("-", "-") line = line.replace(".", ".") line = line.replace("!", "!") line = line.replace("(", "(") line = line.replace(")", ")") line = line.replace("$", "$") lines[i] = "<br>" + line text = "".join(lines) return text
def _gc(): import gc gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache()
cheetah = os.path.join(os.path.dirname(__file__), "42.png")
my_css = """body { background: linear-gradient(to right, #ece9e6, #ffffff); /* 背景渐变 */ font-family: 'Arial Rounded MT Bold', sans-serif; /* 字体 */}
#healthy_img { width: 1032px; height: 480px; transition: transform 0.5s; display: block; margin-left: auto; margin-right: auto; margin-top: 0;}
#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: 20px;}
.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);}
.control-height { min-height: 500px;}
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;}
@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): _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"> 济卫士——你的智能健康顾问 </span> </center> """)
chatbot = gr.Chatbot(label='Qwen-Chat', elem_id="qwen-chat-container") 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) gr.Image(type="pil", value=cheetah, elem_id="healthy_img")
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()
Qwen/test.py+294-294