Spaces:
Sleeping
Sleeping
Update ui.py
Browse files
ui.py
CHANGED
|
@@ -1,152 +1,152 @@
|
|
| 1 |
-
# ui.py
|
| 2 |
-
import streamlit as st
|
| 3 |
-
from time import sleep
|
| 4 |
-
import html
|
| 5 |
-
from PIL import Image
|
| 6 |
-
import io
|
| 7 |
-
import base64
|
| 8 |
-
from utils import render_latex, process_image, MAX_FILE_SIZE_MB # Импортируем MAX_FILE_SIZE_MB
|
| 9 |
-
import api
|
| 10 |
-
import time # Для замера времени выполнения
|
| 11 |
-
|
| 12 |
-
def configure_sidebar(): # Или в main(), если хочешь в основной части
|
| 13 |
-
"""Настраивает боковую панель."""
|
| 14 |
-
with st.sidebar:
|
| 15 |
-
st.markdown("""
|
| 16 |
-
## ⚙️ Settings
|
| 17 |
-
""")
|
| 18 |
-
selected_model = st.selectbox("Select Model", api.MODEL_OPTIONS, index=0) # Добавляем выпадающий список
|
| 19 |
-
temperature = st.slider("Temperature", 0.0, 2.0, 1.0)
|
| 20 |
-
max_tokens = st.slider("Max Tokens", 1, 8192, 8192, key="max_tokens_slider")
|
| 21 |
-
system_prompt = st.text_area("System Prompt (Optional)", value="")
|
| 22 |
-
|
| 23 |
-
st.markdown("""
|
| 24 |
-
---
|
| 25 |
-
### 💡 This project is open-source. Check it out here:
|
| 26 |
-
- [GASIFHFS on Github](https://github.com/SparkleSavvy/GASIFHFS)
|
| 27 |
-
---
|
| 28 |
-
### ❤️ Created by:
|
| 29 |
-
- [SparkleSavvy](https://github.com/SparkleSavvy)
|
| 30 |
-
""")
|
| 31 |
-
return selected_model, temperature, max_tokens, system_prompt
|
| 32 |
-
|
| 33 |
-
def display_messages():
|
| 34 |
-
"""Отображает историю сообщений."""
|
| 35 |
-
for message in st.session_state.messages:
|
| 36 |
-
if message["role"] in ["user", "assistant"]:
|
| 37 |
-
with st.chat_message(message["role"]):
|
| 38 |
-
st.markdown(message["content"], unsafe_allow_html=True) # Рендерим всё
|
| 39 |
-
|
| 40 |
-
def handle_image_upload():
|
| 41 |
-
"""Обрабатывает загрузку изображений."""
|
| 42 |
-
uploaded_files = st.file_uploader(
|
| 43 |
-
f"Upload images (optional, max {MAX_FILE_SIZE_MB}MB each)",
|
| 44 |
-
type=["jpg", "jpeg", "png", "gif", "webp"],
|
| 45 |
-
accept_multiple_files=True
|
| 46 |
-
)
|
| 47 |
-
uploaded_images_data = []
|
| 48 |
-
if uploaded_files:
|
| 49 |
-
for uploaded_file in uploaded_files:
|
| 50 |
-
try:
|
| 51 |
-
image_data, image_format = process_image(uploaded_file)
|
| 52 |
-
# Убрали проверку if image_data and image_format:, так как теперь
|
| 53 |
-
# process_image выбрасывает исключение ValueError если ошибка
|
| 54 |
-
if image_format == "gif":
|
| 55 |
-
st.markdown(f'<img src="data:image/gif;base64,{image_data}" alt="Uploaded GIF" style="width: 100%;">', unsafe_allow_html=True)
|
| 56 |
-
else:
|
| 57 |
-
st.image(uploaded_file, caption=f"Uploaded Image {len(uploaded_images_data) + 1}", use_container_width=True)
|
| 58 |
-
uploaded_images_data.append((image_data, image_format))
|
| 59 |
-
except ValueError as e:
|
| 60 |
-
st.error(e) # Выводим сообщение об ошибке из исключения
|
| 61 |
-
return uploaded_images_data
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def process_user_input(temperature, max_tokens, system_prompt, uploaded_images_data):
|
| 65 |
-
"""Обрабатывает ввод пользователя и отправляет запрос."""
|
| 66 |
-
if prompt := st.chat_input("What is up?"):
|
| 67 |
-
message_content = [prompt]
|
| 68 |
-
if uploaded_images_data:
|
| 69 |
-
# Добавляем все изображения в запрос
|
| 70 |
-
for image_data, image_format in uploaded_images_data:
|
| 71 |
-
message_content.insert(-1, {'mime_type': f'image/{image_format}', 'data': image_data})
|
| 72 |
-
|
| 73 |
-
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 74 |
-
with st.chat_message("user"):
|
| 75 |
-
st.markdown(prompt)
|
| 76 |
-
|
| 77 |
-
with st.chat_message("assistant"):
|
| 78 |
-
status_placeholder = st.empty()
|
| 79 |
-
message_placeholder = st.empty()
|
| 80 |
-
full_response = ""
|
| 81 |
-
# Немного светлее основного фона
|
| 82 |
-
status_placeholder.markdown("<span style='background-color: #292929; border-radius: 5px; padding: 5px 10px;'>:hourglass: Sending a request...</span>", unsafe_allow_html=True)
|
| 83 |
-
start_time = time.time()
|
| 84 |
-
|
| 85 |
-
if system_prompt:
|
| 86 |
-
st.session_state.chat_session.history.insert(0, {
|
| 87 |
-
"role": "user",
|
| 88 |
-
"parts": [{"text": system_prompt}]
|
| 89 |
-
})
|
| 90 |
-
st.session_state.chat_session.history.insert(1, {
|
| 91 |
-
"role": "model",
|
| 92 |
-
"parts": [{"text": "Ok."}]
|
| 93 |
-
})
|
| 94 |
-
|
| 95 |
-
response = api.generate_response(
|
| 96 |
-
st.session_state.chat_session,
|
| 97 |
-
message_content,
|
| 98 |
-
generation_config={
|
| 99 |
-
"temperature": temperature,
|
| 100 |
-
"max_output_tokens": max_tokens,
|
| 101 |
-
}
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
if response:
|
| 105 |
-
status_placeholder.markdown("<span style='background-color: #292929; border-radius: 5px; padding: 5px 10px;'>:hourglass: Response generation...</span>", unsafe_allow_html=True)
|
| 106 |
-
for chunk in response:
|
| 107 |
-
for char in chunk.text:
|
| 108 |
-
full_response += char
|
| 109 |
-
message_placeholder.markdown(full_response + " ⬤", unsafe_allow_html=True) # Убрали html.escape
|
| 110 |
-
sleep(0.01)
|
| 111 |
-
|
| 112 |
-
message_placeholder.markdown(full_response, unsafe_allow_html=True) # Убрали html.escape
|
| 113 |
-
|
| 114 |
-
end_time = time.time()
|
| 115 |
-
elapsed_time = end_time - start_time
|
| 116 |
-
status_placeholder.markdown(f"<span style='background-color: #292929; border-radius: 5px; padding: 5px 10px;'>:white_check_mark: Answer generated in {elapsed_time:.2f} sec.</span>", unsafe_allow_html=True)
|
| 117 |
-
|
| 118 |
-
else:
|
| 119 |
-
full_response = "Error occurred while generating response."
|
| 120 |
-
message_placeholder.markdown(full_response)
|
| 121 |
-
status_placeholder.markdown("<span style='background-color: #292929; border-radius: 5px; padding: 5px 10px;'>:x: Error while generating a response.</span>", unsafe_allow_html=True)
|
| 122 |
-
|
| 123 |
-
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
| 124 |
-
st.session_state.latex_segments = []
|
| 125 |
-
|
| 126 |
-
def main():
|
| 127 |
-
"""Основная функция приложения."""
|
| 128 |
-
st.markdown("""
|
| 129 |
-
<style>
|
| 130 |
-
/* Inline display for KaTeX */
|
| 131 |
-
.katex-display { display: inline; }
|
| 132 |
-
.katex-display>.katex { display: inline; }
|
| 133 |
-
.katex-display>.katex>.katex-html { display: inline; }
|
| 134 |
-
</style>
|
| 135 |
-
""", unsafe_allow_html=True)
|
| 136 |
-
st.title("Hello, miracle!")
|
| 137 |
-
st.caption("✦ GASIFHFS | v1.0.2-beta.6")
|
| 138 |
-
|
| 139 |
-
selected_model, temperature, max_tokens, system_prompt = configure_sidebar()
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
model = api.load_model(selected_model)
|
| 143 |
-
st.session_state.chat_session = api.start_chat_session(model)
|
| 144 |
-
|
| 145 |
-
if "messages" not in st.session_state:
|
| 146 |
-
st.session_state.messages = []
|
| 147 |
-
|
| 148 |
-
display_messages()
|
| 149 |
-
|
| 150 |
-
uploaded_image = handle_image_upload()
|
| 151 |
-
|
| 152 |
process_user_input(temperature, max_tokens, system_prompt, uploaded_image)
|
|
|
|
| 1 |
+
# ui.py
|
| 2 |
+
import streamlit as st
|
| 3 |
+
from time import sleep
|
| 4 |
+
import html
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import io
|
| 7 |
+
import base64
|
| 8 |
+
from utils import render_latex, process_image, MAX_FILE_SIZE_MB # Импортируем MAX_FILE_SIZE_MB
|
| 9 |
+
import api
|
| 10 |
+
import time # Для замера времени выполнения
|
| 11 |
+
|
| 12 |
+
def configure_sidebar(): # Или в main(), если хочешь в основной части
|
| 13 |
+
"""Настраивает боковую панель."""
|
| 14 |
+
with st.sidebar:
|
| 15 |
+
st.markdown("""
|
| 16 |
+
## ⚙️ Settings
|
| 17 |
+
""")
|
| 18 |
+
selected_model = st.selectbox("Select Model", api.MODEL_OPTIONS, index=0) # Добавляем выпадающий список
|
| 19 |
+
temperature = st.slider("Temperature", 0.0, 2.0, 1.0)
|
| 20 |
+
max_tokens = st.slider("Max Tokens", 1, 8192, 8192, key="max_tokens_slider")
|
| 21 |
+
system_prompt = st.text_area("System Prompt (Optional)", value="")
|
| 22 |
+
|
| 23 |
+
st.markdown("""
|
| 24 |
+
---
|
| 25 |
+
### 💡 This project is open-source. Check it out here:
|
| 26 |
+
- [GASIFHFS on Github](https://github.com/SparkleSavvy/GASIFHFS)
|
| 27 |
+
---
|
| 28 |
+
### ❤️ Created by:
|
| 29 |
+
- [SparkleSavvy](https://github.com/SparkleSavvy)
|
| 30 |
+
""")
|
| 31 |
+
return selected_model, temperature, max_tokens, system_prompt
|
| 32 |
+
|
| 33 |
+
def display_messages():
|
| 34 |
+
"""Отображает историю сообщений."""
|
| 35 |
+
for message in st.session_state.messages:
|
| 36 |
+
if message["role"] in ["user", "assistant"]:
|
| 37 |
+
with st.chat_message(message["role"]):
|
| 38 |
+
st.markdown(message["content"], unsafe_allow_html=True) # Рендерим всё
|
| 39 |
+
|
| 40 |
+
def handle_image_upload():
|
| 41 |
+
"""Обрабатывает загрузку изображений."""
|
| 42 |
+
uploaded_files = st.file_uploader(
|
| 43 |
+
f"Upload images (optional, max {MAX_FILE_SIZE_MB}MB each)",
|
| 44 |
+
type=["jpg", "jpeg", "png", "gif", "webp"],
|
| 45 |
+
accept_multiple_files=True
|
| 46 |
+
)
|
| 47 |
+
uploaded_images_data = []
|
| 48 |
+
if uploaded_files:
|
| 49 |
+
for uploaded_file in uploaded_files:
|
| 50 |
+
try:
|
| 51 |
+
image_data, image_format = process_image(uploaded_file)
|
| 52 |
+
# Убрали проверку if image_data and image_format:, так как теперь
|
| 53 |
+
# process_image выбрасывает исключение ValueError если ошибка
|
| 54 |
+
if image_format == "gif":
|
| 55 |
+
st.markdown(f'<img src="data:image/gif;base64,{image_data}" alt="Uploaded GIF" style="width: 100%;">', unsafe_allow_html=True)
|
| 56 |
+
else:
|
| 57 |
+
st.image(uploaded_file, caption=f"Uploaded Image {len(uploaded_images_data) + 1}", use_container_width=True)
|
| 58 |
+
uploaded_images_data.append((image_data, image_format))
|
| 59 |
+
except ValueError as e:
|
| 60 |
+
st.error(e) # Выводим сообщение об ошибке из исключения
|
| 61 |
+
return uploaded_images_data
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def process_user_input(temperature, max_tokens, system_prompt, uploaded_images_data):
|
| 65 |
+
"""Обрабатывает ввод пользователя и отправляет запрос."""
|
| 66 |
+
if prompt := st.chat_input("What is up?"):
|
| 67 |
+
message_content = [prompt]
|
| 68 |
+
if uploaded_images_data:
|
| 69 |
+
# Добавляем все изображения в запрос
|
| 70 |
+
for image_data, image_format in uploaded_images_data:
|
| 71 |
+
message_content.insert(-1, {'mime_type': f'image/{image_format}', 'data': image_data})
|
| 72 |
+
|
| 73 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 74 |
+
with st.chat_message("user"):
|
| 75 |
+
st.markdown(prompt)
|
| 76 |
+
|
| 77 |
+
with st.chat_message("assistant"):
|
| 78 |
+
status_placeholder = st.empty()
|
| 79 |
+
message_placeholder = st.empty()
|
| 80 |
+
full_response = ""
|
| 81 |
+
# Немного светлее основного фона
|
| 82 |
+
status_placeholder.markdown("<span style='background-color: #292929; border-radius: 5px; padding: 5px 10px;'>:hourglass: Sending a request...</span>", unsafe_allow_html=True)
|
| 83 |
+
start_time = time.time()
|
| 84 |
+
|
| 85 |
+
if system_prompt:
|
| 86 |
+
st.session_state.chat_session.history.insert(0, {
|
| 87 |
+
"role": "user",
|
| 88 |
+
"parts": [{"text": system_prompt}]
|
| 89 |
+
})
|
| 90 |
+
st.session_state.chat_session.history.insert(1, {
|
| 91 |
+
"role": "model",
|
| 92 |
+
"parts": [{"text": "Ok."}]
|
| 93 |
+
})
|
| 94 |
+
|
| 95 |
+
response = api.generate_response(
|
| 96 |
+
st.session_state.chat_session,
|
| 97 |
+
message_content,
|
| 98 |
+
generation_config={
|
| 99 |
+
"temperature": temperature,
|
| 100 |
+
"max_output_tokens": max_tokens,
|
| 101 |
+
}
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
if response:
|
| 105 |
+
status_placeholder.markdown("<span style='background-color: #292929; border-radius: 5px; padding: 5px 10px;'>:hourglass: Response generation...</span>", unsafe_allow_html=True)
|
| 106 |
+
for chunk in response:
|
| 107 |
+
for char in chunk.text:
|
| 108 |
+
full_response += char
|
| 109 |
+
message_placeholder.markdown(full_response + " ⬤", unsafe_allow_html=True) # Убрали html.escape
|
| 110 |
+
sleep(0.01)
|
| 111 |
+
|
| 112 |
+
message_placeholder.markdown(full_response, unsafe_allow_html=True) # Убрали html.escape
|
| 113 |
+
|
| 114 |
+
end_time = time.time()
|
| 115 |
+
elapsed_time = end_time - start_time
|
| 116 |
+
status_placeholder.markdown(f"<span style='background-color: #292929; border-radius: 5px; padding: 5px 10px;'>:white_check_mark: Answer generated in {elapsed_time:.2f} sec.</span>", unsafe_allow_html=True)
|
| 117 |
+
|
| 118 |
+
else:
|
| 119 |
+
full_response = "Error occurred while generating response."
|
| 120 |
+
message_placeholder.markdown(full_response)
|
| 121 |
+
status_placeholder.markdown("<span style='background-color: #292929; border-radius: 5px; padding: 5px 10px;'>:x: Error while generating a response.</span>", unsafe_allow_html=True)
|
| 122 |
+
|
| 123 |
+
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
| 124 |
+
st.session_state.latex_segments = []
|
| 125 |
+
|
| 126 |
+
def main():
|
| 127 |
+
"""Основная функция приложения."""
|
| 128 |
+
st.markdown("""
|
| 129 |
+
<style>
|
| 130 |
+
/* Inline display for KaTeX */
|
| 131 |
+
.katex-display { display: inline; }
|
| 132 |
+
.katex-display>.katex { display: inline; }
|
| 133 |
+
.katex-display>.katex>.katex-html { display: inline; }
|
| 134 |
+
</style>
|
| 135 |
+
""", unsafe_allow_html=True)
|
| 136 |
+
st.title("Hello, miracle!")
|
| 137 |
+
st.caption("✦ GASIFHFS | v1.0.2-beta.6")
|
| 138 |
+
|
| 139 |
+
selected_model, temperature, max_tokens, system_prompt = configure_sidebar()
|
| 140 |
+
|
| 141 |
+
if "chat_session" not in st.session_state:
|
| 142 |
+
model = api.load_model(selected_model) # Используем выбранную модель
|
| 143 |
+
st.session_state.chat_session = api.start_chat_session(model)
|
| 144 |
+
|
| 145 |
+
if "messages" not in st.session_state:
|
| 146 |
+
st.session_state.messages = []
|
| 147 |
+
|
| 148 |
+
display_messages()
|
| 149 |
+
|
| 150 |
+
uploaded_image = handle_image_upload()
|
| 151 |
+
|
| 152 |
process_user_input(temperature, max_tokens, system_prompt, uploaded_image)
|