ysharma's picture
ysharma HF staff
update stream code
6caa93d
raw
history blame
6.98 kB
import gradio as gr
import json
import requests
import os
from text_generation import Client, InferenceAPIClient
# Load pre-trained model and tokenizer - for THUDM model
from transformers import AutoModel, AutoTokenizer
tokenizer_glm = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
model_glm = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
model_glm = model_glm.eval()
# Load pre-trained model and tokenizer for Chinese to English translator
from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
model_chtoen = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
tokenizer_chtoen = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M")
# Define function to generate model predictions and update the history
def predict_glm(input, history=[]):
response, history = model_glm.chat(tokenizer_glm, input, history)
# translate Chinese to English
history = [(query, translate_Chinese_English(response)) for query, response in history]
return history, history #[history] + updates
def translate_Chinese_English(chinese_text):
# translate Chinese to English
tokenizer_chtoen.src_lang = "zh"
encoded_zh = tokenizer_chtoen(chinese_text, return_tensors="pt")
generated_tokens = model_chtoen.generate(**encoded_zh, forced_bos_token_id=tokenizer_chtoen.get_lang_id("en"))
trans_eng_text = tokenizer_chtoen.batch_decode(generated_tokens, skip_special_tokens=True)
return trans_eng_text[0]
# Define generator to stream model predictions
def predict_glm_stream_old(input, history=[]): #, top_p, temperature):
top_p = 1.0
temperature = 1.0
for response, history in model_glm.stream_chat(tokenizer_glm, input, history, top_p=1.0, temperature=1.0): #max_length=max_length,
print(f"In for loop resonse is ^^- {response}")
print(f"In for loop history is ^^- {history}")
# translate Chinese to English
history = [(query, translate_Chinese_English(response)) for query, response in history]
print(f"In for loop translated history is ^^- {history}")
yield history, history #[history] + updates
# Define function to generate model predictions and update the history
def predict_glm_stream(input, history=[]): #, top_p, temperature):
for response, updates in model_glm.stream_chat(tokenizer_glm, input, history[-1] if history else history, top_p=1.0, temperature=1.0): #history
print(f"In for loop resonse is ^^- {response}")
print(f"In for loop updates is ^^- {updates}")
# translate Chinese to English
#history = [(query, translate_Chinese_English(response)) for query, response in history]
print(f"In for loop OG history is ^^- {history}")
print(f"In for loop translated history is ^^- {history+updates}")
yield history+updates
"""
def predict(input, max_length, top_p, temperature, history=None):
if history is None:
history = []
for response, history in model.stream_chat(tokenizer, input, history, max_length=max_length, top_p=top_p,
temperature=temperature):
updates = []
for query, response in history:
updates.append(gr.update(visible=True, value="user:" + query)) #用户
updates.append(gr.update(visible=True, value="ChatGLM-6B:" + response))
if len(updates) < MAX_BOXES:
updates = updates + [gr.Textbox.update(visible=False)] * (MAX_BOXES - len(updates))
yield [history] + updates
"""
def reset_textbox():
return gr.update(value="")
def reset_chat(chatbot, state):
# debug
#print(f"^^chatbot value is - {chatbot}")
#print(f"^^state value is - {state}")
return None, []
#title = """<h1 align="center">🔥🔥Comparison: ChatGPT & OpenChatKit </h1><br><h3 align="center">🚀A Gradio Streaming Demo</h3><br>Official Demo: <a href="https://huggingface.co/spaces/togethercomputer/OpenChatKit">OpenChatKit feedback app</a>"""
title = """<h1 align="center">🔥🔥Comparison: ChatGPT & Open Sourced CHatGLM-6B </h1><br><h3 align="center">🚀A Gradio Chatbot Demo</h3>"""
description = """Language models can be conditioned to act like dialogue agents through a conversational prompt that typically takes the form:
```
User: <utterance>
Assistant: <utterance>
User: <utterance>
Assistant: <utterance>
...
```
In this app, you can explore the outputs of multiple LLMs when prompted in similar ways.
"""
with gr.Blocks(css="""#col_container {margin-left: auto; margin-right: auto;}
#chatglm {height: 520px; overflow: auto;} """ ) as demo:
gr.HTML(title)
#with gr.Row():
with gr.Column(): #(scale=10):
with gr.Box():
with gr.Row():
with gr.Column(scale=8):
inputs = gr.Textbox(placeholder="Hi there!", label="Type an input and press Enter ⤵️ " )
with gr.Column(scale=1):
b1 = gr.Button('🏃Run', elem_id = 'run').style(full_width=True)
with gr.Column(scale=1):
b2 = gr.Button('🔄Clear up Chatbots!', elem_id = 'clear').style(full_width=True)
state_glm = gr.State([])
with gr.Box():
chatbot_glm = gr.Chatbot(elem_id="chatglm", label='THUDM-ChatGLM6B')
#with gr.Column(): #(scale=2, elem_id='parameters'):
with gr.Box():
gr.HTML("Parameters for ChatGLM-6B", visible=True)
top_p = gr.Slider(minimum=-0, maximum=1.0,value=0.25, step=0.05,interactive=True, label="Top-p", visible=False)
temperature = gr.Slider(minimum=-0, maximum=5.0, value=0.6, step=0.1, interactive=True, label="Temperature", visible=False)
#top_k = gr.Slider( minimum=1, maximum=50, value=50, step=1, interactive=True, label="Top-k", visible=False)
#repetition_penalty = gr.Slider( minimum=0.1, maximum=3.0, value=1.01, step=0.01, interactive=True, label="Repetition Penalty", visible=False)
inputs.submit(reset_textbox, [], [inputs])
inputs.submit( predict_glm_stream,
[inputs, chatbot_glm, ], #[inputs, state_glm, ],
[chatbot_glm],) #[chatbot_glm, state_glm],)
b1.click( predict_glm_stream,
[inputs, chatbot_glm, ], #[inputs, state_glm, ],
[chatbot_glm],) #[chatbot_glm, state_glm],)
#b2.click(reset_chat, [chatbot_chatgpt, state_chatgpt], [chatbot_chatgpt, state_chatgpt])
b2.click(reset_chat, [chatbot_glm, state_glm], [chatbot_glm, state_glm])
gr.HTML('''<center><a href="https://huggingface.co/spaces/ysharma/OpenChatKit_ChatGPT_Comparison?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space and run securely with your OpenAI API Key</center>''')
gr.Markdown(description)
demo.queue(concurrency_count=16).launch(height= 800, debug=True)