Spaces:
Runtime error
Runtime error
| # app.py — Kashmir AO Action Plan for Inf (Full Version) | |
| import os | |
| import gradio as gr | |
| from openai import OpenAI | |
| # --------------------------- | |
| # Setup OpenAI | |
| # --------------------------- | |
| client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | |
| # --------------------------- | |
| # Knowledge Base placeholder | |
| # --------------------------- | |
| KNOWLEDGE_BASE = """ | |
| Embedded doctrinal and operational notes for Kashmir AO. | |
| """ | |
| # --------------------------- | |
| # Helper functions | |
| # --------------------------- | |
| def generate_standard_report(answers): | |
| """Generate standard analyst report from answers + KB context.""" | |
| text_blob = "\n".join(f"{q}: {a}" for q, a in answers.items()) | |
| prompt = f"""You are a military analyst. Based on the following answers and knowledge base, write a structured, advisory style report for the commander. | |
| Knowledge Base: | |
| {KNOWLEDGE_BASE} | |
| Answers: | |
| {text_blob} | |
| Report:""" | |
| try: | |
| resp = client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=[{"role": "user", "content": prompt}], | |
| max_tokens=500 | |
| ) | |
| return resp.choices[0].message.content.strip() | |
| except Exception as e: | |
| return f"[Error generating report: {e}]" | |
| def generate_enhanced_report(answers_a, answers_b, answers_c, gate): | |
| """Generate enhanced analyst report (sectioned).""" | |
| text_blob = "\n".join( | |
| f"Section A: {answers_a}\nSection B: {answers_b}\nSection C: {answers_c}\nGate: {gate}" | |
| ) | |
| prompt = f"""You are a senior staff officer. Based on the following sectioned answers and doctrinal context, prepare an advisory intelligence report for the commander. | |
| Knowledge Base: | |
| {KNOWLEDGE_BASE} | |
| Answers: | |
| {text_blob} | |
| Report:""" | |
| try: | |
| resp = client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=[{"role": "user", "content": prompt}], | |
| max_tokens=600 | |
| ) | |
| return resp.choices[0].message.content.strip() | |
| except Exception as e: | |
| return f"[Error generating enhanced report: {e}]" | |
| # --------------------------- | |
| # Threat Status Evaluator | |
| # --------------------------- | |
| def derive_threat_status(answers): | |
| """Simple heuristic threat evaluation.""" | |
| status = "Green" | |
| desc = "Prepared for peacetime security; no immediate or future attack indicators." | |
| text_blob = " ".join(str(v).lower() for v in answers.values()) | |
| if any(word in text_blob for word in ["engaged", "shooting", "contact", "attack now", "ambush"]): | |
| status = "Red" | |
| desc = "Ready for ongoing attack — hostile activity confirmed." | |
| elif any(word in text_blob for word in ["imminent", "soon", "moving towards", "likely attack", "advance"]): | |
| status = "Orange" | |
| desc = "Prepared for imminent attack — strong indicators from inputs." | |
| elif any(word in text_blob for word in ["possible", "expected", "threat", "risk", "movement detected"]): | |
| status = "Blue" | |
| desc = "Ready for anticipated short-term attack probability." | |
| return status, desc | |
| # --------------------------- | |
| # Doctrinal summary constant | |
| # --------------------------- | |
| DOCTRINAL_SUMMARY_DETAILED = """ | |
| # 📘 Doctrinal Summary (Sanitized, Detailed) | |
| Purpose and Approach | |
| - Intelligence is treated as a combat function, not just support. Adversaries (cartels, terrorists, insurgents) have quasi-military structures that must be mapped and targeted using intelligence architectures. | |
| - Objective: Give the commander a persistent, adaptive situational picture by embedding Command, Control, Communications, Intelligence, Surveillance, Reconnaissance (C3ISR) across the AO. | |
| - Scope: Covers architecture, zoning, collection posture, force protection, staff planning, and doctrinal lenses. No tactical timings or unit counts are provided here. | |
| Doctrinal Lenses | |
| - Threat vs. Situational Awareness: Distinguish enemy threat indicators from the commander’s broader situational awareness. | |
| - The 5Ds (Detect, Deter, Deny, Deliver, Destroy): Each lens shifts how intelligence and reconnaissance assets should be tasked. | |
| - Red Teaming & Vulnerability Analysis: Commanders must ask not only what is seen but why something was *not* seen. | |
| Command & Control Embedding | |
| - Rear Area: Secure HQ and sustainment. | |
| - Forward Areas: Distributed tactical nodes with reconnaissance, HUMINT, and CI integration. | |
| - Deep Forward: Covert placements close to adversary leadership or logistics. | |
| - Tactical Ops Centers (TOCs): Covert urban/rural apartments acting as intelligence fusion and relay nodes. | |
| Force Protection | |
| - Randomize movement, guard routines, and convoy timings. | |
| - Use counterintelligence not only to detect spies but also to map and attack enemy intent and surveillance. | |
| Collection Integration | |
| - HUMINT, TACHUMINT, Reconnaissance, Surveillance, and CI nodes all feed Tactical Ops Centers. | |
| - SIIE (Structured Integrated Intelligence Environment) ensures commanders see a fused picture, not fragments. | |
| Staff Guidance | |
| - Align staff planning with commander’s intent *and* with adversary threat reality. | |
| - Avoid overreliance on external MI units; embed unit-level intelligence. | |
| - Differentiate between Advance Warning, Surprise, and Situational Awareness — they are not the same. | |
| Outcome | |
| - Commanders who apply these doctrines convert intelligence from passive reporting into an active weapon system. | |
| - Security forces must think of intelligence as combat, structuring AO into zones, embedding covert/ overt nodes, and preempting threats before they manifest. | |
| """ | |
| # --------------------------- | |
| # Build Gradio UI | |
| # --------------------------- | |
| with gr.Blocks() as demo: | |
| gr.HTML('<img src="https://huggingface.co/spaces/Militaryint/ops/resolve/main/banner.png" width="100%">') | |
| gr.Markdown("# Kashmir AO Action Plan for Inf — ARMY Analyst Tool & Battle Planner") | |
| # ----------- Standard Analyst Tab ----------- | |
| with gr.Tab("Standard Analyst"): | |
| std_questions = [ | |
| "When/where was the enemy sighted?", | |
| "Direction of movement?", | |
| "Enemy size and strength?", | |
| "Weapons and equipment observed?", | |
| "Vehicles or on foot?", | |
| "Proximity to roads?", | |
| "Proximity to camps?", | |
| "Support of locals?", | |
| "Enemy formation/disposition?", | |
| "Terrain type?" | |
| ] | |
| std_inputs = [gr.Textbox(label=q) for q in std_questions] | |
| std_btn = gr.Button("Generate Standard Report") | |
| std_output = gr.Markdown() | |
| def on_std_click(*answers): | |
| return generate_standard_report(dict(zip(std_questions, answers))) | |
| std_btn.click(on_std_click, inputs=std_inputs, outputs=std_output) | |
| # ----------- Enhanced Analyst Tab ----------- | |
| with gr.Tab("Enhanced Analyst (Sectioned)"): | |
| ENH_SECTION_A = [ | |
| "Does the unit have Ops + Int integration?", | |
| "Does the unit have intelligence SOPs?", | |
| "Reconnaissance & Surveillance plan integrated?", | |
| "Force Protection SOP & threat conditions?", | |
| "Forward intelligence projection capability?" | |
| ] | |
| ENH_SECTION_B = [ | |
| "Vulnerability analysis tools in place?", | |
| "Randomness in troop/officer movement?", | |
| "Source vetting & counterintelligence registry?", | |
| "Intelligence treated as doctrine repository?", | |
| "CI used in base/ops vulnerability analysis?" | |
| ] | |
| ENH_SECTION_C = [ | |
| "Embedded intelligence in routine ops?", | |
| "Advance warning system present?", | |
| "Capability for deliberate vs quick ops?", | |
| "Projected command/control nodes?", | |
| "Distinction between SA, Advance Warn, Surprise?" | |
| ] | |
| a_inputs = [gr.Textbox(label=q) for q in ENH_SECTION_A] | |
| b_inputs = [gr.Textbox(label=q) for q in ENH_SECTION_B] | |
| c_inputs = [gr.Textbox(label=q) for q in ENH_SECTION_C] | |
| gate_q = gr.Textbox(label="Does the commander want AI to supply the report?") | |
| enh_btn = gr.Button("Generate Enhanced Report") | |
| enh_output = gr.Markdown() | |
| def on_enh_click(*args): | |
| answers_a = dict(zip(ENH_SECTION_A, args[:len(ENH_SECTION_A)])) | |
| answers_b = dict(zip(ENH_SECTION_B, args[len(ENH_SECTION_A):len(ENH_SECTION_A)+len(ENH_SECTION_B)])) | |
| answers_c = dict(zip(ENH_SECTION_C, args[len(ENH_SECTION_A)+len(ENH_SECTION_B):-1])) | |
| gate = args[-1] | |
| return generate_enhanced_report(answers_a, answers_b, answers_c, gate) | |
| enh_btn.click(on_enh_click, inputs=a_inputs+b_inputs+c_inputs+[gate_q], outputs=enh_output) | |
| # ----------- Doctrinal Summary Tab ----------- | |
| with gr.Tab("Doctrinal Summary (Sanitized, Detailed)"): | |
| gr.Markdown(DOCTRINAL_SUMMARY_DETAILED) | |
| # ----------- Threat Status Tab (NEW) ----------- | |
| with gr.Tab("Threat Status"): | |
| gr.Markdown("### 🛡️ Threat Status Indicator\nColors indicate readiness levels derived from your inputs in Standard/Enhanced tabs.") | |
| status_out = gr.HTML("<div style='font-size:20px;'>Awaiting evaluation...</div>") | |
| eval_btn = gr.Button("Evaluate Threat Status") | |
| def on_eval(): | |
| # Placeholder, since live state wiring not connected | |
| dummy_answers = {"sample": "no threat"} | |
| status, desc = derive_threat_status(dummy_answers) | |
| color_map = {"Red":"#FF4C4C","Orange":"#FFA500","Blue":"#1E90FF","Green":"#32CD32"} | |
| html = f"<div style='padding:1em;border-radius:8px;background:{color_map[status]};color:white;font-size:20px;'><b>{status}</b>: {desc}</div>" | |
| return html | |
| eval_btn.click(on_eval, inputs=None, outputs=status_out) | |
| # --------------------------- | |
| # Launch app | |
| # --------------------------- | |
| if __name__ == "__main__": | |
| demo.launch() | |