|
import gradio as gr |
|
from PIL import Image |
|
import io |
|
import 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 |
|
|
|
|
|
def send_message(message, image=None): |
|
|
|
response = "Это ответ бота на ваше сообщение." |
|
return response, "" |
|
|
|
css = """ |
|
footer {visibility: hidden !important;} |
|
.chat-container {height: 90vh; display: flex; flex-direction: column;} |
|
.chat-messages {flex: 1; overflow-y: auto; padding: 10px;} |
|
.input-group {display: flex; align-items: center; padding: 10px;} |
|
.image-preview {max-width: 200px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);} |
|
""" |
|
|
|
|
|
with gr.Blocks(css=css) as demo: |
|
chat_history = gr.Markdown("Привет! Я Помогатор, готов помочь тебе с любыми вопросами!) 😊").style( |
|
container=True, |
|
scroll="auto", |
|
height="auto", |
|
max_height="400px" |
|
) |
|
with gr.Row(): |
|
input_message = gr.Textbox(placeholder="Введите ваше сообщение здесь...", lines=2, interactive=True, max_lines=5) |
|
send_button = gr.Button("Отправить") |
|
attach_button = gr.File(label="", file_count="single", interactive=True) |
|
attach_button.style(icon="paperclip", hide_label=True) |
|
clear_button = gr.Button(label="") |
|
clear_button.style(icon="times", hide_label=True, visible=False) |
|
|
|
def preview_image(file_info): |
|
if file_info is not None: |
|
clear_button.style(visible=True) |
|
attach_button.style(visible=False) |
|
image = Image.open(io.BytesIO(file_info["content"])) |
|
img_str = encode_image_to_base64(image) |
|
return f"data:image/jpeg;base64,{img_str}" |
|
else: |
|
clear_button.style(visible=False) |
|
attach_button.style(visible=True) |
|
return None |
|
|
|
def clear_image(): |
|
attach_button.reset() |
|
clear_button.style(visible=False) |
|
attach_button.style(visible=True) |
|
return None |
|
|
|
def handle_send(message, image=None): |
|
response, img_str = send_message(message, image) |
|
new_message = f"**Вы:** {message}\n\n" if message else "" |
|
new_message += f"**Помогатор:** {response}\n\n" |
|
chat_history.update(new_message + chat_history.value) |
|
input_message.reset() |
|
clear_image() |
|
|
|
send_button.click(handle_send, inputs=[input_message, attach_button], outputs=[]) |
|
attach_button.change(preview_image, inputs=[attach_button], outputs=[chat_history]) |
|
clear_button.click(clear_image, inputs=[], outputs=[chat_history]) |
|
|
|
|
|
demo.launch() |