File size: 1,552 Bytes
adc6d8b
 
 
 
de811b0
adc6d8b
de811b0
adc6d8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import dotenv
import base64
import os
import requests
import gradio as gr
import PIL
import numpy as np

dotenv.load_dotenv()


def process_image(image) : 
    # img_name = f"{np.random.randint(0, 100)}.jpg"
    img_name = f"{1}.jpg"
    PIL.Image.fromarray(image.astype('uint8'), 'RGB').save(img_name)
    image = open(img_name, "rb").read()
    base64_image = base64_image = base64.b64encode(image).decode('utf-8')
    openai_api_key = os.getenv('OPENAI_API_KEY')
    # oai_org = os.getenv('OAI_ORG')

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {openai_api_key}"
    }

    payload = {
        "model": "gpt-4-vision-preview",
        "messages": [
        {
            "role": "user",
            "content": [
            {
                "type": "text",
                "text": "What's in this image?"
            },
            {
                "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)

    try :
        out = response.json()
        out = out["choices"][0]["message"]["content"]
        print("out : ", out)
        print("type(out) : ", type(out))

        return f"{out}"
    except Exception as e :
        return f"{e}"

iface = gr.Interface(fn=process_image, inputs="image", outputs="text")
iface.launch()