|
import gradio as gr |
|
import requests |
|
import os |
|
import base64 |
|
from PIL import Image |
|
import io |
|
|
|
|
|
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 |
|
|
|
|
|
def ask_openai_with_image(instruction, image): |
|
|
|
|
|
instruction = instruction.strip() |
|
start = f"Ты помощник студентов. Ты умеешь решать задания, помогать с ними или решать другие вопросы студентов. Ты добрый, приветливый и понятный для студентов любого возраста. Если тебе отправят фото, то ты должен будешь решить задание с фото. Решай правильно, понятно и красиво. Можно отвечать с markdown." |
|
|
|
if image != None: |
|
|
|
base64_image = encode_image_to_base64(image) |
|
|
|
|
|
|
|
payload = { |
|
"model": "gpt-4-vision-preview", |
|
"messages": [ |
|
{ |
|
"role": "user", |
|
"content": start, |
|
}, |
|
{ |
|
"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": start, |
|
}, |
|
{ |
|
"role": "user", |
|
"content": instruction, |
|
} |
|
], |
|
"max_tokens": 4095, |
|
} |
|
|
|
|
|
|
|
api_key = os.getenv("API_KEY") |
|
|
|
|
|
headers = { |
|
'Authorization': f'Bearer {api_key}', |
|
'Content-Type': 'application/json', |
|
} |
|
|
|
|
|
url = "https://api.openai.com/v1/chat/completions" |
|
|
|
|
|
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: |
|
|
|
return f"Error processing the image response: {e}" |
|
else: |
|
|
|
return f"Error: {response.status_code} - {response.text}" |
|
|
|
|
|
with gr.Blocks() as demo: |
|
with gr.Row(): |
|
with gr.Column(): |
|
instructions = gr.Textbox(label="Дополнительный ввод") |
|
image_input = gr.Image(label="Фото задания", type="pil") |
|
submit_button = gr.Button("Решить") |
|
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() |