import streamlit as st
import google.generativeai as genai
from PIL import Image
import io
import base64
import time
from config import Config
from models.gemini import GeminiModel
gemini_model = GeminiModel(api_key=st.secrets["GOOGLE_API_KEY"])
def process_image(uploaded_file):
"""Processes uploaded images with format conversion and size checks."""
if uploaded_file.size > Config.get_max_file_size() * 1024 * 1024:
raise ValueError(f"File size too large. Max: {Config.get_max_file_size()}MB")
try:
img = Image.open(uploaded_file)
if img.format not in ("JPEG", "PNG", "GIF", "WEBP"):
raise ValueError(f"Unsupported format: {img.format}")
if img.format == "PNG" and 'transparency' in img.info:
img = img.convert("RGBA")
background = Image.new("RGBA", img.size, (255, 255, 255))
img = Image.alpha_composite(background, img).convert("RGB")
elif img.format == "GIF" and img.is_animated:
frames = []
for frame in range(img.n_frames):
img.seek(frame)
frames.append(img.convert("RGB"))
buffered = io.BytesIO()
frames[0].save(buffered, format="GIF", save_all=True, append_images=frames[1:], loop=0)
return base64.b64encode(buffered.getvalue()).decode(), "gif"
else:
img = img.convert("RGB")
buffered = io.BytesIO()
img.save(buffered, format="JPEG")
return base64.b64encode(buffered.getvalue()).decode(), "jpeg"
except (IOError, ValueError, AttributeError) as e:
raise ValueError(f"Image processing failed: {str(e)}")
def configure_sidebar():
"""Configures the sidebar with model selection and settings."""
with st.sidebar:
st.markdown("## ⚙️ Settings")
selected_model = st.selectbox("Select Model", Config.get_model_options(), format_func=lambda x: x)
temperature = st.number_input("Temperature", 0.0, 2.0, 0.9, 0.1)
max_tokens = st.number_input("Max Tokens", 1, 65536, 8192, 100)
top_p = st.number_input("Top P", 0.0, 1.0, 0.95, 0.05)
system_prompt = st.text_area("System Prompt (Optional)", value="")
if st.button("Clear Chat"):
st.session_state.messages = []
if "chat_session" in st.session_state:
del st.session_state["chat_session"]
st.markdown(f"""
---
### 💡 Open Source Project:
- [GitHub Repo](https://github.com/SparkleSavvy/GASIFHFS)
---
### ❤️ Created by:
- [SparkleSavvy](https://github.com/SparkleSavvy)
""")
return selected_model, temperature, max_tokens, system_prompt, top_p
def display_messages():
"""Displays chat messages with proper styling."""
for message in st.session_state.messages:
if message["role"] in ["user", "assistant"]:
with st.chat_message(message["role"]):
st.markdown(message["content"], unsafe_allow_html=True)
def handle_image_upload():
"""Handles image uploads with validation and processing."""
uploaded_files = st.file_uploader(
f"Upload images (max {Config.get_max_file_size()}MB each)",
type=["jpg", "jpeg", "png", "gif", "webp"],
accept_multiple_files=True,
key="file_uploader"
)
processed_files = []
if uploaded_files:
for file in uploaded_files:
try:
data, fmt = process_image(file)
processed_files.append((data, fmt))
except ValueError as e:
st.error(e)
if processed_files:
st.markdown("**Attached files:**")
cols = st.columns(3)
for i, (data, fmt) in enumerate(processed_files):
with cols[i % 3]:
if fmt == "gif":
st.markdown(f'', unsafe_allow_html=True)
else:
st.image(f"data:image/{fmt};base64,{data}", width=100)
return processed_files
def process_user_input(temperature, max_tokens, system_prompt, top_p, uploaded_images):
"""Handles user input and generates responses."""
if prompt := st.chat_input("Ask something..."):
if prompt:
message_content = []
# Add images first
for data, fmt in uploaded_images:
message_content.append({
"mime_type": f"image/{fmt}",
"data": data
})
# Add user prompt last
message_content.append(prompt)
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
status = st.empty()
message_area = st.empty()
full_response = ""
# Stage 1: Preparing request
status.markdown("§ Preparing request...", unsafe_allow_html=True)
time.sleep(0.1)
response = gemini_model.generate_response(
st.session_state.chat_session,
message_content,
{
"temperature": temperature,
"max_output_tokens": max_tokens,
"top_p": top_p
}
)
if response:
# Stage 2: Generating response
status.markdown("§ Generating response...", unsafe_allow_html=True)
for chunk in response:
for char in chunk.text:
full_response += char
message_area.markdown(full_response + " ▌", unsafe_allow_html=True)
time.sleep(0.01)
# Stage 3: Finalizing
status.markdown("✓ Done", unsafe_allow_html=True)
message_area.markdown(full_response, unsafe_allow_html=True)
st.session_state.messages.append({"role": "assistant", "content": full_response})
else:
status.markdown("✕ Error generating response", unsafe_allow_html=True)
message_area.markdown("Please try again.")
def main():
st.markdown("""
""", unsafe_allow_html=True)
st.title("Hello, miracle!")
st.caption("✦ GASIFHFS | v1.0.2-beta.8")
selected_model, temperature, max_tokens, system_prompt, top_p = configure_sidebar()
# Initialize chat session when needed
if "chat_session" not in st.session_state or \
selected_model != st.session_state.get("last_model", None) or \
system_prompt != st.session_state.get("last_system_prompt", ""):
try:
model = gemini_model.load_model(selected_model)
st.session_state.chat_session = gemini_model.start_chat_session(model)
if system_prompt:
try:
st.session_state.chat_session.send_message(system_prompt)
except Exception as e:
st.markdown(f"""