CoolFace
Apppublic

mlpc-lab/BLIVA

sourceHugging Faceapache-2.0updated 3y agoView on Hugging Face
9likes
app.py152 linesDownload Raw Back to root
1import argparse2import os3import random4 5import numpy as np6import torch7import torch.backends.cudnn as cudnn8import gradio as gr9 10from bliva.common.config import Config11from bliva.common.dist_utils import get_rank12from bliva.common.registry import registry13from bliva.conversation.conversation import Chat, CONV_VISION, CONV_DIRECT14 15# imports modules for registration16 17from bliva.models import *18from bliva.processors import *19from bliva.models import load_model_and_preprocess20from evaluate import disable_torch_init21 22def parse_args():23    parser = argparse.ArgumentParser(description="Demo")24    parser.add_argument("--model_name",default='bliva_vicuna', type=str, help='model name')25    parser.add_argument("--gpu_id", type=int, default=0, help="specify the gpu to load the model.")26    args = parser.parse_args()27    return args28 29# ========================================30#             Model Initialization31# ========================================32 33print('Initializing Chat')34args = parse_args()35 36if torch.cuda.is_available():37    device='cuda:{}'.format(args.gpu_id)38else:39    device=torch.device('cpu')40 41disable_torch_init()42if args.model_name == "blip2_vicuna_instruct":43    model, vis_processors, _ = load_model_and_preprocess(name=args.model_name, model_type="vicuna7b", is_eval=True, device=device)44elif args.model_name == "bliva_vicuna":45    model, vis_processors, _ = load_model_and_preprocess(name=args.model_name, model_type="vicuna7b", is_eval=True, device=device)46elif args.model_name == "bliva_flant5":47    model, vis_processors, _ = load_model_and_preprocess(name=args.model_name, model_type="flant5xxl", is_eval=True, device=device)48else:49    print("Model not found")    50    51vis_processor = vis_processors["eval"]52 53 54# vis_processor_cfg = cfg.datasets_cfg.cc_sbu_align.vis_processor.train55# vis_processor = registry.get_processor_class(vis_processor_cfg.name).from_config(vis_processor_cfg)56chat = Chat(model, vis_processor, device=device)57print('Initialization Finished')58 59# ========================================60#             Gradio Setting61# ========================================62 63def gradio_reset(chat_state, img_list):64    if chat_state is not None:65        chat_state.messages = []66    if img_list is not None:67        img_list = []68    return None, gr.update(value=None, interactive=True), gr.update(placeholder='Please upload your image first', interactive=False),gr.update(value="Upload & Start Chat", interactive=True), chat_state, img_list69 70def upload_img(gr_img, text_input, chat_state):71    if gr_img is None:72        return None, None, gr.update(interactive=True), chat_state, None73    chat_state = CONV_DIRECT.copy()   #CONV_VISION.copy()74    img_list = []75    llm_message = chat.upload_img(gr_img, chat_state, img_list)76    return gr.update(interactive=False), gr.update(interactive=True, placeholder='Type and press Enter'), gr.update(value="Start Chatting", interactive=False), chat_state, img_list77 78def gradio_ask(user_message, chatbot, chat_state):79    if len(user_message) == 0:80        return gr.update(interactive=True, placeholder='Input should not be empty!'), chatbot, chat_state81    chat.ask(user_message, chat_state)82    chatbot = chatbot + [[user_message, None]]83    return '', chatbot, chat_state84 85 86def gradio_answer(chatbot, chat_state, img_list, num_beams, temperature):87    llm_message = chat.answer(conv=chat_state,88                              img_list=img_list,89                              num_beams=num_beams,90                              temperature=temperature,91                              max_new_tokens=300,92                              max_length=2000)[0]93    chatbot[-1][1] = llm_message[0]94    return chatbot, chat_state, img_list95 96title = """<h1 align="center">Demo of BLIVA</h1>"""97description = """<h3>This is the demo of BLIVA. Upload your images and start chatting!. <br> To use 98            example questions, click example image, hit upload, and press enter in the chatbox.</h3>"""99article = """<p><a href='https://gordonhu608.github.io/bliva/'><img src='https://img.shields.io/badge/Project-Page-Green'></a></p><p><a href='https://github.com/mlpc-ucsd/BLIVA'><img src='https://img.shields.io/badge/Github-Code-blue'></a></p><p><a href='https://arxiv.org/abs/2308.09936'><img src='https://img.shields.io/badge/Paper-ArXiv-red'></a></p>100"""101 102#TODO show examples below103 104with gr.Blocks() as demo:105    gr.Markdown(title)106    gr.Markdown(description)107    gr.Markdown(article)108 109    with gr.Row():110        with gr.Column(scale=0.5):111            image = gr.Image(type="pil")112            upload_button = gr.Button(value="Upload & Start Chat", interactive=True, variant="primary")113            clear = gr.Button("Restart ๐Ÿ”„")114            115            num_beams = gr.Slider(116                minimum=1,117                maximum=10,118                value=5,119                step=1,120                interactive=True,121                label="beam search numbers)",122            )123            124            temperature = gr.Slider(125                minimum=0.1,126                maximum=2.0,127                value=1.0,128                step=0.1,129                interactive=True,130                label="Temperature",131            )132 133        with gr.Column():134            chat_state = gr.State()135            img_list = gr.State()136            chatbot = gr.Chatbot(label='BLIVA')137            text_input = gr.Textbox(label='User', placeholder='Please upload your image first', interactive=False)138            139            gr.Examples(examples=[140                [f"images/example.jpg", "Describe this image in detail."],141                [f"images/img3.jpg", "What is this image about?"],142                [f"images/img4.jpg", "What is the title of this movie?"],143            ], inputs=[image, text_input])          144            145    upload_button.click(upload_img, [image, text_input, chat_state], [image, text_input, upload_button, chat_state, img_list])146    147    text_input.submit(gradio_ask, [text_input, chatbot, chat_state], [text_input, chatbot, chat_state]).then(148        gradio_answer, [chatbot, chat_state, img_list, num_beams, temperature], [chatbot, chat_state, img_list]149    )150    clear.click(gradio_reset, [chat_state, img_list], [chatbot, image, text_input, upload_button, chat_state, img_list], queue=False)151 152demo.launch(enable_queue=True)