Ai
1 Star 0 Fork 1

EulixOS/LLM

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
web_demo_vision.py 6.82 KB
一键复制 编辑 原始数据 按行查看 历史
Jim-Pirror 提交于 2024-09-04 18:12 +08:00 . first commit
from transformers import AutoModel, AutoTokenizer
import gradio as gr
import mdtex2html
import time
tokenizer = AutoTokenizer.from_pretrained("/home/visualglm-6b", trust_remote_code=True, revision="")
model = AutoModel.from_pretrained("/home/visualglm-6b", trust_remote_code=True, revision="").half().mlu()
model = model.eval()
"""Override Chatbot.postprocess"""
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):
"""copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
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("`", "\`")
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 predict(input, image_path, chatbot, max_length, top_p, temperature, history):
if image_path is None:
return [(input, "图片为空!请重新上传图片并重试。")]
start_time = time.time() # Record start time
chatbot.append((parse_text(input), ""))
for response, history in model.stream_chat(tokenizer, image_path, input, history, max_length=max_length, top_p=top_p,
temperature=temperature):
chatbot[-1] = (parse_text(input), parse_text(response))
end_time = time.time() # Record end time
elapsed_time = end_time - start_time # Calculate elapsed time in seconds
tokens = len(tokenizer(response, return_tensors='pt')['input_ids'][0]) # Calculate the number of tokens in the response
# Print or store the inference time and speed
inference_time_ms = elapsed_time * 1000 # Convert to milliseconds
speed_ms_per_token = inference_time_ms / tokens
# 将推理时间和速度信息添加到 response 的第一行
response_with_info = f"推理时间:{elapsed_time:.2f} s,速度:{speed_ms_per_token:.2f} ms/token\n{response}"
# 更新 chatbot 中的最后一个对话
chatbot[-1] = (parse_text(input), parse_text(response_with_info))
print(f"推理时间: {elapsed_time:.2f} s, 速度: {speed_ms_per_token:.2f} ms/token")
yield chatbot, history
def predict_new_image(image_path, chatbot, max_length, top_p, temperature):
# 设置输入和历史变量
input, history = "描述这张图片。", []
chatbot.append((parse_text(input), ""))
# 记录开始时间
start_time = time.time()
# 对模型进行推理,返回图像描述的响应
for response, history in model.stream_chat(tokenizer, image_path, input, history, max_length=max_length,
top_p=top_p,
temperature=temperature):
# 记录结束时间
end_time = time.time()
# 计算经过的时间(秒)
elapsed_time = end_time - start_time
# 检查响应是否为字符串
if isinstance(response, str):
# 计算响应中的令牌数量
tokens = len(tokenizer(response, return_tensors='pt')['input_ids'][0])
elif isinstance(response, int):
# 将单一令牌的响应视为一个令牌
tokens = 1
else:
# 输出错误信息并跳过当前迭代
print("无效的响应格式。期望一个字符串或整数。")
continue
# 计算推理时间和速度
inference_time_ms = elapsed_time * 1000 # 转换为毫秒
speed_ms_per_token = inference_time_ms / tokens
# 将推理时间和速度信息添加到 response 的第一行
response_with_info = f"推理时间:{elapsed_time:.2f} s,速度:{speed_ms_per_token:.2f} ms/token\n{response}"
# 更新 chatbot 中的最后一个对话
chatbot[-1] = (parse_text(input), parse_text(response_with_info))
# 打印推理时间和速度信息
print(f"推理时间:{elapsed_time:.2f} s,速度:{speed_ms_per_token:.2f} ms/token")
# 返回 chatbot 和历史
yield chatbot, history
def reset_user_input():
return gr.update(value='')
def reset_state():
return None, [], []
with gr.Blocks() as demo:
gr.HTML("""<h1 align="center">VisualGLM</h1>""")
image_path = gr.Image(type="filepath", label="Image Prompt", value=None)
chatbot = gr.Chatbot()
with gr.Row():
with gr.Column(scale=4):
with gr.Column(scale=12):
user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10)
with gr.Column(min_width=32, scale=1):
submitBtn = gr.Button("Submit", variant="primary")
with gr.Column(scale=1):
emptyBtn = gr.Button("Clear History")
max_length = gr.Slider(0, 4096, value=2048, step=1.0, label="Maximum length", interactive=True)
top_p = gr.Slider(0, 1, value=0.4, step=0.01, label="Top P", interactive=True)
temperature = gr.Slider(0, 1, value=0.8, step=0.01, label="Temperature", interactive=True)
history = gr.State([])
submitBtn.click(predict, [user_input, image_path, chatbot, max_length, top_p, temperature, history], [chatbot, history],
show_progress=True)
image_path.upload(predict_new_image, [image_path, chatbot, max_length, top_p, temperature], [chatbot, history],
show_progress=True)
image_path.clear(reset_state, outputs=[image_path, chatbot, history], show_progress=True)
submitBtn.click(reset_user_input, [], [user_input])
emptyBtn.click(reset_state, outputs=[image_path, chatbot, history], show_progress=True)
demo.queue().launch(share=True, inbrowser=True)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/eulixos/llm.git
git@gitee.com:eulixos/llm.git
eulixos
llm
LLM
master

搜索帮助