Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,520 +1,519 @@
|
|
1 |
-
import os
|
2 |
-
import io
|
3 |
-
import requests
|
4 |
-
import streamlit as st
|
5 |
-
from openai import OpenAI
|
6 |
-
from PyPDF2 import PdfReader
|
7 |
-
import urllib.parse
|
8 |
-
from dotenv import load_dotenv
|
9 |
-
from openai import OpenAI
|
10 |
-
from io import BytesIO
|
11 |
-
from streamlit_extras.colored_header import colored_header
|
12 |
-
from streamlit_extras.add_vertical_space import add_vertical_space
|
13 |
-
from streamlit_extras.switch_page_button import switch_page
|
14 |
-
import json
|
15 |
-
import pandas as pd
|
16 |
-
from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode, DataReturnMode
|
17 |
-
import time
|
18 |
-
import random
|
19 |
-
import aiohttp
|
20 |
-
import asyncio
|
21 |
-
from PyPDF2 import PdfWriter
|
22 |
-
|
23 |
-
load_dotenv()
|
24 |
-
|
25 |
-
# ---------------------- Configuration ----------------------
|
26 |
-
st.set_page_config(page_title="Building Regulations Chatbot", layout="wide", initial_sidebar_state="expanded")
|
27 |
-
# Load environment variables from .env file
|
28 |
-
load_dotenv()
|
29 |
-
|
30 |
-
# Set OpenAI API key
|
31 |
-
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
32 |
-
|
33 |
-
# ---------------------- Session State Initialization ----------------------
|
34 |
-
|
35 |
-
if 'pdf_contents' not in st.session_state:
|
36 |
-
st.session_state.pdf_contents = []
|
37 |
-
if 'chat_history' not in st.session_state:
|
38 |
-
st.session_state.chat_history = []
|
39 |
-
if 'processed_pdfs' not in st.session_state:
|
40 |
-
st.session_state.processed_pdfs = False
|
41 |
-
if 'id_counter' not in st.session_state:
|
42 |
-
st.session_state.id_counter = 0
|
43 |
-
if 'assistant_id' not in st.session_state:
|
44 |
-
st.session_state.assistant_id = None
|
45 |
-
if 'thread_id' not in st.session_state:
|
46 |
-
st.session_state.thread_id = None
|
47 |
-
if 'file_ids' not in st.session_state:
|
48 |
-
st.session_state.file_ids = []
|
49 |
-
|
50 |
-
|
51 |
-
# ---------------------- Helper Functions ----------------------
|
52 |
-
|
53 |
-
def get_vector_stores():
|
54 |
-
try:
|
55 |
-
vector_stores = client.beta.vector_stores.list()
|
56 |
-
return vector_stores
|
57 |
-
except Exception as e:
|
58 |
-
return f"Error retrieving vector stores: {str(e)}"
|
59 |
-
|
60 |
-
|
61 |
-
def fetch_pdfs(city_code):
|
62 |
-
url = f"http://91.203.213.50:5000/oereblex/{city_code}"
|
63 |
-
response = requests.get(url)
|
64 |
-
if response.status_code == 200:
|
65 |
-
data = response.json()
|
66 |
-
print("First data:", data.get('data', [])[0] if data.get('data') else None)
|
67 |
-
return data.get('data', [])
|
68 |
-
else:
|
69 |
-
st.error(f"Failed to fetch PDFs for city code {city_code}")
|
70 |
-
return None
|
71 |
-
|
72 |
-
|
73 |
-
def download_pdf(url, doc_title):
|
74 |
-
# Add 'https://' scheme if it's missing
|
75 |
-
if not url.startswith(('http://', 'https://')):
|
76 |
-
url = 'https://' + url
|
77 |
-
|
78 |
-
try:
|
79 |
-
response = requests.get(url)
|
80 |
-
response.raise_for_status() # Raise an exception for bad status codes
|
81 |
-
|
82 |
-
# Sanitize doc_title to create a valid filename
|
83 |
-
sanitized_title = ''.join(c for c in doc_title if c.isalnum() or c in (' ', '_', '-')).rstrip()
|
84 |
-
sanitized_title = sanitized_title.replace(' ', '_')
|
85 |
-
filename = f"{sanitized_title}.pdf"
|
86 |
-
|
87 |
-
# Ensure filename is unique by appending the id_counter if necessary
|
88 |
-
if os.path.exists(filename):
|
89 |
-
filename = f"{sanitized_title}_{st.session_state.id_counter}.pdf"
|
90 |
-
st.session_state.id_counter += 1
|
91 |
-
|
92 |
-
# Save the PDF content to a file
|
93 |
-
with open(filename, 'wb') as f:
|
94 |
-
f.write(response.content)
|
95 |
-
|
96 |
-
return filename
|
97 |
-
except requests.RequestException as e:
|
98 |
-
st.error(f"Failed to download PDF from {url}. Error: {str(e)}")
|
99 |
-
return None
|
100 |
-
|
101 |
-
|
102 |
-
# Helper function to upload file to OpenAI
|
103 |
-
def upload_file_to_openai(file_path):
|
104 |
-
try:
|
105 |
-
file = client.files.create(
|
106 |
-
file=open(file_path, 'rb'),
|
107 |
-
purpose='assistants'
|
108 |
-
)
|
109 |
-
return file.id
|
110 |
-
except Exception as e:
|
111 |
-
st.error(f"Failed to upload file {file_path}. Error: {str(e)}")
|
112 |
-
return None
|
113 |
-
|
114 |
-
|
115 |
-
def create_assistant():
|
116 |
-
assistant = client.beta.assistants.create(
|
117 |
-
name="Building Regulations Assistant",
|
118 |
-
instructions="You are an expert on building regulations. Use the provided documents to answer questions accurately.",
|
119 |
-
model="gpt-4o-mini",
|
120 |
-
tools=[{"type": "file_search"}]
|
121 |
-
)
|
122 |
-
st.session_state.assistant_id = assistant.id
|
123 |
-
return assistant.id
|
124 |
-
|
125 |
-
|
126 |
-
def format_response(response, citations):
|
127 |
-
"""Format the response with proper markdown structure."""
|
128 |
-
formatted_text = f"""
|
129 |
-
### Response
|
130 |
-
{response}
|
131 |
-
|
132 |
-
{"### Citations" if citations else ""}
|
133 |
-
{"".join([f"- {citation}\n" for citation in citations]) if citations else ""}
|
134 |
-
"""
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
print("
|
165 |
-
print("Received
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
"
|
178 |
-
"
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
st.session_state.thread_id
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
)
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
thread
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
)
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
citation_entry
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
response_container
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
final_formatted_response
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
margin-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
margin-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
<div
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
<div
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
response
|
384 |
-
|
385 |
-
|
386 |
-
"
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
st.
|
398 |
-
col1
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
pdfs
|
413 |
-
|
414 |
-
st.
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
df = df
|
427 |
-
|
428 |
-
"
|
429 |
-
"
|
430 |
-
"
|
431 |
-
"
|
432 |
-
"
|
433 |
-
"
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
gb =
|
442 |
-
gb.
|
443 |
-
gb.configure_column("
|
444 |
-
gb.
|
445 |
-
gb.
|
446 |
-
gb.
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
st.session_state.
|
469 |
-
st.
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
file_name
|
482 |
-
|
483 |
-
|
484 |
-
file_id
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
st.
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
|
|
1 |
+
import os
|
2 |
+
import io
|
3 |
+
import requests
|
4 |
+
import streamlit as st
|
5 |
+
from openai import OpenAI
|
6 |
+
from PyPDF2 import PdfReader
|
7 |
+
import urllib.parse
|
8 |
+
from dotenv import load_dotenv
|
9 |
+
from openai import OpenAI
|
10 |
+
from io import BytesIO
|
11 |
+
from streamlit_extras.colored_header import colored_header
|
12 |
+
from streamlit_extras.add_vertical_space import add_vertical_space
|
13 |
+
from streamlit_extras.switch_page_button import switch_page
|
14 |
+
import json
|
15 |
+
import pandas as pd
|
16 |
+
from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode, DataReturnMode
|
17 |
+
import time
|
18 |
+
import random
|
19 |
+
import aiohttp
|
20 |
+
import asyncio
|
21 |
+
from PyPDF2 import PdfWriter
|
22 |
+
|
23 |
+
load_dotenv()
|
24 |
+
|
25 |
+
# ---------------------- Configuration ----------------------
|
26 |
+
st.set_page_config(page_title="Building Regulations Chatbot", layout="wide", initial_sidebar_state="expanded")
|
27 |
+
# Load environment variables from .env file
|
28 |
+
load_dotenv()
|
29 |
+
|
30 |
+
# Set OpenAI API key
|
31 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
32 |
+
|
33 |
+
# ---------------------- Session State Initialization ----------------------
|
34 |
+
|
35 |
+
if 'pdf_contents' not in st.session_state:
|
36 |
+
st.session_state.pdf_contents = []
|
37 |
+
if 'chat_history' not in st.session_state:
|
38 |
+
st.session_state.chat_history = []
|
39 |
+
if 'processed_pdfs' not in st.session_state:
|
40 |
+
st.session_state.processed_pdfs = False
|
41 |
+
if 'id_counter' not in st.session_state:
|
42 |
+
st.session_state.id_counter = 0
|
43 |
+
if 'assistant_id' not in st.session_state:
|
44 |
+
st.session_state.assistant_id = None
|
45 |
+
if 'thread_id' not in st.session_state:
|
46 |
+
st.session_state.thread_id = None
|
47 |
+
if 'file_ids' not in st.session_state:
|
48 |
+
st.session_state.file_ids = []
|
49 |
+
|
50 |
+
|
51 |
+
# ---------------------- Helper Functions ----------------------
|
52 |
+
|
53 |
+
def get_vector_stores():
|
54 |
+
try:
|
55 |
+
vector_stores = client.beta.vector_stores.list()
|
56 |
+
return vector_stores
|
57 |
+
except Exception as e:
|
58 |
+
return f"Error retrieving vector stores: {str(e)}"
|
59 |
+
|
60 |
+
|
61 |
+
def fetch_pdfs(city_code):
|
62 |
+
url = f"http://91.203.213.50:5000/oereblex/{city_code}"
|
63 |
+
response = requests.get(url)
|
64 |
+
if response.status_code == 200:
|
65 |
+
data = response.json()
|
66 |
+
print("First data:", data.get('data', [])[0] if data.get('data') else None)
|
67 |
+
return data.get('data', [])
|
68 |
+
else:
|
69 |
+
st.error(f"Failed to fetch PDFs for city code {city_code}")
|
70 |
+
return None
|
71 |
+
|
72 |
+
|
73 |
+
def download_pdf(url, doc_title):
|
74 |
+
# Add 'https://' scheme if it's missing
|
75 |
+
if not url.startswith(('http://', 'https://')):
|
76 |
+
url = 'https://' + url
|
77 |
+
|
78 |
+
try:
|
79 |
+
response = requests.get(url)
|
80 |
+
response.raise_for_status() # Raise an exception for bad status codes
|
81 |
+
|
82 |
+
# Sanitize doc_title to create a valid filename
|
83 |
+
sanitized_title = ''.join(c for c in doc_title if c.isalnum() or c in (' ', '_', '-')).rstrip()
|
84 |
+
sanitized_title = sanitized_title.replace(' ', '_')
|
85 |
+
filename = f"{sanitized_title}.pdf"
|
86 |
+
|
87 |
+
# Ensure filename is unique by appending the id_counter if necessary
|
88 |
+
if os.path.exists(filename):
|
89 |
+
filename = f"{sanitized_title}_{st.session_state.id_counter}.pdf"
|
90 |
+
st.session_state.id_counter += 1
|
91 |
+
|
92 |
+
# Save the PDF content to a file
|
93 |
+
with open(filename, 'wb') as f:
|
94 |
+
f.write(response.content)
|
95 |
+
|
96 |
+
return filename
|
97 |
+
except requests.RequestException as e:
|
98 |
+
st.error(f"Failed to download PDF from {url}. Error: {str(e)}")
|
99 |
+
return None
|
100 |
+
|
101 |
+
|
102 |
+
# Helper function to upload file to OpenAI
|
103 |
+
def upload_file_to_openai(file_path):
|
104 |
+
try:
|
105 |
+
file = client.files.create(
|
106 |
+
file=open(file_path, 'rb'),
|
107 |
+
purpose='assistants'
|
108 |
+
)
|
109 |
+
return file.id
|
110 |
+
except Exception as e:
|
111 |
+
st.error(f"Failed to upload file {file_path}. Error: {str(e)}")
|
112 |
+
return None
|
113 |
+
|
114 |
+
|
115 |
+
def create_assistant():
|
116 |
+
assistant = client.beta.assistants.create(
|
117 |
+
name="Building Regulations Assistant",
|
118 |
+
instructions="You are an expert on building regulations. Use the provided documents to answer questions accurately.",
|
119 |
+
model="gpt-4o-mini",
|
120 |
+
tools=[{"type": "file_search"}]
|
121 |
+
)
|
122 |
+
st.session_state.assistant_id = assistant.id
|
123 |
+
return assistant.id
|
124 |
+
|
125 |
+
|
126 |
+
def format_response(response, citations):
|
127 |
+
"""Format the response with proper markdown structure."""
|
128 |
+
formatted_text = f"""
|
129 |
+
### Response
|
130 |
+
{response}
|
131 |
+
|
132 |
+
{"### Citations" if citations else ""}
|
133 |
+
{"".join([f"- {citation}\n" for citation in citations]) if citations else ""}
|
134 |
+
"""return formatted_text.strip()
|
135 |
+
|
136 |
+
def response_generator(response, citations):
|
137 |
+
"""Generator for streaming response with structured output."""
|
138 |
+
# First yield the response header
|
139 |
+
yield "### Response\n\n"
|
140 |
+
time.sleep(0.1)
|
141 |
+
|
142 |
+
# Yield the main response word by word
|
143 |
+
words = response.split()
|
144 |
+
for i, word in enumerate(words):
|
145 |
+
yield word + " "
|
146 |
+
# Add natural pauses at punctuation
|
147 |
+
if word.endswith(('.', '!', '?', ':')):
|
148 |
+
time.sleep(0.1)
|
149 |
+
else:
|
150 |
+
time.sleep(0.05)
|
151 |
+
|
152 |
+
# If there are citations, yield them with proper formatting
|
153 |
+
if citations:
|
154 |
+
# Add some spacing before citations
|
155 |
+
yield "\n\n### Citations\n\n"
|
156 |
+
time.sleep(0.1)
|
157 |
+
|
158 |
+
for citation in citations:
|
159 |
+
yield f"- {citation}\n"
|
160 |
+
time.sleep(0.05)
|
161 |
+
|
162 |
+
def chat_with_assistant(file_ids, user_message):
|
163 |
+
print("----- Starting chat_with_assistant -----")
|
164 |
+
print("Received file_ids:", file_ids)
|
165 |
+
print("Received user_message:", user_message)
|
166 |
+
|
167 |
+
# Create attachments for each file_id
|
168 |
+
attachments = [{"file_id": file_id, "tools": [{"type": "file_search"}]} for file_id in file_ids]
|
169 |
+
print("Attachments created:", attachments)
|
170 |
+
|
171 |
+
if st.session_state.thread_id is None:
|
172 |
+
print("No existing thread_id found. Creating a new thread.")
|
173 |
+
thread = client.beta.threads.create(
|
174 |
+
messages=[
|
175 |
+
{
|
176 |
+
"role": "user",
|
177 |
+
"content": user_message,
|
178 |
+
"attachments": attachments,
|
179 |
+
}
|
180 |
+
]
|
181 |
+
)
|
182 |
+
st.session_state.thread_id = thread.id
|
183 |
+
print("New thread created with id:", st.session_state.thread_id)
|
184 |
+
else:
|
185 |
+
print(f"Existing thread_id found: {st.session_state.thread_id}. Adding message to the thread.")
|
186 |
+
message = client.beta.threads.messages.create(
|
187 |
+
thread_id=st.session_state.thread_id,
|
188 |
+
role="user",
|
189 |
+
content=user_message,
|
190 |
+
attachments=attachments
|
191 |
+
)
|
192 |
+
print("Message added to thread with id:", message.id)
|
193 |
+
|
194 |
+
try:
|
195 |
+
thread = client.beta.threads.retrieve(thread_id=st.session_state.thread_id)
|
196 |
+
print("Retrieved thread:", thread)
|
197 |
+
except Exception as e:
|
198 |
+
print(f"Error retrieving thread with id {st.session_state.thread_id}: {e}")
|
199 |
+
return "An error occurred while processing your request.", []
|
200 |
+
|
201 |
+
try:
|
202 |
+
run = client.beta.threads.runs.create_and_poll(
|
203 |
+
thread_id=thread.id, assistant_id=st.session_state.assistant_id
|
204 |
+
)
|
205 |
+
print("Run created and polled:", run)
|
206 |
+
except Exception as e:
|
207 |
+
print("Error during run creation and polling:", e)
|
208 |
+
return "An error occurred while processing your request.", []
|
209 |
+
|
210 |
+
try:
|
211 |
+
messages = list(client.beta.threads.messages.list(thread_id=thread.id, run_id=run.id))
|
212 |
+
print("Retrieved messages:", messages)
|
213 |
+
except Exception as e:
|
214 |
+
print("Error retrieving messages:", e)
|
215 |
+
return "An error occurred while retrieving messages.", []
|
216 |
+
|
217 |
+
# Process the first message content
|
218 |
+
if messages and messages[0].content:
|
219 |
+
message_content = messages[0].content[0].text
|
220 |
+
print("Raw message content:", message_content)
|
221 |
+
|
222 |
+
annotations = message_content.annotations
|
223 |
+
citations = []
|
224 |
+
seen_citations = set()
|
225 |
+
|
226 |
+
# Process annotations and citations
|
227 |
+
for index, annotation in enumerate(annotations):
|
228 |
+
message_content.value = message_content.value.replace(annotation.text, f"[{index}]")
|
229 |
+
if file_citation := getattr(annotation, "file_citation", None):
|
230 |
+
try:
|
231 |
+
cited_file = client.files.retrieve(file_citation.file_id)
|
232 |
+
citation_entry = f"[{index}] {cited_file.filename}"
|
233 |
+
if citation_entry not in seen_citations:
|
234 |
+
citations.append(citation_entry)
|
235 |
+
seen_citations.add(citation_entry)
|
236 |
+
except Exception as e:
|
237 |
+
print(f"Error retrieving cited file for annotation {index}: {e}")
|
238 |
+
|
239 |
+
# Create a container for the response with proper styling
|
240 |
+
response_container = st.container()
|
241 |
+
with response_container:
|
242 |
+
message_placeholder = st.empty()
|
243 |
+
streaming_content = ""
|
244 |
+
|
245 |
+
# Stream the response with structure
|
246 |
+
for chunk in response_generator(message_content.value, citations):
|
247 |
+
streaming_content += chunk
|
248 |
+
# Use markdown for proper formatting during streaming
|
249 |
+
message_placeholder.markdown(streaming_content + "▌")
|
250 |
+
|
251 |
+
# Final formatted response
|
252 |
+
final_formatted_response = format_response(message_content.value, citations)
|
253 |
+
message_placeholder.markdown(final_formatted_response)
|
254 |
+
|
255 |
+
return final_formatted_response, citations
|
256 |
+
else:
|
257 |
+
return "No response received from the assistant.", []
|
258 |
+
|
259 |
+
|
260 |
+
# ---------------------- Streamlit App ----------------------
|
261 |
+
|
262 |
+
# ---------------------- Custom CSS Injection ----------------------
|
263 |
+
|
264 |
+
# Inject custom CSS to style chat messages
|
265 |
+
st.markdown("""
|
266 |
+
<style>
|
267 |
+
/* Style for the chat container */
|
268 |
+
.chat-container {
|
269 |
+
display: flex;
|
270 |
+
flex-direction: column;
|
271 |
+
gap: 1.5rem;
|
272 |
+
}
|
273 |
+
|
274 |
+
/* Style for individual chat messages */
|
275 |
+
.chat-message {
|
276 |
+
margin-bottom: 1.5rem;
|
277 |
+
}
|
278 |
+
|
279 |
+
/* Style for user messages */
|
280 |
+
.chat-message.user > div:first-child {
|
281 |
+
color: #1E90FF; /* Dodger Blue for "You" */
|
282 |
+
font-weight: bold;
|
283 |
+
margin-bottom: 0.5rem;
|
284 |
+
}
|
285 |
+
|
286 |
+
/* Style for assistant messages */
|
287 |
+
.chat-message.assistant > div:first-child {
|
288 |
+
color: #32CD32; /* Lime Green for "Assistant" */
|
289 |
+
font-weight: bold;
|
290 |
+
margin-bottom: 0.5rem;
|
291 |
+
}
|
292 |
+
|
293 |
+
/* Style for the message content */
|
294 |
+
.message-content {
|
295 |
+
padding: 1rem;
|
296 |
+
border-radius: 0.5rem;
|
297 |
+
line-height: 1.5;
|
298 |
+
}
|
299 |
+
|
300 |
+
.message-content h3 {
|
301 |
+
color: #444;
|
302 |
+
margin-top: 1rem;
|
303 |
+
margin-bottom: 0.5rem;
|
304 |
+
font-size: 1.1rem;
|
305 |
+
}
|
306 |
+
|
307 |
+
.message-content ul {
|
308 |
+
margin-top: 0.5rem;
|
309 |
+
margin-bottom: 0.5rem;
|
310 |
+
padding-left: 1.5rem;
|
311 |
+
}
|
312 |
+
|
313 |
+
.message-content li {
|
314 |
+
margin-bottom: 0.25rem;
|
315 |
+
}
|
316 |
+
</style>
|
317 |
+
""", unsafe_allow_html=True)
|
318 |
+
|
319 |
+
page = st.sidebar.selectbox("Choose a page", ["Documents", "Home", "Admin"])
|
320 |
+
|
321 |
+
if page == "Home":
|
322 |
+
st.title("Building Regulations Chatbot", anchor=False)
|
323 |
+
|
324 |
+
# Sidebar improvements
|
325 |
+
with st.sidebar:
|
326 |
+
colored_header("Selected Documents", description="Documents for chat")
|
327 |
+
if 'selected_pdfs' in st.session_state and not st.session_state.selected_pdfs.empty:
|
328 |
+
for _, pdf in st.session_state.selected_pdfs.iterrows():
|
329 |
+
st.write(f"- {pdf['Doc Title']}")
|
330 |
+
else:
|
331 |
+
st.write("No documents selected. Please go to the Documents page.")
|
332 |
+
|
333 |
+
# Main chat area improvements
|
334 |
+
colored_header("Chat", description="Ask questions about building regulations")
|
335 |
+
|
336 |
+
# Chat container with custom CSS class
|
337 |
+
st.markdown('<div class="chat-container" id="chat-container">', unsafe_allow_html=True)
|
338 |
+
for chat in st.session_state.chat_history:
|
339 |
+
with st.container():
|
340 |
+
if chat['role'] == 'user':
|
341 |
+
st.markdown(f"""
|
342 |
+
<div class="chat-message user">
|
343 |
+
<div><strong>You</strong></div>
|
344 |
+
<div class="message-content">{chat['content']}</div>
|
345 |
+
</div>
|
346 |
+
""", unsafe_allow_html=True)
|
347 |
+
else:
|
348 |
+
st.markdown(f"""
|
349 |
+
<div class="chat-message assistant">
|
350 |
+
<div><strong>Assistant</strong></div>
|
351 |
+
<div class="message-content">{chat['content']}</div>
|
352 |
+
</div>
|
353 |
+
""", unsafe_allow_html=True)
|
354 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
355 |
+
|
356 |
+
# Inject JavaScript to auto-scroll the chat container
|
357 |
+
st.markdown("""
|
358 |
+
<script>
|
359 |
+
const chatContainer = document.getElementById('chat-container');
|
360 |
+
if (chatContainer) {
|
361 |
+
chatContainer.scrollTop = chatContainer.scrollHeight;
|
362 |
+
}
|
363 |
+
</script>
|
364 |
+
""", unsafe_allow_html=True)
|
365 |
+
|
366 |
+
# Chat input improvements
|
367 |
+
with st.form("chat_form", clear_on_submit=True):
|
368 |
+
user_input = st.text_area("Ask a question about building regulations...", height=100)
|
369 |
+
col1, col2 = st.columns([3, 1])
|
370 |
+
with col2:
|
371 |
+
submit = st.form_submit_button("Send", use_container_width=True)
|
372 |
+
|
373 |
+
if submit and user_input.strip() != "":
|
374 |
+
# Add user message to chat history
|
375 |
+
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
376 |
+
|
377 |
+
if not st.session_state.file_ids:
|
378 |
+
st.error("Please process PDFs first.")
|
379 |
+
else:
|
380 |
+
with st.spinner("Generating response..."):
|
381 |
+
try:
|
382 |
+
response, citations = chat_with_assistant(st.session_state.file_ids, user_input)
|
383 |
+
# The response is already formatted, so we can add it directly to chat history
|
384 |
+
st.session_state.chat_history.append({
|
385 |
+
"role": "assistant",
|
386 |
+
"content": response
|
387 |
+
})
|
388 |
+
except Exception as e:
|
389 |
+
st.error(f"Error generating response: {str(e)}")
|
390 |
+
|
391 |
+
# Rerun the app to update the chat display
|
392 |
+
st.rerun()
|
393 |
+
|
394 |
+
# Footer improvements
|
395 |
+
add_vertical_space(2)
|
396 |
+
st.markdown("---")
|
397 |
+
col1, col2 = st.columns(2)
|
398 |
+
with col1:
|
399 |
+
st.caption("Powered by OpenAI GPT-4 and Pinecone")
|
400 |
+
with col2:
|
401 |
+
st.caption("© 2023 Your Company Name")
|
402 |
+
|
403 |
+
elif page == "Documents":
|
404 |
+
st.title("Document Selection")
|
405 |
+
|
406 |
+
city_code_input = st.text_input("Enter city code:", key="city_code_input")
|
407 |
+
load_documents_button = st.button("Load Documents", key="load_documents_button")
|
408 |
+
|
409 |
+
if load_documents_button and city_code_input:
|
410 |
+
with st.spinner("Fetching PDFs..."):
|
411 |
+
pdfs = fetch_pdfs(city_code_input)
|
412 |
+
if pdfs:
|
413 |
+
st.session_state.available_pdfs = pdfs
|
414 |
+
st.success(f"Found {len(pdfs)} PDFs")
|
415 |
+
else:
|
416 |
+
st.error("No PDFs found")
|
417 |
+
|
418 |
+
if 'available_pdfs' in st.session_state:
|
419 |
+
st.write(f"Total PDFs: {len(st.session_state.available_pdfs)}")
|
420 |
+
|
421 |
+
# Create a DataFrame from the available PDFs
|
422 |
+
df = pd.DataFrame(st.session_state.available_pdfs)
|
423 |
+
|
424 |
+
# Select and rename only the specified columns
|
425 |
+
df = df[['municipality', 'abbreviation', 'doc_title', 'file_title', 'file_href', 'enactment_date', 'prio']]
|
426 |
+
df = df.rename(columns={
|
427 |
+
"municipality": "Municipality",
|
428 |
+
"abbreviation": "Abbreviation",
|
429 |
+
"doc_title": "Doc Title",
|
430 |
+
"file_title": "File Title",
|
431 |
+
"file_href": "File Href",
|
432 |
+
"enactment_date": "Enactment Date",
|
433 |
+
"prio": "Prio"
|
434 |
+
})
|
435 |
+
|
436 |
+
# Add a checkbox column to the DataFrame at the beginning
|
437 |
+
df.insert(0, "Select", False)
|
438 |
+
|
439 |
+
# Configure grid options
|
440 |
+
gb = GridOptionsBuilder.from_dataframe(df)
|
441 |
+
gb.configure_default_column(enablePivot=True, enableValue=True, enableRowGroup=True)
|
442 |
+
gb.configure_column("Select", header_name="Select", cellRenderer='checkboxRenderer')
|
443 |
+
gb.configure_column("File Href", cellRenderer='linkRenderer')
|
444 |
+
gb.configure_selection(selection_mode="multiple", use_checkbox=True)
|
445 |
+
gb.configure_side_bar()
|
446 |
+
gridOptions = gb.build()
|
447 |
+
|
448 |
+
# Display the AgGrid
|
449 |
+
grid_response = AgGrid(
|
450 |
+
df,
|
451 |
+
gridOptions=gridOptions,
|
452 |
+
enable_enterprise_modules=True,
|
453 |
+
update_mode=GridUpdateMode.MODEL_CHANGED,
|
454 |
+
data_return_mode=DataReturnMode.FILTERED_AND_SORTED,
|
455 |
+
fit_columns_on_grid_load=False,
|
456 |
+
)
|
457 |
+
|
458 |
+
# Get the selected rows
|
459 |
+
selected_rows = grid_response['selected_rows']
|
460 |
+
|
461 |
+
# Debug: Print the structure of selected_rows
|
462 |
+
st.write("Debug - Selected Rows Structure:", selected_rows)
|
463 |
+
|
464 |
+
if st.button("Process Selected PDFs"):
|
465 |
+
if len(selected_rows) > 0: # Check if there are any selected rows
|
466 |
+
# Convert selected_rows to a DataFrame
|
467 |
+
st.session_state.selected_pdfs = pd.DataFrame(selected_rows)
|
468 |
+
st.session_state.assistant_id = create_assistant()
|
469 |
+
with st.spinner("Processing PDFs and creating/updating assistant..."):
|
470 |
+
file_ids = []
|
471 |
+
|
472 |
+
for _, pdf in st.session_state.selected_pdfs.iterrows():
|
473 |
+
# Debug: Print each pdf item
|
474 |
+
st.write("Debug - PDF item:", pdf)
|
475 |
+
|
476 |
+
file_href = pdf['File Href']
|
477 |
+
doc_title = pdf['Doc Title']
|
478 |
+
|
479 |
+
# Pass doc_title to download_pdf
|
480 |
+
file_name = download_pdf(file_href, doc_title)
|
481 |
+
if file_name:
|
482 |
+
file_path = f"./{file_name}"
|
483 |
+
file_id = upload_file_to_openai(file_path)
|
484 |
+
if file_id:
|
485 |
+
file_ids.append(file_id)
|
486 |
+
else:
|
487 |
+
st.warning(f"Failed to upload {doc_title}. Skipping this file.")
|
488 |
+
else:
|
489 |
+
st.warning(f"Failed to download {doc_title}. Skipping this file.")
|
490 |
+
|
491 |
+
st.session_state.file_ids = file_ids
|
492 |
+
st.success("PDFs processed successfully. You can now chat on the Home page.")
|
493 |
+
else:
|
494 |
+
st.warning("Select at least one PDF.")
|
495 |
+
|
496 |
+
|
497 |
+
elif page == "Admin":
|
498 |
+
st.title("Admin Panel")
|
499 |
+
st.header("Vector Stores Information")
|
500 |
+
|
501 |
+
vector_stores = get_vector_stores()
|
502 |
+
json_vector_stores = json.dumps([vs.model_dump() for vs in vector_stores])
|
503 |
+
st.write(json_vector_stores)
|
504 |
+
|
505 |
+
# Add a button to go back to the main page
|
506 |
+
|
507 |
+
|
508 |
+
|
509 |
+
|
510 |
+
|
511 |
+
|
512 |
+
|
513 |
+
|
514 |
+
|
515 |
+
|
516 |
+
|
517 |
+
|
518 |
+
|
519 |
+
|
|