-
Notifications
You must be signed in to change notification settings - Fork 98
/
gpt4v.py
69 lines (60 loc) · 1.76 KB
/
gpt4v.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
import os
import base64
import requests
from io import BytesIO
# Get OpenAI API Key from environment variable
api_key = os.environ["OPENAI_API_KEY"]
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
metaprompt = '''
- For any marks mentioned in your answer, please highlight them with [].
'''
# Function to encode the image
def encode_image_from_file(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def encode_image_from_pil(image):
buffered = BytesIO()
image.save(buffered, format="JPEG")
return base64.b64encode(buffered.getvalue()).decode('utf-8')
def prepare_inputs(message, image):
# # Path to your image
# image_path = "temp.jpg"
# # Getting the base64 string
# base64_image = encode_image(image_path)
base64_image = encode_image_from_pil(image)
payload = {
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "system",
"content": [
metaprompt
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": message,
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
],
"max_tokens": 800
}
return payload
def request_gpt4v(message, image):
payload = prepare_inputs(message, image)
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
res = response.json()['choices'][0]['message']['content']
return res