CosmickVisions commited on
Commit
a4a0207
·
verified ·
1 Parent(s): 6082279

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +170 -113
app.py CHANGED
@@ -34,6 +34,7 @@ from langchain.text_splitter import RecursiveCharacterTextSplitter
34
  from langchain.chains import ConversationalRetrievalChain
35
  from langchain.memory import ConversationBufferMemory
36
  from langchain_community.document_loaders import TextLoader
 
37
 
38
  # Set page config
39
  st.set_page_config(
@@ -45,6 +46,7 @@ st.set_page_config(
45
  # Custom CSS
46
  st.markdown("""
47
  <style>
 
48
  .main-header {
49
  font-size: 2.5rem;
50
  color: #4285F4;
@@ -80,6 +82,65 @@ st.markdown("""
80
  border-radius: 4px;
81
  background-color: #f5eee9;
82
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  </style>
84
  """, unsafe_allow_html=True)
85
 
@@ -1031,11 +1092,80 @@ def setup_rag_chain():
1031
  st.warning(f"Error setting up RAG chain: {str(e)}")
1032
  return None
1033
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1034
  def get_assistant_response(client, prompt, context=None, model="llama3-70b-8192"):
1035
  """Get response from GROQ assistant with context awareness"""
1036
  if client is None:
1037
  return "I'm unable to connect to my knowledge base right now. Please check the API configuration."
1038
 
 
 
 
 
 
 
 
1039
  # Set up RAG chain if available
1040
  rag_chain = None
1041
  try:
@@ -1115,121 +1245,48 @@ def chatbot_interface():
1115
  if "analysis_results" in st.session_state:
1116
  current_context += f"Analysis results: {st.session_state.analysis_results}\n"
1117
 
1118
- # Create chatbot container
1119
- chat_container = st.container()
 
1120
 
1121
- with chat_container:
1122
- # Create a custom expandable chat interface
1123
- st.markdown("""
1124
- <style>
1125
- .chat-container {
1126
- position: fixed;
1127
- bottom: 0;
1128
- right: 20px;
1129
- width: 400px;
1130
- background-color: white;
1131
- border-radius: 10px 10px 0 0;
1132
- box-shadow: 0 0 10px rgba(0,0,0,0.2);
1133
- z-index: 1000;
1134
- }
1135
- .chat-header {
1136
- padding: 10px 15px;
1137
- background-color: #4285F4;
1138
- color: white;
1139
- border-radius: 10px 10px 0 0;
1140
- font-weight: bold;
1141
- cursor: pointer;
1142
- }
1143
- .chat-messages {
1144
- max-height: 300px;
1145
- overflow-y: auto;
1146
- padding: 10px;
1147
- }
1148
- .chat-input {
1149
- padding: 10px;
1150
- border-top: 1px solid #eee;
1151
- }
1152
- </style>
1153
-
1154
- <div class="chat-container" id="chat-container">
1155
- <div class="chat-header" onclick="toggleChat()">
1156
- 💬 Cosmick AI Assistant - Click to toggle
1157
- </div>
1158
- <div id="chat-content">
1159
- <div class="chat-messages" id="chat-messages">
1160
- <div id="messages-container"></div>
1161
- </div>
1162
- <div class="chat-input">
1163
- <input type="text" id="user-input" placeholder="Ask me anything...">
1164
- <button onclick="sendMessage()">Send</button>
1165
- </div>
1166
- </div>
1167
- </div>
1168
-
1169
- <script>
1170
- function toggleChat() {
1171
- const content = document.getElementById('chat-content');
1172
- if (content.style.display === 'none') {
1173
- content.style.display = 'block';
1174
- } else {
1175
- content.style.display = 'none';
1176
- }
1177
- }
1178
 
1179
- function sendMessage() {
1180
- const input = document.getElementById('user-input');
1181
- const message = input.value;
1182
- if (message.trim() === '') return;
1183
-
1184
- // Clear input
1185
- input.value = '';
1186
-
1187
- // Add message to UI
1188
- const messagesContainer = document.getElementById('messages-container');
1189
- messagesContainer.innerHTML += `<div style="margin-bottom: 10px;"><strong>You:</strong> ${message}</div>`;
1190
-
1191
- // Send message to Streamlit
1192
- window.parent.postMessage({
1193
- type: 'streamlit:message',
1194
- data: {
1195
- type: 'chatbot_message',
1196
- message: message
1197
- }
1198
- }, '*');
1199
- }
1200
- </script>
1201
- """, unsafe_allow_html=True)
1202
-
1203
- # Create a container for the actual chat interface using Streamlit components
1204
- chat_placeholder = st.empty()
1205
-
1206
- with chat_placeholder:
1207
- # Display chat messages
1208
- for message in st.session_state.messages:
1209
- if message["role"] == "user":
1210
- st.markdown(f"**You:** {message['content']}")
1211
- else:
1212
- st.markdown(f"**Assistant:** {message['content']}")
1213
-
1214
- # Chat input
1215
- user_input = st.chat_input("Ask me anything about image, video, document or data analysis...")
1216
-
1217
- if user_input:
1218
- # Add user message to history
1219
- st.session_state.messages.append({"role": "user", "content": user_input})
1220
-
1221
- # Get assistant response
1222
- response = get_assistant_response(
1223
- st.session_state.groq_client,
1224
- user_input,
1225
- context=current_context
1226
- )
1227
-
1228
- # Add assistant response to history
1229
- st.session_state.messages.append({"role": "assistant", "content": response})
1230
-
1231
- # Rerun to update chat display
1232
- st.rerun()
1233
 
1234
  def main():
1235
  # Header - Updated title
 
34
  from langchain.chains import ConversationalRetrievalChain
35
  from langchain.memory import ConversationBufferMemory
36
  from langchain_community.document_loaders import TextLoader
37
+ import re
38
 
39
  # Set page config
40
  st.set_page_config(
 
46
  # Custom CSS
47
  st.markdown("""
48
  <style>
49
+ /* Original CSS */
50
  .main-header {
51
  font-size: 2.5rem;
52
  color: #4285F4;
 
82
  border-radius: 4px;
83
  background-color: #f5eee9;
84
  }
85
+
86
+ /* New chatbot styling */
87
+ .chat-container {
88
+ background-color: white;
89
+ border-radius: 16px;
90
+ box-shadow: 0 6px 16px rgba(0,0,0,0.1);
91
+ padding: 20px;
92
+ margin-top: 25px;
93
+ transition: box-shadow 0.3s ease;
94
+ }
95
+ .chat-container:hover {
96
+ box-shadow: 0 8px 20px rgba(0,0,0,0.2);
97
+ }
98
+ .user-message {
99
+ background: linear-gradient(45deg, #4285F4, #5C89BC);
100
+ color: white;
101
+ border-radius: 20px 20px 6px 20px;
102
+ padding: 14px 18px;
103
+ margin-left: auto;
104
+ max-width: 80%;
105
+ margin-bottom: 12px;
106
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
107
+ width: fit-content;
108
+ float: right;
109
+ clear: both;
110
+ }
111
+ .bot-message {
112
+ background-color: #F0F0F0;
113
+ color: #333333;
114
+ border-radius: 20px 20px 20px 6px;
115
+ padding: 14px 18px;
116
+ margin-right: auto;
117
+ max-width: 80%;
118
+ margin-bottom: 12px;
119
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
120
+ width: fit-content;
121
+ float: left;
122
+ clear: both;
123
+ }
124
+ .message-container {
125
+ overflow: auto;
126
+ margin-bottom: 20px;
127
+ max-height: 400px;
128
+ }
129
+ .chat-header {
130
+ padding: 10px 15px;
131
+ background-color: #4285F4;
132
+ color: white;
133
+ border-radius: 10px 10px 0 0;
134
+ font-weight: bold;
135
+ margin-bottom: 10px;
136
+ }
137
+ .chat-input {
138
+ padding: 10px;
139
+ border-top: 1px solid #eee;
140
+ }
141
+ .clear-float {
142
+ clear: both;
143
+ }
144
  </style>
145
  """, unsafe_allow_html=True)
146
 
 
1092
  st.warning(f"Error setting up RAG chain: {str(e)}")
1093
  return None
1094
 
1095
+ def parse_command(command, analysis_types=None):
1096
+ """Parse user command and return function to execute"""
1097
+ command = command.lower().strip()
1098
+
1099
+ # Image analysis commands
1100
+ if "analyze image" in command and analysis_types:
1101
+ return "analyze_image", analysis_types
1102
+
1103
+ # Video analysis commands
1104
+ elif "process video" in command and analysis_types:
1105
+ return "process_video", analysis_types
1106
+
1107
+ # Data analysis commands
1108
+ elif "run query" in command:
1109
+ query = re.search(r"run query\s*:\s*(.*)", command, re.IGNORECASE)
1110
+ if query:
1111
+ return "run_query", query.group(1)
1112
+
1113
+ # Document analysis commands
1114
+ elif "process document" in command:
1115
+ return "process_document", None
1116
+
1117
+ # Help commands
1118
+ elif any(x in command for x in ["what can you do", "help", "capabilities"]):
1119
+ return "help", None
1120
+
1121
+ # No command detected
1122
+ return None, None
1123
+
1124
+ def execute_command(command_type, params):
1125
+ """Execute a command based on the parsed command"""
1126
+ if command_type == "analyze_image":
1127
+ st.write("To analyze an image, please upload an image in the Image Analysis section and select your desired analysis types.")
1128
+ return "I can help you analyze images. Please upload an image in the Image Analysis section and select which features you want to detect."
1129
+
1130
+ elif command_type == "process_video":
1131
+ st.write("To process a video, please upload a video in the Video Analysis section and select your desired analysis types.")
1132
+ return "I can help you process videos. Please upload a video in the Video Analysis section and select which features you want to detect."
1133
+
1134
+ elif command_type == "run_query":
1135
+ st.write("To run a BigQuery query, please go to the Data Analysis section.")
1136
+ return f"I can help you run the query: {params}. Please go to the Data Analysis section to execute it."
1137
+
1138
+ elif command_type == "process_document":
1139
+ st.write("To process a document, please upload a document in the Document Analysis section.")
1140
+ return "I can help you analyze documents. Please upload a document in the Document Analysis section."
1141
+
1142
+ elif command_type == "help":
1143
+ capabilities = """
1144
+ I can help you with several tasks in the Cosmick Cloud AI Analyzer:
1145
+
1146
+ 1. **Image Analysis** - I can identify objects, text, faces, and labels in images
1147
+ 2. **Video Analysis** - I can process videos to detect objects, faces, and text
1148
+ 3. **Document Analysis** - I can extract text and structure from documents
1149
+ 4. **Data Analysis** - I can help query and visualize data in BigQuery
1150
+
1151
+ Try asking me specific questions about your analysis results or how to use the app!
1152
+ """
1153
+ return capabilities
1154
+
1155
+ return None
1156
+
1157
  def get_assistant_response(client, prompt, context=None, model="llama3-70b-8192"):
1158
  """Get response from GROQ assistant with context awareness"""
1159
  if client is None:
1160
  return "I'm unable to connect to my knowledge base right now. Please check the API configuration."
1161
 
1162
+ # Check if the input is a command
1163
+ command_type, params = parse_command(prompt)
1164
+ if command_type:
1165
+ command_response = execute_command(command_type, params)
1166
+ if command_response:
1167
+ return command_response
1168
+
1169
  # Set up RAG chain if available
1170
  rag_chain = None
1171
  try:
 
1245
  if "analysis_results" in st.session_state:
1246
  current_context += f"Analysis results: {st.session_state.analysis_results}\n"
1247
 
1248
+ # Create chatbot container with improved styling
1249
+ st.markdown('<div class="chat-container">', unsafe_allow_html=True)
1250
+ st.markdown('<div class="chat-header">💬 Cosmick AI Assistant</div>', unsafe_allow_html=True)
1251
 
1252
+ # Display chat message history with improved styling
1253
+ st.markdown('<div class="message-container">', unsafe_allow_html=True)
1254
+ for message in st.session_state.messages:
1255
+ if message["role"] == "user":
1256
+ st.markdown(f'<div class="user-message">{message["content"]}</div>', unsafe_allow_html=True)
1257
+ else:
1258
+ st.markdown(f'<div class="bot-message">{message["content"]}</div>', unsafe_allow_html=True)
1259
+ st.markdown('<div class="clear-float"></div>', unsafe_allow_html=True)
1260
+ st.markdown('</div>', unsafe_allow_html=True)
1261
+
1262
+ # Chat input
1263
+ user_input = st.chat_input("Ask me anything about image, video, document or data analysis...")
1264
+
1265
+ if user_input:
1266
+ # Add user message to history
1267
+ st.session_state.messages.append({"role": "user", "content": user_input})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1268
 
1269
+ # Check if it's a command
1270
+ command_type, params = parse_command(user_input)
1271
+
1272
+ if command_type:
1273
+ # Execute command
1274
+ response = execute_command(command_type, params)
1275
+ else:
1276
+ # Get assistant response
1277
+ response = get_assistant_response(
1278
+ st.session_state.groq_client,
1279
+ user_input,
1280
+ context=current_context
1281
+ )
1282
+
1283
+ # Add assistant response to history
1284
+ st.session_state.messages.append({"role": "assistant", "content": response})
1285
+
1286
+ # Rerun to update chat display
1287
+ st.rerun()
1288
+
1289
+ st.markdown('</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1290
 
1291
  def main():
1292
  # Header - Updated title