Spaces:
Running
on
T4
Running
on
T4
File size: 15,157 Bytes
045894b 48e8dfb 045894b 48e8dfb 045894b aea9f3e 045894b 8e4225b 045894b 8e4225b 045894b 8e4225b 045894b 8e4225b 045894b 8e4225b 045894b 8e4225b 045894b 8e4225b 045894b 8e4225b 045894b 8e4225b 045894b 8e4225b 045894b 8e4225b 045894b 8e4225b 045894b |
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 315 316 317 318 319 320 321 322 323 324 325 326 327 |
import os
import wget
apex_file = wget.download(os.getenv('apex'))
os.system('tar zxvf {}'.format(apex_file))
os.system('ls -l; cd apex;'
'pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" .; cd ..')
# os.system('pip install gradio --upgrade')
resources = os.getenv('resources')
resources_tokenizer = os.getenv('resources_tokenizer')
_ = wget.download(resources_tokenizer)
resources_filename = wget.download(resources)
os.system('tar zxvf {}'.format(resources_filename))
# if not os.path.exists('./model_optim_rng.pth'):
# resources_weight = os.getenv('resources_weight')
# _ = wget.download(resources_weight)
os.system('ls -l')
import time
import argparse
import datetime
import json
import re
import os
import gradio as gr
import requests
from utils import (
mplug_owl, load_demo_refresh_model_list, vote_last_response,
upvote_last_response, downvote_last_response, flag_last_response, regenerate,
add_text, after_process_image, get_inputs, init,
headers, no_change_btn, enable_btn, disable_btn, get_window_url_params
)
from gradio_css import code_highlight_css
from gradio_patch import Chatbot as grChatbot
from conversation import default_conversation
SHARED_UI_WARNING = f'''### [NOTE]
You can duplicate and use it with a paid private GPU.
<a class="duplicate-button" style="display:inline-block" target="_blank" href="https://huggingface.co./spaces/MAGAer13/mPLUG-Owl?duplicate=true"><img style="margin-top:0;margin-bottom:0" src="https://huggingface.co./datasets/huggingface/badges/raw/main/duplicate-this-space-xl-dark.svg" alt="Duplicate Space"></a>
Alternatively, you can also use the Colab demo on our project page.
<a style="display:inline-block" href="https://https://github.com/X-PLUG/mPLUG-Owl"><img style="margin-top:0;margin-bottom:0" src="https://img.shields.io/badge/Project%20Page-online-brightgreen"></a>
'''
io = None
init()
model = mplug_owl(device="cuda")
log_dir = ""
def load_demo(url_params, request: gr.Request):
dropdown_update = gr.Dropdown.update(visible=True)
if "model" in url_params:
model = url_params["model"]
if model in models:
dropdown_update = gr.Dropdown.update(
value=model, visible=True)
state = default_conversation.copy()
return (state,
dropdown_update,
gr.Chatbot.update(visible=True),
gr.Textbox.update(visible=True),
gr.Button.update(visible=True),
gr.Row.update(visible=True),
gr.Accordion.update(visible=True))
def contains_chinese(string):
pattern = re.compile(r'[一-龥]')
match = pattern.search(string)
return match is not None
def clear_history(request: gr.Request):
state = default_conversation.copy()
return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
def http_bot(state, topk, max_new_tokens, random_seed, request: gr.Request):
prompt = after_process_image(state.get_prompt())
images = state.get_images()
state.messages[-1][-1] = "▌"
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
# if contains_chinese(prompt):
# state.messages[-1][-1] = "**CURRENTLY WE ONLY SUPPORT ENGLISH. PLEASE REFRESH THIS PAGE TO RESTART.**"
# yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
# return
try:
data = get_inputs(prompt, images, topk, max_new_tokens, random_seed)
output = model.prediction(data, log_dir)
print(output)
# output = output.replace("```", "")
state.messages[-1][-1] = output + "▌"
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
time.sleep(0.03)
except requests.exceptions.RequestException as e:
state.messages[-1][-1] = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
return
state.messages[-1][-1] = state.messages[-1][-1][:-1]
yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
def add_text_http_bot(state, text, image, video, topk, max_new_tokens, random_seed, request: gr.Request):
if len(text) <= 0 and (image is None or video is None):
state.skip_next = True
return (state, state.to_gradio_chatbot(), "", None, None) + (no_change_btn,) * 5
if image is not None:
multimodal_msg = None
if '<image>' not in text:
text = text + '\n<image>'
if multimodal_msg is not None:
return (state, state.to_gradio_chatbot(), multimodal_msg, None, None) + (
no_change_btn,) * 5
text = (text, image)
if video is not None:
num_frames = 4
if '<image>' not in text:
text = text + '\n<image>' * num_frames
text = (text, video)
state.append_message(state.roles[0], text)
state.append_message(state.roles[1], None)
state.skip_next = False
yield (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
prompt = after_process_image(state.get_prompt())
images = state.get_images()
state.messages[-1][-1] = "▌"
yield (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
# if contains_chinese(prompt):
# state.messages[-1][-1] = "**CURRENTLY WE ONLY SUPPORT ENGLISH. PLEASE REFRESH THIS PAGE TO RESTART OR CLEAR HISTORY.**"
# yield (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
# return
try:
data = get_inputs(prompt, images, topk, max_new_tokens, random_seed)
output = model.prediction(data, log_dir)
print(output)
# output = output.replace("```", "")
state.messages[-1][-1] = output + "▌"
yield (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
time.sleep(0.03)
except requests.exceptions.RequestException as e:
state.messages[-1][-1] = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
yield (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
return
state.messages[-1][-1] = state.messages[-1][-1][:-1]
yield (state, state.to_gradio_chatbot(), "", None, None) + (enable_btn,) * 5
def regenerate_http_bot(state, topk, max_new_tokens, random_seed, request: gr.Request):
state.messages[-1][-1] = None
state.skip_next = False
yield (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
prompt = after_process_image(state.get_prompt())
images = state.get_images()
state.messages[-1][-1] = " "
yield (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
# if contains_chinese(prompt):
# state.messages[-1][-1] = "**CURRENTLY WE ONLY SUPPORT ENGLISH. PLEASE REFRESH THIS PAGE TO RESTART OR CLEAR HISTORY.**"
# yield (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
# return
try:
data = get_inputs(prompt, images, topk, max_new_tokens, random_seed)
output = model.prediction(data, log_dir)
print(">>>> output:", output)
# output = output.replace("```", "")
state.messages[-1][-1] = output + " "
yield (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
time.sleep(0.03)
except requests.exceptions.RequestException as e:
print(e)
state.messages[-1][-1] = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
yield (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
return
state.messages[-1][-1] = state.messages[-1][-1][:-1]
yield (state, state.to_gradio_chatbot(), "", None, None) + (enable_btn,) * 5
title_markdown = ("""
# mPLUG-Owl🦉 (GitHub Repo: https://github.com/X-PLUG/mPLUG-Owl)
If you like our project, please give us a star on Github for latest update.
""")
tos_markdown = ("""
**Notice:** The output is generated by top-k sampling scheme and may involve some randomness. For multiple image and video, we cannot ensure it's performance since only image-text pairs are used during training.
### Terms of use
By using this service, users are required to agree to the following terms:
The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
Copyright 2023 Alibaba DAMO Academy.
""")
learn_more_markdown = ("""
### License
The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
""")
css = code_highlight_css + """
version 1.0
"""
def build_demo():
# with gr.Blocks(title="mPLUG-Owl🦉", theme=gr.themes.Base(), css=css) as demo:
with gr.Blocks(title="mPLUG-Owl🦉", css=css) as demo:
state = gr.State()
gr.Markdown(title_markdown)
with gr.Row():
with gr.Column(scale=3):
imagebox = gr.Image(type="pil")
videobox = gr.Video()
with gr.Accordion("Parameters", open=True, visible=False) as parameter_row:
topk = gr.Slider(minimum=1, maximum=5, value=5, step=1, interactive=True, label="Top K",)
max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",)
temperature = gr.Slider(minimum=0, maximum=10, value=1, step=0.1, interactive=True, label="Temperature",)
gr.Markdown(tos_markdown)
with gr.Column(scale=6):
chatbot = grChatbot(elem_id="chatbot", visible=False).style(height=800)
with gr.Row():
with gr.Column(scale=8):
textbox = gr.Textbox(show_label=False,
placeholder="Enter text and press ENTER", visible=False).style(container=False)
with gr.Column(scale=1, min_width=60):
submit_btn = gr.Button(value="Submit", visible=False)
with gr.Row(visible=False) as button_row:
upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
clear_btn = gr.Button(value="🗑️ Clear history", interactive=False)
gr.Examples(examples=[
[f"examples/monday.jpg", "Explain why this meme is funny."],
[f'examples/rap.jpeg', 'Can you write me a master rap song that rhymes very well based on this image?'],
[f'examples/titanic.jpeg', 'What happened at the end of this movie?'],
[f'examples/vga.jpeg', 'What is funny about this image? Describe it panel by panel.'],
[f'examples/mug_ad.jpeg', 'We design new mugs shown in the image. Can you help us write an advertisement?'],
[f'examples/laundry.jpeg', 'Why this happens and how to fix it?'],
[f'examples/ca.jpeg', "What do you think about the person's behavior?"],
[f'examples/monalisa-fun.jpg', 'Do you know who drew this painting?'],
# [f"examples/Yao_Ming.jpeg", "What is the name of the man on the right?"],
], inputs=[imagebox, textbox])
gr.Examples(examples=[
[f"examples/surf.mp4", "What is the man doing?"],
[f"examples/yoga.mp4", "What did the woman doing?"],
], inputs=[videobox, textbox])
gr.Markdown(learn_more_markdown)
url_params = gr.JSON(visible=False)
btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
upvote_btn.click(upvote_last_response,
[state], [textbox, upvote_btn, downvote_btn, flag_btn])
downvote_btn.click(downvote_last_response,
[state], [textbox, upvote_btn, downvote_btn, flag_btn])
flag_btn.click(flag_last_response,
[state], [textbox, upvote_btn, downvote_btn, flag_btn])
# regenerate_btn.click(regenerate, state,
# [state, chatbot, textbox, imagebox] + btn_list).then(
# http_bot, [state, topk, max_output_tokens, temperature],
# [state, chatbot] + btn_list)
regenerate_btn.click(regenerate_http_bot, [state, topk, max_output_tokens, temperature],
[state, chatbot, textbox, imagebox, videobox] + btn_list)
clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox, videobox] + btn_list)
# textbox.submit(add_text, [state, textbox, imagebox], [state, chatbot, textbox, imagebox] + btn_list
# ).then(http_bot, [state, topk, max_output_tokens, temperature],
# [state, chatbot] + btn_list)
textbox.submit(add_text_http_bot, [state, textbox, imagebox, videobox, topk, max_output_tokens, temperature], [state, chatbot, textbox, imagebox, videobox] + btn_list)
submit_btn.click(add_text_http_bot, [state, textbox, imagebox, videobox, topk, max_output_tokens, temperature], [state, chatbot, textbox, imagebox, videobox] + btn_list)
demo.load(load_demo, [url_params], [state,
chatbot, textbox, submit_btn, button_row, parameter_row],
_js=get_window_url_params)
return demo
if __name__ == "__main__":
cur_dir = os.getenv("cur_dir")
log_dir = cur_dir + "log"
parser = argparse.ArgumentParser()
parser.add_argument("--host", type=str, default="0.0.0.0")
parser.add_argument("--debug", action="store_true", help="using debug mode")
parser.add_argument("--port", type=int)
parser.add_argument("--concurrency-count", type=int, default=4)
args = parser.parse_args()
demo = build_demo()
demo.queue(concurrency_count=args.concurrency_count, status_update_rate=10, api_open=False).launch(server_name=args.host, debug=args.debug, server_port=args.port, share=False)
|