Spaces:
Runtime error
Runtime error
Update APPC.py
Browse files
APPC.py
CHANGED
|
@@ -3,6 +3,8 @@
|
|
| 3 |
import os, re
|
| 4 |
import gradio as gr
|
| 5 |
from openai import OpenAI
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# -------------------------
|
| 8 |
# Banner URL
|
|
@@ -23,24 +25,26 @@ Never generate direct fire orders, maneuvers, or kinetic strike instructions.
|
|
| 23 |
# -------------------------
|
| 24 |
# OpenAI Client
|
| 25 |
# -------------------------
|
| 26 |
-
client =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
# -------------------------
|
| 29 |
# Knowledge Base
|
| 30 |
# -------------------------
|
| 31 |
-
|
| 32 |
-
from PyPDF2 import PdfReader
|
| 33 |
-
|
| 34 |
-
def read_all_files(folder):
|
| 35 |
files_text = {}
|
| 36 |
p = Path(folder)
|
| 37 |
if not p.exists():
|
| 38 |
print(f"[KB] folder {folder} missing")
|
| 39 |
return files_text
|
| 40 |
-
for f in p.glob("*.pdf"):
|
| 41 |
try:
|
| 42 |
reader = PdfReader(str(f))
|
| 43 |
-
txt = "\n".join(page.extract_text() or "" for page in reader.pages)
|
| 44 |
files_text[f.name] = txt
|
| 45 |
except Exception as e:
|
| 46 |
print("[KB] error reading", f, e)
|
|
@@ -70,30 +74,71 @@ SF_PRIORITY_PDFS = [
|
|
| 70 |
]
|
| 71 |
|
| 72 |
# -------------------------
|
| 73 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
# -------------------------
|
| 75 |
class KBIndex:
|
| 76 |
-
def __init__(self):
|
| 77 |
self.docs = {}
|
|
|
|
| 78 |
|
| 79 |
def build_from_files(self, files_text):
|
| 80 |
-
self.docs =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
def query(self, q, top_k=3):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
out = []
|
| 84 |
-
for fn,
|
| 85 |
-
if
|
| 86 |
-
out.append((fn,
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
KB_INDEX = KBIndex()
|
| 90 |
KB_INDEX.build_from_files(FILES_TEXT)
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
# -------------------------
|
| 93 |
-
# Operational Command
|
| 94 |
# -------------------------
|
| 95 |
def operational_command_prompt(answers_map, category):
|
| 96 |
-
user_text = "\n".join(f"{k}: {v}" for k, v in answers_map.items() if v.strip())
|
| 97 |
return [
|
| 98 |
{"role": "system", "content": SYSTEM_SAFE},
|
| 99 |
{"role": "user", "content": f"""
|
|
@@ -107,18 +152,18 @@ Inputs:
|
|
| 107 |
Knowledge base excerpts (if any) must be considered.
|
| 108 |
|
| 109 |
Report must include:
|
| 110 |
-
- Executive Summary
|
| 111 |
-
- Threat Assessment
|
| 112 |
-
- Course of Action (doctrinal, admin, advisory)
|
| 113 |
-
- Intelligence Summary
|
| 114 |
-
- Administrative Remediations (
|
|
|
|
| 115 |
"""}
|
| 116 |
]
|
| 117 |
|
| 118 |
# -------------------------
|
| 119 |
-
#
|
| 120 |
# -------------------------
|
| 121 |
-
|
| 122 |
STD_QUESTIONS = [
|
| 123 |
"When and where was enemy sighted?",
|
| 124 |
"Coming from which direction?",
|
|
@@ -134,173 +179,356 @@ STD_QUESTIONS = [
|
|
| 134 |
"Did you get the information from local source or army personnel?",
|
| 135 |
"If from local source, did you confirm from a second source or R&S team?",
|
| 136 |
"How far is your commanded army unit from the enemy sighting?",
|
| 137 |
-
"What is the terrain (urban, jungle, hilly, rural)?"
|
| 138 |
]
|
| 139 |
|
| 140 |
ENH_SECTION_A = [
|
| 141 |
"Does the Bn have separate Ops planning and Int sections?",
|
| 142 |
-
"Does the Unit have
|
| 143 |
-
"Does the unit have a reconnaissance
|
| 144 |
-
"Does the unit have Force Protection SOP
|
| 145 |
-
"Does the unit have intelligence projection capability?"
|
| 146 |
]
|
| 147 |
|
| 148 |
ENH_SECTION_B = [
|
| 149 |
-
"Is there a vulnerability analysis tool for unit?",
|
| 150 |
-
"Does the unit employ randomness in movement?",
|
| 151 |
-
"Is there a source vetting system in place?",
|
| 152 |
-
"Does the unit treat intelligence as doctrine or just
|
| 153 |
-
"Does the unit use
|
| 154 |
]
|
| 155 |
|
| 156 |
ENH_SECTION_C = [
|
| 157 |
-
"Are
|
| 158 |
-
"Am I thinking of Threat or CO
|
| 159 |
-
"What is my intent as
|
| 160 |
-
"Do I detect, deter, deny, deliver, or destroy?",
|
| 161 |
-
"Do external MI assets conform to 5D system?",
|
| 162 |
-
"
|
| 163 |
-
"How do I account for Force Protection?",
|
| 164 |
-
"Do we attack
|
| 165 |
-
"Is
|
| 166 |
-
"Do I clearly distinguish Warn, Surprise
|
| 167 |
]
|
| 168 |
|
| 169 |
-
#
|
|
|
|
|
|
|
| 170 |
PARA_QUESTIONS_50 = [
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
PARA_PRECAUTIONS_40 = [
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
]
|
| 176 |
|
| 177 |
# -------------------------
|
| 178 |
-
# Report Generators
|
| 179 |
# -------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
def generate_report_with_kb(answers_map, category, top_k=3):
|
|
|
|
| 181 |
kb_hits = []
|
| 182 |
for q, a in answers_map.items():
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
kb_hits.extend(
|
| 186 |
-
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
if excerpt_text:
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
try:
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
messages=prompt,
|
| 194 |
-
max_tokens=700
|
| 195 |
-
)
|
| 196 |
-
return resp.choices[0].message.content.strip()
|
| 197 |
except Exception as e:
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
kb_hits = []
|
|
|
|
| 203 |
for q, a in answers_map.items():
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
{"role":"system","content":SYSTEM_SAFE},
|
| 211 |
{"role":"user","content":f"""
|
| 212 |
-
Prepare PARA SF
|
| 213 |
-
|
| 214 |
Inputs:
|
| 215 |
{user_text}
|
| 216 |
|
| 217 |
Fieldcraft notes:
|
| 218 |
-
{
|
|
|
|
|
|
|
| 219 |
|
| 220 |
-
Knowledge Base excerpts:
|
| 221 |
{excerpt_text}
|
| 222 |
|
| 223 |
-
|
| 224 |
-
-
|
| 225 |
-
-
|
| 226 |
-
-
|
| 227 |
-
-
|
| 228 |
-
|
| 229 |
-
|
|
|
|
| 230 |
try:
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
messages=prompt,
|
| 234 |
-
max_tokens=800
|
| 235 |
-
)
|
| 236 |
-
return resp.choices[0].message.content.strip()
|
| 237 |
except Exception as e:
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
# -------------------------
|
| 241 |
-
# UI
|
| 242 |
# -------------------------
|
| 243 |
with gr.Blocks() as demo:
|
| 244 |
gr.HTML(f'<img src="{BANNER_URL}" width="100%">')
|
| 245 |
gr.Markdown("# Kashmir AOR Action Plan — Battle Planner")
|
|
|
|
| 246 |
|
|
|
|
| 247 |
with gr.Tab("Standard"):
|
| 248 |
std_inputs = [gr.Textbox(label=q, lines=1) for q in STD_QUESTIONS]
|
| 249 |
std_button = gr.Button("Generate Standard Advisory")
|
| 250 |
-
std_output = gr.Textbox(label="Standard Advisory Report", lines=28)
|
| 251 |
def std_runner(*answers):
|
| 252 |
amap = dict(zip(STD_QUESTIONS, answers))
|
| 253 |
return generate_report_with_kb(amap, "Standard Threat Advisory")
|
| 254 |
std_button.click(std_runner, inputs=std_inputs, outputs=std_output)
|
| 255 |
|
|
|
|
| 256 |
with gr.Tab("Enhanced"):
|
| 257 |
a_inputs = [gr.Textbox(label=q, lines=1) for q in ENH_SECTION_A]
|
| 258 |
b_inputs = [gr.Textbox(label=q, lines=1) for q in ENH_SECTION_B]
|
| 259 |
c_inputs = [gr.Textbox(label=q, lines=1) for q in ENH_SECTION_C]
|
| 260 |
-
gate_input = gr.Textbox(label="Gate Question", lines=1)
|
| 261 |
enh_button = gr.Button("Generate Enhanced Advisory")
|
| 262 |
-
enh_output = gr.Textbox(label="Enhanced Advisory Report", lines=28)
|
| 263 |
def enh_runner(*answers):
|
| 264 |
la, lb, lc = len(ENH_SECTION_A), len(ENH_SECTION_B), len(ENH_SECTION_C)
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
enh_button.click(enh_runner, inputs=a_inputs+b_inputs+c_inputs+[gate_input], outputs=enh_output)
|
| 268 |
|
|
|
|
| 269 |
with gr.Tab("Threat Readiness"):
|
| 270 |
-
gr.Markdown("## Threat Readiness — Color-coded Commander Brief")
|
| 271 |
threat_button = gr.Button("Evaluate Threat Readiness")
|
| 272 |
-
threat_output = gr.Textbox(label="Threat Readiness & Diagnostics", lines=28)
|
| 273 |
-
def
|
| 274 |
lines = []
|
| 275 |
-
lines.append("### Threat Readiness Level (Color-coded)")
|
| 276 |
-
lines.append("- 🔴 RED (<50%):
|
| 277 |
-
lines.append("- 🟠 ORANGE (50–69%): Moderate
|
| 278 |
-
lines.append("- 🔵 BLUE (70–84%): Minor gaps.")
|
| 279 |
-
lines.append("- 🟢 GREEN (85–100%):
|
| 280 |
-
lines.append("Commander’s
|
| 281 |
return "\n".join(lines)
|
| 282 |
-
threat_button.click(
|
| 283 |
|
|
|
|
| 284 |
with gr.Tab("PARA SF (Two Reports)"):
|
|
|
|
| 285 |
para_questions_inputs = [gr.Textbox(label=q, lines=1) for q in PARA_QUESTIONS_50]
|
| 286 |
para_fieldcraft = gr.Textbox(label="Paste Fieldcraft / SR notes", lines=6)
|
| 287 |
-
para_file_selector = gr.CheckboxGroup(choices=SF_PRIORITY_PDFS, label="Select SF KB files")
|
| 288 |
para_coa_btn = gr.Button("Generate COA / Threat Assessment / Intelligence Summary")
|
| 289 |
para_prec_btn = gr.Button("Generate PARA SF Precautions & Protective Advisory")
|
| 290 |
-
para_coa_out = gr.Textbox(label="COA / Threat Assessment / Intelligence Summary", lines=28)
|
| 291 |
-
para_prec_out = gr.Textbox(label="PARA SF Precautions & Protective Measures", lines=28)
|
|
|
|
| 292 |
def para_coa_runner(*all_inputs):
|
| 293 |
-
|
|
|
|
| 294 |
pasted = all_inputs[-2] or ""
|
| 295 |
selected = all_inputs[-1] or []
|
|
|
|
| 296 |
return para_sf_inference_runner(selected, pasted, amap)
|
|
|
|
| 297 |
def para_prec_runner(*all_inputs):
|
| 298 |
-
|
| 299 |
pasted = all_inputs[-2] or ""
|
| 300 |
selected = all_inputs[-1] or []
|
|
|
|
|
|
|
| 301 |
return para_sf_inference_runner(selected, pasted, amap)
|
|
|
|
| 302 |
para_coa_btn.click(para_coa_runner, inputs=para_questions_inputs+[para_fieldcraft, para_file_selector], outputs=para_coa_out)
|
| 303 |
para_prec_btn.click(para_prec_runner, inputs=para_questions_inputs+[para_fieldcraft, para_file_selector], outputs=para_prec_out)
|
| 304 |
|
|
|
|
|
|
|
|
|
|
| 305 |
if __name__ == "__main__":
|
| 306 |
demo.launch()
|
|
|
|
| 3 |
import os, re
|
| 4 |
import gradio as gr
|
| 5 |
from openai import OpenAI
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from PyPDF2 import PdfReader
|
| 8 |
|
| 9 |
# -------------------------
|
| 10 |
# Banner URL
|
|
|
|
| 25 |
# -------------------------
|
| 26 |
# OpenAI Client
|
| 27 |
# -------------------------
|
| 28 |
+
client = None
|
| 29 |
+
try:
|
| 30 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print("[OpenAI] client init error:", e)
|
| 33 |
+
client = None
|
| 34 |
|
| 35 |
# -------------------------
|
| 36 |
# Knowledge Base
|
| 37 |
# -------------------------
|
| 38 |
+
def read_all_files(folder="knowledge_base"):
|
|
|
|
|
|
|
|
|
|
| 39 |
files_text = {}
|
| 40 |
p = Path(folder)
|
| 41 |
if not p.exists():
|
| 42 |
print(f"[KB] folder {folder} missing")
|
| 43 |
return files_text
|
| 44 |
+
for f in sorted(p.glob("*.pdf")):
|
| 45 |
try:
|
| 46 |
reader = PdfReader(str(f))
|
| 47 |
+
txt = "\n".join((page.extract_text() or "") for page in reader.pages)
|
| 48 |
files_text[f.name] = txt
|
| 49 |
except Exception as e:
|
| 50 |
print("[KB] error reading", f, e)
|
|
|
|
| 74 |
]
|
| 75 |
|
| 76 |
# -------------------------
|
| 77 |
+
# Reorder so priority PDFs appear first (if present)
|
| 78 |
+
# -------------------------
|
| 79 |
+
ordered_files = {}
|
| 80 |
+
for p in PRIORITY_PDFS:
|
| 81 |
+
for k in list(FILES_TEXT.keys()):
|
| 82 |
+
if k.lower() == p.lower():
|
| 83 |
+
ordered_files[k] = FILES_TEXT.pop(k)
|
| 84 |
+
break
|
| 85 |
+
for k, v in FILES_TEXT.items():
|
| 86 |
+
ordered_files[k] = v
|
| 87 |
+
FILES_TEXT = ordered_files
|
| 88 |
+
|
| 89 |
+
# -------------------------
|
| 90 |
+
# KB Index (naive chunking & query)
|
| 91 |
# -------------------------
|
| 92 |
class KBIndex:
|
| 93 |
+
def __init__(self, chunk_size=1200):
|
| 94 |
self.docs = {}
|
| 95 |
+
self.chunk_size = chunk_size
|
| 96 |
|
| 97 |
def build_from_files(self, files_text):
|
| 98 |
+
self.docs = {}
|
| 99 |
+
for fn, txt in files_text.items():
|
| 100 |
+
if not txt:
|
| 101 |
+
continue
|
| 102 |
+
chunks = []
|
| 103 |
+
for i in range(0, len(txt), self.chunk_size):
|
| 104 |
+
chunks.append(txt[i:i+self.chunk_size])
|
| 105 |
+
self.docs[fn] = chunks
|
| 106 |
|
| 107 |
def query(self, q, top_k=3):
|
| 108 |
+
ql = q.lower().strip()
|
| 109 |
+
results = []
|
| 110 |
+
if not ql:
|
| 111 |
+
return results
|
| 112 |
+
for fn, chunks in self.docs.items():
|
| 113 |
+
best = []
|
| 114 |
+
for ch in chunks:
|
| 115 |
+
if ql in ch.lower():
|
| 116 |
+
best.append((fn, ch[:800]))
|
| 117 |
+
results.extend(best)
|
| 118 |
+
# return first top_k unique filenames/chunks
|
| 119 |
+
seen = set()
|
| 120 |
out = []
|
| 121 |
+
for fn, ch in results:
|
| 122 |
+
if (fn, ch) not in seen:
|
| 123 |
+
out.append((fn, ch))
|
| 124 |
+
seen.add((fn,ch))
|
| 125 |
+
if len(out) >= top_k:
|
| 126 |
+
break
|
| 127 |
+
return out
|
| 128 |
|
| 129 |
KB_INDEX = KBIndex()
|
| 130 |
KB_INDEX.build_from_files(FILES_TEXT)
|
| 131 |
|
| 132 |
+
print("[KB] Indexed files (priority first):")
|
| 133 |
+
for f in FILES_TEXT.keys():
|
| 134 |
+
print(" -", f)
|
| 135 |
+
print("[KB] Total chunks indexed:", sum(len(v) for v in KB_INDEX.docs.values()))
|
| 136 |
+
|
| 137 |
# -------------------------
|
| 138 |
+
# Operational Command — Template
|
| 139 |
# -------------------------
|
| 140 |
def operational_command_prompt(answers_map, category):
|
| 141 |
+
user_text = "\n".join(f"{k}: {v}" for k, v in answers_map.items() if str(v).strip())
|
| 142 |
return [
|
| 143 |
{"role": "system", "content": SYSTEM_SAFE},
|
| 144 |
{"role": "user", "content": f"""
|
|
|
|
| 152 |
Knowledge base excerpts (if any) must be considered.
|
| 153 |
|
| 154 |
Report must include:
|
| 155 |
+
- Executive Summary (2-4 lines)
|
| 156 |
+
- Threat Assessment (administrative & doctrinal)
|
| 157 |
+
- Course of Action (doctrinal, admin, advisory; non-actionable)
|
| 158 |
+
- Intelligence Summary (sources & KB citations)
|
| 159 |
+
- Administrative Remediations (prioritized)
|
| 160 |
+
Please clearly cite KB filenames used (filename::chunk indicator).
|
| 161 |
"""}
|
| 162 |
]
|
| 163 |
|
| 164 |
# -------------------------
|
| 165 |
+
# Standard / Enhanced Questions
|
| 166 |
# -------------------------
|
|
|
|
| 167 |
STD_QUESTIONS = [
|
| 168 |
"When and where was enemy sighted?",
|
| 169 |
"Coming from which direction?",
|
|
|
|
| 179 |
"Did you get the information from local source or army personnel?",
|
| 180 |
"If from local source, did you confirm from a second source or R&S team?",
|
| 181 |
"How far is your commanded army unit from the enemy sighting?",
|
| 182 |
+
"What is the terrain (urban, semi-urban, jungle, hilly, rural)?"
|
| 183 |
]
|
| 184 |
|
| 185 |
ENH_SECTION_A = [
|
| 186 |
"Does the Bn have separate Ops planning and Int sections?",
|
| 187 |
+
"Does the Unit have an intelligence SOP / COA template?",
|
| 188 |
+
"Does the unit have a reconnaissance & surveillance plan?",
|
| 189 |
+
"Does the unit have Force Protection SOP and Threat Levels?",
|
| 190 |
+
"Does the unit have intelligence projection capability (forward nodes)?"
|
| 191 |
]
|
| 192 |
|
| 193 |
ENH_SECTION_B = [
|
| 194 |
+
"Is there a vulnerability analysis tool for the unit?",
|
| 195 |
+
"Does the unit employ randomness in movement and tasks?",
|
| 196 |
+
"Is there a source vetting / CI system in place?",
|
| 197 |
+
"Does the unit treat intelligence as doctrine or just data?",
|
| 198 |
+
"Does the unit use CI in vulnerability & operational reviews?"
|
| 199 |
]
|
| 200 |
|
| 201 |
ENH_SECTION_C = [
|
| 202 |
+
"Are intelligence personnel embedded in routine ops?",
|
| 203 |
+
"Am I thinking of the Threat or the CO's Situational Awareness?",
|
| 204 |
+
"What is my intent as a staff planning element?",
|
| 205 |
+
"Do I detect, deter, deny, deliver, or destroy (5D options)?",
|
| 206 |
+
"Do external MI assets conform to the 5D system?",
|
| 207 |
+
"Have I made a vulnerability assessment (Deter/Deny)?",
|
| 208 |
+
"How do I account for Force Protection based on gaps?",
|
| 209 |
+
"Do we attack threat SA, freedom of movement, tactics, or local support?",
|
| 210 |
+
"Is operation Deliberate or Quick and do I have projected int assets?",
|
| 211 |
+
"Do I clearly distinguish Advance Warn, Surprise and Situational Awareness?"
|
| 212 |
]
|
| 213 |
|
| 214 |
+
# -------------------------
|
| 215 |
+
# PARA SF Questions (50 real concise Qs)
|
| 216 |
+
# -------------------------
|
| 217 |
PARA_QUESTIONS_50 = [
|
| 218 |
+
"Exact location (grid / place) of sighting?",
|
| 219 |
+
"Date and time of first observation?",
|
| 220 |
+
"Direction of enemy approach?",
|
| 221 |
+
"Estimated number of personnel?",
|
| 222 |
+
"Observed leader(s) or commanders?",
|
| 223 |
+
"Enemy weapons observed (small arms, crew-served)?",
|
| 224 |
+
"Presence of vehicles (type / count)?",
|
| 225 |
+
"Signs of explosives or IED activity?",
|
| 226 |
+
"Observed rates of movement (stationary / moving)?",
|
| 227 |
+
"Formation or dispersion (tight / spread)?",
|
| 228 |
+
"Use of local population for support?",
|
| 229 |
+
"Local sympathizers identified (names/roles)?",
|
| 230 |
+
"Logistics / resupply indicators?",
|
| 231 |
+
"Known routes used by enemy?",
|
| 232 |
+
"Recent history of enemy attacks in area?",
|
| 233 |
+
"Patterns of life detected (timings, routines)?",
|
| 234 |
+
"Use of communications (radios, phones, signals)?",
|
| 235 |
+
"Evidence of foreign or external support?",
|
| 236 |
+
"Sanctuary / hideouts identified?",
|
| 237 |
+
"Medical support observed (casualty handling)?",
|
| 238 |
+
"Use of deception or camouflage?",
|
| 239 |
+
"Counter-surveillance signs noted?",
|
| 240 |
+
"Electronic signature / unusual transmissions?",
|
| 241 |
+
"Use of snipers or precision shooters?",
|
| 242 |
+
"Use of indirect fires or mortars observed?",
|
| 243 |
+
"Known HVTs (leadership, infrastructure) in area?",
|
| 244 |
+
"Enemy morale indicators (behavior, chatter)?",
|
| 245 |
+
"Training level (disciplined / ad hoc)?",
|
| 246 |
+
"Use of booby traps or delayed attacks?",
|
| 247 |
+
"Any previous successful ambushes nearby?",
|
| 248 |
+
"Civilian movement patterns near enemy locations?",
|
| 249 |
+
"Sources of local intel for friendly forces?",
|
| 250 |
+
"Credibility of available human sources?",
|
| 251 |
+
"Any known double-agents or compromised sources?",
|
| 252 |
+
"Physical terrain features exploited by enemy?",
|
| 253 |
+
"Weather impacts on enemy movement?",
|
| 254 |
+
"Recent arrests/detentions related to enemy?",
|
| 255 |
+
"Any legal or jurisdictional constraints locally?",
|
| 256 |
+
"Evidence of command-and-control nodes?",
|
| 257 |
+
"Access to fuel/facility caches?",
|
| 258 |
+
"Enemy ability to disperse quickly?",
|
| 259 |
+
"Likelihood of reinforcement from nearby areas?",
|
| 260 |
+
"Time-to-redeploy for friendly quick reaction forces?",
|
| 261 |
+
"Observations on enemy sustainment posture?",
|
| 262 |
+
"Any indicators of planned escalation?",
|
| 263 |
+
"Local civilian sentiment (hostile/neutral/supportive)?",
|
| 264 |
+
"Possible safe-exit routes for friendly forces?",
|
| 265 |
+
"Any cultural or legal sensitivities to consider?",
|
| 266 |
+
"Any open-source / social media indicators?",
|
| 267 |
+
"Urgency rating (low / med / high) from observer field notes?"
|
| 268 |
]
|
| 269 |
+
|
| 270 |
+
# -------------------------
|
| 271 |
+
# PARA SF Precautions / Protective Measures (40 items)
|
| 272 |
+
# -------------------------
|
| 273 |
PARA_PRECAUTIONS_40 = [
|
| 274 |
+
"Maintain strict radio burst discipline and short transmissions",
|
| 275 |
+
"Use alternate communication paths and pre-planned authentication",
|
| 276 |
+
"Document and register all human sources with CI vetting",
|
| 277 |
+
"Establish secure, auditable intelligence logs",
|
| 278 |
+
"Define and rehearse contingency exfiltration routes",
|
| 279 |
+
"Maintain camouflage and concealment SOPs for observation posts",
|
| 280 |
+
"Rotate observation posts and R&S teams to avoid predictability",
|
| 281 |
+
"Implement randomized foot and vehicle movement schedules",
|
| 282 |
+
"Limit use of identified local infrastructure to reduce signature",
|
| 283 |
+
"Use layered reporting with secondary confirmation requirement",
|
| 284 |
+
"Pre-authorize administrative response windows to reduce delay",
|
| 285 |
+
"Audit base layout and relocate critical assets from perimeter",
|
| 286 |
+
"Maintain medical evacuation planning and casualty drills",
|
| 287 |
+
"Ensure secure caches for critical supplies and spares",
|
| 288 |
+
"Institute source validation and cross-source corroboration",
|
| 289 |
+
"Use non-attributable liaison methods with local police/DEA",
|
| 290 |
+
"Formalize SOP for evidence handling and chain-of-custody",
|
| 291 |
+
"Maintain a log of all civilian interactions and transactions",
|
| 292 |
+
"Conduct red-team administrative audits quarterly",
|
| 293 |
+
"Maintain a vulnerability register and prioritized fixes",
|
| 294 |
+
"Limit exposure of leadership movements via need-to-know",
|
| 295 |
+
"Implement force protection route checklists before movement",
|
| 296 |
+
"Deploy observation posts with concealment and escape plans",
|
| 297 |
+
"Mandate brief, formatted SITREPs with required fields",
|
| 298 |
+
"Establish covert Forward Tactical C2 nodes (administrative only)",
|
| 299 |
+
"Use document-based debrief templates to capture lessons",
|
| 300 |
+
"Set up area role cards and single-point contacts per sector",
|
| 301 |
+
"Institute secure storage for source identity and vetting info",
|
| 302 |
+
"Limit public posting of unit schedules and training events",
|
| 303 |
+
"Use liaison with local law enforcement for non-operational support",
|
| 304 |
+
"Schedule regular doctrine & SOP training sessions",
|
| 305 |
+
"Maintain an audit trail for all intelligence product changes",
|
| 306 |
+
"Set thresholds for escalation to higher HQ (administrative)",
|
| 307 |
+
"Maintain alternate rendezvous points and safe houses",
|
| 308 |
+
"Ensure all unit members have basic fieldcraft refresher training",
|
| 309 |
+
"Plan periodic concealment and movement drills (administrative)",
|
| 310 |
+
"Maintain a simple, unclassified index of likely HVT indicators",
|
| 311 |
+
"Ensure information security (passwords, devices) audits quarterly",
|
| 312 |
+
"Establish a schedule for reviewing and updating SOPs"
|
| 313 |
]
|
| 314 |
|
| 315 |
# -------------------------
|
| 316 |
+
# Report Generators (KB-first, then fallback to OpenAI SF doctrine)
|
| 317 |
# -------------------------
|
| 318 |
+
def call_chat_api_system_user(messages, max_tokens=800, model="gpt-4o-mini"):
|
| 319 |
+
if client is None:
|
| 320 |
+
raise RuntimeError("OpenAI client not available.")
|
| 321 |
+
resp = client.chat.completions.create(model=model, messages=messages, max_tokens=max_tokens)
|
| 322 |
+
try:
|
| 323 |
+
return resp.choices[0].message.content
|
| 324 |
+
except Exception:
|
| 325 |
+
return resp.choices[0].message.content
|
| 326 |
+
|
| 327 |
def generate_report_with_kb(answers_map, category, top_k=3):
|
| 328 |
+
# Build KB hits per question (lens)
|
| 329 |
kb_hits = []
|
| 330 |
for q, a in answers_map.items():
|
| 331 |
+
query = (str(a).strip() or q)
|
| 332 |
+
hits = KB_INDEX.query(query, top_k=top_k)
|
| 333 |
+
kb_hits.extend(hits)
|
| 334 |
+
# Compose prompt
|
| 335 |
+
excerpt_text = ""
|
| 336 |
+
if kb_hits:
|
| 337 |
+
seen = set()
|
| 338 |
+
for fn, txt in kb_hits:
|
| 339 |
+
key = f"{fn}"
|
| 340 |
+
if key not in seen:
|
| 341 |
+
excerpt_text += f"\n--- {fn} ---\n{txt[:1200]}\n"
|
| 342 |
+
seen.add(key)
|
| 343 |
+
# Build messages
|
| 344 |
+
messages = operational_command_prompt(answers_map, category)
|
| 345 |
if excerpt_text:
|
| 346 |
+
messages[1]["content"] += f"\nKnowledge Base excerpts (priority applied):\n{excerpt_text}\n"
|
| 347 |
+
else:
|
| 348 |
+
# Indicate we'll fallback to SF doctrine
|
| 349 |
+
messages[1]["content"] += "\n[No KB excerpts found for these inputs; assistant may fallback to authoritative SF doctrine for doctrinal guidance.]\n"
|
| 350 |
+
# Call model
|
| 351 |
try:
|
| 352 |
+
out = call_chat_api_system_user(messages, max_tokens=900)
|
| 353 |
+
return out.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
except Exception as e:
|
| 355 |
+
# Fallback deterministic admin report
|
| 356 |
+
lines = ["[FALLBACK NON-ACTIONABLE REPORT — AI unavailable]\n"]
|
| 357 |
+
lines.append("Executive Summary: Administrative findings based on inputs.\n")
|
| 358 |
+
lines.append("Key Issues:")
|
| 359 |
+
for q, a in answers_map.items():
|
| 360 |
+
lines.append(f"- {q}: {'[no answer]' if not str(a).strip() else str(a)}")
|
| 361 |
+
lines.append("\nAdministrative Recommendations (deterministic):")
|
| 362 |
+
lines.append("- Ensure SITREP templates have mandatory fields (time, geo, observer).")
|
| 363 |
+
lines.append("- Institute source vetting and require secondary confirmation of local reports.")
|
| 364 |
+
lines.append("- Conduct a quarterly vulnerability audit and publish remediations.")
|
| 365 |
+
lines.append(f"\nError: {e}")
|
| 366 |
+
return "\n".join(lines)
|
| 367 |
+
|
| 368 |
+
# PARA SF runner (KB first + SF doctrine fallback)
|
| 369 |
+
def para_sf_inference_runner(selected_files, pasted_notes, answers_map):
|
| 370 |
+
# Force priority list: if selected_files provided use them, else use SF_PRIORITY_PDFS present in KB
|
| 371 |
+
selected = selected_files or [p for p in SF_PRIORITY_PDFS if p in FILES_TEXT]
|
| 372 |
kb_hits = []
|
| 373 |
+
# pull KB excerpts only from selected first, then general KB if needed
|
| 374 |
for q, a in answers_map.items():
|
| 375 |
+
query = (str(a).strip() or q)
|
| 376 |
+
# search within selected files first
|
| 377 |
+
for fn in selected:
|
| 378 |
+
if fn in KB_INDEX.docs:
|
| 379 |
+
for ch in KB_INDEX.docs[fn]:
|
| 380 |
+
if query.lower() in ch.lower():
|
| 381 |
+
kb_hits.append((fn, ch[:1200]))
|
| 382 |
+
break
|
| 383 |
+
# if not found in selected, do general query
|
| 384 |
+
if not any(fn == k for k,_ in kb_hits):
|
| 385 |
+
hits = KB_INDEX.query(query, top_k=1)
|
| 386 |
+
if hits:
|
| 387 |
+
kb_hits.extend(hits)
|
| 388 |
+
excerpt_text = ""
|
| 389 |
+
if kb_hits:
|
| 390 |
+
seen = set()
|
| 391 |
+
for fn, txt in kb_hits:
|
| 392 |
+
if fn not in seen:
|
| 393 |
+
excerpt_text += f"\n--- {fn} ---\n{txt[:1200]}\n"
|
| 394 |
+
seen.add(fn)
|
| 395 |
+
# Compose user text
|
| 396 |
+
user_text = "\n".join(f"{k}: {v}" for k, v in answers_map.items() if str(v).strip())
|
| 397 |
+
messages = [
|
| 398 |
{"role":"system","content":SYSTEM_SAFE},
|
| 399 |
{"role":"user","content":f"""
|
| 400 |
+
Prepare a NON-ACTIONABLE PARA SF advisory using the 5D lens and doctrine.
|
|
|
|
| 401 |
Inputs:
|
| 402 |
{user_text}
|
| 403 |
|
| 404 |
Fieldcraft notes:
|
| 405 |
+
{pasted_notes}
|
| 406 |
+
|
| 407 |
+
Selected SF KB files (priority): {selected}
|
| 408 |
|
| 409 |
+
Knowledge Base excerpts (if any):
|
| 410 |
{excerpt_text}
|
| 411 |
|
| 412 |
+
Output required:
|
| 413 |
+
- Executive Summary (2-4 lines)
|
| 414 |
+
- Doctrinal Course of Action (administrative / doctrinal guidance only)
|
| 415 |
+
- Threat Assessment (high-level, non-actionable)
|
| 416 |
+
- Intelligence Summary (sources cited)
|
| 417 |
+
- PARA SF Precautions & Protective Measures (administrative list)
|
| 418 |
+
Cite KB filenames used.
|
| 419 |
+
"""}]
|
| 420 |
try:
|
| 421 |
+
out = call_chat_api_system_user(messages, max_tokens=1000)
|
| 422 |
+
return out.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 423 |
except Exception as e:
|
| 424 |
+
# Fallback deterministic extraction of precautions
|
| 425 |
+
lines = [f"[FALLBACK NON-ACTIONABLE PARA SF REPORT — AI unavailable: {e}]\n"]
|
| 426 |
+
lines.append("Executive Summary: See fieldcraft and KB for details.\n")
|
| 427 |
+
lines.append("Top observed inputs (sample):")
|
| 428 |
+
cnt = 0
|
| 429 |
+
for k,v in answers_map.items():
|
| 430 |
+
if v and cnt < 8:
|
| 431 |
+
lines.append(f"- {k}: {v}")
|
| 432 |
+
cnt += 1
|
| 433 |
+
lines.append("\nPrecautions (sample deterministic):")
|
| 434 |
+
for i, itm in enumerate(PARA_PRECAUTIONS_40[:12], start=1):
|
| 435 |
+
lines.append(f"{i}. {itm} — Admin remediation: document & audit.")
|
| 436 |
+
return "\n".join(lines)
|
| 437 |
|
| 438 |
# -------------------------
|
| 439 |
+
# Gradio UI
|
| 440 |
# -------------------------
|
| 441 |
with gr.Blocks() as demo:
|
| 442 |
gr.HTML(f'<img src="{BANNER_URL}" width="100%">')
|
| 443 |
gr.Markdown("# Kashmir AOR Action Plan — Battle Planner")
|
| 444 |
+
gr.Markdown("⚠️ **NON-ACTIONABLE — Doctrinal / Administrative guidance only.**")
|
| 445 |
|
| 446 |
+
# ---- Standard Tab ----
|
| 447 |
with gr.Tab("Standard"):
|
| 448 |
std_inputs = [gr.Textbox(label=q, lines=1) for q in STD_QUESTIONS]
|
| 449 |
std_button = gr.Button("Generate Standard Advisory")
|
| 450 |
+
std_output = gr.Textbox(label="Standard Advisory Report (sanitized)", lines=28)
|
| 451 |
def std_runner(*answers):
|
| 452 |
amap = dict(zip(STD_QUESTIONS, answers))
|
| 453 |
return generate_report_with_kb(amap, "Standard Threat Advisory")
|
| 454 |
std_button.click(std_runner, inputs=std_inputs, outputs=std_output)
|
| 455 |
|
| 456 |
+
# ---- Enhanced Tab ----
|
| 457 |
with gr.Tab("Enhanced"):
|
| 458 |
a_inputs = [gr.Textbox(label=q, lines=1) for q in ENH_SECTION_A]
|
| 459 |
b_inputs = [gr.Textbox(label=q, lines=1) for q in ENH_SECTION_B]
|
| 460 |
c_inputs = [gr.Textbox(label=q, lines=1) for q in ENH_SECTION_C]
|
| 461 |
+
gate_input = gr.Textbox(label="Gate Question / Final Note", lines=1)
|
| 462 |
enh_button = gr.Button("Generate Enhanced Advisory")
|
| 463 |
+
enh_output = gr.Textbox(label="Enhanced Advisory Report (sanitized)", lines=28)
|
| 464 |
def enh_runner(*answers):
|
| 465 |
la, lb, lc = len(ENH_SECTION_A), len(ENH_SECTION_B), len(ENH_SECTION_C)
|
| 466 |
+
vals = list(answers)
|
| 467 |
+
# map A/B/C into a single answers_map for generation
|
| 468 |
+
amap = {}
|
| 469 |
+
for i, q in enumerate(ENH_SECTION_A):
|
| 470 |
+
amap[q] = vals[i] if i < len(vals) else ""
|
| 471 |
+
for j, q in enumerate(ENH_SECTION_B):
|
| 472 |
+
idx = la + j
|
| 473 |
+
amap[q] = vals[idx] if idx < len(vals) else ""
|
| 474 |
+
for k, q in enumerate(ENH_SECTION_C):
|
| 475 |
+
idx = la + lb + k
|
| 476 |
+
amap[q] = vals[idx] if idx < len(vals) else ""
|
| 477 |
+
gate = vals[-1] if vals else ""
|
| 478 |
+
# include gate as special entry
|
| 479 |
+
if gate:
|
| 480 |
+
amap["Gate Assessment"] = gate
|
| 481 |
+
return generate_report_with_kb(amap, "Enhanced 5D Advisory")
|
| 482 |
enh_button.click(enh_runner, inputs=a_inputs+b_inputs+c_inputs+[gate_input], outputs=enh_output)
|
| 483 |
|
| 484 |
+
# ---- Threat Readiness Tab ----
|
| 485 |
with gr.Tab("Threat Readiness"):
|
| 486 |
+
gr.Markdown("## Threat Readiness — Color-coded Commander Brief (administrative)")
|
| 487 |
threat_button = gr.Button("Evaluate Threat Readiness")
|
| 488 |
+
threat_output = gr.Textbox(label="Threat Readiness & Diagnostics (sanitized)", lines=28)
|
| 489 |
+
def threat_runner():
|
| 490 |
lines = []
|
| 491 |
+
lines.append("### Threat Readiness Level (Color-coded) — Administrative Brief")
|
| 492 |
+
lines.append("- 🔴 RED (<50%): Significant administrative vulnerabilities. Prioritize SOP, CI, audits.")
|
| 493 |
+
lines.append("- 🟠 ORANGE (50–69%): Moderate gaps; schedule doctrinal reviews and R&S validation.")
|
| 494 |
+
lines.append("- 🔵 BLUE (70–84%): Minor gaps; plan targeted training and audits.")
|
| 495 |
+
lines.append("- 🟢 GREEN (85–100%): Strong readiness; maintain periodic reviews.\n")
|
| 496 |
+
lines.append("Commander’s Guide: Use remedial actions focused on doctrine, SOP updates, source vetting and audits. This brief is non-actionable.")
|
| 497 |
return "\n".join(lines)
|
| 498 |
+
threat_button.click(threat_runner, inputs=[], outputs=threat_output)
|
| 499 |
|
| 500 |
+
# ---- PARA SF Tab ----
|
| 501 |
with gr.Tab("PARA SF (Two Reports)"):
|
| 502 |
+
gr.Markdown("## PARA SF — Two Separate Administrative Advisories (Non-Actionable)")
|
| 503 |
para_questions_inputs = [gr.Textbox(label=q, lines=1) for q in PARA_QUESTIONS_50]
|
| 504 |
para_fieldcraft = gr.Textbox(label="Paste Fieldcraft / SR notes", lines=6)
|
| 505 |
+
para_file_selector = gr.CheckboxGroup(choices=SF_PRIORITY_PDFS, label="Select SF KB files (optional)")
|
| 506 |
para_coa_btn = gr.Button("Generate COA / Threat Assessment / Intelligence Summary")
|
| 507 |
para_prec_btn = gr.Button("Generate PARA SF Precautions & Protective Advisory")
|
| 508 |
+
para_coa_out = gr.Textbox(label="COA / Threat Assessment / Intelligence Summary (sanitized)", lines=28)
|
| 509 |
+
para_prec_out = gr.Textbox(label="PARA SF Precautions & Protective Measures (sanitized)", lines=28)
|
| 510 |
+
|
| 511 |
def para_coa_runner(*all_inputs):
|
| 512 |
+
# last two inputs are pasted notes and file selector
|
| 513 |
+
answers = list(all_inputs[:-2])
|
| 514 |
pasted = all_inputs[-2] or ""
|
| 515 |
selected = all_inputs[-1] or []
|
| 516 |
+
amap = dict(zip(PARA_QUESTIONS_50, answers))
|
| 517 |
return para_sf_inference_runner(selected, pasted, amap)
|
| 518 |
+
|
| 519 |
def para_prec_runner(*all_inputs):
|
| 520 |
+
answers = list(all_inputs[:-2])
|
| 521 |
pasted = all_inputs[-2] or ""
|
| 522 |
selected = all_inputs[-1] or []
|
| 523 |
+
amap = dict(zip(PARA_QUESTIONS_50, answers))
|
| 524 |
+
# We'll run the same inference but return the precautions section — model is asked to include it
|
| 525 |
return para_sf_inference_runner(selected, pasted, amap)
|
| 526 |
+
|
| 527 |
para_coa_btn.click(para_coa_runner, inputs=para_questions_inputs+[para_fieldcraft, para_file_selector], outputs=para_coa_out)
|
| 528 |
para_prec_btn.click(para_prec_runner, inputs=para_questions_inputs+[para_fieldcraft, para_file_selector], outputs=para_prec_out)
|
| 529 |
|
| 530 |
+
# -------------------------
|
| 531 |
+
# Launch
|
| 532 |
+
# -------------------------
|
| 533 |
if __name__ == "__main__":
|
| 534 |
demo.launch()
|