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17
 
 
 
 
d61a8aa
8c7aa17
d61a8aa
8c7aa17
 
 
 
 
d61a8aa
 
 
 
 
8c7aa17
d61a8aa
8c7aa17
 
 
 
018d0ff
8c7aa17
 
018d0ff
8c7aa17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018d0ff
8c7aa17
 
 
 
 
018d0ff
 
 
8c7aa17
 
 
 
 
 
018d0ff
 
 
8c7aa17
 
 
 
 
 
 
 
 
 
 
 
 
018d0ff
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
304
305
306
307
308
309
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
345
346
347
348
349
350
351
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
# import streamlit as st
# from langchain_openai import OpenAIEmbeddings  # Changed to OpenAI embeddings
# from langchain_chroma import Chroma 
# from langchain_groq import ChatGroq
# import os
# from dotenv import load_dotenv

# # Page config
# st.set_page_config(
#     page_title="UK Construction Regulations Assistant",
#     page_icon="πŸ—οΈ",
#     layout="wide"
# )

# # Load environment variables
# load_dotenv()

# # Initialize RAG components
# @st.cache_resource
# def init_rag():
#     """Initialize RAG components with caching"""
#     try:
#         # Check if main_chroma_data exists
#         if not os.path.exists("./main_chroma_data"):
#             st.error("Error: main_chroma_data directory not found. Please check the directory path.")
#             return None, None

#         # Initialize embeddings
#         try:
#             embeddings = OpenAIEmbeddings(
#                 api_key=os.getenv("OPENAI_API_KEY")
#             )
#         except Exception as e:
#             st.error(f"Error initializing embeddings: {str(e)}")
#             return None, None

#         # Initialize vector store
#         try:
#             vectorstore = Chroma(
#                 collection_name="main_construction_rag",
#                 embedding_function=embeddings,
#                 persist_directory="./main_chroma_data"
#             )
#         except Exception as e:
#             st.error(f"Error initializing vector store: {str(e)}")
#             return None, None

#         # Check if GROQ API key is set
#         groq_api_key = os.getenv("GROQ_API_KEY")
#         if not groq_api_key:
#             st.error("Error: GROQ_API_KEY not found in environment variables")
#             return None, None

#         # Initialize LLM
#         try:
#             llm = ChatGroq(
#                 api_key=groq_api_key,
#                 model_name="llama-3.3-70b-versatile",
#                 temperature=0
#             )
#         except Exception as e:
#             st.error(f"Error initializing LLM: {str(e)}")
#             return None, None

#         return vectorstore, llm
#     except Exception as e:
#         st.error(f"Error initializing RAG system: {str(e)}")
#         return None, None

# # Initialize
# vectorstore, llm = init_rag()

# # Sidebar for feedback
# with st.sidebar:
#     st.title("πŸ“ Feedback")
#     feedback = st.text_area("Share your feedback on the answers:", height=100)
#     if st.button("Submit Feedback"):
#         st.success("Thank you for your feedback!")

# # Main interface
# st.title("πŸ—οΈ UK Construction Regulations Assistant")
# st.markdown("""
# This AI assistant helps answer questions about UK construction regulations using:
# - Official Building Regulations documents
# - Expert YouTube content from LABC, RICS, and other authorities
# - Technical documentation and guidance
# """)

# # User input
# question = st.text_input("Enter your question about UK construction regulations:")

# if st.button("Get Answer"):
#     if not question:
#         st.warning("Please enter a question.")
#     elif vectorstore is None or llm is None:
#         st.error("RAG system not properly initialized. Please check the errors above.")
#     else:
#         with st.spinner("Searching regulations and generating answer..."):
#             try:
#                 # Get relevant documents
#                 docs = vectorstore.similarity_search(question, k=4)
#                 contexts = [doc.page_content for doc in docs]
                
#                 # Generate answer
#                 context_text = "\n\n".join(contexts)
#                 prompt = f"""Based on the following context from UK Building Regulations, provide a clear and detailed answer to the question.
#                 Include specific references to regulations where available.
                
#                 Question: {question}
                
#                 Context: {context_text}
                
#                 Answer:"""
                
#                 response = llm.invoke(prompt)
                
#                 # Display answer
#                 st.markdown("### Answer")
#                 st.write(response.content)
                
#                 # Display sources
#                 with st.expander("View Source Documents"):
#                     for i, context in enumerate(contexts, 1):
#                         st.markdown(f"**Source {i}:**")
#                         st.markdown(context)
#                         st.divider()
                        
#                 # Add thumbs up/down for answer quality
#                 col1, col2 = st.columns(2)
#                 with col1:
#                     if st.button("πŸ‘ Helpful"):
#                         st.success("Thank you for your feedback!")
#                 with col2:
#                     if st.button("πŸ‘Ž Not Helpful"):
#                         st.info("Thank you for your feedback. Please let us know how we can improve in the sidebar.")
                        
#             except Exception as e:
#                 st.error(f"Error generating answer: {str(e)}")

# # Footer
# st.markdown("---")
# st.markdown("*This is a research project. Always verify information with official sources.*")


# # SQLite compatibility fix for Chromadb
# import sqlite3
# print(f"SQLite version: {sqlite3.sqlite_version}")

# # Try alternative vector store approach if SQLite version is too old
# import os
# os.environ["LANGCHAIN_CHROMA_ALLOW_DEPRECATED_BACKEND"] = "true"

# import streamlit as st
# from langchain_huggingface import HuggingFaceEmbeddings
# from langchain_chroma import Chroma  # Updated from langchain_community.vectorstores
# from langchain_groq import ChatGroq
# import os
# from dotenv import load_dotenv
# from cloud_storage import download_vectorstore

# # Page config
# st.set_page_config(
#     page_title="UK Building Regulations Assistant",
#     page_icon="πŸ—οΈ",
#     layout="wide"
# )

# # Load environment variables
# load_dotenv()

# # Initialize RAG components
# @st.cache_resource
# def init_rag():
#     """Initialize RAG components with caching"""
#     try:
#         # Check if main_chroma_data exists
#         if not os.path.exists("./main_chroma_data"):
#             download_vectorstore()
#             # st.error("Error: main_chroma_data directory not found. Please check the directory path.")
#             # return None, None

#         # Initialize embeddings
#         try:
#             embeddings = HuggingFaceEmbeddings(
#                 model_name="sentence-transformers/all-mpnet-base-v2",
#                 encode_kwargs={'normalize_embeddings': True}  # Added for stability
#             )
#         except Exception as e:
#             st.error(f"Error initializing embeddings: {str(e)}")
#             return None, None

#         # Initialize vector store
#         # try:
#         #     vectorstore = Chroma(
#         #         collection_name="main_construction_rag",
#         #         embedding_function=embeddings,
#         #         persist_directory="./main_chroma_data"
#         #     )
#         # except Exception as e:
#         #     st.error(f"Error initializing vector store: {str(e)}")
#         #     return None, None
        
#         # Initialize vector store
#         try:
#             vectorstore = Chroma(
#                 collection_name="main_construction_rag",
#                 embedding_function=embeddings,
#                 persist_directory="./main_chroma_data"
#             )
#         except Exception as e:
#             st.warning("Using deprecated backend due to SQLite version constraints")
#             # Use alternative initialization if needed
#             from langchain_community.vectorstores import Chroma as ChromaDeprecated
#             vectorstore = ChromaDeprecated(
#                 collection_name="main_construction_rag",
#                 embedding_function=embeddings,
#                 persist_directory="./main_chroma_data"
#             )

#         # Check if GROQ API key is set
#         groq_api_key = os.getenv("GROQ_API_KEY")
#         if not groq_api_key:
#             st.error("Error: GROQ_API_KEY not found in environment variables")
#             return None, None

#         # Initialize LLM
#         try:
#             llm = ChatGroq(
#                 api_key=groq_api_key,
#                 model_name="llama-3.3-70b-versatile",
#                 temperature=0.1
#             )
#         except Exception as e:
#             st.error(f"Error initializing LLM: {str(e)}")
#             return None, None

#         return vectorstore, llm
#     except Exception as e:
#         st.error(f"Error initializing RAG system: {str(e)}")
#         return None, None



# # Initialize
# vectorstore, llm = init_rag()

# # Sidebar for feedback
# with st.sidebar:
#     st.title("πŸ“ StructureGPT Feedback")
#     feedback = st.text_area("Share your feedback on the answers:", height=100)
#     if st.button("Submit Feedback"):
#         st.success("Thank you for your feedback!")

# # Main interface
# st.title("πŸ—οΈ StructureGPT - UK Building Regulations AI Assistant")
# st.markdown("""
# This AI assistant helps answer questions about UK building regulations using:
# - Official Building Regulations documents
# - Expert YouTube content from LABC, RICS, and other authorities
# - Technical documentation and guidance
# """)

# # Add testing phase notice with warning styling
# st.warning("""
# ⚠️ **TESTING PHASE** - StructureGPT is currently in beta testing, focusing only on UK Building Regulations Parts A (Structure), B (Fire Safety), and C (Site Preparation and Resistance to Contaminants and Moisture). Additional regulation parts will be added soon.
# """)

# # User input
# question = st.text_input("Enter your question about UK building regulations:")

# if st.button("Get Answer"):
#     if not question:
#         st.warning("Please enter a question.")
#     elif vectorstore is None or llm is None:
#         st.error("RAG system not properly initialized. Please check the errors above.")
#     else:
#         with st.spinner("Searching regulations and generating answer..."):
#             try:
#                 # Get relevant documents
#                 docs = vectorstore.similarity_search(question, k=4)
#                 contexts = [doc.page_content for doc in docs]
                
#                 # Generate answer
#                 context_text = "\n\n".join(contexts)
#                 prompt = f"""Based on the following context from UK Building Regulations, provide a clear and detailed answer to the question.
#                 Include specific references to regulations where available.
                
#                 Question: {question}
                
#                 Context: {context_text}
                
#                 Answer:"""
                
#                 response = llm.invoke(prompt)
                
#                 # Display answer
#                 st.markdown("### Answer")
#                 st.write(response.content)
                
#                 # Display sources
#                 with st.expander("View Source Documents"):
#                     for i, context in enumerate(contexts, 1):
#                         st.markdown(f"**Source {i}:**")
#                         st.markdown(context)
#                         st.divider()
                        
#                 # Add thumbs up/down for answer quality
#                 col1, col2 = st.columns(2)
#                 with col1:
#                     if st.button("πŸ‘ Helpful"):
#                         st.success("Thank you for your feedback!")
#                 with col2:
#                     if st.button("πŸ‘Ž Not Helpful"):
#                         st.info("Thank you for your feedback. Please let us know how we can improve in the sidebar.")
                        
#             except Exception as e:
#                 st.error(f"Error generating answer: {str(e)}")

# # Footer
# st.markdown("---")
# st.markdown("*StructureGPT is a research project in testing phase. Currently supporting Parts A (Structure), B (Fire Safety), and C (Site Preparation) of UK Building Regulations. Always verify information with official sources.*")


# SQLite compatibility fix for Chromadb
import sqlite3
print(f"SQLite version: {sqlite3.sqlite_version}")

# Try alternative vector store approach if SQLite version is too old
import os
os.environ["LANGCHAIN_CHROMA_ALLOW_DEPRECATED_BACKEND"] = "true"

import streamlit as st
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_chroma import Chroma
from langchain_groq import ChatGroq
import os
from dotenv import load_dotenv
from cloud_storage import download_vectorstore

# Page config
st.set_page_config(
    page_title="StructureGPT - UK Building Regulations Assistant",
    page_icon="πŸ—οΈ",
    layout="wide"
)

# Load environment variables
load_dotenv()

# Initialize RAG components
@st.cache_resource
def init_rag():
    """Initialize RAG components with caching"""
    try:
        # Check if main_chroma_data exists
        if not os.path.exists("./main_chroma_data"):
            download_vectorstore()

        # Initialize embeddings
        try:
            embeddings = HuggingFaceEmbeddings(
                model_name="sentence-transformers/all-mpnet-base-v2",
                encode_kwargs={'normalize_embeddings': True}  # Added for stability
            )
        except Exception as e:
            st.error(f"Error initializing embeddings: {str(e)}")
            return None, None, None

        # Initialize vector store
        try:
            vectorstore = Chroma(
                collection_name="main_construction_rag",
                embedding_function=embeddings,
                persist_directory="./main_chroma_data"
            )
        except Exception as e:
            st.warning("Using deprecated backend due to SQLite version constraints")
            # Use alternative initialization if needed
            from langchain_community.vectorstores import Chroma as ChromaDeprecated
            vectorstore = ChromaDeprecated(
                collection_name="main_construction_rag",
                embedding_function=embeddings,
                persist_directory="./main_chroma_data"
            )

        # Check if GROQ API key is set
        groq_api_key = os.getenv("GROQ_API_KEY")
        if not groq_api_key:
            st.error("Error: GROQ_API_KEY not found in environment variables")
            return None, None, None

        # Initialize LLMs - both models
        try:
            llm_70b = ChatGroq(
                api_key=groq_api_key,
                model_name="llama-3.3-70b-versatile",
                temperature=0.1
            )
            
            llm_8b = ChatGroq(
                api_key=groq_api_key,
                model_name="llama3-8b-8192",
                temperature=0.1
            )
        except Exception as e:
            st.error(f"Error initializing LLMs: {str(e)}")
            return None, None, None

        return vectorstore, llm_70b, llm_8b
    except Exception as e:
        st.error(f"Error initializing RAG system: {str(e)}")
        return None, None, None

# Initialize
vectorstore, llm_70b, llm_8b = init_rag()

# Sidebar for model selection and feedback
with st.sidebar:
    st.title("πŸ”§ Model Settings")
    
    # Model selection toggle
    model_option = st.radio(
        "Select Model:",
        ["Llama-3.3-70B (More accurate, slower)", "Llama3-8B (Faster, less accurate)"],
        index=0,  # Default to 70B model
        help="Choose between more accurate (70B) or faster (8B) model"
    )
    
    # Display selected model details
    if model_option == "Llama-3.3-70B (More accurate, slower)":
        st.info("Using Llama-3.3-70B: Higher accuracy but slightly slower responses")
        selected_llm = llm_70b
    else:
        st.info("Using Llama3-8B: Faster responses with good accuracy")
        selected_llm = llm_8b
    
    st.divider()
    
    # Feedback section
    st.title("πŸ“ Feedback")
    feedback = st.text_area("Share your feedback on the answers:", height=100)
    if st.button("Submit Feedback"):
        st.success("Thank you for your feedback!")

# Main interface
st.title("πŸ—οΈ StructureGPT - UK Building Regulations AI Assistant")
st.markdown("""
This AI assistant helps answer questions about UK building regulations using:
- Official Building Regulations documents
- Expert YouTube content from LABC, RICS, and other authorities
- Technical documentation and guidance
""")

# Add testing phase notice with warning styling
st.warning("""
⚠️ **TESTING PHASE** - StructureGPT is currently in beta testing, focusing only on UK Building Regulations Parts A (Structure), B (Fire Safety), and C (Site Preparation and Resistance to Contaminants and Moisture). Additional regulation parts will be added soon.
""")

# User input
question = st.text_input("Enter your question about UK building regulations:")

if st.button("Get Answer"):
    if not question:
        st.warning("Please enter a question.")
    elif vectorstore is None or selected_llm is None:
        st.error("RAG system not properly initialized. Please check the errors above.")
    else:
        with st.spinner(f"Searching regulations and generating answer using {model_option.split(' ')[0]}..."):
            try:
                # Get relevant documents
                docs = vectorstore.similarity_search(question, k=4)
                contexts = [doc.page_content for doc in docs]
                
                # Generate answer
                context_text = "\n\n".join(contexts)
                prompt = f"""Based on the following context from UK Building Regulations, provide a clear and detailed answer to the question.
                Include specific references to regulations where available.
                
                Question: {question}
                
                Context: {context_text}
                
                Answer:"""
                
                response = selected_llm.invoke(prompt)
                
                # Display answer
                st.markdown("### Answer")
                st.write(response.content)
                
                # Display model used
                st.caption(f"Answer generated using {model_option.split(' ')[0]}")
                
                # Display sources
                with st.expander("View Source Documents"):
                    for i, context in enumerate(contexts, 1):
                        st.markdown(f"**Source {i}:**")
                        st.markdown(context)
                        st.divider()
                
                # Add feedback section
                st.subheader("Was this answer helpful?")
                col1, col2 = st.columns(2)
                with col1:
                    if st.button("πŸ‘ Helpful"):
                        st.success("Thank you for your feedback!")
                with col2:
                    if st.button("πŸ‘Ž Not Helpful"):
                        st.info("Thank you for your feedback. Please let us know how we can improve in the sidebar.")
                        
            except Exception as e:
                st.error(f"Error generating answer: {str(e)}")

# Footer
st.markdown("---")
st.markdown("*StructureGPT is a research project in testing phase. Currently supporting Parts A (Structure), B (Fire Safety), and C (Site Preparation) of UK Building Regulations. Always verify information with official sources.*")