CoolFace
Apppublic

AiCodeCraft/Gemini-Interface-Deluxe

sourceHugging Facemitupdated 11mo agoView on Hugging Face
1likes
_zip_app.py163 linesDownload Raw Back to root
1import streamlit as st2import google.generativeai as genai3from PIL import Image4import io5import base646import pandas as pd7import zipfile8import PyPDF29 10st.set_page_config(page_title="Gemini AI Chat", layout="wide")11 12st.title("🤖 Gemini AI Chat Interface")13st.markdown("""14**Welcome to the Gemini AI Chat Interface!**15Chat seamlessly with Google's advanced Gemini AI models, supporting multiple input types.16🔗 [GitHub Profile](https://github.com/volkansah) | 17📂 [Project Repository](https://github.com/volkansah/gemini-ai-chat) | 18💬 [Soon](https://aicodecraft.io)19""")20 21# Session State Management22if "messages" not in st.session_state:23    st.session_state.messages = []24if "uploaded_content" not in st.session_state:25    st.session_state.uploaded_content = None26 27# File Processing Functions28def encode_image(image):29    buffered = io.BytesIO()30    image.save(buffered, format="JPEG")31    return base64.b64encode(buffered.getvalue()).decode('utf-8')32 33def process_file(uploaded_file):34    file_type = uploaded_file.name.split('.')[-1].lower()35    36    if file_type in ["jpg", "jpeg", "png"]:37        return {"type": "image", "content": Image.open(uploaded_file).convert('RGB')}38    39    code_extensions = ["html", "css", "php", "js", "py", "java", "c", "cpp"]40    if file_type in ["txt"] + code_extensions:41        return {"type": "text", "content": uploaded_file.read().decode("utf-8")}42    43    if file_type in ["csv", "xlsx"]:44        df = pd.read_csv(uploaded_file) if file_type == "csv" else pd.read_excel(uploaded_file)45        return {"type": "text", "content": df.to_string()}46    47    if file_type == "pdf":48        reader = PyPDF2.PdfReader(uploaded_file)49        return {"type": "text", "content": "".join(page.extract_text() for page in reader.pages if page.extract_text())}50    51    if file_type == "zip":52        with zipfile.ZipFile(uploaded_file) as z:53            # Fix: Define newline character outside f-string54            newline = "\n"55            return {"type": "text", "content": f"ZIP Contents:{newline}{newline.join(z.namelist())}"}56    57    return {"type": "error", "content": "Unsupported file format"}58 59# Sidebar Configuration60with st.sidebar:61    api_key = st.text_input("Google AI API Key", type="password")62    model = st.selectbox("Model", [63        "gemini-1.5-flash",64        "gemini-1.5-pro",65        "gemini-1.5-flash-8B",66        "gemini-1.5-pro-vision-latest",67        "gemini-1.0-pro",68        "gemini-1.0-pro-vision-latest",69        "gemini-2.0-pro-exp-02-05",70        "gemini-2.0-flash-lite",71        "gemini-2.0-flash-exp-image-generation",72        "gemini-2.0-flash",73        "gemini-2.0-flash-thinking-exp-01-21"74    ])75    temperature = st.slider("Temperature", 0.0, 1.0, 0.7)76    max_tokens = st.slider("Max Tokens", 1, 2048, 1000)77 78# File Upload Section79uploaded_file = st.file_uploader("Upload File (Image/Text/PDF/ZIP)", 80                               type=["jpg", "jpeg", "png", "txt", "pdf", "zip", 81                                     "csv", "xlsx", "html", "css", "php", "js", "py"])82 83if uploaded_file:84    processed = process_file(uploaded_file)85    st.session_state.uploaded_content = processed86    87    if processed["type"] == "image":88        st.image(processed["content"], caption="Uploaded Image", use_container_width=True)89    elif processed["type"] == "text":90        st.text_area("File Preview", processed["content"], height=200)91 92# Chat History Display93for message in st.session_state.messages:94    with st.chat_message(message["role"]):95        st.markdown(message["content"])96 97# Chat Input Processing98if prompt := st.chat_input("Your message..."):99    if not api_key:100        st.warning("API Key benötigt!")101        st.stop()102    103    try:104        # Configure Gemini105        genai.configure(api_key=api_key)106        model_instance = genai.GenerativeModel(model)107        108        # Build content payload109        content = []110        111        # Add text input112        content.append({"text": prompt})113        114        # Add file content115        if st.session_state.uploaded_content:116            if st.session_state.uploaded_content["type"] == "image":117                content.append({118                    "inline_data": {119                        "mime_type": "image/jpeg",120                        "data": encode_image(st.session_state.uploaded_content["content"])121                    }122                })123            elif st.session_state.uploaded_content["type"] == "text":124                content[0]["text"] += f"\n\n[File Content]\n{st.session_state.uploaded_content['content']}"125        126        # Add to chat history127        st.session_state.messages.append({"role": "user", "content": prompt})128        with st.chat_message("user"):129            st.markdown(prompt)130        131        # Generate response132        response = model_instance.generate_content(133            content,134            generation_config=genai.types.GenerationConfig(135                temperature=temperature,136                max_output_tokens=max_tokens137            )138        )139        140        # Display response141        with st.chat_message("assistant"):142            st.markdown(response.text)143        st.session_state.messages.append({"role": "assistant", "content": response.text})144        145    except Exception as e:146        st.error(f"API Error: {str(e)}")147        if "vision" not in model and st.session_state.uploaded_content["type"] == "image":148            st.error("Für Bilder einen Vision-fähigen Modell auswählen!")149# Instructions in the sidebar150with st.sidebar:151    st.markdown("""152    ## 📝 Instructions:153    1. Enter your Google AI API key154    2. Select a model (use vision models for image analysis)155    3. Adjust temperature and max tokens if needed156    4. Optional: Set a system prompt157    5. Upload an image (optional)158    6. Type your message and press Enter159    ### About160    🔗 [GitHub Profile](https://github.com/volkansah) | 161    📂 [Project Repository](https://github.com/volkansah/gemini-ai-chat) | 162    💬 [Soon](https://aicodecraft.io)163    """)