Download Qwen/run.py from Sheerio/InsightCompanion: direct link, hf CLI and curl.
- Browser
- Download file 9.9 kB
-
https://huggingface.co/Sheerio/InsightCompanion/resolve/main/Qwen/run.py
- Command line
-
hf download hf://Sheerio/InsightCompanion/Qwen/run.py
-
curl -L -o run.py https://huggingface.co/Sheerio/InsightCompanion/resolve/main/Qwen/run.py
9.9 kB
| 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("<", "<") | |
| 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() | |
| 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() | |