File size: 4,163 Bytes
f63951f
99ad768
61ddbf5
83eef3f
f63951f
99ad768
1b96f25
 
 
 
 
 
83eef3f
 
 
 
 
 
 
 
 
99ad768
433ad14
 
83eef3f
 
 
 
433ad14
43b505a
83eef3f
433ad14
83eef3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43b505a
83eef3f
 
 
43b505a
83eef3f
43b505a
83eef3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from PIL import Image
import io
import base64

# Функция для кодирования изображения в 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 = f"Вы сказали: {message}"
    if image:
        img_str = encode_image_to_base64(image)
        return response, f"data:image/jpeg;base64,{img_str}"
    return response, None

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:
    with gr.Row().style(equal_height=False):
        chat_history = gr.Markdown("Привет! Я Помогатор, готов помочь тебе с любыми вопросами!) 😊").style(
            container=True, 
            scroll="auto", 
            height="auto", 
            max_height="400px"
        )
    with gr.Row().style(justify_content="center", padding="10px"):
        with gr.Column(scale=12):
            input_message = gr.Textbox(placeholder="Введите ваше сообщение здесь...", lines=2, interactive=True, max_lines=5)
        with gr.Column(scale=1, min_width="50px"):
            send_button = gr.Button("Отправить")
        with gr.Column(scale=1, min_width="50px"):
            attach_button = gr.File(label="", file_count="single", interactive=True)
            attach_button.style(icon="paperclip", hide_label=True)
        with gr.Column(scale=1, min_width="50px"):
            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"![uploaded image]({img_str})\n\n" if img_str 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()