ziyadsuper2017 commited on
Commit
dfb90bd
·
1 Parent(s): 5a9dbe4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -48
app.py CHANGED
@@ -3,19 +3,21 @@ from PIL import Image
3
  import io
4
  import base64
5
  import uuid
6
-
7
- # Assuming google.generativeai is correctly imported as genai and the API key is set
8
  import google.generativeai as genai
9
 
10
- api_key = "AIzaSyC70u1sN87IkoxOoIj4XCAPw97ae2LZwNM" # Replace with your actual API key
 
11
  genai.configure(api_key=api_key)
12
 
 
13
  generation_config = genai.GenerationConfig(
14
  temperature=0.9,
15
  max_output_tokens=3000
16
  )
17
 
18
- safety_settings = SAFETY_SETTINGS = [
 
19
  {
20
  "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
21
  "threshold": "BLOCK_NONE",
@@ -34,6 +36,7 @@ safety_settings = SAFETY_SETTINGS = [
34
  },
35
  ]
36
 
 
37
  if 'chat_history' not in st.session_state:
38
  st.session_state['chat_history'] = []
39
  if 'file_uploader_key' not in st.session_state:
@@ -43,6 +46,7 @@ if 'use_vision_model' not in st.session_state:
43
 
44
  st.title("Gemini Chatbot")
45
 
 
46
  def get_image_base64(image):
47
  image = image.convert("RGB")
48
  buffered = io.BytesIO()
@@ -55,29 +59,30 @@ def clear_conversation():
55
  st.session_state['file_uploader_key'] = str(uuid.uuid4())
56
  st.session_state['use_vision_model'] = False
57
 
58
- def send_message():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  user_input = st.session_state.user_input
60
  uploaded_files = st.session_state.uploaded_files
61
- if uploaded_files:
62
- st.session_state['use_vision_model'] = True
63
- prompts = []
64
- for entry in st.session_state['chat_history']:
65
- for part in entry['parts']:
66
- if 'text' in part:
67
- prompts.append(part['text'])
68
- elif 'data' in part:
69
- prompts.append("[Image]")
70
- if user_input:
71
- prompts.append(user_input)
72
- st.session_state['chat_history'].append({"role": "user", "parts": [{"text": user_input}]})
73
- if uploaded_files:
74
- for uploaded_file in uploaded_files:
75
- base64_image = get_image_base64(Image.open(uploaded_file))
76
- prompts.append("[Image]")
77
- st.session_state['chat_history'].append({
78
- "role": "user",
79
- "parts": [{"mime_type": uploaded_file.type, "data": base64_image}]
80
- })
81
  model_name = 'gemini-pro-vision' if st.session_state['use_vision_model'] else 'gemini-pro'
82
  model = genai.GenerativeModel(
83
  model_name=model_name,
@@ -97,31 +102,30 @@ def send_message():
97
  response_text = response.text if hasattr(response, "text") else "No response text found."
98
  if response_text:
99
  st.session_state['chat_history'].append({"role": "model", "parts": [{"text": response_text}]})
 
 
 
 
 
 
 
 
 
 
100
  st.session_state.user_input = ''
101
  st.session_state.uploaded_files = []
102
  st.session_state.file_uploader_key = str(uuid.uuid4())
103
- display_chat_history()
104
-
105
- def display_chat_history():
106
- for entry in st.session_state['chat_history']:
107
- role = entry["role"]
108
- parts = entry["parts"][0]
109
- if 'text' in parts:
110
- st.markdown(f"{role.title()}: {parts['text']}")
111
- elif 'data' in parts:
112
- st.image(Image.open(io.BytesIO(base64.b64decode(parts['data']))), caption='Uploaded Image')
113
 
114
- def get_chat_history_str():
115
- chat_history_str = "\n".join(
116
- f"{entry['role'].title()}: {part['text']}" if 'text' in part
117
- else f"{entry['role'].title()}: (Image)"
118
- for entry in st.session_state['chat_history']
119
- for part in entry['parts']
120
- )
121
- return chat_history_str
122
 
123
- user_input = st.text_area("Enter your message here:", key="user_input")
 
 
 
 
124
 
 
125
  uploaded_files = st.file_uploader(
126
  "Upload images:",
127
  type=["png", "jpg", "jpeg"],
@@ -129,16 +133,22 @@ uploaded_files = st.file_uploader(
129
  key=st.session_state.file_uploader_key
130
  )
131
 
132
- send_button = st.button("Send", on_click=send_message)
 
 
 
 
 
133
 
 
134
  clear_button = st.button("Clear Conversation", on_click=clear_conversation)
135
 
136
- # Function to download the chat history
137
  def download_chat_history():
138
  chat_history_str = get_chat_history_str()
139
  return chat_history_str
140
 
141
- # Add a button to download the chat history as a text file
142
  download_button = st.download_button(
143
  label="Download Chat",
144
  data=download_chat_history(),
@@ -147,4 +157,20 @@ download_button = st.download_button(
147
  )
148
 
149
  # Ensure the file_uploader widget state is tied to the randomly generated key
150
- st.session_state.uploaded_files = uploaded_files
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import io
4
  import base64
5
  import uuid
6
+ from gtts import gTTS
 
7
  import google.generativeai as genai
8
 
9
+ # Set your API key
10
+ api_key = "YOUR_ACTUAL_API_KEY" # Replace with your actual API key
11
  genai.configure(api_key=api_key)
12
 
13
+ # Configure the generative AI model
14
  generation_config = genai.GenerationConfig(
15
  temperature=0.9,
16
  max_output_tokens=3000
17
  )
18
 
19
+ # Safety settings configuration
20
+ safety_settings = [
21
  {
22
  "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
23
  "threshold": "BLOCK_NONE",
 
36
  },
37
  ]
38
 
39
+ # Initialize session state
40
  if 'chat_history' not in st.session_state:
41
  st.session_state['chat_history'] = []
42
  if 'file_uploader_key' not in st.session_state:
 
46
 
47
  st.title("Gemini Chatbot")
48
 
49
+ # Helper functions for image processing and chat history management
50
  def get_image_base64(image):
51
  image = image.convert("RGB")
52
  buffered = io.BytesIO()
 
59
  st.session_state['file_uploader_key'] = str(uuid.uuid4())
60
  st.session_state['use_vision_model'] = False
61
 
62
+ def display_chat_history():
63
+ for entry in st.session_state['chat_history']:
64
+ role = entry["role"]
65
+ parts = entry["parts"][0]
66
+ if 'text' in parts:
67
+ st.markdown(f"{role.title()}: {parts['text']}")
68
+ elif 'data' in parts:
69
+ st.image(Image.open(io.BytesIO(base64.b64decode(parts['data']))), caption='Uploaded Image')
70
+
71
+ def get_chat_history_str():
72
+ chat_history_str = "\n".join(
73
+ f"{entry['role'].title()}: {part['text']}" if 'text' in part
74
+ else f"{entry['role'].title()}: (Image)"
75
+ for entry in st.session_state['chat_history']
76
+ for part in entry['parts']
77
+ )
78
+ return chat_history_str
79
+
80
+ # Send message function with TTS integration
81
+ def send_message(tts=False):
82
  user_input = st.session_state.user_input
83
  uploaded_files = st.session_state.uploaded_files
84
+ # Your existing code that processes user input and uploaded files...
85
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  model_name = 'gemini-pro-vision' if st.session_state['use_vision_model'] else 'gemini-pro'
87
  model = genai.GenerativeModel(
88
  model_name=model_name,
 
102
  response_text = response.text if hasattr(response, "text") else "No response text found."
103
  if response_text:
104
  st.session_state['chat_history'].append({"role": "model", "parts": [{"text": response_text}]})
105
+
106
+ # If TTS is enabled, convert the response text to speech
107
+ if tts:
108
+ tts = gTTS(text=response_text, lang='en')
109
+ tts_file = BytesIO()
110
+ tts.write_to_fp(tts_file)
111
+ tts_file.seek(0)
112
+ st.audio(tts_file, format='audio/mp3')
113
+
114
+ # Clear the input fields after sending the message
115
  st.session_state.user_input = ''
116
  st.session_state.uploaded_files = []
117
  st.session_state.file_uploader_key = str(uuid.uuid4())
 
 
 
 
 
 
 
 
 
 
118
 
119
+ # Display the updated chat history
120
+ display_chat_history()
 
 
 
 
 
 
121
 
122
+ # User input text area
123
+ user_input = st.text_area(
124
+ "Enter your message here:",
125
+ key="user_input"
126
+ )
127
 
128
+ # File uploader for images
129
  uploaded_files = st.file_uploader(
130
  "Upload images:",
131
  type=["png", "jpg", "jpeg"],
 
133
  key=st.session_state.file_uploader_key
134
  )
135
 
136
+ # Send message button
137
+ send_button = st.button(
138
+ "Send",
139
+ on_click=send_message,
140
+ args=(False,) # TTS disabled by default when clicking the Send button
141
+ )
142
 
143
+ # Clear conversation button
144
  clear_button = st.button("Clear Conversation", on_click=clear_conversation)
145
 
146
+ # Function to download the chat history as a text file
147
  def download_chat_history():
148
  chat_history_str = get_chat_history_str()
149
  return chat_history_str
150
 
151
+ # Download button for the chat history
152
  download_button = st.download_button(
153
  label="Download Chat",
154
  data=download_chat_history(),
 
157
  )
158
 
159
  # Ensure the file_uploader widget state is tied to the randomly generated key
160
+ st.session_state.uploaded_files = uploaded_files
161
+
162
+ # JavaScript to capture the Ctrl+Enter event and trigger a button click
163
+ st.markdown(
164
+ """
165
+ <script>
166
+ // Use jQuery to capture the Ctrl+Enter event and click the 'Send' button
167
+ $(document).on('keydown', 'textarea', function(e) {
168
+ if (e.keyCode == 13 && e.ctrlKey) {
169
+ $('button:contains("Send")').click();
170
+ e.preventDefault();
171
+ }
172
+ });
173
+ </script>
174
+ """,
175
+ unsafe_allow_html=True
176
+ )