CoolFace
Apppublic

Sparkles-AI/gpt4mini

sourceHugging Faceotherupdated 3y agoView on Hugging Face
0likes
app.py154 linesDownload Raw Back to root
1import argparse2import os3import random4 5import numpy as np6import torch7import torch.backends.cudnn as cudnn8import gradio as gr9 10from minigpt4.common.config import Config11from minigpt4.common.dist_utils import get_rank12from minigpt4.common.registry import registry13from minigpt4.conversation.conversation import Chat, CONV_VISION14 15# imports modules for registration16from minigpt4.datasets.builders import *17from minigpt4.models import *18from minigpt4.processors import *19from minigpt4.runners import *20from minigpt4.tasks import *21 22def parse_args():23    parser = argparse.ArgumentParser(description="Demo")24    parser.add_argument("--cfg-path", type=str, default='eval_configs/minigpt4.yaml', help="path to configuration file.")25    parser.add_argument(26        "--options",27        nargs="+",28        help="override some settings in the used config, the key-value pair "29        "in xxx=yyy format will be merged into config file (deprecate), "30        "change to --cfg-options instead.",31    )32    args = parser.parse_args()33    return args34 35 36def setup_seeds(config):37    seed = config.run_cfg.seed + get_rank()38 39    random.seed(seed)40    np.random.seed(seed)41    torch.manual_seed(seed)42 43    cudnn.benchmark = False44    cudnn.deterministic = True45    46# ========================================47#             Model Initialization48# ========================================49 50SHARED_UI_WARNING = f'''### [NOTE] It is possible that you are waiting in a lengthy queue.51 52You can duplicate and use it with a paid private GPU.53 54<a class="duplicate-button" style="display:inline-block" target="_blank" href="https://huggingface.co/spaces/Vision-CAIR/minigpt4?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>55 56Alternatively, you can also use the demo on our [project page](https://minigpt-4.github.io).57'''58 59print('Initializing Chat')60cfg = Config(parse_args())61 62model_config = cfg.model_cfg63model_cls = registry.get_model_class(model_config.arch)64model = model_cls.from_config(model_config).to('cuda:0')65 66vis_processor_cfg = cfg.datasets_cfg.cc_align.vis_processor.train67vis_processor = registry.get_processor_class(vis_processor_cfg.name).from_config(vis_processor_cfg)68chat = Chat(model, vis_processor)69print('Initialization Finished')70 71# ========================================72#             Gradio Setting73# ========================================74 75def gradio_reset(chat_state, img_list):76    if chat_state is not None:77        chat_state.messages = []78    if img_list is not None:79        img_list = []80    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_list81 82def upload_img(gr_img, text_input, chat_state):83    if gr_img is None:84        return None, None, gr.update(interactive=True), chat_state, None85    chat_state = CONV_VISION.copy()86    img_list = []87    llm_message = chat.upload_img(gr_img, chat_state, img_list)88    return gr.update(interactive=False), gr.update(interactive=True, placeholder='Type and press Enter'), gr.update(value="Start Chatting", interactive=False), chat_state, img_list89 90def gradio_ask(user_message, chatbot, chat_state):91    if len(user_message) == 0:92        return gr.update(interactive=True, placeholder='Input should not be empty!'), chatbot, chat_state93    chat.ask(user_message, chat_state)94    chatbot = chatbot + [[user_message, None]]95    return '', chatbot, chat_state96 97 98def gradio_answer(chatbot, chat_state, img_list, num_beams, temperature):99    llm_message = chat.answer(conv=chat_state, img_list=img_list, max_new_tokens=300, num_beams=1, temperature=temperature, max_length=2000)[0]100    chatbot[-1][1] = llm_message101    return chatbot, chat_state, img_list102 103title = """<h1 align="center">Demo of MiniGPT-4</h1>"""104description = """<h3>This is the demo of MiniGPT-4. Upload your images and start chatting!</h3>"""105article = """<div style='display:flex; gap: 0.25rem; '><a href='https://minigpt-4.github.io'><img src='https://img.shields.io/badge/Project-Page-Green'></a><a href='https://github.com/Vision-CAIR/MiniGPT-4'><img src='https://img.shields.io/badge/Github-Code-blue'></a><a href='https://github.com/TsuTikgiau/blip2-llm/blob/release_prepare/MiniGPT_4.pdf'><img src='https://img.shields.io/badge/Paper-PDF-red'></a></div>106"""107 108#TODO show examples below109 110with gr.Blocks() as demo:111    gr.Markdown(title)112    gr.Markdown(SHARED_UI_WARNING)113    gr.Markdown(description)114    gr.Markdown(article)115 116    with gr.Row():117        with gr.Column(scale=0.5):118            image = gr.Image(type="pil")119            upload_button = gr.Button(value="Upload & Start Chat", interactive=True, variant="primary")120            clear = gr.Button("Restart")121            122            num_beams = gr.Slider(123                minimum=1,124                maximum=5,125                value=1,126                step=1,127                interactive=True,128                label="beam search numbers)",129            )130            131            temperature = gr.Slider(132                minimum=0.1,133                maximum=2.0,134                value=1.0,135                step=0.1,136                interactive=True,137                label="Temperature",138            )139            140 141        with gr.Column():142            chat_state = gr.State()143            img_list = gr.State()144            chatbot = gr.Chatbot(label='MiniGPT-4')145            text_input = gr.Textbox(label='User', placeholder='Please upload your image first', interactive=False)146    147    upload_button.click(upload_img, [image, text_input, chat_state], [image, text_input, upload_button, chat_state, img_list])148    149    text_input.submit(gradio_ask, [text_input, chatbot, chat_state], [text_input, chatbot, chat_state]).then(150        gradio_answer, [chatbot, chat_state, img_list, num_beams, temperature], [chatbot, chat_state, img_list]151    )152    clear.click(gradio_reset, [chat_state, img_list], [chatbot, image, text_input, upload_button, chat_state, img_list], queue=False)153 154demo.launch(enable_queue=True)