-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmodeling.py
169 lines (133 loc) · 5.1 KB
/
modeling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import json
from PIL import Image
from fire import Fire
from openai import OpenAI
from pydantic import BaseModel
from typing import Optional, List
from data_loading import convert_image_to_text, load_image
from openai import AzureOpenAI
class EvalModel(BaseModel, arbitrary_types_allowed=True):
model_path: str
temperature: float = 0.0
max_image_size: int = 1024
def resize_image(self, image: Image) -> Image:
h, w = image.size
if h <= self.max_image_size and w <= self.max_image_size:
return image
factor = self.max_image_size / max(h, w)
h = round(h * factor)
w = round(w * factor)
if image.mode == "RGBA":
image = image.convert("RGB")
image = image.resize((h, w), Image.LANCZOS)
return image
def run(self, prompt: str, image: Image = None) -> str:
raise NotImplementedError
class GPTModel(EvalModel):
model_path: str = ""
timeout: int = 60
engine: str = ""
client: Optional[OpenAI]
def load(self):
with open(self.model_path) as f:
info = json.load(f)
self.engine = info["engine"]
self.client = AzureOpenAI(
azure_endpoint=info["endpoint"],
api_key=info["key"],
api_version=info["api_version"],
)
def make_messages(self, prompt: str, image: Image = None) -> List[dict]:
inputs = [{"type": "text", "text": prompt}]
if image:
image_text = convert_image_to_text(self.resize_image(image))
url = f"data:image/jpeg;base64,{image_text}"
inputs.append({"type": "image_url", "image_url": {"url": url}})
return [{"role": "user", "content": inputs}]
def run(self, prompt: str, image: Image = None) -> str:
self.load()
output = ""
error_message = "The response was filtered"
while not output:
try:
response = self.client.chat.completions.create(
model=self.engine,
messages=self.make_messages(prompt, image),
temperature=self.temperature,
max_tokens=1024,
)
if response.choices[0].finish_reason == "content_filter":
raise ValueError(error_message)
output = response.choices[0].message.content
except Exception as e:
print(e)
if error_message in str(e):
output = error_message
if not output:
print("OpenAIModel request failed, retrying.")
return output
class GPT4oModel(GPTModel):
model_path: str = "gpt4o.json"
class GPT4tModel(GPTModel):
model_path: str = "gpt4t.json"
class O1Model(GPTModel):
model_path = "o1-full-high.json"
reasoning_effort: str = ""
def load(self):
with open(self.model_path) as f:
info = json.load(f)
self.engine = info["engine"]
self.reasoning_effort = info["reasoning_effort"]
self.client = AzureOpenAI(
azure_endpoint=info["endpoint"],
api_key=info["key"],
api_version="2024-12-01-preview",
)
def run(self, prompt: str, image: Image = None) -> str:
self.load()
output = ""
error_message = "The response was filtered"
while not output:
try:
response = self.client.chat.completions.create(
model=self.engine,
messages=self.make_messages(prompt, image),
reasoning_effort=self.reasoning_effort,
)
if response.choices[0].finish_reason == "content_filter":
raise ValueError(error_message)
output = response.choices[0].message.content
except Exception as e:
print(e)
if error_message in str(e):
output = error_message
if not output:
print("OpenAIModel request failed, retrying.")
return output
def select_model(model_name: str, **kwargs) -> EvalModel:
model_map = dict(
o1=O1Model,
gpt4o=GPT4oModel,
gpt4t=GPT4tModel,
)
model_class = model_map.get(model_name)
if model_class is None:
raise ValueError(f"{model_name}. Choose from {list(model_map.keys())}")
return model_class(**kwargs)
def test_model(
prompt: str = "Can you describe the image in detail?",
image_path: str = "https://www.thesprucecrafts.com/thmb/H-VsgPFaCjTnQQ6u0fLt6X6v3Ic=/750x0/filters:no_upscale():max_bytes(150000):strip_icc()/Chesspieces-GettyImages-667749253-59c339e9685fbe001167cdce.jpg",
model_name: str = "gemini_vision",
**kwargs,
):
model = select_model(model_name, **kwargs)
print(locals())
print(model.run(prompt, load_image(image_path)))
"""
python modeling.py test_model --model_name o1
python modeling.py test_model --model_name gpt4t
python modeling.py test_model --model_name gpt4v
python modeling.py test_model --model_name gpt4o
"""
if __name__ == "__main__":
Fire()