tony-42069 commited on
Commit
33a83d7
·
1 Parent(s): 6f52539

Enhance UI and pre-load PDF instead of upload

Browse files
Files changed (1) hide show
  1. app.py +96 -86
app.py CHANGED
@@ -1,5 +1,4 @@
1
  import streamlit as st
2
- import tempfile
3
  import os
4
  from pdf_processor import PDFProcessor
5
  from rag_engine import RAGEngine
@@ -22,95 +21,106 @@ if 'processed_file' not in st.session_state:
22
  st.session_state.processed_file = False
23
 
24
  # Page config
25
- st.set_page_config(page_title="Concept Definition Chatbot", layout="wide")
26
- st.title("Concept Definition Chatbot")
 
 
 
 
27
 
28
- # Sidebar for PDF upload
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  with st.sidebar:
30
- st.header("Upload PDF")
31
- uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
 
 
 
 
 
 
 
 
32
 
33
- if uploaded_file is not None and not st.session_state.processed_file:
34
- with st.spinner("Processing PDF..."):
35
- try:
36
- # Save uploaded file temporarily
37
- with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
38
- tmp_file.write(uploaded_file.getvalue())
39
- tmp_path = tmp_file.name
40
-
41
- # Process PDF
42
- processor = PDFProcessor()
43
- chunks = processor.process_pdf(tmp_path)
44
-
45
- # Initialize RAG engine
46
- st.session_state.rag_engine.initialize_vector_store(chunks)
47
- st.session_state.processed_file = True
48
-
49
- # Clean up
50
- os.unlink(tmp_path)
51
- except ValueError as e:
52
- st.error(f"Configuration Error: {str(e)}")
53
- st.stop()
54
- except ConnectionError as e:
55
- st.error(f"Connection Error: {str(e)}")
56
- st.stop()
57
- except Exception as e:
58
- st.error(f"Unexpected Error: {str(e)}")
59
- st.stop()
60
- st.success("PDF processed successfully!")
61
 
62
- # Main chat interface
63
- if st.session_state.processed_file:
64
- # Initialize chat history
65
- if "messages" not in st.session_state:
66
- st.session_state.messages = []
67
 
68
- # Display chat messages
69
- for message in st.session_state.messages:
70
- with st.chat_message(message["role"]):
71
- st.markdown(message["content"])
72
- if "sources" in message:
73
- with st.expander("View Sources"):
74
- for source in message["sources"]:
75
- st.markdown(f"**Page {source['page']}:**\n{source['text']}")
76
 
77
- # Chat input
78
- if prompt := st.chat_input("Ask a question about the concepts in your PDF"):
79
- # Add user message to chat history
80
- st.session_state.messages.append({"role": "user", "content": prompt})
81
-
82
- # Display user message
83
- with st.chat_message("user"):
84
- st.markdown(prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
- # Get bot response
87
- with st.chat_message("assistant"):
88
- with st.spinner("Thinking..."):
89
- try:
90
- response = st.session_state.rag_engine.answer_question(prompt)
91
-
92
- # Display response
93
- st.markdown(response["answer"])
94
-
95
- # Display sources in expander
96
- with st.expander("View Sources"):
97
- for source in response["sources"]:
98
- st.markdown(f"**Page {source['page']}:**\n{source['text']}")
99
-
100
- # Add assistant response to chat history
101
- st.session_state.messages.append({
102
- "role": "assistant",
103
- "content": response["answer"],
104
- "sources": response["sources"]
105
- })
106
- except ValueError as e:
107
- st.error(f"Configuration Error: {str(e)}")
108
- st.stop()
109
- except ConnectionError as e:
110
- st.error(f"Connection Error: {str(e)}")
111
- st.stop()
112
- except Exception as e:
113
- st.error(f"Unexpected Error: {str(e)}")
114
- st.stop()
115
- else:
116
- st.info("Please upload a PDF file to start chatting.")
 
1
  import streamlit as st
 
2
  import os
3
  from pdf_processor import PDFProcessor
4
  from rag_engine import RAGEngine
 
21
  st.session_state.processed_file = False
22
 
23
  # Page config
24
+ st.set_page_config(
25
+ page_title="CRE Knowledge Assistant",
26
+ page_icon="🏢",
27
+ layout="wide",
28
+ initial_sidebar_state="expanded"
29
+ )
30
 
31
+ # Custom CSS
32
+ st.markdown("""
33
+ <style>
34
+ .stApp {
35
+ max-width: 1200px;
36
+ margin: 0 auto;
37
+ }
38
+ .main-header {
39
+ font-size: 2.5rem;
40
+ color: #1E3A8A;
41
+ margin-bottom: 2rem;
42
+ text-align: center;
43
+ }
44
+ .chat-container {
45
+ background-color: #F3F4F6;
46
+ padding: 2rem;
47
+ border-radius: 1rem;
48
+ margin-bottom: 2rem;
49
+ }
50
+ .sidebar-content {
51
+ padding: 1.5rem;
52
+ background-color: #F8FAFC;
53
+ border-radius: 0.5rem;
54
+ }
55
+ </style>
56
+ """, unsafe_allow_html=True)
57
+
58
+ # Main content
59
+ st.markdown('<h1 class="main-header">Commercial Real Estate Knowledge Assistant</h1>', unsafe_allow_html=True)
60
+
61
+ # Initialize RAG engine with pre-loaded PDF if not already done
62
+ if not st.session_state.processed_file:
63
+ with st.spinner("Initializing knowledge base..."):
64
+ try:
65
+ # Process the pre-loaded PDF
66
+ pdf_path = os.path.join("Dataset", "Commercial Lending 101.pdf")
67
+ processor = PDFProcessor()
68
+ chunks = processor.process_pdf(pdf_path)
69
+
70
+ # Initialize RAG engine
71
+ st.session_state.rag_engine.initialize_vector_store(chunks)
72
+ st.session_state.processed_file = True
73
+ except Exception as e:
74
+ st.error(f"Error initializing knowledge base: {str(e)}")
75
+ st.stop()
76
+
77
+ # Sidebar with information
78
  with st.sidebar:
79
+ st.markdown('<div class="sidebar-content">', unsafe_allow_html=True)
80
+ st.image("https://raw.githubusercontent.com/tony-42069/cre-chatbot-rag/main/Dataset/commercial-lending-101.png",
81
+ use_column_width=True)
82
+ st.markdown("""
83
+ ### About
84
+ This AI assistant is trained on commercial real estate knowledge and can help you understand:
85
+ - Commercial lending concepts
86
+ - Real estate terminology
87
+ - Market analysis
88
+ - Investment strategies
89
 
90
+ ### How to Use
91
+ Simply type your question in the chat box below and press Enter. The assistant will provide detailed answers based on the commercial real estate knowledge base.
92
+ """)
93
+ st.markdown('</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
+ # Chat interface
96
+ st.markdown('<div class="chat-container">', unsafe_allow_html=True)
 
 
 
97
 
98
+ if "messages" not in st.session_state:
99
+ st.session_state.messages = []
 
 
 
 
 
 
100
 
101
+ # Display chat messages
102
+ for message in st.session_state.messages:
103
+ with st.chat_message(message["role"]):
104
+ st.markdown(message["content"])
105
+
106
+ # Chat input
107
+ if prompt := st.chat_input("Ask me anything about commercial real estate..."):
108
+ # Add user message to chat history
109
+ st.session_state.messages.append({"role": "user", "content": prompt})
110
+
111
+ # Display user message
112
+ with st.chat_message("user"):
113
+ st.markdown(prompt)
114
+
115
+ # Generate response
116
+ with st.chat_message("assistant"):
117
+ with st.spinner("Thinking..."):
118
+ try:
119
+ response = st.session_state.rag_engine.get_response(prompt)
120
+ st.markdown(response)
121
+ # Add assistant response to chat history
122
+ st.session_state.messages.append({"role": "assistant", "content": response})
123
+ except Exception as e:
124
+ st.error(f"Error generating response: {str(e)}")
125
 
126
+ st.markdown('</div>', unsafe_allow_html=True)