Update model.py
Browse files
model.py
CHANGED
@@ -1,47 +1,48 @@
|
|
1 |
-
# Importing the requirements
|
2 |
-
import torch
|
3 |
-
from transformers import AutoModel, AutoTokenizer
|
4 |
-
import spaces
|
5 |
-
|
6 |
-
|
7 |
-
# Device for the model
|
8 |
-
device = "cuda"
|
9 |
-
|
10 |
-
# Load the model and tokenizer
|
11 |
-
model = AutoModel.from_pretrained(
|
12 |
-
"openbmb/MiniCPM-
|
13 |
-
)
|
14 |
-
model = model.to(device=device)
|
15 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
16 |
-
"openbmb/MiniCPM-
|
17 |
-
)
|
18 |
-
model.eval()
|
19 |
-
|
20 |
-
|
21 |
-
@spaces.GPU(duration=120)
|
22 |
-
def answer_question(image, question):
|
23 |
-
"""
|
24 |
-
Generates an answer to a given question based on the provided image and question.
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
|
|
|
1 |
+
# Importing the requirements
|
2 |
+
import torch
|
3 |
+
from transformers import AutoModel, AutoTokenizer
|
4 |
+
import spaces
|
5 |
+
|
6 |
+
|
7 |
+
# Device for the model
|
8 |
+
device = "cuda"
|
9 |
+
|
10 |
+
# Load the model and tokenizer
|
11 |
+
model = AutoModel.from_pretrained(
|
12 |
+
"openbmb/MiniCPM-V-2_6", trust_remote_code=True, attn_implementation='sdpa', torch_dtype=torch.bfloat16
|
13 |
+
)
|
14 |
+
model = model.to(device=device)
|
15 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
16 |
+
"openbmb/MiniCPM-V-2_6", trust_remote_code=True
|
17 |
+
)
|
18 |
+
model.eval()
|
19 |
+
|
20 |
+
|
21 |
+
@spaces.GPU(duration=120)
|
22 |
+
def answer_question(image, question):
|
23 |
+
"""
|
24 |
+
Generates an answer to a given question based on the provided image and question.
|
25 |
+
|
26 |
+
Args:
|
27 |
+
- image (str): The path to the image file.
|
28 |
+
- question (str): The question text.
|
29 |
+
|
30 |
+
Returns:
|
31 |
+
str: The generated answer to the question.
|
32 |
+
"""
|
33 |
+
# Message format for the model
|
34 |
+
msgs = [{"role": "user", "content": [image, question]}]
|
35 |
+
|
36 |
+
# Generate the answer
|
37 |
+
res = model.chat(
|
38 |
+
image=None,
|
39 |
+
msgs=msgs,
|
40 |
+
tokenizer=tokenizer,
|
41 |
+
sampling=True,
|
42 |
+
temperature=0.7,
|
43 |
+
stream=True,
|
44 |
+
system_prompt="You are an AI assistant specialized in visual content analysis. Given an image and a related question, analyze the image thoroughly and provide a precise and informative answer based on the visible content. Ensure your response is clear, accurate, and directly addresses the question.",
|
45 |
+
)
|
46 |
+
|
47 |
+
# Return the answer
|
48 |
+
return "".join(res)
|