ziyadsuper2017 commited on
Commit
326cdbe
·
1 Parent(s): e2815a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -31
app.py CHANGED
@@ -23,8 +23,8 @@ if 'chat_history' not in st.session_state:
23
  st.session_state['chat_history'] = []
24
  if 'file_uploader_key' not in st.session_state:
25
  st.session_state['file_uploader_key'] = str(uuid.uuid4())
26
- if 'last_model_used' not in st.session_state:
27
- st.session_state['last_model_used'] = 'text'
28
 
29
  # UI layout
30
  st.title("Gemini Chatbot")
@@ -41,29 +41,39 @@ def get_image_base64(image):
41
  def clear_conversation():
42
  st.session_state['chat_history'] = []
43
  st.session_state['file_uploader_key'] = str(uuid.uuid4())
44
- st.session_state['last_model_used'] = 'text'
45
 
46
  # Function to send message and clear input
47
  def send_message():
48
  user_input = st.session_state.user_input
49
  uploaded_files = st.session_state.uploaded_files
50
 
51
- # Determine which model to use based on input type
52
- model_name = 'gemini-pro-vision' if uploaded_files else 'gemini-pro'
53
- st.session_state['last_model_used'] = 'vision' if uploaded_files else 'text'
 
 
 
 
 
54
 
55
- # Prepare prompts for conversation
56
- prompts = []
57
  if user_input:
58
- prompts.append({"role": "user", "parts": [{"text": user_input}]})
59
-
60
- # Append images to prompts if uploaded
 
61
  if uploaded_files:
62
  for uploaded_file in uploaded_files:
63
- prompts.append({"role": "user", "parts": [{"mime_type": uploaded_file.type, "data": get_image_base64(Image.open(uploaded_file))}]})
64
-
65
- # Create a new list combining chat history with current prompts
66
- combined_prompts = st.session_state['chat_history'] + prompts
 
 
 
 
 
67
 
68
  # Use the appropriate model for interaction
69
  model = genai.GenerativeModel(
@@ -71,19 +81,34 @@ def send_message():
71
  generation_config=generation_config,
72
  safety_settings=safety_settings
73
  )
74
- response = model.generate_content(combined_prompts)
 
 
75
  response_text = response.text if hasattr(response, "text") else "No response text found."
76
-
77
- # Update chat history and display the model response
78
- for prompt in prompts:
79
- st.session_state['chat_history'].append(prompt)
80
- st.session_state['chat_history'].append({"role": "model", "parts": [{"text": response_text}]})
81
 
82
  # Clear the user input and reset the file uploader widget
83
  st.session_state.user_input = ''
84
  st.session_state.uploaded_files = []
85
  st.session_state.file_uploader_key = str(uuid.uuid4())
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  # Multiline text input for the user to send messages
88
  user_input = st.text_area("Enter your message here:", key="user_input")
89
 
@@ -101,15 +126,5 @@ send_button = st.button("Send", on_click=send_message)
101
  # Button to clear the conversation
102
  clear_button = st.button("Clear Conversation", on_click=clear_conversation)
103
 
104
- # Display the chat history
105
- for entry in st.session_state['chat_history']:
106
- role = entry["role"]
107
- parts = entry["parts"][0]
108
- if 'text' in parts:
109
- st.markdown(f"{role.title()}: {parts['text']}")
110
- elif 'data' in parts:
111
- # Display the image
112
- st.image(Image.open(io.BytesIO(base64.b64decode(parts['data']))), caption='Uploaded Image')
113
-
114
  # Ensure the file_uploader widget state is tied to the randomly generated key
115
  st.session_state.uploaded_files = uploaded_files
 
23
  st.session_state['chat_history'] = []
24
  if 'file_uploader_key' not in st.session_state:
25
  st.session_state['file_uploader_key'] = str(uuid.uuid4())
26
+ if 'use_vision_model' not in st.session_state:
27
+ st.session_state['use_vision_model'] = False
28
 
29
  # UI layout
30
  st.title("Gemini Chatbot")
 
41
  def clear_conversation():
42
  st.session_state['chat_history'] = []
43
  st.session_state['file_uploader_key'] = str(uuid.uuid4())
44
+ st.session_state['use_vision_model'] = False
45
 
46
  # Function to send message and clear input
47
  def send_message():
48
  user_input = st.session_state.user_input
49
  uploaded_files = st.session_state.uploaded_files
50
 
51
+ # If images are uploaded, switch to using the vision model
52
+ if uploaded_files:
53
+ st.session_state['use_vision_model'] = True
54
+
55
+ # Prepare the prompt with chat history for the vision model
56
+ chat_history_str = "\n".join(
57
+ part['text'] for entry in st.session_state['chat_history'] for part in entry['parts'] if 'text' in part
58
+ )
59
 
60
+ # If there is text input, add it to the chat history string
 
61
  if user_input:
62
+ chat_history_str += f"\n{user_input}"
63
+ st.session_state['chat_history'].append({"role": "user", "parts": [{"text": user_input}]})
64
+
65
+ # Add uploaded images to chat history string and session state
66
  if uploaded_files:
67
  for uploaded_file in uploaded_files:
68
+ base64_image = get_image_base64(Image.open(uploaded_file))
69
+ chat_history_str += f"\n[Image]"
70
+ st.session_state['chat_history'].append({
71
+ "role": "user",
72
+ "parts": [{"mime_type": uploaded_file.type, "data": base64_image}]
73
+ })
74
+
75
+ # Determine which model to use based on whether an image has been uploaded
76
+ model_name = 'gemini-pro-vision' if st.session_state['use_vision_model'] else 'gemini-pro'
77
 
78
  # Use the appropriate model for interaction
79
  model = genai.GenerativeModel(
 
81
  generation_config=generation_config,
82
  safety_settings=safety_settings
83
  )
84
+
85
+ # Generate content from the chat history or the latest prompt
86
+ response = model.generate_content([{"role": "user", "parts": [{"text": chat_history_str}]}])
87
  response_text = response.text if hasattr(response, "text") else "No response text found."
88
+
89
+ # Display the model response
90
+ if response_text:
91
+ st.session_state['chat_history'].append({"role": "model", "parts": [{"text": response_text}]})
 
92
 
93
  # Clear the user input and reset the file uploader widget
94
  st.session_state.user_input = ''
95
  st.session_state.uploaded_files = []
96
  st.session_state.file_uploader_key = str(uuid.uuid4())
97
 
98
+ # Display chat history
99
+ display_chat_history()
100
+
101
+ # Function to display the chat history
102
+ def display_chat_history():
103
+ for entry in st.session_state['chat_history']:
104
+ role = entry["role"]
105
+ parts = entry["parts"][0]
106
+ if 'text' in parts:
107
+ st.markdown(f"{role.title()}: {parts['text']}")
108
+ elif 'data' in parts:
109
+ # Display the image
110
+ st.image(Image.open(io.BytesIO(base64.b64decode(parts['data']))), caption='Uploaded Image')
111
+
112
  # Multiline text input for the user to send messages
113
  user_input = st.text_area("Enter your message here:", key="user_input")
114
 
 
126
  # Button to clear the conversation
127
  clear_button = st.button("Clear Conversation", on_click=clear_conversation)
128
 
 
 
 
 
 
 
 
 
 
 
129
  # Ensure the file_uploader widget state is tied to the randomly generated key
130
  st.session_state.uploaded_files = uploaded_files