Alibrown commited on
Commit
94d6ea4
·
verified ·
1 Parent(s): a14313a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -0
app.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import google.generativeai as genai
3
+ from PIL import Image
4
+ import io
5
+ import base64
6
+ import pandas as pd
7
+ import zipfile
8
+ import PyPDF2
9
+
10
+ st.set_page_config(page_title="Gemini AI Chat", layout="wide")
11
+
12
+ st.title("🤖 Gemini AI Chat Interface")
13
+ st.markdown("""
14
+ **Welcome to the Gemini AI Chat Interface!**
15
+ Chat 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 Management
22
+ if "messages" not in st.session_state:
23
+ st.session_state.messages = []
24
+ if "uploaded_content" not in st.session_state:
25
+ st.session_state.uploaded_content = None
26
+
27
+ # File Processing Functions
28
+ def encode_image(image):
29
+ buffered = io.BytesIO()
30
+ image.save(buffered, format="JPEG")
31
+ return base64.b64encode(buffered.getvalue()).decode('utf-8')
32
+
33
+ def 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
+ if file_type in ["txt", *code_extensions := ["html", "css", "php", "js", "py", "java", "c", "cpp"]]:
40
+ return {"type": "text", "content": uploaded_file.read().decode("utf-8")}
41
+
42
+ if file_type in ["csv", "xlsx"]:
43
+ df = pd.read_csv(uploaded_file) if file_type == "csv" else pd.read_excel(uploaded_file)
44
+ return {"type": "text", "content": df.to_string()}
45
+
46
+ if file_type == "pdf":
47
+ reader = PyPDF2.PdfReader(uploaded_file)
48
+ return {"type": "text", "content": "".join(page.extract_text() for page in reader.pages if page.extract_text())}
49
+
50
+ if file_type == "zip":
51
+ with zipfile.ZipFile(uploaded_file) as z:
52
+ return {"type": "text", "content": f"ZIP Contents:\n{'\n'.join(z.namelist())}"}
53
+
54
+ return {"type": "error", "content": "Unsupported file format"}
55
+
56
+ # Sidebar Configuration
57
+ with st.sidebar:
58
+ api_key = st.text_input("Google AI API Key", type="password")
59
+ model = st.selectbox("Model", [
60
+ "gemini-1.5-flash",
61
+ "gemini-1.5-pro",
62
+ "gemini-1.5-flash-8B",
63
+ "gemini-1.5-pro-vision-latest",
64
+ "gemini-1.0-pro",
65
+ "gemini-1.0-pro-vision-latest",
66
+
67
+ "gemini-2.0-pro-exp-02-05",
68
+ "gemini-2.0-flash-lite",
69
+ "gemini-2.0-flash-exp-image-generation",
70
+ "gemini-2.0-flash",
71
+ "gemini-2.0-flash-thinking-exp-01-21"
72
+ ])
73
+ temperature = st.slider("Temperature", 0.0, 1.0, 0.7)
74
+ max_tokens = st.slider("Max Tokens", 1, 2048, 1000)
75
+
76
+ # File Upload Section
77
+ uploaded_file = st.file_uploader("Upload File (Image/Text/PDF/ZIP)",
78
+ type=["jpg", "jpeg", "png", "txt", "pdf", "zip",
79
+ "csv", "xlsx", "html", "css", "php", "js", "py"])
80
+
81
+ if uploaded_file:
82
+ processed = process_file(uploaded_file)
83
+ st.session_state.uploaded_content = processed
84
+
85
+ if processed["type"] == "image":
86
+ st.image(processed["content"], caption="Uploaded Image", use_container_width=True)
87
+ elif processed["type"] == "text":
88
+ st.text_area("File Preview", processed["content"], height=200)
89
+
90
+ # Chat History Display
91
+ for message in st.session_state.messages:
92
+ with st.chat_message(message["role"]):
93
+ st.markdown(message["content"])
94
+
95
+ # Chat Input Processing
96
+ if prompt := st.chat_input("Your message..."):
97
+ if not api_key:
98
+ st.warning("API Key benötigt!")
99
+ st.stop()
100
+
101
+ try:
102
+ # Configure Gemini
103
+ genai.configure(api_key=api_key)
104
+ model_instance = genai.GenerativeModel(model)
105
+
106
+ # Build content payload
107
+ content = []
108
+
109
+ # Add text input
110
+ content.append({"text": prompt})
111
+
112
+ # Add file content
113
+ if st.session_state.uploaded_content:
114
+ if st.session_state.uploaded_content["type"] == "image":
115
+ content.append({
116
+ "inline_data": {
117
+ "mime_type": "image/jpeg",
118
+ "data": encode_image(st.session_state.uploaded_content["content"])
119
+ }
120
+ })
121
+ elif st.session_state.uploaded_content["type"] == "text":
122
+ content[0]["text"] += f"\n\n[File Content]\n{st.session_state.uploaded_content['content']}"
123
+
124
+ # Add to chat history
125
+ st.session_state.messages.append({"role": "user", "content": prompt})
126
+ with st.chat_message("user"):
127
+ st.markdown(prompt)
128
+
129
+ # Generate response
130
+ response = model_instance.generate_content(
131
+ content,
132
+ generation_config=genai.types.GenerationConfig(
133
+ temperature=temperature,
134
+ max_output_tokens=max_tokens
135
+ )
136
+ )
137
+
138
+ # Display response
139
+ with st.chat_message("assistant"):
140
+ st.markdown(response.text)
141
+ st.session_state.messages.append({"role": "assistant", "content": response.text})
142
+
143
+ except Exception as e:
144
+ st.error(f"API Error: {str(e)}")
145
+ if "vision" not in model and st.session_state.uploaded_content["type"] == "image":
146
+ st.error("Für Bilder einen Vision-fähigen Modell auswählen!")