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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
| 3 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 4 |
+
from langchain.chains import LLMChain
|
| 5 |
+
from langchain.prompts import PromptTemplate
|
| 6 |
+
from langchain.memory import ConversationSummaryMemory
|
| 7 |
+
from langchain.memory.chat_message_histories import StreamlitChatMessageHistory
|
| 8 |
+
import base64
|
| 9 |
+
import io
|
| 10 |
+
import time
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from st_multimodal_chatinput import multimodal_chatinput
|
| 13 |
+
|
| 14 |
+
# Set your Google API key here
|
| 15 |
+
GOOGLE_API_KEY = "AIzaSyC9ScRqi9g-YghNuS5w7o7Erwtd5RIN_Zo"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def convert_to_base64(uploaded_file):
|
| 19 |
+
"""Convert uploaded image to Base64 format (supports JPEG and PNG)"""
|
| 20 |
+
image = Image.open(uploaded_file)
|
| 21 |
+
buffered = io.BytesIO()
|
| 22 |
+
|
| 23 |
+
# Preserve format (default to PNG if unknown)
|
| 24 |
+
format = image.format if image.format in ["JPEG", "PNG"] else "PNG"
|
| 25 |
+
|
| 26 |
+
image.save(buffered, format=format)
|
| 27 |
+
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def text():
|
| 31 |
+
st.title("Gemini 2.0 Thinking Experimental")
|
| 32 |
+
st.markdown("""
|
| 33 |
+
<style>
|
| 34 |
+
.anim-typewriter {
|
| 35 |
+
animation: typewriter 3s steps(40) 1s 1 normal both,
|
| 36 |
+
blinkTextCursor 800ms steps(40) infinite normal;
|
| 37 |
+
overflow: hidden;
|
| 38 |
+
white-space: nowrap;
|
| 39 |
+
border-right: 3px solid;
|
| 40 |
+
font-family: serif;
|
| 41 |
+
font-size: 0.9em;
|
| 42 |
+
}
|
| 43 |
+
@keyframes typewriter {
|
| 44 |
+
from { width: 0; }
|
| 45 |
+
to { width: 100%; }
|
| 46 |
+
}
|
| 47 |
+
@keyframes blinkTextCursor {
|
| 48 |
+
from { border-right-color: rgba(255,255,255,0.75); }
|
| 49 |
+
to { border-right-color: transparent; }
|
| 50 |
+
}
|
| 51 |
+
.dot-pulse {
|
| 52 |
+
position: relative;
|
| 53 |
+
left: -9999px;
|
| 54 |
+
width: 10px;
|
| 55 |
+
height: 10px;
|
| 56 |
+
border-radius: 5px;
|
| 57 |
+
background-color: #9880ff;
|
| 58 |
+
color: #9880ff;
|
| 59 |
+
box-shadow: 9999px 0 0 -5px;
|
| 60 |
+
animation: dot-pulse 1.5s infinite linear;
|
| 61 |
+
animation-delay: 0.25s;
|
| 62 |
+
}
|
| 63 |
+
</style>
|
| 64 |
+
""", unsafe_allow_html=True)
|
| 65 |
+
|
| 66 |
+
# Initialize session state
|
| 67 |
+
if "messages" not in st.session_state:
|
| 68 |
+
st.session_state.messages = []
|
| 69 |
+
st.session_state.chat_history = StreamlitChatMessageHistory()
|
| 70 |
+
st.session_state.memory = ConversationSummaryMemory(
|
| 71 |
+
llm=ChatGoogleGenerativeAI(model="gemini-2.0-flash-thinking-exp-01-21", google_api_key=GOOGLE_API_KEY),
|
| 72 |
+
memory_key="history",
|
| 73 |
+
chat_memory=st.session_state.chat_history
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# Initialize Gemini model
|
| 77 |
+
llm = ChatGoogleGenerativeAI(
|
| 78 |
+
model="gemini-2.0-flash-thinking-exp-01-21",
|
| 79 |
+
google_api_key=GOOGLE_API_KEY,
|
| 80 |
+
temperature=0.3,
|
| 81 |
+
streaming=True,
|
| 82 |
+
timeout=60,
|
| 83 |
+
max_retries=3
|
| 84 |
+
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# Display chat messages
|
| 88 |
+
chat_container = st.container()
|
| 89 |
+
with chat_container:
|
| 90 |
+
# Show initial bot message
|
| 91 |
+
if len(st.session_state.messages) == 0:
|
| 92 |
+
animated_text = '<div class="anim-typewriter">Hello π, how may I assist you today?</div>'
|
| 93 |
+
#st.chat_message("assistant").markdown(animated_text, unsafe_allow_html=True)
|
| 94 |
+
st.session_state.messages.append({"role": "assistant", "content": "Hello π, how may I assist you today?"})
|
| 95 |
+
|
| 96 |
+
# Display historical messages
|
| 97 |
+
for message in st.session_state.messages[0:]: # Skip first static message
|
| 98 |
+
if message["role"] == "user":
|
| 99 |
+
if message.get("image"):
|
| 100 |
+
st.chat_message("user", avatar="π§").markdown(
|
| 101 |
+
f'{message["content"]}<br><img src="{message["image"]}" width="200">',
|
| 102 |
+
unsafe_allow_html=True
|
| 103 |
+
)
|
| 104 |
+
else:
|
| 105 |
+
st.chat_message("user", avatar="π§").markdown(message["content"])
|
| 106 |
+
else:
|
| 107 |
+
st.chat_message("assistant", avatar="π€").markdown(message["content"])
|
| 108 |
+
|
| 109 |
+
# Chat input with multimodal support
|
| 110 |
+
user_input = st.chat_input("Say something", accept_file=True, file_type=["png", "jpg", "jpeg"])
|
| 111 |
+
|
| 112 |
+
if user_input:
|
| 113 |
+
# Process user input
|
| 114 |
+
image_url = ""
|
| 115 |
+
message_content = [{"type": "text", "text": user_input.text}]
|
| 116 |
+
|
| 117 |
+
if user_input["files"]:
|
| 118 |
+
uploaded_file = user_input["files"][0]
|
| 119 |
+
image_base64 = convert_to_base64(uploaded_file)
|
| 120 |
+
image_url = f"data:image/jpeg;base64,{image_base64}"
|
| 121 |
+
message_content.append({"type": "image_url", "image_url": image_url})
|
| 122 |
+
|
| 123 |
+
# Add user message to UI
|
| 124 |
+
with chat_container:
|
| 125 |
+
if image_url:
|
| 126 |
+
st.chat_message("user", avatar="π§").markdown(
|
| 127 |
+
f'''
|
| 128 |
+
|
| 129 |
+
{user_input.text}
|
| 130 |
+
<br>
|
| 131 |
+
<img src="{image_url}" width="200" style="margin-top: 10px; border-radius: 8px;">
|
| 132 |
+
|
| 133 |
+
''',
|
| 134 |
+
unsafe_allow_html=True
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
else:
|
| 138 |
+
st.chat_message("user", avatar="π§").markdown(user_input.text)
|
| 139 |
+
|
| 140 |
+
# Store in session state
|
| 141 |
+
st.session_state.messages.append({
|
| 142 |
+
"role": "user",
|
| 143 |
+
"content": user_input.text,
|
| 144 |
+
"image": image_url if user_input["files"] else ""
|
| 145 |
+
})
|
| 146 |
+
|
| 147 |
+
# Create LangChain message
|
| 148 |
+
user_message = HumanMessage(content=message_content)
|
| 149 |
+
st.session_state.chat_history.add_message(user_message)
|
| 150 |
+
|
| 151 |
+
# Generate streaming response
|
| 152 |
+
history = st.session_state.chat_history.messages
|
| 153 |
+
typing_container = st.empty()
|
| 154 |
+
|
| 155 |
+
def stream_generator(history, user_message):
|
| 156 |
+
# Placeholder for "Thinking..." and "Typing..."
|
| 157 |
+
typing_container = st.empty()
|
| 158 |
+
|
| 159 |
+
# Show "Thinking..." first
|
| 160 |
+
typing_container.markdown('<p class="fade-text">Thinking...</p>', unsafe_allow_html=True)
|
| 161 |
+
|
| 162 |
+
st.markdown("""
|
| 163 |
+
<style>
|
| 164 |
+
@keyframes fade {
|
| 165 |
+
0% { opacity: 0.3; }
|
| 166 |
+
50% { opacity: 1; }
|
| 167 |
+
100% { opacity: 0.3; }
|
| 168 |
+
}
|
| 169 |
+
.fade-text {
|
| 170 |
+
font-size: 16px;
|
| 171 |
+
font-weight: bold;
|
| 172 |
+
color: #3498db;
|
| 173 |
+
animation: fade 1.5s infinite;
|
| 174 |
+
}
|
| 175 |
+
</style>
|
| 176 |
+
""", unsafe_allow_html=True)
|
| 177 |
+
|
| 178 |
+
response = llm.stream(history + [user_message])
|
| 179 |
+
|
| 180 |
+
# Buffer for partial words
|
| 181 |
+
buffer = ""
|
| 182 |
+
|
| 183 |
+
# Flag to change message
|
| 184 |
+
first_chunk_received = False
|
| 185 |
+
|
| 186 |
+
# Pause settings
|
| 187 |
+
PAUSE_AFTER = {".", "!", "?", ",", ";", ":"}
|
| 188 |
+
PAUSE_MULTIPLIER = 2.5 # Pause longer for punctuation
|
| 189 |
+
|
| 190 |
+
for chunk in response:
|
| 191 |
+
if not first_chunk_received:
|
| 192 |
+
typing_container.empty()
|
| 193 |
+
typing_container.markdown('<p class="fade-text">Typing...</p>', unsafe_allow_html=True)
|
| 194 |
+
first_chunk_received = True
|
| 195 |
+
|
| 196 |
+
content = buffer + chunk.content
|
| 197 |
+
words = content.split(' ')
|
| 198 |
+
|
| 199 |
+
# Check if last word is complete
|
| 200 |
+
if not content.endswith(' '):
|
| 201 |
+
buffer = words.pop()
|
| 202 |
+
else:
|
| 203 |
+
buffer = ""
|
| 204 |
+
|
| 205 |
+
for word in words:
|
| 206 |
+
yield word + ' ' # Stream word-by-word
|
| 207 |
+
|
| 208 |
+
# Add delay for natural pauses
|
| 209 |
+
base_delay = 0.03
|
| 210 |
+
last_char = word[-1] if word else ''
|
| 211 |
+
time.sleep(base_delay * PAUSE_MULTIPLIER if last_char in PAUSE_AFTER else base_delay)
|
| 212 |
+
|
| 213 |
+
# Yield any remaining content in buffer
|
| 214 |
+
if buffer:
|
| 215 |
+
yield buffer
|
| 216 |
+
time.sleep(0.03)
|
| 217 |
+
|
| 218 |
+
# Clear "Typing..." message after response finishes
|
| 219 |
+
typing_container.empty()
|
| 220 |
+
|
| 221 |
+
# Generate streaming response
|
| 222 |
+
with st.chat_message("assistant", avatar="π€"):
|
| 223 |
+
|
| 224 |
+
full_response = st.write_stream(
|
| 225 |
+
stream_generator(
|
| 226 |
+
st.session_state.chat_history.messages,
|
| 227 |
+
user_message
|
| 228 |
+
)
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
typing_container.empty() # Remove status message
|
| 232 |
+
|
| 233 |
+
# Update session state
|
| 234 |
+
st.session_state.messages.append({
|
| 235 |
+
"role": "assistant",
|
| 236 |
+
"content": full_response
|
| 237 |
+
})
|
| 238 |
+
|
| 239 |
+
# Update conversation memory
|
| 240 |
+
ai_message = AIMessage(content=full_response)
|
| 241 |
+
st.session_state.chat_history.add_message(ai_message)
|
| 242 |
+
st.session_state.memory.save_context(
|
| 243 |
+
{"input": user_message.content},
|
| 244 |
+
{"output": ai_message.content}
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
#st.sidebar.subheader("Raw Chat History")
|
| 248 |
+
#st.sidebar.write(st.session_state.chat_history.messages)
|