| 1 | import argparse |
| 2 | |
| 3 | import gradio as gr |
| 4 | |
| 5 | from mlx_vlm import load |
| 6 | |
| 7 | from .prompt_utils import apply_chat_template |
| 8 | from .utils import load, load_config, load_image_processor, stream_generate |
| 9 | |
| 10 | |
| 11 | def parse_arguments(): |
| 12 | parser = argparse.ArgumentParser( |
| 13 | description="Generate text from an image using a model." |
| 14 | ) |
| 15 | parser.add_argument( |
| 16 | "--model", |
| 17 | type=str, |
| 18 | default="qnguyen3/nanoLLaVA", |
| 19 | help="The path to the local model directory or Hugging Face repo.", |
| 20 | ) |
| 21 | return parser.parse_args() |
| 22 | |
| 23 | |
| 24 | args = parse_arguments() |
| 25 | config = load_config(args.model) |
| 26 | model, processor = load(args.model, {"trust_remote_code": True}) |
| 27 | image_processor = load_image_processor(args.model) |
| 28 | |
| 29 | |
| 30 | def chat(message, history, temperature, max_tokens): |
| 31 | chat = [] |
| 32 | if len(message.files) >= 1: |
| 33 | chat.append(message.text) |
| 34 | else: |
| 35 | raise gr.Error("Please upload an image. Text only chat is not supported.") |
| 36 | |
| 37 | files = message.files[-1].path |
| 38 | if model.config.model_type != "paligemma": |
| 39 | messages = apply_chat_template(processor, config, chat) |
| 40 | else: |
| 41 | messages = message.text |
| 42 | |
| 43 | response = "" |
| 44 | for chunk in stream_generate( |
| 45 | model, processor, files, messages, image_processor, max_tokens, temp=temperature |
| 46 | ): |
| 47 | response += chunk |
| 48 | yield response |
| 49 | |
| 50 | |
| 51 | demo = gr.ChatInterface( |
| 52 | fn=chat, |
| 53 | title="MLX-VLM Chat UI", |
| 54 | additional_inputs_accordion=gr.Accordion( |
| 55 | label="⚙️ Parameters", open=False, render=False |
| 56 | ), |
| 57 | additional_inputs=[ |
| 58 | gr.Slider( |
| 59 | minimum=0, maximum=1, step=0.1, value=0.1, label="Temperature", render=False |
| 60 | ), |
| 61 | gr.Slider( |
| 62 | minimum=128, |
| 63 | maximum=4096, |
| 64 | step=1, |
| 65 | value=200, |
| 66 | label="Max new tokens", |
| 67 | render=False, |
| 68 | ), |
| 69 | ], |
| 70 | description=f"Now Running {args.model}", |
| 71 | multimodal=True, |
| 72 | ) |
| 73 | |
| 74 | demo.launch(inbrowser=True) |