Spaces:
Sleeping
Sleeping
File size: 16,582 Bytes
36deff5 7a71a9c 59d8bcf 36deff5 eaab8c7 36deff5 9942da6 36deff5 9942da6 36deff5 5c562e2 4ac587b 5c562e2 36deff5 2946af2 bfe0fc7 36deff5 98bbfe6 36deff5 98bbfe6 36deff5 98bbfe6 36deff5 98bbfe6 36deff5 98bbfe6 36deff5 98bbfe6 eaab8c7 36deff5 eaab8c7 36deff5 eaab8c7 f656c8f eaab8c7 36deff5 eaab8c7 36deff5 eaab8c7 36deff5 00f89f7 36deff5 eaab8c7 36deff5 eaab8c7 36deff5 99d4e94 36deff5 00f89f7 36deff5 ecd102d 00f89f7 36deff5 ecd102d 36deff5 6f054c1 e3768f8 21e17cc 17c4968 124ef75 e3768f8 21e17cc 17c4968 e3768f8 17c4968 21e17cc 17c4968 4c38303 e3768f8 21e17cc 17c4968 ffa0f17 e3768f8 4ac587b 36deff5 4ac587b 36deff5 aa9ea62 f9fcbab b1cd9b8 aa9ea62 b1cd9b8 36deff5 aa9ea62 4ac587b 36deff5 7b866c6 36deff5 c870bd4 98bbfe6 7b866c6 98bbfe6 36deff5 98bbfe6 36deff5 a6fb87c 36deff5 |
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 |
# -*- coding: utf-8 -*-
"""Defense QA Chatbot - Streamlit Version with Password Protection"""
import streamlit as st
import pandas as pd
import numpy as np
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
import pickle
import os
import warnings
warnings.filterwarnings("ignore")
torch.manual_seed(42)
np.random.seed(42)
# ========== Page Config ==========
st.set_page_config(
page_title="Mission Assistant",
layout="wide",
initial_sidebar_state="collapsed"
)
# ========== Custom CSS ==========
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
* {
font-family: 'Inter', sans-serif;
}
.main {
background: linear-gradient(to bottom, #0f172a 0%, #1e293b 100%);
}
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
.header-container {
background: linear-gradient(135deg, #1e40af 0%, #3b82f6 50%, #60a5fa 100%);
padding: 43px 30px;
text-align: center;
color: white;
border-radius: 16px;
margin: -60px -20px 20px -20px;
box-shadow: 0 8px 32px rgba(59, 130, 246, 0.3);
}
.header-container h1 {
margin: 0 0 12px 0;
font-size: 36px;
font-weight: 700;
}
.header-container p {
margin: 0;
font-size: 16px;
opacity: 0.95;
}
.stChatMessage {
background: rgba(30, 41, 59, 0.6);
border-radius: 12px;
border: 1px solid rgba(148, 163, 184, 0.3);
margin: 10px 0;
}
.stTextInput input, .stTextArea textarea {
background: rgba(30, 41, 59, 0.8) !important;
color: #f1f5f9 !important;
border: 2px solid rgba(148, 163, 184, 0.4) !important;
border-radius: 12px !important;
font-size: 15px !important;
}
.stTextArea textarea {
min-height: 100px !important;
}
.stButton button {
background: linear-gradient(135deg, #2563eb, #1e40af) !important;
color: white !important;
border: none !important;
border-radius: 10px !important;
font-weight: 600 !important;
padding: 12px 24px !important;
width: 100%;
}
.stButton button:hover {
background: linear-gradient(135deg, #1e40af, #1e3a8a) !important;
transform: translateY(-2px);
}
.streamlit-expanderHeader {
background: rgba(51, 65, 85, 0.9) !important;
color: #60a5fa !important;
border-radius: 12px !important;
font-weight: 600 !important;
}
.streamlit-expanderContent {
background: rgba(30, 41, 59, 0.8) !important;
border: 1px solid rgba(148, 163, 184, 0.3) !important;
border-radius: 0 0 12px 12px !important;
}
.info-box {
background: rgba(51, 65, 85, 0.5);
padding: 20px;
border-radius: 10px;
border: 1px solid rgba(148, 163, 184, 0.3);
color: #e2e8f0;
}
.info-box h3 {
color: #60a5fa;
font-size: 16px;
font-weight: 600;
margin-bottom: 12px;
border-bottom: 2px solid #3b82f6;
padding-bottom: 8px;
}
.footer-container {
text-align: center;
padding: 30px 20px;
margin-top: 50px;
margin-bottom: 20px;
color: #64748b;
border-top: 1px solid rgba(148, 163, 184, 0.3);
}
.nwtc-badge {
display: inline-block;
background: rgba(59, 130, 246, 0.1);
padding: 10px 20px;
border-radius: 8px;
margin-top: 10px;
border: 1px solid rgba(59, 130, 246, 0.3);
color: #3b82f6;
font-weight: 600;
}
.login-box {
background: rgba(30, 41, 59, 0.8);
padding: 40px;
border-radius: 16px;
border: 1px solid rgba(148, 163, 184, 0.3);
text-align: center;
max-width: 500px;
margin: 100px auto;
}
</style>
""", unsafe_allow_html=True)
# ========== Configuration ==========
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model_name = "huawei-noah/TinyBERT_General_4L_312D"
max_length = 512
MODEL_PATH = "tinybert_defense_aug.pt"
EMBEDDINGS_PATH = "defense_embeddings_p3.pkl"
# ========== Helper Functions ==========
def mean_pooling(last_hidden, mask):
mask = mask.unsqueeze(-1).type_as(last_hidden)
summed = (last_hidden * mask).sum(dim=1)
counts = mask.sum(dim=1).clamp(min=1e-6)
emb = summed / counts
emb = F.normalize(emb, p=2, dim=1)
return emb
# ========== Chatbot Class ==========
class DefenseQAChatbot:
def __init__(self, model, tokenizer, device, embeddings_path):
self.model = model.eval()
self.tok = tokenizer
self.device = device
with open(embeddings_path, 'rb') as f:
saved_data = pickle.load(f)
self.response_embs = saved_data['embeddings']
if 'responses' in saved_data:
self.responses = saved_data['responses']
else:
num_embeddings = len(self.response_embs)
self.responses = [f"Defense Response #{i+1}" for i in range(num_embeddings)]
def _embed_one(self, text):
with torch.no_grad():
enc = self.tok([text], truncation=True, padding="longest",
max_length=max_length, return_tensors="pt").to(self.device)
out = self.model(**enc)
emb = mean_pooling(out.last_hidden_state, enc["attention_mask"])
return emb[0].cpu().numpy()
def get_response(self, user_prompt, top_k=5, reject=0.55):
if not user_prompt.strip():
return "Please ask a question about defense protocols."
q = self._embed_one(user_prompt)
sims = self.response_embs @ q
top = np.argpartition(-sims, min(top_k, len(sims)-1))[:top_k]
top = top[np.argsort(-sims[top])]
best = top[0]
score = float(sims[best])
# ุฅุฐุง ุงูุซูุฉ ู
ูุฎูุถุฉ ุฌุฏุงู
if score < reject:
return "I couldn't find a reliable answer. Please try rephrasing your question or ask about specific defense protocols and procedures."
# ุฅุฑุฌุงุน ุงูุฅุฌุงุจุฉ ุจุฏูู ุชูููู
response_text = self.responses[best]
return response_text
# ========== Password Protection ==========
# ========== Password Protection ==========
def check_password():
"""Returns True if user entered correct password"""
def password_entered():
"""Checks whether password is correct"""
# ุบููุฑ ููู
ุฉ ุงูุณุฑ ููุง
CORRECT_PASSWORD = "NWTC@2025"
if st.session_state["password"] == CORRECT_PASSWORD:
st.session_state["password_correct"] = True
del st.session_state["password"]
else:
st.session_state["password_correct"] = False
if "password_correct" not in st.session_state:
st.markdown("""
<div class="header-container">
<div style="display: flex; align-items: center; justify-content: center; gap: 20px;">
<h1 style="margin: 0;">Mission Assistant</h1>
</div>
<p style="margin-top: 15px; font-size: 18px;">Secure Access Required</p>
</div>
""", unsafe_allow_html=True)
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
st.markdown("""
<div class="login-box">
<h2 style="color: #60a5fa; margin-bottom: 20px;">๐ Enter Access Code</h2>
<p style="color: #cbd5e1; margin-bottom: 30px;">
This system is restricted to authorized personnel only
</p>
</div>
""", unsafe_allow_html=True)
st.text_input(
"Password",
type="password",
on_change=password_entered,
key="password",
label_visibility="collapsed",
placeholder="Enter your access code..."
)
st.markdown("""
<p style="text-align: center; color: #64748b; font-size: 13px; margin-top: 20px;">
๐ธ๐ฆ Made by NWTC
</p>
""", unsafe_allow_html=True)
return False
elif not st.session_state["password_correct"]:
st.markdown("""
<div class="header-container">
<h1>Mission Assistant</h1>
<p style="margin-top: 15px; font-size: 18px;">Secure Access Required</p>
</div>
""", unsafe_allow_html=True)
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
st.markdown("""
<div class="login-box">
<h2 style="color: #60a5fa; margin-bottom: 20px;">๐ Enter Access Code</h2>
<p style="color: #cbd5e1; margin-bottom: 30px;">
This system is restricted to authorized personnel only
</p>
</div>
""", unsafe_allow_html=True)
st.text_input(
"Password",
type="password",
on_change=password_entered,
key="password",
label_visibility="collapsed",
placeholder="Enter your access code..."
)
st.error("โ Access Denied - Incorrect password")
st.markdown("""
<p style="text-align: center; color: #64748b; font-size: 13px; margin-top: 20px;">
๐ธ๐ฆ Made by NWTC
</p>
""", unsafe_allow_html=True)
return False
else:
return True
if not check_password():
st.stop()
# ========== Load Model (Cached) ==========
@st.cache_resource
def load_model():
try:
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name).to(device)
if os.path.exists(MODEL_PATH):
# Try loading with weights_only=False
try:
ckpt = torch.load(MODEL_PATH, map_location=device, weights_only=False)
except:
# Fallback to old method
ckpt = torch.load(MODEL_PATH, map_location=device)
model.load_state_dict(ckpt["model_state"])
model.eval()
chatbot = DefenseQAChatbot(
model=model,
tokenizer=tokenizer,
device=device,
embeddings_path=EMBEDDINGS_PATH
)
return chatbot
except Exception as e:
st.error(f"Error loading model: {str(e)}")
st.stop()
chatbot = load_model()
# ========== Initialize Session State ==========
if "messages" not in st.session_state:
st.session_state.messages = []
# ========== Header ==========
# ========== Header ==========
st.markdown("""
<div class="header-container">
<h1 style="margin: 0;">Mission Assistant</h1>
</div>
""", unsafe_allow_html=True)
# ========== Info Expander ==========
with st.expander("๐ก Quick Questions & Examples"):
st.markdown("""
<p style="color: #cbd5e1; font-size: 14px; margin-bottom: 20px; text-align: center;">
Click any question to ask instantly
</p>
""", unsafe_allow_html=True)
# Organize questions by category
categories = {
"C2/STAFF": [
"What elements make up a C2 system in military operations?",
"What is the purpose of coordination measures in staff operations?"
],
"INTEL/RECON": [
"What are the key components of intelligence operations according to ADP 2-0?",
"Why are reconnaissance objectives important in planning missions?",
],
"TACTICAL": [
"What is the goal of tactical weapon positioning?",
"What are common maneuver forms used in offensive operations?",
],
"OE/ENVIRONMENT": [
"What details should be included when describing an area-type disposition?",
"What is terrain analysis and why is it important in military operations?",
"How does precipitation affect operational planning?"
]
}
# Create tabs for categories
tabs = st.tabs(list(categories.keys()))
for tab, (category, questions) in zip(tabs, categories.items()):
with tab:
for i, question in enumerate(questions):
if st.button(
f"โ {question}",
key=f"{category}_{i}",
use_container_width=True
):
st.session_state.messages.append({"role": "user", "content": question})
with st.chat_message("assistant"):
with st.spinner("Analyzing..."):
response = chatbot.get_response(question)
st.markdown(response)
st.session_state.messages.append({"role": "assistant", "content": response})
st.rerun()
# ========== Chat Display ==========
# Empty state - only show when no messages
if len(st.session_state.messages) == 0:
st.markdown(
"""
<div style="text-align: center; padding: 100px 20px; color: #64748b;">
<div style="font-size: 100px; font-weight: 700; color: #475569; margin-bottom: 20px;">
NWTC
</div>
<p style="font-size: 15px; margin: 0; color: #94a3b8; line-height: 1.8; max-width: 900px; margin: 0 auto;">
Ask only about:<br>
โข C2 (command & staff)<br>
โข Intel/Recon (intelligence collection, analysis & reconnaissance tasks)<br>
โข OE/Environment (terrain, weather, infrastructure & civil factors)<br>
โข Tactical concepts & techniques (high-level; no step-by-step actionable instructions)
</p>
</div>
""",
unsafe_allow_html=True
)
# Chat container with fixed height
chat_container = st.container()
with chat_container:
for message in st.session_state.messages:
if message["role"] == "user":
st.markdown(f"""
<div style="background: linear-gradient(90deg, rgba(59, 130, 246, 0.25), rgba(37, 99, 235, 0.1));
border-left: 4px solid #3b82f6;
border-radius: 12px;
padding: 15px 20px;
margin: 12px 0;">
<div style="color: #60a5fa; font-weight: 600; margin-bottom: 8px;">๐ค You</div>
<div style="color: #e2e8f0; line-height: 1.6;">{message["content"]}</div>
</div>
""", unsafe_allow_html=True)
else:
st.markdown(f"""
<div style="background: linear-gradient(90deg, rgba(16, 185, 129, 0.25), rgba(5, 150, 105, 0.1));
border-left: 4px solid #10b981;
border-radius: 12px;
padding: 15px 20px;
margin: 12px 0;">
<div style="color: #34d399; font-weight: 600; margin-bottom: 8px;">๐ค Assistant</div>
<div style="color: #e2e8f0; line-height: 1.6;">{message["content"]}</div>
</div>
""", unsafe_allow_html=True)
# ========== Chat Input & Clear Button ==========
col1, col2 = st.columns([5, 1])
with col1:
prompt = st.chat_input("Enter your inquiry here...")
with col2:
if st.button("๐๏ธ Clear", use_container_width=True):
st.session_state.messages = []
st.rerun()
# Process message
if prompt:
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("assistant"):
with st.spinner("Analyzing..."):
response = chatbot.get_response(prompt)
st.markdown(response)
st.session_state.messages.append({"role": "assistant", "content": response})
st.rerun()
# ========== Footer ==========
st.markdown("""
<div class="footer-container">
<p style="font-size: 14px; margin: 8px 0;">
Powered by Advanced Natural Language Processing
</p>
<div class="nwtc-badge">
๐ธ๐ฆ Made by NWTC
</div>
</div>
""", unsafe_allow_html=True) |