Views
No views yet
transformers library:1import gradio as gr
2from transformers import AutoProcessor, MllamaForConditionalGeneration
3
4# Use GPU if available, otherwise CPU
5device = "cuda" if torch.cuda.is_available() else "cpu"
6
7# Load the model and processor
8model_name = "ruslanmv/Llama-3.2-11B-Vision-Instruct"
9processor = AutoProcessor.from_pretrained(model_name)
10model = MllamaForConditionalGeneration.from_pretrained(
11 model_name,
12 torch_dtype=torch.bfloat16,
13 device_map="auto",
14)
15
16# Function to generate model response
17def predict(message, image):
18 messages = [{"role": "user", "content": [
19 {"type": "image"},
20 {"type": "text", "text": message}
21 ]}]
22 input_text = processor.apply_chat_template(messages, add_generation_prompt=True)
23 inputs = processor(image, input_text, return_tensors="pt").to(device)
24 response = model.generate(**inputs, max_new_tokens=100)
25 return processor.decode(response[0], skip_special_tokens=True)
26
27# Gradio interface
28with gr.Blocks() as demo:
29 gr.Markdown("# Simple Multimodal Chatbot")
30 with gr.Row():
31 with gr.Column(): # Message input on the left
32 text_input = gr.Textbox(label="Message")
33 submit_button = gr.Button("Send")
34 with gr.Column(): # Image input on the right
35 image_input = gr.Image(type="pil", label="Upload an Image")
36 chatbot = gr.Chatbot() # Chatbot output at the bottom
37
38 def respond(message, image, history):
39 history = history + [(message, "")]
40 response = predict(message, image)
41 history[-1] = (message, response)
42 return history
43
44 submit_button.click(
45 fn=respond,
46 inputs=[text_input, image_input, chatbot],
47 outputs=chatbot
48 )
49
50demo.launch()