Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -18,118 +18,93 @@ def ask_openai_with_image(instruction, image):
|
|
| 18 |
if not instruction and not image:
|
| 19 |
emj = random.choice(emojis)
|
| 20 |
raise gr.Error(f"{emj} Заполни пожалуйста хотя бы 1 поле")
|
| 21 |
-
|
| 22 |
-
if image
|
| 23 |
-
# Кодируем загруженное изображение в base64
|
| 24 |
base64_image = encode_image_to_base64(image)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
"type": "text",
|
| 40 |
-
"text": instruction,
|
| 41 |
-
},
|
| 42 |
-
{
|
| 43 |
-
"type": "image_url",
|
| 44 |
-
"image_url": {
|
| 45 |
-
"url": f"data:image/jpeg;base64,{base64_image}",
|
| 46 |
-
"detail": "high",
|
| 47 |
-
},
|
| 48 |
-
},
|
| 49 |
-
],
|
| 50 |
-
}
|
| 51 |
-
],
|
| 52 |
-
"max_tokens": 4095,
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
if image == None:
|
| 56 |
-
# Создаем данные для запроса с закодированным изображением
|
| 57 |
-
payload = {
|
| 58 |
-
"model": "gpt-4-vision-preview",
|
| 59 |
-
"messages": [
|
| 60 |
-
{
|
| 61 |
-
"role": "user",
|
| 62 |
-
"content": start,
|
| 63 |
},
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
# API ключ для OpenAI
|
| 74 |
api_key = os.getenv("API_KEY")
|
| 75 |
-
|
| 76 |
-
# Заголовки для запроса
|
| 77 |
headers = {
|
| 78 |
'Authorization': f'Bearer {api_key}',
|
| 79 |
'Content-Type': 'application/json',
|
| 80 |
}
|
| 81 |
-
|
| 82 |
-
# URL для запроса к API OpenAI
|
| 83 |
url = "https://api.openai.com/v1/chat/completions"
|
| 84 |
|
| 85 |
-
# Отправляем запрос в OpenAI
|
| 86 |
response = requests.post(url, headers=headers, json=payload)
|
| 87 |
|
| 88 |
-
# Проверяем ответ и возвращаем результат
|
| 89 |
if response.status_code == 200:
|
| 90 |
response_json = response.json()
|
| 91 |
try:
|
| 92 |
-
# Пытаемся извлечь текст из ответа
|
| 93 |
otvet = response_json["choices"][0]["message"]["content"]
|
| 94 |
-
print(f"Генерация \"{instruction}\": {otvet}")
|
| 95 |
return otvet
|
| 96 |
except Exception as e:
|
| 97 |
-
# Если есть ошибка в структуре JSON, выводим ее
|
| 98 |
return f"Error processing the image response: {e}"
|
| 99 |
else:
|
| 100 |
-
# Если произошла ошибка, возвращаем сообщение об ошибке
|
| 101 |
return f"Error: {response.status_code} - {response.text}"
|
| 102 |
-
|
| 103 |
css = """
|
| 104 |
footer {visibility: hidden !important;}
|
| 105 |
"""
|
| 106 |
|
| 107 |
with gr.Blocks(css=css, theme='YTheme/KidsShool') as demo:
|
| 108 |
-
chat_history = gr.
|
| 109 |
|
| 110 |
with gr.Row():
|
| 111 |
-
|
| 112 |
instructions = gr.Textbox(label="Введите ваше сообщение здесь", placeholder="Привет!) ...", lines=2)
|
| 113 |
submit_button = gr.Button(value="Отправить")
|
| 114 |
|
| 115 |
-
def send_message(instruction, image):
|
| 116 |
response = ask_openai_with_image(instruction, image)
|
| 117 |
-
|
|
|
|
| 118 |
|
| 119 |
submit_button.click(
|
| 120 |
fn=send_message,
|
| 121 |
-
inputs=[instructions,
|
| 122 |
-
outputs=[]
|
| 123 |
)
|
| 124 |
|
| 125 |
def show_image_input():
|
| 126 |
-
|
| 127 |
|
| 128 |
-
image_input_button = gr.Button(value="🖼️")
|
| 129 |
image_input_button.click(
|
| 130 |
fn=show_image_input,
|
| 131 |
inputs=[],
|
| 132 |
-
outputs=[]
|
| 133 |
)
|
| 134 |
|
| 135 |
demo.launch()
|
|
|
|
| 18 |
if not instruction and not image:
|
| 19 |
emj = random.choice(emojis)
|
| 20 |
raise gr.Error(f"{emj} Заполни пожалуйста хотя бы 1 поле")
|
| 21 |
+
|
| 22 |
+
if image is not None:
|
|
|
|
| 23 |
base64_image = encode_image_to_base64(image)
|
| 24 |
+
content = [
|
| 25 |
+
{
|
| 26 |
+
"role": "user",
|
| 27 |
+
"content": start,
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"role": "user",
|
| 31 |
+
"content": instruction,
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"role": "user",
|
| 35 |
+
"content": {
|
| 36 |
+
"type": "image_url",
|
| 37 |
+
"image_url": f"data:image/jpeg;base64,{base64_image}",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
},
|
| 39 |
+
},
|
| 40 |
+
]
|
| 41 |
+
else:
|
| 42 |
+
content = [
|
| 43 |
+
{
|
| 44 |
+
"role": "user",
|
| 45 |
+
"content": start,
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"role": "user",
|
| 49 |
+
"content": instruction,
|
| 50 |
+
},
|
| 51 |
+
]
|
| 52 |
|
| 53 |
+
payload = {
|
| 54 |
+
"model": "gpt-4-vision-preview",
|
| 55 |
+
"messages": content,
|
| 56 |
+
"max_tokens": 4095,
|
| 57 |
+
}
|
| 58 |
|
|
|
|
| 59 |
api_key = os.getenv("API_KEY")
|
|
|
|
|
|
|
| 60 |
headers = {
|
| 61 |
'Authorization': f'Bearer {api_key}',
|
| 62 |
'Content-Type': 'application/json',
|
| 63 |
}
|
|
|
|
|
|
|
| 64 |
url = "https://api.openai.com/v1/chat/completions"
|
| 65 |
|
|
|
|
| 66 |
response = requests.post(url, headers=headers, json=payload)
|
| 67 |
|
|
|
|
| 68 |
if response.status_code == 200:
|
| 69 |
response_json = response.json()
|
| 70 |
try:
|
|
|
|
| 71 |
otvet = response_json["choices"][0]["message"]["content"]
|
|
|
|
| 72 |
return otvet
|
| 73 |
except Exception as e:
|
|
|
|
| 74 |
return f"Error processing the image response: {e}"
|
| 75 |
else:
|
|
|
|
| 76 |
return f"Error: {response.status_code} - {response.text}"
|
| 77 |
+
|
| 78 |
css = """
|
| 79 |
footer {visibility: hidden !important;}
|
| 80 |
"""
|
| 81 |
|
| 82 |
with gr.Blocks(css=css, theme='YTheme/KidsShool') as demo:
|
| 83 |
+
chat_history = gr.State(value="Привет! 👋 Я - **Помогатор**, помощник студентов...")
|
| 84 |
|
| 85 |
with gr.Row():
|
| 86 |
+
image_input_button = gr.Button(value="🖼️ Загрузить изображение")
|
| 87 |
instructions = gr.Textbox(label="Введите ваше сообщение здесь", placeholder="Привет!) ...", lines=2)
|
| 88 |
submit_button = gr.Button(value="Отправить")
|
| 89 |
|
| 90 |
+
def send_message(instruction, image, chat_history):
|
| 91 |
response = ask_openai_with_image(instruction, image)
|
| 92 |
+
new_chat_history = chat_history + "\n\n" + instruction + "\n\n" + response
|
| 93 |
+
return new_chat_history
|
| 94 |
|
| 95 |
submit_button.click(
|
| 96 |
fn=send_message,
|
| 97 |
+
inputs=[instructions, image_input_button, chat_history],
|
| 98 |
+
outputs=[chat_history]
|
| 99 |
)
|
| 100 |
|
| 101 |
def show_image_input():
|
| 102 |
+
return gr.update(value=True)
|
| 103 |
|
|
|
|
| 104 |
image_input_button.click(
|
| 105 |
fn=show_image_input,
|
| 106 |
inputs=[],
|
| 107 |
+
outputs=[image_input_button]
|
| 108 |
)
|
| 109 |
|
| 110 |
demo.launch()
|