-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpt_api.py
88 lines (68 loc) Β· 2.13 KB
/
gpt_api.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
import base64
import requests
#from api_keys import OPENAI_API_KEY
from openai import OpenAI
import streamlit as st
# OpenAI API Key
api_key = st.secrets["OPENAI_API_KEY"]
# Function to encode the image
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def image_to_text(base64_image, prompt):
# Getting the base64 string
#base64_image = encode_image(image_path) #use this if image_path is given
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
payload = {
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
],
"max_tokens": 300
}
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
print("RESPONSE: ", response)
print(" ")
return response.json()['choices'][0]['message']['content']
def text_to_text(text_input, prompt):
client = OpenAI(api_key=api_key)
response = client.chat.completions.create(
model="gpt-3.5-turbo-0125",
messages=[
{"role": "system", "content": prompt},
{"role": "user", "content": text_input}
]
)
return response.choices[0].message.content
def text_to_text_v2(user_prompt, json_format=False):
client = OpenAI(api_key=api_key)
response = client.chat.completions.create(
# model="gpt-3.5-turbo-0125",
response_format={"type": "json_object"},
model = "gpt-4-1106-preview",
messages=[
{"role": "user", "content": user_prompt},
]
)
return response.choices[0].message.content
if __name__ == "__main__":
image_path = "posts_cristiano/2024-02-15_16-29-45_UTC.jpg"
# prompt = "What objects are in the image?"
# image_to_text(image_path, prompt)