-
Notifications
You must be signed in to change notification settings - Fork 0
/
OpenAI.py
60 lines (50 loc) · 1.74 KB
/
OpenAI.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
import base64
import requests
import time
from dotenv import load_dotenv
import os
import json
load_dotenv(dotenv_path='.env.local')
api_key = os.getenv("OPENAI_API_KEY")
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
image_path = "food.jpg"
base64_image = encode_image(image_path)
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
payload = {
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
# 肉, 野菜, 魚介類, 麺, 揚げ物, 穀物, パン, デザート・スイーツ
"text": "画像の料理が次のリストの何%を占めているかjsonで教えて。[Meat, Vegetables, Seafood, Noodles, Fried food, Grains, Bread, Desserts and Sweets] json以外は答えないで",
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}",
"detail": "auto",
}
}
]
}
],
"max_tokens": 100,
}
start_time = time.time()
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
end_time = time.time()
response_data = response.json()
content = response_data['choices'][0]['message']['content']
json_content = content.strip("```json\n").strip("\n```")
parsed_json = json.loads(json_content)
for key, value in parsed_json.items():
print(f"{key}: {value}%")
print(f"\nResponse time: {end_time - start_time} seconds")