AiCodeCraft/Gemini-Interface-Deluxe
1
1import streamlit as st2import google.generativeai as genai3from PIL import Image4import io5import base646import pandas as pd7import zipfile8import PyPDF29 10# Konfiguration der Seite11st.set_page_config(page_title="Gemini AI Chat", layout="wide")12 13st.title("🤖 Gemini AI Chat Interface")14st.markdown("""15**Welcome to the Gemini AI Chat Interface!**16Chat seamlessly with Google's advanced Gemini AI models, supporting multiple input types.17🔗 [GitHub Profile](https://github.com/volkansah) | 18📂 [Project Repository](https://github.com/volkansah/gemini-ai-chat) | 19💬 [Soon](https://aicodecraft.io)20""")21 22# Session State Management23if "messages" not in st.session_state:24 st.session_state.messages = []25if "uploaded_content" not in st.session_state:26 st.session_state.uploaded_content = None27 28# Funktionen zur Dateiverarbeitung29def encode_image(image):30 buffered = io.BytesIO()31 image.save(buffered, format="JPEG")32 return base64.b64encode(buffered.getvalue()).decode('utf-8')33 34def process_file(uploaded_file):35 file_type = uploaded_file.name.split('.')[-1].lower()36 37 if file_type in ["jpg", "jpeg", "png"]:38 return {"type": "image", "content": Image.open(uploaded_file).convert('RGB')}39 40 code_extensions = ["html", "css", "php", "js", "py", "java", "c", "cpp"]41 if file_type in ["txt"] + code_extensions:42 return {"type": "text", "content": uploaded_file.read().decode("utf-8")}43 44 if file_type in ["csv", "xlsx"]:45 df = pd.read_csv(uploaded_file) if file_type == "csv" else pd.read_excel(uploaded_file)46 return {"type": "text", "content": df.to_string()}47 48 if file_type == "pdf":49 reader = PyPDF2.PdfReader(uploaded_file)50 return {"type": "text", "content": "".join(page.extract_text() for page in reader.pages if page.extract_text())}51 52 if file_type == "zip":53 with zipfile.ZipFile(uploaded_file) as z: # <- Hier beginnt der Block54 newline = "\n"55 content = f"ZIP Contents:{newline}"56 57 text_extensions = ('.txt', '.csv', '.py', '.html', '.js', '.css', 58 '.php', '.json', '.xml', '.c', '.cpp', '.java', 59 '.cs', '.rb', '.go', '.ts', '.swift', '.kt', '.rs', '.sh', '.sql')60 61 for file_info in z.infolist():62 if not file_info.is_dir():63 try:64 with z.open(file_info.filename) as file:65 if file_info.filename.lower().endswith(text_extensions):66 file_content = file.read().decode('utf-8')67 content += f"{newline}📄 {file_info.filename}:{newline}{file_content}{newline}"68 else:69 raw_content = file.read()70 try:71 decoded_content = raw_content.decode('utf-8')72 content += f"{newline}📄 {file_info.filename} (unbekannte Erweiterung):{newline}{decoded_content}{newline}"73 except UnicodeDecodeError:74 content += f"{newline}⚠️ Binärdatei ignoriert: {file_info.filename}{newline}"75 except Exception as e:76 content += f"{newline}❌ Fehler bei {file_info.filename}: {str(e)}{newline}"77 78 return {"type": "text", "content": content} # Korrekt eingerückt79 80 return {"type": "error", "content": "Unsupported file format"}81 82# Sidebar für Einstellungen83with st.sidebar:84 api_key = st.text_input("Google AI API Key", type="password")85 model = st.selectbox("Model", [86 "gemini-2.5-flash", 87 "gemini-2.5-pro", 88 "gemini-1.5-flash", 89 "gemini-1.5-pro",90 ])91 temperature = st.slider("Temperature", 0.0, 1.0, 0.7)92 max_tokens = st.slider("Max Tokens", 1, 100000, 1000)93 94# Datei-Upload95uploaded_file = st.file_uploader("Upload File (Image/Text/PDF/ZIP)", 96 type=["jpg", "jpeg", "png", "txt", "pdf", "zip", 97 "csv", "xlsx", "html", "css", "php", "js", "py"])98 99if uploaded_file:100 processed = process_file(uploaded_file)101 st.session_state.uploaded_content = processed102 103 if processed["type"] == "image":104 st.image(processed["content"], caption="Uploaded Image", use_container_width=True)105 elif processed["type"] == "text":106 st.text_area("File Preview", processed["content"], height=200)107 108# Chat-Historie anzeigen109for message in st.session_state.messages:110 with st.chat_message(message["role"]):111 st.markdown(message["content"])112 113# Chat-Eingabe verarbeiten114if prompt := st.chat_input("Your message..."):115 if not api_key:116 st.warning("API Key benötigt!")117 st.stop()118 119 try:120 # API konfigurieren121 genai.configure(api_key=api_key)122 123 # Modell auswählen124 model_instance = genai.GenerativeModel(model)125 126 # Inhalt vorbereiten127 content = [{"text": prompt}]128 129 # Dateiinhalt hinzufügen130 if st.session_state.uploaded_content:131 if st.session_state.uploaded_content["type"] == "image":132 if "vision" not in model.lower():133 st.error("Bitte ein Vision-Modell für Bilder auswählen!")134 st.stop()135 content.append({136 "inline_data": {137 "mime_type": "image/jpeg",138 "data": encode_image(st.session_state.uploaded_content["content"])139 }140 })141 elif st.session_state.uploaded_content["type"] == "text":142 content[0]["text"] += f"\n\n[File Content]\n{st.session_state.uploaded_content['content']}"143 144 # Nachricht zur Historie hinzufügen145 st.session_state.messages.append({"role": "user", "content": prompt})146 with st.chat_message("user"):147 st.markdown(prompt)148 149 # Antwort generieren150 response = model_instance.generate_content(151 content,152 generation_config=genai.types.GenerationConfig(153 temperature=temperature,154 max_output_tokens=max_tokens155 )156 )157 158 # Überprüfen, ob die Antwort gültig ist159 if not response.candidates:160 st.error("API Error: Keine gültige Antwort erhalten. Überprüfe die Eingabe oder das Modell.")161 else:162 # Antwort anzeigen163 with st.chat_message("assistant"):164 st.markdown(response.text)165 st.session_state.messages.append({"role": "assistant", "content": response.text})166 167 except Exception as e:168 st.error(f"API Error: {str(e)}")169 if "vision" not in model and st.session_state.uploaded_content["type"] == "image":170 st.error("Für Bilder einen Vision-fähigen Modell auswählen!")171 172# Instructions in the sidebar173with st.sidebar:174 st.markdown("""175 ## 📝 Instructions:176 1. Enter your Google AI API key177 2. Select a model (use vision models for image analysis)178 3. Adjust temperature and max tokens if needed179 4. Optional: Set a system prompt180 5. Upload an image (optional)181 6. Type your message and press Enter182 ### About183 🔗 [GitHub Profile](https://github.com/volkansah) | 184 📂 [Project Repository](https://github.com/volkansah/gemini-ai-chat) | 185 💬 [Soon](https://aicodecraft.io)186 """)