-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
205 lines (150 loc) · 6.72 KB
/
main.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
import os
import base64
import io
import random
import json
from openai import OpenAI
from dotenv import load_dotenv
from PIL import Image, ImageDraw, ImageFont
load_dotenv()
OPENAI_SECRET_KEY = os.getenv('OPENAI_SECRET_KEY')
PROMPT = """
Hey, here a couple screenshots of a section from a webpage. Each section has the same content but is designed a bit differently. Sections are labelled "A", "B", "C" and "D".
Only one of the sections is correctly and cleanly designed, the rest have some obvious design flaws. Tell me which one is correct.
Please make the first 2 characters of your answer #A, #B, #C or #D depending on which section you think is correctly designed. This is SUPER IMPORTANT. After that you can give your reasoning.
"""
MAX_CORRECT_ITERATIONS = 4
MAX_TOTAL_ITERATIONS = 12
def main():
print("Initializing OpenAI client...")
client = OpenAI(api_key=OPENAI_SECRET_KEY)
results = []
for dataset_index in range(12):
print(f"######### DATASET ENTRY {dataset_index} #########")
path_prefix = f"./data/screenshots/{dataset_index}"
correctIterationIndex = 0
for iterationIndex in range(0, MAX_TOTAL_ITERATIONS):
print("--------------------")
print(f"Iteration number: {iterationIndex + 1}")
indexes = [0, 1, 2, 3]
random.shuffle(indexes)
if (indexes[0] == 0):
correctAnswer = "A"
elif (indexes[1] == 0):
correctAnswer = "B"
elif (indexes[2] == 0):
correctAnswer = "C"
elif (indexes[3] == 0):
correctAnswer = "D"
print("Printing labels on images...")
imageA = getImageWithLabel("Section A:", f"{path_prefix}/{indexes[0]}.png")
imageB = getImageWithLabel("Section B:", f"{path_prefix}/{indexes[1]}.png")
imageC = getImageWithLabel("Section C:", f"{path_prefix}/{indexes[2]}.png")
imageD = getImageWithLabel("Section D:", f"{path_prefix}/{indexes[3]}.png")
print("Calling API...")
response = client.chat.completions.create(
model="gpt-4-vision-preview",
max_tokens=2048,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": PROMPT
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{imageToBase64(imageA)}",
"detail": "high"
}
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{imageToBase64(imageB)}",
"detail": "high"
}
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{imageToBase64(imageC)}",
"detail": "high"
}
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{imageToBase64(imageD)}",
"detail": "high"
}
}
]
},
]
)
parsedResponse = parseResponse(response.choices[0].message.content)
if (parsedResponse == None):
if (iterationIndex == MAX_TOTAL_ITERATIONS - 1):
results.append({
"resultStatus": "error"
})
print("ERROR")
else:
realAnswer = parsedResponse[0]
reasoning = parsedResponse[1]
if ((realAnswer == correctAnswer and correctIterationIndex == (MAX_CORRECT_ITERATIONS - 1)) or realAnswer != correctAnswer):
resultStatus = "correct" if correctAnswer == realAnswer else "wrong"
print("Result: " + resultStatus)
output_path_prefix = path_prefix.replace("data", "results")
os.makedirs(output_path_prefix, exist_ok=True)
imageA.save(f"{output_path_prefix}/A.png")
imageB.save(f"{output_path_prefix}/B.png")
imageC.save(f"{output_path_prefix}/C.png")
imageD.save(f"{output_path_prefix}/D.png")
results.append({
"resultStatus": resultStatus,
"correctAnswer": correctAnswer,
"realAnswer": realAnswer,
"reasoning": reasoning,
"try": correctIterationIndex + 1
})
break
correctIterationIndex += 1
json_string = json.dumps(results, indent=4)
with open('results/data.json', 'w') as file:
file.write(json_string)
def parseResponse(response):
if response and response[0] == '#' and response[1] in ('A', 'B', 'C', 'D'):
return (response[1], response[2:])
else:
return None
def getImageWithLabel(label, image_path):
# Load the image
image = Image.open(image_path)
imageWithExtraSpace = Image.new('RGB', (image.width, image.height + 100), 'black')
imageWithExtraSpace.paste(image, (0, 100))
# Initialize the drawing context with the image as background
draw = ImageDraw.Draw(imageWithExtraSpace)
# Specify the font and size (optional, if you want a specific font style)
font = ImageFont.truetype('./data/Inter-Regular.ttf', size=36)
# Position for the label
(x, y) = (25, 25)
# Text color
color = 'rgb(255,255,255)'
# Add text to image
draw.text((x, y), label, fill=color, font=font)
return imageWithExtraSpace
def imageToBase64(image):
# Create a buffer
buffer = io.BytesIO()
# Save image to buffer
image.save(buffer, format='PNG') # Use the appropriate format
# Convert buffer contents to base64
encoded_image = base64.b64encode(buffer.getvalue())
# Decode bytes to string if necessary
return encoded_image.decode()
if __name__ == "__main__":
main()