Spaces:
Running
on
L4
Running
on
L4
Update app.py
Browse files
app.py
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
"""
|
2 |
-
Universal RAG PDF Chatbot with Enhanced Safety Checks and Improved Context Management - COMPLETE UPDATED VERSION
|
3 |
|
4 |
This is a general-purpose RAG (Retrieval-Augmented Generation) chatbot that can work with any set of PDF documents.
|
5 |
It includes comprehensive safety checks and can provide educational responses even when information isn't in the documents.
|
@@ -50,6 +50,11 @@ SAFETY_CONFIG = {
|
|
50 |
'educational_alternatives': True, # Always provide educational alternatives
|
51 |
'allow_general_knowledge': True # Allow answers from general knowledge when appropriate
|
52 |
}
|
|
|
|
|
|
|
|
|
|
|
53 |
# ====== END CONFIGURATION SECTION ======
|
54 |
|
55 |
# Set environment variables
|
@@ -63,6 +68,101 @@ np.float_ = np.float64
|
|
63 |
# Streamlit Page Config
|
64 |
st.set_page_config(page_title=APP_TITLE, layout=APP_LAYOUT)
|
65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
# Initialize essential session state variables only
|
67 |
if "messages" not in st.session_state:
|
68 |
st.session_state.messages = []
|
@@ -1235,22 +1335,25 @@ def process_query(prompt, context_docs):
|
|
1235 |
st.title(APP_TITLE)
|
1236 |
|
1237 |
# Sidebar info
|
1238 |
-
st.sidebar.title("System
|
1239 |
-
st.sidebar.info("Educational Assistant with
|
1240 |
-
|
|
|
|
|
1241 |
for pdf in PDF_FILES:
|
1242 |
display_name = os.path.basename(pdf)
|
1243 |
-
st.sidebar.write(f"
|
1244 |
|
1245 |
# Safety configuration display
|
1246 |
st.sidebar.markdown("---")
|
1247 |
-
st.sidebar.write("
|
1248 |
-
st.sidebar.write("
|
1249 |
-
st.sidebar.write("
|
|
|
1250 |
if SAFETY_CONFIG['allow_general_knowledge']:
|
1251 |
-
st.sidebar.write("
|
1252 |
if SAFETY_CONFIG['educational_alternatives']:
|
1253 |
-
st.sidebar.write("
|
1254 |
|
1255 |
# Initialize welcome message
|
1256 |
if not st.session_state.messages:
|
@@ -1268,13 +1371,13 @@ if not st.session_state.messages:
|
|
1268 |
else:
|
1269 |
topic_preview = ""
|
1270 |
|
1271 |
-
welcome_msg = f"Hello! I'm your educational assistant with built-in safety features.{topic_preview} I can answer questions using the uploaded documents or provide general educational information when appropriate. What would you like to explore today?"
|
1272 |
st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
|
1273 |
|
1274 |
# Clear conversation button
|
1275 |
col1, col2 = st.columns([4, 1])
|
1276 |
with col2:
|
1277 |
-
if st.button("New Conversation"):
|
1278 |
st.session_state.conversation_id += 1
|
1279 |
st.session_state.messages = []
|
1280 |
|
@@ -1312,7 +1415,7 @@ if retriever:
|
|
1312 |
|
1313 |
# Generate response
|
1314 |
with st.chat_message("assistant"):
|
1315 |
-
with st.spinner("
|
1316 |
try:
|
1317 |
# Process query with enhanced safety checks
|
1318 |
retrieved_docs = retriever.get_relevant_documents(prompt)
|
|
|
1 |
"""
|
2 |
+
Universal RAG PDF Chatbot with Enhanced Safety Checks and Improved Context Management - COMPLETE UPDATED VERSION WITH PASSWORD PROTECTION
|
3 |
|
4 |
This is a general-purpose RAG (Retrieval-Augmented Generation) chatbot that can work with any set of PDF documents.
|
5 |
It includes comprehensive safety checks and can provide educational responses even when information isn't in the documents.
|
|
|
50 |
'educational_alternatives': True, # Always provide educational alternatives
|
51 |
'allow_general_knowledge': True # Allow answers from general knowledge when appropriate
|
52 |
}
|
53 |
+
|
54 |
+
# ====== PASSWORD AUTHENTICATION CONFIGURATION ======
|
55 |
+
# Password can be set in Streamlit secrets or environment variable
|
56 |
+
CHATBOT_PASSWORD = st.secrets.get("CHATBOT_PASSWORD", os.getenv("CHATBOT_PASSWORD", "edu123"))
|
57 |
+
|
58 |
# ====== END CONFIGURATION SECTION ======
|
59 |
|
60 |
# Set environment variables
|
|
|
68 |
# Streamlit Page Config
|
69 |
st.set_page_config(page_title=APP_TITLE, layout=APP_LAYOUT)
|
70 |
|
71 |
+
# ====== PASSWORD AUTHENTICATION SYSTEM ======
|
72 |
+
def check_password():
|
73 |
+
"""Check password and manage authentication."""
|
74 |
+
|
75 |
+
# Initialize authentication state
|
76 |
+
if "authenticated" not in st.session_state:
|
77 |
+
st.session_state.authenticated = False
|
78 |
+
|
79 |
+
if "login_attempts" not in st.session_state:
|
80 |
+
st.session_state.login_attempts = 0
|
81 |
+
|
82 |
+
# If already authenticated, return True
|
83 |
+
if st.session_state.authenticated:
|
84 |
+
return True
|
85 |
+
|
86 |
+
# Display login screen
|
87 |
+
st.markdown("""
|
88 |
+
<div style='text-align: center; padding: 2rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; margin-bottom: 2rem;'>
|
89 |
+
<h1 style='color: white; margin-bottom: 1rem;'>π Educational PDF Chatbot</h1>
|
90 |
+
<p style='color: white; font-size: 1.1em;'>This educational assistant requires authentication for access.</p>
|
91 |
+
</div>
|
92 |
+
""", unsafe_allow_html=True)
|
93 |
+
|
94 |
+
# Check for too many failed attempts
|
95 |
+
if st.session_state.login_attempts >= 5:
|
96 |
+
st.error("Too many failed login attempts. Please wait a few minutes before trying again.")
|
97 |
+
st.info("If you continue to have trouble, please contact the administrator.")
|
98 |
+
st.stop()
|
99 |
+
|
100 |
+
# Login form
|
101 |
+
with st.form("login_form"):
|
102 |
+
st.subheader("π Enter Password to Continue")
|
103 |
+
password = st.text_input(
|
104 |
+
"Password",
|
105 |
+
type="password",
|
106 |
+
placeholder="Enter your access password...",
|
107 |
+
help="Enter the password provided to you for accessing this educational chatbot"
|
108 |
+
)
|
109 |
+
submit_button = st.form_submit_button("π Access Chatbot", use_container_width=True)
|
110 |
+
|
111 |
+
if submit_button:
|
112 |
+
if password == CHATBOT_PASSWORD:
|
113 |
+
st.session_state.authenticated = True
|
114 |
+
st.session_state.login_attempts = 0
|
115 |
+
st.success("β
Access granted! Loading your educational assistant...")
|
116 |
+
st.rerun()
|
117 |
+
else:
|
118 |
+
st.session_state.login_attempts += 1
|
119 |
+
remaining_attempts = 5 - st.session_state.login_attempts
|
120 |
+
|
121 |
+
if remaining_attempts > 0:
|
122 |
+
st.error(f"β Incorrect password. Attempts remaining: {remaining_attempts}")
|
123 |
+
else:
|
124 |
+
st.error("π« Too many failed attempts. Access temporarily blocked.")
|
125 |
+
|
126 |
+
# Additional information in sidebar
|
127 |
+
st.sidebar.markdown("""
|
128 |
+
### π Access Information
|
129 |
+
|
130 |
+
**To access this educational chatbot:**
|
131 |
+
- Enter the provided access password
|
132 |
+
- Maximum 5 attempts allowed
|
133 |
+
- Contact administrator if you need help
|
134 |
+
|
135 |
+
**Features available after login:**
|
136 |
+
- PDF document analysis
|
137 |
+
- Educational Q&A system
|
138 |
+
- Context-aware responses
|
139 |
+
- Safe content filtering
|
140 |
+
- Conversation management
|
141 |
+
""")
|
142 |
+
|
143 |
+
st.sidebar.markdown("---")
|
144 |
+
st.sidebar.info("π‘οΈ This system includes comprehensive safety features and educational content filtering.")
|
145 |
+
|
146 |
+
return False
|
147 |
+
|
148 |
+
# Check authentication before loading the rest of the application
|
149 |
+
if not check_password():
|
150 |
+
st.stop()
|
151 |
+
|
152 |
+
# ====== AUTHENTICATED USER INTERFACE ======
|
153 |
+
|
154 |
+
# Add logout functionality in sidebar
|
155 |
+
st.sidebar.markdown("---")
|
156 |
+
st.sidebar.success("β
Access Authorized")
|
157 |
+
st.sidebar.write("Welcome to your educational assistant!")
|
158 |
+
|
159 |
+
if st.sidebar.button("πͺ Logout", use_container_width=True):
|
160 |
+
st.session_state.authenticated = False
|
161 |
+
st.session_state.messages = []
|
162 |
+
st.session_state.conversation_id = 0
|
163 |
+
st.success("π Successfully logged out!")
|
164 |
+
st.rerun()
|
165 |
+
|
166 |
# Initialize essential session state variables only
|
167 |
if "messages" not in st.session_state:
|
168 |
st.session_state.messages = []
|
|
|
1335 |
st.title(APP_TITLE)
|
1336 |
|
1337 |
# Sidebar info
|
1338 |
+
st.sidebar.title("System Information")
|
1339 |
+
st.sidebar.info("Educational Assistant with Advanced Security")
|
1340 |
+
|
1341 |
+
st.sidebar.markdown("---")
|
1342 |
+
st.sidebar.write("**Documents loaded:**")
|
1343 |
for pdf in PDF_FILES:
|
1344 |
display_name = os.path.basename(pdf)
|
1345 |
+
st.sidebar.write(f"β’ {display_name}")
|
1346 |
|
1347 |
# Safety configuration display
|
1348 |
st.sidebar.markdown("---")
|
1349 |
+
st.sidebar.write("**Security Features:**")
|
1350 |
+
st.sidebar.write("β Content filtering enabled")
|
1351 |
+
st.sidebar.write("β Educational focus maintained")
|
1352 |
+
st.sidebar.write("β Password protection active")
|
1353 |
if SAFETY_CONFIG['allow_general_knowledge']:
|
1354 |
+
st.sidebar.write("β General knowledge fallback available")
|
1355 |
if SAFETY_CONFIG['educational_alternatives']:
|
1356 |
+
st.sidebar.write("β Alternative topic suggestions")
|
1357 |
|
1358 |
# Initialize welcome message
|
1359 |
if not st.session_state.messages:
|
|
|
1371 |
else:
|
1372 |
topic_preview = ""
|
1373 |
|
1374 |
+
welcome_msg = f"Hello! I'm your secure educational assistant with built-in safety features.{topic_preview} I can answer questions using the uploaded documents or provide general educational information when appropriate. What would you like to explore today?"
|
1375 |
st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
|
1376 |
|
1377 |
# Clear conversation button
|
1378 |
col1, col2 = st.columns([4, 1])
|
1379 |
with col2:
|
1380 |
+
if st.button("π New Conversation", use_container_width=True):
|
1381 |
st.session_state.conversation_id += 1
|
1382 |
st.session_state.messages = []
|
1383 |
|
|
|
1415 |
|
1416 |
# Generate response
|
1417 |
with st.chat_message("assistant"):
|
1418 |
+
with st.spinner("Processing your question..."):
|
1419 |
try:
|
1420 |
# Process query with enhanced safety checks
|
1421 |
retrieved_docs = retriever.get_relevant_documents(prompt)
|