File size: 3,493 Bytes
f63951f
99ad768
 
67da721
99ad768
61ddbf5
f63951f
99ad768
1b96f25
 
 
 
 
 
99ad768
 
1b96f25
99ad768
1b96f25
c0cbb22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b96f25
f63951f
99ad768
 
 
 
 
 
 
 
 
 
 
 
 
 
61ddbf5
99ad768
f63951f
1b96f25
 
99ad768
1b96f25
 
99ad768
 
f63951f
99ad768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b96f25
99ad768
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
import gradio as gr
import requests
import os
import base64
from PIL import Image
import io

# Функция для кодирования изображения в base64
def encode_image_to_base64(image):
    buffered = io.BytesIO()
    image.save(buffered, format="JPEG")
    img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
    return img_str

# Функция для отправки запроса в OpenAI с изображением и получения ответа
def ask_openai_with_image(instruction, image):

    # Убираем пробелы с начала и конца инструкции
    instruction = instruction.strip()
    if image != None
        # Кодируем загруженное изображение в base64
        base64_image = encode_image_to_base64(image)


        # Создаем данные для запроса с закодированным изображением
        payload = {
            "model": "gpt-4-vision-preview",
            "messages": [
                {
                    "role": "user",
                    "content": instruction,
                },
                {
                    "role": "system",
                    "content": f"data:image/jpeg;base64,{base64_image}",
                }
            ],
            "max_tokens": 4095,
        }

    if image == None
        # Создаем данные для запроса с закодированным изображением
        payload = {
            "model": "gpt-4-vision-preview",
            "messages": [
                {
                    "role": "user",
                    "content": instruction,
                }
            ],
            "max_tokens": 4095,
}    


    # API ключ для OpenAI
    api_key = os.getenv("API_KEY")

    # Заголовки для запроса
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json',
    }

    # URL для запроса к API OpenAI
    url = "https://api.openai.com/v1/chat/completions"

    # Отправляем запрос в OpenAI
    response = requests.post(url, headers=headers, json=payload)

    # Проверяем ответ и возвращаем результат
    if response.status_code == 200:
        response_json = response.json()
        try:
            # Пытаемся извлечь текст из ответа
            return response_json["choices"][0]["message"]["content"]
        except Exception as e:
            # Если есть ошибка в структуре JSON, выводим ее
            return f"Error processing the image response: {e}"
    else:
        # Если произошла ошибка, возвращаем сообщение об ошибке
        return f"Error: {response.status_code} - {response.text}"

# Создаем интерфейс с помощью Gradio
with gr.Blocks() as demo:
    with gr.Row():
        with gr.Column():
            instructions = gr.Textbox(label="Instructions", placeholder="Enter the instructions here...")
            image_input = gr.Image(label="Upload an image", type="pil")
            submit_button = gr.Button("Submit")
        with gr.Column():
            output_markdown = gr.Markdown(label="AI Response")

    submit_button.click(
        fn=ask_openai_with_image,
        inputs=[instructions, image_input],
        outputs=[output_markdown]
    )

demo.launch()