Spaces:
Paused
Paused
ManishThota
commited on
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
5 |
+
|
6 |
+
# Set default device to CUDA for GPU acceleration
|
7 |
+
device = 'cuda' if torch.cuda.is_available() else "cpu"
|
8 |
+
# torch.set_default_device("cuda")
|
9 |
+
|
10 |
+
# Initialize the model and tokenizer
|
11 |
+
model = AutoModelForCausalLM.from_pretrained("ManishThota/Sparrow").to(device)
|
12 |
+
tokenizer = AutoTokenizer.from_pretrained("ManishThota/Sparrow", trust_remote_code=True)
|
13 |
+
|
14 |
+
def predict_answer(image, question):
|
15 |
+
# Convert PIL image to RGB if not already
|
16 |
+
image = image.convert("RGB")
|
17 |
+
|
18 |
+
# # Format the text input for the model
|
19 |
+
# text = f"A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. USER: <image>\n{question} ASSISTANT:"
|
20 |
+
|
21 |
+
# Tokenize the text input
|
22 |
+
encoding = tokenizer(image, question, return_tensors='pt').to(device)
|
23 |
+
|
24 |
+
out = model.generate(**encoding)
|
25 |
+
# Preprocess the image for the model
|
26 |
+
generated_text = tokenizer.decode(out[0], skip_special_tokens=True)
|
27 |
+
|
28 |
+
# # Generate the answer
|
29 |
+
# output_ids = model.generate(
|
30 |
+
# input_ids,
|
31 |
+
# max_new_tokens=100,
|
32 |
+
# images=image_tensor,
|
33 |
+
# use_cache=True)[0]
|
34 |
+
|
35 |
+
# # Decode the generated tokens to get the answer
|
36 |
+
# answer = tokenizer.decode(output_ids[input_ids.shape[1]:], skip_special_tokens=True).strip()
|
37 |
+
|
38 |
+
return generated_text
|
39 |
+
|
40 |
+
def gradio_predict(image, question):
|
41 |
+
answer = predict_answer(image, question)
|
42 |
+
return answer
|
43 |
+
|
44 |
+
# Define the Gradio interface
|
45 |
+
iface = gr.Interface(
|
46 |
+
fn=gradio_predict,
|
47 |
+
inputs=[gr.Image(type="pil", label="Upload or Drag an Image"), gr.Textbox(label="Question", placeholder="e.g. What are the colors of the bus in the image?", scale=4)],
|
48 |
+
outputs=gr.TextArea(label="Answer"),
|
49 |
+
title="Sparrow-based Visual Question Answering",
|
50 |
+
description="An interactive chat model that can answer questions about images.",
|
51 |
+
)
|
52 |
+
|
53 |
+
# Launch the app
|
54 |
+
iface.queue().launch(debug=True)
|