CoolFace
Apppublic

AiCodeCraft/Gemini-Interface-Deluxe

sourceHugging Facemitupdated 11mo agoView on Hugging Face
1likes
version_1_0_app.py141 linesDownload Raw Back to root
1# Copyright Volkan Kücükbudak2# Github: https://github.com/volkansah3import streamlit as st4import google.generativeai as genai5from PIL import Image6import io7import base648 9st.set_page_config(page_title="Gemini AI Chat", layout="wide")10 11st.title("🤖 Gemini AI Chat Interface")12st.markdown("""13**Welcome to the Gemini AI Chat Interface!**14Chat seamlessly with Google's advanced Gemini AI models, supporting both text and image inputs.15🔗 [GitHub Profile](https://github.com/volkansah) | 16📂 [Project Repository](https://github.com/volkansah/gemini-ai-chat) | 17💬 [Soon](https://aicodecraft.io)18 19Follow me for more innovative projects and updates!20""")21 22 23def encode_image(image):24    """Convert PIL Image to base64 string"""25    buffered = io.BytesIO()26    image.save(buffered, format="JPEG")27    image_bytes = buffered.getvalue()28    encoded_image = base64.b64encode(image_bytes).decode('utf-8')29    return encoded_image30 31# Sidebar for settings32with st.sidebar:33    api_key = st.text_input("Enter Google AI API Key", type="password")34    model = st.selectbox(35        "Select Model",36        [37            "gemini-1.5-flash",38            "gemini-1.5-pro",39            "gemini-1.5-flash-8B",40            "gemini-1.5-pro-vision-latest",41            "gemini-1.0-pro",42            "gemini-1.0-pro-vision-latest",43 44            "gemini-2.0-pro-exp-02-05",45            "gemini-2.0-flash-lite",46            "gemini-2.0-flash-exp-image-generation",47            "gemini-2.0-flash",48            "gemini-2.0-flash-thinking-exp-01-21"49        ]50    )51    52    temperature = st.slider("Temperature", 0.0, 1.0, 0.7)53    max_tokens = st.slider("Max Tokens", 1, 2048, 1000000)54    system_prompt = st.text_area("System Prompt (Optional)")55 56# Initialize session state for chat history57if "messages" not in st.session_state:58    st.session_state.messages = []59 60# Display chat history61for message in st.session_state.messages:62    with st.chat_message(message["role"]):63        st.markdown(message["content"])64 65# File uploader for images66uploaded_file = st.file_uploader("Upload an image (optional)", type=["jpg", "jpeg", "png"])67uploaded_image = None68if uploaded_file is not None:69    uploaded_image = Image.open(uploaded_file).convert('RGB')70    st.image(uploaded_image, caption="Uploaded Image", use_container_width=True)71 72# Chat input73user_input = st.chat_input("Type your message here...")74 75if user_input and api_key:76    try:77        # Configure the API78        genai.configure(api_key=api_key)79        80        # Add user message to chat history81        st.session_state.messages.append({"role": "user", "content": user_input})82        with st.chat_message("user"):83            st.markdown(user_input)84 85        # Prepare the model and content86        model_instance = genai.GenerativeModel(model_name=model)87        88        content = []89        if uploaded_image:90            # Convert image to base6491            encoded_image = encode_image(uploaded_image)92            content = [93                {"text": user_input},94                {95                    "inline_data": {96                        "mime_type": "image/jpeg",97                        "data": encoded_image98                    }99                }100            ]101        else:102            content = [{"text": user_input}]103 104        # Generate response105        response = model_instance.generate_content(106            content,107            generation_config=genai.types.GenerationConfig(108                temperature=temperature,109                max_output_tokens=max_tokens110            )111        )112 113        # Display assistant response114        with st.chat_message("assistant"):115            st.markdown(response.text)116        117        # Add assistant response to chat history118        st.session_state.messages.append({"role": "assistant", "content": response.text})119 120    except Exception as e:121        st.error(f"Error: {str(e)}")122        st.error("If using an image, make sure to select a vision-enabled model (ones with 'vision' in the name)")123 124elif not api_key and user_input:125    st.warning("Please enter your API key in the sidebar first.")126 127# Instructions in the sidebar128with st.sidebar:129    st.markdown("""130    ## 📝 Instructions:131    1. Enter your Google AI API key132    2. Select a model (use vision models for image analysis)133    3. Adjust temperature and max tokens if needed134    4. Optional: Set a system prompt135    5. Upload an image (optional)136    6. Type your message and press Enter137    ### About138    🔗 [GitHub Profile](https://github.com/volkansah) | 139    📂 [Project Repository](https://github.com/volkansah/gemini-ai-chat) | 140    💬 [Soon](https://aicodecraft.io)141    """)