TechyCode commited on
Commit
0bd7570
Β·
verified Β·
1 Parent(s): 9d15070

Update src/app_updated.py

Browse files
Files changed (1) hide show
  1. src/app_updated.py +209 -201
src/app_updated.py CHANGED
@@ -1,202 +1,210 @@
1
- import streamlit as st
2
- import os
3
- import dotenv
4
- import uuid
5
-
6
- # Patch sqlite3 for Streamlit Cloud compatibility
7
- if os.name == 'posix':
8
- __import__('pysqlite3')
9
- import sys
10
- sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
11
-
12
- from langchain.schema import HumanMessage, AIMessage
13
- from langchain_groq import ChatGroq
14
-
15
- from rag_methods import (
16
- load_doc_to_db,
17
- load_url_to_db,
18
- stream_llm_response,
19
- stream_llm_rag_response,
20
- )
21
-
22
- dotenv.load_dotenv()
23
-
24
- # --- Custom CSS Styling ---
25
- def apply_custom_css():
26
- st.markdown("""
27
- <style>
28
- .main .block-container {
29
- padding-top: 2rem;
30
- padding-bottom: 2rem;
31
- }
32
- h1, h2, h3, h4 {
33
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
34
- font-weight: 600;
35
- }
36
- .app-title {
37
- text-align: center;
38
- color: #4361ee;
39
- font-size: 2.2rem;
40
- font-weight: 700;
41
- margin-bottom: 1.5rem;
42
- padding: 1rem;
43
- border-radius: 10px;
44
- background: linear-gradient(90deg, rgba(67, 97, 238, 0.1), rgba(58, 12, 163, 0.1));
45
- text-shadow: 0px 0px 2px rgba(0,0,0,0.1);
46
- }
47
- .chat-container {
48
- border-radius: 10px;
49
- padding: 10px;
50
- margin-bottom: 1rem;
51
- }
52
- .message-container {
53
- padding: 0.8rem;
54
- margin-bottom: 0.8rem;
55
- border-radius: 8px;
56
- }
57
- .user-message {
58
- background-color: rgba(67, 97, 238, 0.15);
59
- border-left: 4px solid #4361ee;
60
- }
61
- .assistant-message {
62
- background-color: rgba(58, 12, 163, 0.1);
63
- border-left: 4px solid #3a0ca3;
64
- }
65
- .document-list {
66
- background-color: rgba(67, 97, 238, 0.05);
67
- border-radius: 8px;
68
- padding: 0.7rem;
69
- }
70
- .upload-container {
71
- border: 2px dashed rgba(67, 97, 238, 0.5);
72
- border-radius: 10px;
73
- padding: 1rem;
74
- margin-bottom: 1rem;
75
- text-align: center;
76
- }
77
- .status-indicator {
78
- font-size: 0.85rem;
79
- font-weight: 600;
80
- padding: 0.3rem 0.7rem;
81
- border-radius: 20px;
82
- display: inline-block;
83
- margin-bottom: 0.5rem;
84
- }
85
- .status-active {
86
- background-color: rgba(46, 196, 182, 0.2);
87
- color: #2EC4B6;
88
- }
89
- .status-inactive {
90
- background-color: rgba(231, 111, 81, 0.2);
91
- color: #E76F51;
92
- }
93
- @media screen and (max-width: 768px) {
94
- .app-title {
95
- font-size: 1.8rem;
96
- padding: 0.7rem;
97
- }
98
- }
99
- </style>
100
- """, unsafe_allow_html=True)
101
-
102
- # --- Page Setup ---
103
- st.set_page_config(
104
- page_title="RAG-Xpert: An Enhanced RAG Framework",
105
- page_icon="πŸ“š",
106
- layout="centered",
107
- initial_sidebar_state="expanded"
108
- )
109
-
110
- apply_custom_css()
111
-
112
- st.markdown('<h1 class="app-title">πŸ“š RAG-Xpert: An Enhanced Retrieval-Augmented Generation Framework πŸ€–</h1>', unsafe_allow_html=True)
113
-
114
- # --- Session Initialization ---
115
- if "session_id" not in st.session_state:
116
- st.session_state.session_id = str(uuid.uuid4())
117
- if "rag_sources" not in st.session_state:
118
- st.session_state.rag_sources = []
119
- if "messages" not in st.session_state:
120
- st.session_state.messages = [
121
- {"role": "user", "content": "Hello"},
122
- {"role": "assistant", "content": "Hi there! How can I assist you today?"}
123
- ]
124
-
125
- # --- Sidebar ---
126
- with st.sidebar:
127
- st.markdown("""
128
- <div style="
129
- text-align: center;
130
- padding: 1rem 0;
131
- margin-bottom: 1.5rem;
132
- background: linear-gradient(to right, #4361ee22, #3a0ca322);
133
- border-radius: 10px;">
134
- <div style="font-size: 0.85rem; color: #888;">Developed By</div>
135
- <div style="font-size: 1.2rem; font-weight: 700; color: #4361ee;">Uditanshu Pandey</div>
136
- </div>
137
- """, unsafe_allow_html=True)
138
-
139
- is_vector_db_loaded = "vector_db" in st.session_state and st.session_state.vector_db is not None
140
- rag_status = st.toggle("Enable Knowledge Enhancement (RAG)", value=is_vector_db_loaded, key="use_rag", disabled=not is_vector_db_loaded)
141
-
142
- if rag_status:
143
- st.markdown('<div class="status-indicator status-active">RAG Mode: Active βœ“</div>', unsafe_allow_html=True)
144
- else:
145
- st.markdown('<div class="status-indicator status-inactive">RAG Mode: Inactive βœ—</div>', unsafe_allow_html=True)
146
-
147
- st.toggle("Show Retrieved Context", key="debug_mode", value=False)
148
- st.button("🧹 Clear Chat History", on_click=lambda: st.session_state.messages.clear(), type="primary")
149
-
150
- st.markdown("<h3 style='text-align: center; color: #4361ee; margin-top: 1.5rem;'>πŸ“š Knowledge Sources</h3>", unsafe_allow_html=True)
151
- st.markdown('<div class="upload-container">', unsafe_allow_html=True)
152
- st.file_uploader("πŸ“„ Upload Documents", type=["pdf", "txt", "docx", "md"], accept_multiple_files=True, on_change=load_doc_to_db, key="rag_docs")
153
- st.markdown('</div>', unsafe_allow_html=True)
154
-
155
- st.text_input("🌐 Add Webpage URL", placeholder="https://example.com", on_change=load_url_to_db, key="rag_url")
156
-
157
- doc_count = len(st.session_state.rag_sources) if is_vector_db_loaded else 0
158
- with st.expander(f"πŸ“‘ Knowledge Base ({doc_count} sources)"):
159
- if doc_count:
160
- st.markdown('<div class="document-list">', unsafe_allow_html=True)
161
- for i, source in enumerate(st.session_state.rag_sources):
162
- st.markdown(f"**{i+1}.** {source}")
163
- st.markdown('</div>', unsafe_allow_html=True)
164
- else:
165
- st.info("No documents added yet. Upload files or add URLs to enhance the assistant's knowledge.")
166
-
167
- # --- Initialize LLM ---
168
- llm_stream = ChatGroq(
169
- model_name="meta-llama/llama-4-scout-17b-16e-instruct",
170
- api_key=os.getenv("GROQ_API_KEY"),
171
- temperature=0.4,
172
- max_tokens=1024,
173
- )
174
-
175
- # --- Chat Display ---
176
- st.markdown('<div class="chat-container">', unsafe_allow_html=True)
177
- for message in st.session_state.messages:
178
- avatar = "πŸ‘€" if message["role"] == "user" else "πŸ€–"
179
- css_class = "user-message" if message["role"] == "user" else "assistant-message"
180
- with st.chat_message(message["role"], avatar=avatar):
181
- st.markdown(f'<div class="message-container {css_class}">{message["content"]}</div>', unsafe_allow_html=True)
182
- st.markdown('</div>', unsafe_allow_html=True)
183
-
184
- # --- User Input Handling ---
185
- if prompt := st.chat_input("Ask me anything..."):
186
- st.session_state.messages.append({"role": "user", "content": prompt})
187
- with st.chat_message("user", avatar="πŸ‘€"):
188
- st.markdown(f'<div class="message-container user-message">{prompt}</div>', unsafe_allow_html=True)
189
-
190
- with st.chat_message("assistant", avatar="πŸ€–"):
191
- thinking_placeholder = st.empty()
192
- thinking_placeholder.info("Thinking... Please wait a moment.")
193
- messages = [
194
- HumanMessage(content=m["content"]) if m["role"] == "user" else AIMessage(content=m["content"])
195
- for m in st.session_state.messages
196
- ]
197
- if not st.session_state.use_rag:
198
- thinking_placeholder.empty()
199
- st.write_stream(stream_llm_response(llm_stream, messages))
200
- else:
201
- thinking_placeholder.info("Searching knowledge base... Please wait.")
 
 
 
 
 
 
 
 
202
  st.write_stream(stream_llm_rag_response(llm_stream, messages))
 
1
+ import streamlit as st
2
+ import os
3
+ import dotenv
4
+ import uuid
5
+ import logging
6
+
7
+ # Configure environment for Hugging Face Spaces
8
+ os.environ["HF_HOME"] = "/tmp/.cache/huggingface"
9
+ os.environ["TRANSFORMERS_CACHE"] = "/tmp/.cache/huggingface"
10
+ os.environ["HUGGINGFACE_HUB_CACHE"] = "/tmp/.cache/huggingface"
11
+
12
+ # Create necessary directories
13
+ os.makedirs("/tmp/.cache/huggingface", exist_ok=True)
14
+ os.makedirs("/tmp/chroma_persistent_db", exist_ok=True)
15
+ os.makedirs("/tmp/source_files", exist_ok=True)
16
+
17
+ # Configure logging
18
+ logging.basicConfig(level=logging.INFO)
19
+ logger = logging.getLogger(__name__)
20
+
21
+ from langchain.schema import HumanMessage, AIMessage
22
+ from langchain_groq import ChatGroq
23
+ from rag_methods import (
24
+ load_doc_to_db,
25
+ load_url_to_db,
26
+ stream_llm_response,
27
+ stream_llm_rag_response,
28
+ )
29
+
30
+ dotenv.load_dotenv()
31
+
32
+ # --- Custom CSS Styling ---
33
+ def apply_custom_css():
34
+ st.markdown("""
35
+ <style>
36
+ .main .block-container {
37
+ padding-top: 2rem;
38
+ padding-bottom: 2rem;
39
+ }
40
+ h1, h2, h3, h4 {
41
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
42
+ font-weight: 600;
43
+ }
44
+ .app-title {
45
+ text-align: center;
46
+ color: #4361ee;
47
+ font-size: 2.2rem;
48
+ font-weight: 700;
49
+ margin-bottom: 1.5rem;
50
+ padding: 1rem;
51
+ border-radius: 10px;
52
+ background: linear-gradient(90deg, rgba(67, 97, 238, 0.1), rgba(58, 12, 163, 0.1));
53
+ text-shadow: 0px 0px 2px rgba(0,0,0,0.1);
54
+ }
55
+ .chat-container {
56
+ border-radius: 10px;
57
+ padding: 10px;
58
+ margin-bottom: 1rem;
59
+ }
60
+ .message-container {
61
+ padding: 0.8rem;
62
+ margin-bottom: 0.8rem;
63
+ border-radius: 8px;
64
+ }
65
+ .user-message {
66
+ background-color: rgba(67, 97, 238, 0.15);
67
+ border-left: 4px solid #4361ee;
68
+ }
69
+ .assistant-message {
70
+ background-color: rgba(58, 12, 163, 0.1);
71
+ border-left: 4px solid #3a0ca3;
72
+ }
73
+ .document-list {
74
+ background-color: rgba(67, 97, 238, 0.05);
75
+ border-radius: 8px;
76
+ padding: 0.7rem;
77
+ }
78
+ .upload-container {
79
+ border: 2px dashed rgba(67, 97, 238, 0.5);
80
+ border-radius: 10px;
81
+ padding: 1rem;
82
+ margin-bottom: 1rem;
83
+ text-align: center;
84
+ }
85
+ .status-indicator {
86
+ font-size: 0.85rem;
87
+ font-weight: 600;
88
+ padding: 0.3rem 0.7rem;
89
+ border-radius: 20px;
90
+ display: inline-block;
91
+ margin-bottom: 0.5rem;
92
+ }
93
+ .status-active {
94
+ background-color: rgba(46, 196, 182, 0.2);
95
+ color: #2EC4B6;
96
+ }
97
+ .status-inactive {
98
+ background-color: rgba(231, 111, 81, 0.2);
99
+ color: #E76F51;
100
+ }
101
+ @media screen and (max-width: 768px) {
102
+ .app-title {
103
+ font-size: 1.8rem;
104
+ padding: 0.7rem;
105
+ }
106
+ }
107
+ </style>
108
+ """, unsafe_allow_html=True)
109
+
110
+ # --- Page Setup ---
111
+ st.set_page_config(
112
+ page_title="RAG-Xpert: An Enhanced RAG Framework",
113
+ page_icon="πŸ“š",
114
+ layout="centered",
115
+ initial_sidebar_state="expanded"
116
+ )
117
+
118
+ apply_custom_css()
119
+
120
+ st.markdown('<h1 class="app-title">πŸ“š RAG-Xpert: An Enhanced Retrieval-Augmented Generation Framework πŸ€–</h1>', unsafe_allow_html=True)
121
+
122
+ # --- Session Initialization ---
123
+ if "session_id" not in st.session_state:
124
+ st.session_state.session_id = str(uuid.uuid4())
125
+ if "rag_sources" not in st.session_state:
126
+ st.session_state.rag_sources = []
127
+ if "messages" not in st.session_state:
128
+ st.session_state.messages = [
129
+ {"role": "user", "content": "Hello"},
130
+ {"role": "assistant", "content": "Hi there! How can I assist you today?"}
131
+ ]
132
+
133
+ # --- Sidebar ---
134
+ with st.sidebar:
135
+ st.markdown("""
136
+ <div style="
137
+ text-align: center;
138
+ padding: 1rem 0;
139
+ margin-bottom: 1.5rem;
140
+ background: linear-gradient(to right, #4361ee22, #3a0ca322);
141
+ border-radius: 10px;">
142
+ <div style="font-size: 0.85rem; color: #888;">Developed By</div>
143
+ <div style="font-size: 1.2rem; font-weight: 700; color: #4361ee;">Uditanshu Pandey</div>
144
+ </div>
145
+ """, unsafe_allow_html=True)
146
+
147
+ is_vector_db_loaded = "vector_db" in st.session_state and st.session_state.vector_db is not None
148
+ rag_status = st.toggle("Enable Knowledge Enhancement (RAG)", value=is_vector_db_loaded, key="use_rag", disabled=not is_vector_db_loaded)
149
+
150
+ if rag_status:
151
+ st.markdown('<div class="status-indicator status-active">RAG Mode: Active βœ“</div>', unsafe_allow_html=True)
152
+ else:
153
+ st.markdown('<div class="status-indicator status-inactive">RAG Mode: Inactive βœ—</div>', unsafe_allow_html=True)
154
+
155
+ st.toggle("Show Retrieved Context", key="debug_mode", value=False)
156
+ st.button("🧹 Clear Chat History", on_click=lambda: st.session_state.messages.clear(), type="primary")
157
+
158
+ st.markdown("<h3 style='text-align: center; color: #4361ee; margin-top: 1.5rem;'>πŸ“š Knowledge Sources</h3>", unsafe_allow_html=True)
159
+ st.markdown('<div class="upload-container">', unsafe_allow_html=True)
160
+ st.file_uploader("πŸ“„ Upload Documents", type=["pdf", "txt", "docx", "md"], accept_multiple_files=True, on_change=load_doc_to_db, key="rag_docs")
161
+ st.markdown('</div>', unsafe_allow_html=True)
162
+
163
+ st.text_input("🌐 Add Webpage URL", placeholder="https://example.com", on_change=load_url_to_db, key="rag_url")
164
+
165
+ doc_count = len(st.session_state.rag_sources) if is_vector_db_loaded else 0
166
+ with st.expander(f"πŸ“‘ Knowledge Base ({doc_count} sources)"):
167
+ if doc_count:
168
+ st.markdown('<div class="document-list">', unsafe_allow_html=True)
169
+ for i, source in enumerate(st.session_state.rag_sources):
170
+ st.markdown(f"**{i+1}.** {source}")
171
+ st.markdown('</div>', unsafe_allow_html=True)
172
+ else:
173
+ st.info("No documents added yet. Upload files or add URLs to enhance the assistant's knowledge.")
174
+
175
+ # --- Initialize LLM ---
176
+ llm_stream = ChatGroq(
177
+ model_name="meta-llama/llama-4-scout-17b-16e-instruct",
178
+ api_key=os.getenv("GROQ_API_KEY"),
179
+ temperature=0.4,
180
+ max_tokens=1024,
181
+ )
182
+
183
+ # --- Chat Display ---
184
+ st.markdown('<div class="chat-container">', unsafe_allow_html=True)
185
+ for message in st.session_state.messages:
186
+ avatar = "πŸ‘€" if message["role"] == "user" else "πŸ€–"
187
+ css_class = "user-message" if message["role"] == "user" else "assistant-message"
188
+ with st.chat_message(message["role"], avatar=avatar):
189
+ st.markdown(f'<div class="message-container {css_class}">{message["content"]}</div>', unsafe_allow_html=True)
190
+ st.markdown('</div>', unsafe_allow_html=True)
191
+
192
+ # --- User Input Handling ---
193
+ if prompt := st.chat_input("Ask me anything..."):
194
+ st.session_state.messages.append({"role": "user", "content": prompt})
195
+ with st.chat_message("user", avatar="πŸ‘€"):
196
+ st.markdown(f'<div class="message-container user-message">{prompt}</div>', unsafe_allow_html=True)
197
+
198
+ with st.chat_message("assistant", avatar="πŸ€–"):
199
+ thinking_placeholder = st.empty()
200
+ thinking_placeholder.info("Thinking... Please wait a moment.")
201
+ messages = [
202
+ HumanMessage(content=m["content"]) if m["role"] == "user" else AIMessage(content=m["content"])
203
+ for m in st.session_state.messages
204
+ ]
205
+ if not st.session_state.use_rag:
206
+ thinking_placeholder.empty()
207
+ st.write_stream(stream_llm_response(llm_stream, messages))
208
+ else:
209
+ thinking_placeholder.info("Searching knowledge base... Please wait.")
210
  st.write_stream(stream_llm_rag_response(llm_stream, messages))