Spaces:
Sleeping
Sleeping
Download app.py from DEADS1KE/GASIFHFS: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/spaces/DEADS1KE/GASIFHFS/resolve/main/app.py
- Command line
-
hf download hf://spaces/DEADS1KE/GASIFHFS/app.py
-
curl -L -o app.py https://huggingface.co/spaces/DEADS1KE/GASIFHFS/resolve/main/app.py
11.2 kB
| 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'<img src="data:image/gif;base64,{data}" style="max-width:100px;max-height:100px;">', 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("<span style='background:#292929;padding:5px;border-radius:5px;'>§ Preparing request...</span>", 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("<span style='background:#292929;padding:5px;border-radius:5px;'>§ Generating response...</span>", 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("<span style='background:#292929;padding:5px;border-radius:5px;color:#00ff00;'>✓ Done</span>", 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("<span style='background:#292929;padding:5px;border-radius:5px;color:#ff4444;'>✕ Error generating response</span>", unsafe_allow_html=True) | |
| message_area.markdown("Please try again.") | |
| def main(): | |
| st.markdown(""" | |
| <style> | |
| /* Main colors */ | |
| :root { | |
| --primary-color: #2563eb; | |
| --accent-color: #1e40af; | |
| --background-color: #f8fafc; | |
| --text-color: #1e293b; | |
| } | |
| /* Chat messages */ | |
| .chat-message.user { | |
| background-color: var(--background-color); | |
| border: 1px solid var(--primary-color); | |
| border-radius: 12px; | |
| animation: fadeIn 0.3s ease-in-out; | |
| } | |
| .chat-message.assistant { | |
| background-color: white; | |
| border: 1px solid var(--accent-color); | |
| border-radius: 12px; | |
| animation: fadeIn 0.3s ease-in-out; | |
| } | |
| /* Input area */ | |
| .stChatInputContainer { | |
| background: var(--background-color); | |
| padding: 16px; | |
| border-radius: 12px; | |
| box-shadow: 0 2px 8px rgba(0,0,0,0.1); | |
| } | |
| /* File uploader */ | |
| .stFileUploader { | |
| margin-top: 8px; | |
| } | |
| .stFileUploader>div>div>div>div { | |
| border: 1px dashed var(--primary-color); | |
| background: white; | |
| border-radius: 8px; | |
| padding: 8px; | |
| } | |
| .stFileUploader>div>div>div>div:hover { | |
| background: var(--background-color); | |
| } | |
| /* Buttons */ | |
| .stButton>button { | |
| background-color: var(--primary-color); | |
| color: white; | |
| border-radius: 8px; | |
| transition: all 0.2s ease-in-out; | |
| } | |
| .stButton>button:hover { | |
| background-color: var(--accent-color); | |
| transform: scale(1.05); | |
| } | |
| @keyframes fadeIn { | |
| 0% { opacity: 0; transform: translateY(10px); } | |
| 100% { opacity: 1; transform: translateY(0); } | |
| } | |
| </style> | |
| """, 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""" | |
| <div style='background:#292929;padding:10px;border-radius:5px;margin-bottom:10px;color:orange;animation:fadeIn 0.3s ease-in-out;'> | |
| ⚠️ Failed to set system prompt: {str(e)} | |
| </div> | |
| """, unsafe_allow_html=True) | |
| except Exception as e: | |
| st.markdown(f""" | |
| <div style='background:#292929;padding:10px;border-radius:5px;margin-bottom:10px;color:orange;animation:fadeIn 0.3s ease-in-out;'> | |
| ⚠️ Failed to initialize model: {str(e)} | |
| </div> | |
| <div style='margin-top:10px;color:orange;'> | |
| Available models: {", ".join(gemini_model.list_available_models())} | |
| </div> | |
| """, unsafe_allow_html=True) | |
| return | |
| # Initialize messages if not exists | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] | |
| # Display existing messages | |
| display_messages() | |
| # Handle image uploads and process user input | |
| uploaded_images = handle_image_upload() | |
| # Process user input | |
| process_user_input(temperature, max_tokens, system_prompt, top_p, uploaded_images) | |
| if __name__ == "__main__": | |
| main() | |