-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
279 lines (234 loc) · 9.86 KB
/
models.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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import os
import re
import json
import random
import base64
from io import BytesIO
import tempfile
from tqdm import tqdm
import numpy as np
from PIL import Image
from openai import OpenAI, BadRequestError
def resize(image, base_width=None, base_height=None):
# Original dimensions
original_width, original_height = image.size
# Calculate new dimensions
if base_width:
if base_width <= original_width:
return image
w_percent = (base_width / float(original_width))
new_height = int((float(original_height) * float(w_percent)))
new_size = (base_width, new_height)
elif base_height:
if base_height <= original_height:
return image
h_percent = (base_height / float(original_height))
new_width = int((float(original_width) * float(h_percent)))
new_size = (new_width, base_height)
else:
raise ValueError("Either base_width or base_height must be specified")
# Resize the image
resized_img = image.resize(new_size, Image.LANCZOS)
return resized_img
def set_random_seed(seed):
"""Set random seed for reproducibility."""
if seed is not None and seed > 0:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
def convert_pil_image_to_base64(image):
buffered = BytesIO()
image.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode()
class GPT4V:
def __init__(self):
# Get OpenAI API Key from environment variable
api_key = os.environ["OPENAI_API_KEY"]
self.client = OpenAI(api_key=api_key)
def generate(self, prompt, images, temperature=0.0):
prompt = (
"You are required to solve a programming problem. "
+ "Please enclose your code inside a ```python``` block. "
+ " Do not write a main() function. If Call-Based format is used, return the result in an appropriate place instead of printing it.\n\n" \
+ prompt
)
# Convert all images to base64
base64_images = [convert_pil_image_to_base64(resize(image, base_height=480)) for image in images]
interleaved_messages = []
# Split the prompt and interleave text and images
segments = re.split(r'!\[image\]\(.*?\)', prompt)
for i, segment in enumerate(segments):
# Text
if len(segment) > 0:
interleaved_messages.append({"type": "text", "text": segment})
# Image
if i < len(base64_images):
interleaved_messages.append({
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{base64_images[i]}",
}
})
try:
# print(interleaved_messages)
response = self.client.chat.completions.create(
model="gpt-4-vision-preview",
messages=[
{
"role": "system",
"content": [
{"type": "text", "text": "You are a professional programming contester trying to solve algorithmic problems. The problems come with a description and some images, and you should write a Python solution."}
],
},
{
"role": "user",
"content": interleaved_messages
}
],
temperature=temperature,
max_tokens=2048,
)
return response.choices[0].message.content
except BadRequestError as e:
print("OpenAI BadRequestError:", e)
return None
def extract_code(self, response):
pattern = r"```python(.*?)```"
# Use re.DOTALL to make '.' match any character including a newline
matches = re.findall(pattern, response, re.DOTALL)
if matches:
return matches[0]
else:
return response
class GPT4:
def __init__(self):
# Get OpenAI API Key from environment variable
api_key = os.environ["OPENAI_API_KEY"]
self.client = OpenAI(api_key=api_key)
def generate(self, prompt, images, temperature=0.0):
prompt = "You are required to solve a programming problem. Please enclose your code inside a ```python``` block. " \
"Do not write a main() function. If Call-Based format is used, return the result in an appropriate place instead of printing it.\n\n" \
+ prompt
interleaved_messages = []
# Split the prompt and interleave text and images
# image_paths = re.split(r'!\[image\]\((.*?)\)', prompt) # Not used. We replace the images by order.
segments = re.split(r'!\[image\]\(.*?\)', prompt)
for i, segment in enumerate(segments):
# Text
if len(segment) > 0:
interleaved_messages.append({"type": "text", "text": segment})
# Image
if i < len(images):
interleaved_messages.append({"type": "text", "text": f"(Image Unavailable)"})
response = self.client.chat.completions.create(
model="gpt-4-1106-preview", # gpt-4-1106-preview
messages=[
{
"role": "system",
"content": [
{"type": "text", "text": "You are a professional programming contester trying to solve algorithmic problems. The problems come with a description and some images, and you should write a Python solution."}
],
},
{
"role": "user",
"content": interleaved_messages
}
],
temperature=temperature,
max_tokens=2048,
)
return response.choices[0].message.content
def extract_code(self, response):
pattern = r"```python(.*?)```"
# Use re.DOTALL to make '.' match any character including a newline
matches = re.findall(pattern, response, re.DOTALL)
if matches:
return matches[0]
else:
return response
class GEMINI_PRO:
def __init__(self):
import google.generativeai as genai
# Get Google API Key from environment variable
api_key = os.environ["GOOGLE_API_KEY"]
genai.configure(api_key=api_key)
self.genai_package = genai
self.client = genai.GenerativeModel('gemini-pro')
def generate(self, prompt, images, temperature=0.0):
prompt = "You are required to solve a programming problem. Please enclose your code inside a ```python``` block. " \
"Do not write a main() function. If Call-Based format is used, return the result in an appropriate place instead of printing it.\n\n" \
+ prompt
# Split the prompt and interleave text and images
prompt = re.sub(r'!\[image\]\(.*?\)', "(Image Unavailable.)", prompt)
try:
response = self.client.generate_content(prompt,
generation_config=self.genai_package.types.GenerationConfig(
temperature=temperature
)
)
return response.text
except Exception as e:
print(e)
return None
def extract_code(self, response):
pattern = r"```python(.*?)```"
# Use re.DOTALL to make '.' match any character including a newline
matches = re.findall(pattern, response, re.DOTALL)
if matches:
return matches[0]
else:
return response
class GEMINI_PRO_VISION:
def __init__(self):
import google.generativeai as genai
# Get Google API Key from environment variable
api_key = os.environ["GOOGLE_API_KEY"]
genai.configure(api_key=api_key)
self.genai_package = genai
self.client = genai.GenerativeModel('gemini-pro-vision')
def generate(self, prompt, images, temperature=0.0):
meta_prompt = "You are required to solve a programming problem. Please enclose your code inside a ```python``` block. " \
"Do not write a main() function. If Call-Based format is used, return the result in an appropriate place instead of printing it.\n\n"
images = [resize(image, base_height=480) for image in images]
interleaved_messages = [meta_prompt]
# Split the prompt and interleave text and images
segments = re.split(r'!\[image\]\(.*?\)', prompt)
for i, segment in enumerate(segments):
# Text
if len(segment) > 0:
interleaved_messages.append(segment)
# Image
if i < len(images):
interleaved_messages.append(images[i])
# Merge continuous text segments
messages = []
for item in interleaved_messages:
if not messages:
messages.append(item)
continue
if isinstance(item, str) and isinstance(messages[-1], str):
messages[-1] += item
else:
messages.append(item)
try:
response = self.client.generate_content(messages,
generation_config=self.genai_package.types.GenerationConfig(
temperature=temperature
)
)
return response.text
except Exception as e:
print(e)
try:
print(response.prompt_feedback)
except Exception as err:
pass
return None
def extract_code(self, response):
pattern = r"```python(.*?)```"
# Use re.DOTALL to make '.' match any character including a newline
matches = re.findall(pattern, response, re.DOTALL)
if matches:
return matches[0]
else:
return response