Militaryint commited on
Commit
cb3c432
·
verified ·
1 Parent(s): 75fec7a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -117
app.py CHANGED
@@ -1,150 +1,181 @@
1
  """
2
- ARMYINTEL 5DMDMP Training Engine
3
- Purpose: Non‑kinetic military‑intelligence analysis simulator for education and defence training.
4
- Frameworks: 5D (Detect–Deter–Deny–Deliver–Defend) + MDMP
 
5
  """
6
 
7
- import os, json, glob, concurrent.futures
 
8
  from datetime import datetime
9
  from docx import Document
 
10
  from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
11
  import gradio as gr
12
  import openai
 
13
 
14
- # ---------- CONFIG ----------
 
 
15
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
16
  if not OPENAI_API_KEY:
17
- raise ValueError("OPENAI_API_KEY missing in environment secrets.")
 
18
  openai.api_key = OPENAI_API_KEY
19
 
20
- INTEL_TECHNIQUES = [
21
- "HUMINT","SIGINT","IMINT","OSINT","MASINT","COMINT","ELINT","TECHINT",
22
- "FINT","SOCMINT","GEOINT","ALL‑SOURCE INTELLIGENCE","CRISIS INTELLIGENCE",
23
- "COUNTERINTELLIGENCE","RED TEAMING","BLUE TEAMING",
24
- "CTRIP Analysis","SALUT Analysis","Decision Trees",
25
- "Bayesian Reasoning","Network Influence Mapping"
 
26
  ]
27
 
28
- # ---------- KNOWLEDGE‑BASE LOADING ----------
29
- def load_kb_snippets():
30
- kb_text = ""
31
- for f in glob.glob("knowledge_base/*"):
32
- name = os.path.basename(f)
33
- if any(k in name for k in ["5d","5D","mdmp","MDMP","jsonl","SOP","coa"]):
34
- try:
35
- with open(f, "r", encoding="utf‑8", errors="ignore") as fh:
36
- kb_text += f"\n--- {name} ---\n{fh.read()}\n"
37
- except Exception:
38
- pass
39
- return kb_text[:20000] # safety cap
40
-
41
- # ---------- CORE ANALYSIS ----------
42
- def analyze_with_technique(tech, problem, kb_text):
43
  prompt = f"""
44
- Training context: defensive / educational only.
45
-
46
- Using the {tech} discipline, apply the 5D framework (Detect,Deter,Deny,Deliver, Defend)
47
- and MDMP reasoning to analyse the following situation:
48
-
49
- {problem}
50
-
51
- Reference knowledge (for orientation only):
52
- {kb_text}
53
-
54
- Return JSON:
55
- {{
56
- "technique": "{tech}",
57
- "findings": "...",
58
- "5D": {{
59
- "Detect": "...", "Deter": "...", "Deny": "...", "Deliver": "...", "Defend": "..."
60
- }},
61
- "recommended_actions": ["...", "..."],
62
- "confidence": {{"level":"High|Medium|Low","reason":"..."}}
63
- }}
64
  """
65
  try:
66
- resp = openai.ChatCompletion.create(
67
  model="gpt-4-turbo",
68
  messages=[
69
- {"role":"system","content":"You are a senior military intelligence instructor. Provide non‑kinetic, training‑safe analysis."},
70
- {"role":"user","content":prompt}
71
  ],
72
  temperature=0.5,
73
  max_tokens=600
74
  )
75
- txt = resp["choices"][0]["message"]["content"].strip()
76
  try:
77
- data = json.loads(txt)
78
  except:
79
- data = {"technique":tech,"findings":txt,"5D":{},"recommended_actions":[],
80
- "confidence":{"level":"Unknown","reason":"Text only"}}
 
 
 
 
 
 
 
 
 
 
81
  return data
82
  except Exception as e:
83
- return {"technique":tech,"findings":f"Analysis failed: {e}","5D":{},
84
- "recommended_actions":[],"confidence":{"level":"Error","reason":str(e)}}
85
-
86
- # ---------- DOCX REPORT ----------
87
- def build_docx(analyses):
 
 
 
 
 
 
 
88
  os.makedirs("reports", exist_ok=True)
89
- fname = f"reports/ArmyIntel_5D_MDMP_Report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
 
 
90
  doc = Document()
91
- h = doc.add_heading("INTELLIGENCE ANALYSIS – INTELLIGENCE WARFARE 5D MDMP TRAINING REPORT",0)
92
- h.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
93
- doc.add_paragraph(f"Generated on {datetime.now():%d %b %Y %H:%M:%S}", style="Caption")
94
- doc.add_paragraph("—"*30)
95
-
96
- for i,a in enumerate(analyses,1):
97
- doc.add_heading(f"{i}. {a.get('technique','Unknown')}", level=1)
98
- doc.add_paragraph(a.get("findings","No findings."))
99
-
100
- doc.add_heading("5D Analysis", level=2)
101
- for d in ["Detect","Deter","Deny","Deliver","Defend"]:
102
- doc.add_paragraph(f"• {d}: {a.get('5D',{}).get(d,'')}", style="List Bullet")
103
-
104
- doc.add_heading("Recommended Actions", level=2)
105
- if a.get("recommended_actions"):
106
- for r in a["recommended_actions"]:
107
- doc.add_paragraph(f"• {r}", style="List Bullet")
 
 
 
 
 
 
108
  else:
109
- doc.add_paragraph("• None/pendinganalysis")
110
-
111
- c = a.get("confidence",{})
112
- doc.add_paragraph(f"Confidence:{c.get('level','Unknown')} – {c.get('reason','')}")
113
- doc.add_paragraph(" ")
114
-
115
- doc.add_heading("MDMP Summary", level=1)
116
- doc.add_paragraph(
117
- "1. Problem identification → 2. Intelligence gathering → 3. COA development → "
118
- "4. COA analysis → 5. Decision & execution (Training Simulation only)."
119
- )
120
- doc.save(fname)
121
- return fname
122
-
123
- # ---------- MAIN ENGINE ----------
124
- def run_full_analysis(problem):
125
- kb_text = load_kb_snippets()
126
- analyses=[]
127
- with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
128
- futures={pool.submit(analyze_with_technique,t,problem,kb_text):t for t in INTEL_TECHNIQUES}
129
- for f in concurrent.futures.as_completed(futures):
130
- analyses.append(f.result())
131
- return build_docx(analyses)
132
-
133
- # ---------- GRADIO UI ----------
134
- def start_analysis(problem):
135
- if not problem.strip():
136
- problem="Training scenario: suspected hostile surveillance around forward base; assess defensive posture."
137
- path=run_full_analysis(problem)
138
- return path
139
-
140
- demo=gr.Interface(
141
- fn=start_analysis,
142
- inputs=gr.Textbox(label="Enter Training / Defensive Problem", lines=8),
143
- outputs=gr.File(label="Download Training Intelligence Report"),
144
- title="ARMYINTEL 5D + MDMP Training Engine",
145
- description="Educational simulation engine for non‑kinetic intelligence analysis using 21 techniques + 5D + MDMP."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  )
147
 
148
- if __name__=="__main__":
149
- demo.launch(share=True)
150
-
 
1
  """
2
+ ARMYINTEL 5D-MDMP INTELLIGENCE ANALYSIS ENGINE
3
+ Purpose: Comprehensive multi-discipline intelligence synthesis using 5D & MDMP
4
+ Domain: Military Intelligence Training / Defensive Operations
5
+ Frameworks: 5D (Detect, Deter, Deny, Deliver, Destroy) + MDMP
6
  """
7
 
8
+ import os
9
+ import json
10
  from datetime import datetime
11
  from docx import Document
12
+ from docx.shared import Pt
13
  from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
14
  import gradio as gr
15
  import openai
16
+ import concurrent.futures
17
 
18
+ # -------------------------
19
+ # CONFIG
20
+ # -------------------------
21
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
22
  if not OPENAI_API_KEY:
23
+ raise ValueError("OpenAI API Key not found in environment secrets.")
24
+
25
  openai.api_key = OPENAI_API_KEY
26
 
27
+ MILITARY_INTEL_TECHNIQUES = [
28
+ "HUMINT", "SIGINT", "IMINT", "OSINT", "MASINT",
29
+ "COMINT", "ELINT", "TECHINT", "FINT", "SOCMINT",
30
+ "GEOINT", "ALL-SOURCE INTELLIGENCE", "CRISIS INTELLIGENCE",
31
+ "COUNTERINTELLIGENCE", "RED TEAMING", "BLUE TEAMING",
32
+ "CTRIP Analysis", "SALUT Analysis", "Decision Trees",
33
+ "Bayesian Reasoning", "Network Influence Mapping"
34
  ]
35
 
36
+ # -------------------------
37
+ # CORE 5D FUNCTION
38
+ # -------------------------
39
+ def apply_5d_to_technique(technique_name, problem_text):
 
 
 
 
 
 
 
 
 
 
 
40
  prompt = f"""
41
+ Conduct a professional military intelligence analysis for the following operational or training situation:
42
+ Technique: {technique_name}
43
+ Apply the 5D framework (Detect, Deter, Deny, Deliver, Destroy) and give structured findings.
44
+ Include likely enemy capabilities, indicators, vulnerabilities, and recommended defensive measures.
45
+ Problem: {problem_text}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  """
47
  try:
48
+ response = openai.ChatCompletion.create(
49
  model="gpt-4-turbo",
50
  messages=[
51
+ {"role": "system", "content": "You are a senior army intelligence officer producing analytical reports for training and defensive planning."},
52
+ {"role": "user", "content": prompt}
53
  ],
54
  temperature=0.5,
55
  max_tokens=600
56
  )
57
+ text = response['choices'][0]['message']['content'].strip()
58
  try:
59
+ data = json.loads(text)
60
  except:
61
+ data = {
62
+ "technique": technique_name,
63
+ "findings": text,
64
+ "5D": {},
65
+ "recommended_actions": [],
66
+ "confidence": {"level":"Unknown","reason":"Model returned narrative text"}
67
+ }
68
+ data.setdefault("technique", technique_name)
69
+ data.setdefault("findings", "")
70
+ data.setdefault("5D", {})
71
+ data.setdefault("recommended_actions", [])
72
+ data.setdefault("confidence", {"level":"Unknown","reason":"Missing"})
73
  return data
74
  except Exception as e:
75
+ return {
76
+ "technique": technique_name,
77
+ "findings": f"Analysis incomplete: {str(e)}",
78
+ "5D": {},
79
+ "recommended_actions": [],
80
+ "confidence": {"level":"Error","reason": str(e)}
81
+ }
82
+
83
+ # -------------------------
84
+ # DOCX SAVE
85
+ # -------------------------
86
+ def save_docx(report_text, analyses):
87
  os.makedirs("reports", exist_ok=True)
88
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
89
+ filename = f"reports/ArmyIntel_5D_MDMP_Report_{timestamp}.docx"
90
+
91
  doc = Document()
92
+
93
+ # Title Page
94
+ title = doc.add_heading("ARMYINTEL 5D–MDMP INTELLIGENCE REPORT", 0)
95
+ title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
96
+ doc.add_paragraph("Directorate of Military Intelligence (Training Use Only)", style='Intense Quote')
97
+ doc.add_paragraph(f"Report generated on: {datetime.now().strftime('%d %b %Y %H:%M:%S')}", style='Caption')
98
+ doc.add_paragraph("\n---\n", style='Normal')
99
+
100
+ # Individual Technique Analyses
101
+ for i, a in enumerate(analyses, 1):
102
+ doc.add_heading(f"{i}. {a.get('technique','Unknown')}", level=1)
103
+ doc.add_paragraph("Findings:", style='Heading 3')
104
+ doc.add_paragraph(a.get('findings',''), style='Normal')
105
+
106
+ doc.add_paragraph("5D Analysis:", style='Heading 3')
107
+ five_d = a.get('5D', {})
108
+ for d_key in ["Detect","Deter","Deny","Deliver","Destroy"]:
109
+ doc.add_paragraph(f"- {d_key}: {five_d.get(d_key,'')}", style='List Bullet')
110
+
111
+ doc.add_paragraph("Recommended Actions:", style='Heading 3')
112
+ if a.get('recommended_actions'):
113
+ for rec in a.get('recommended_actions', []):
114
+ doc.add_paragraph(f"- {rec}", style='List Bullet')
115
  else:
116
+ doc.add_paragraph("- None provided / pending analysis", style='List Bullet')
117
+
118
+ confidence = a.get('confidence', {})
119
+ doc.add_paragraph(f"Confidence Level: {confidence.get('level','Unknown')}", style='Normal')
120
+ doc.add_paragraph(f"Reason: {confidence.get('reason','')}", style='Normal')
121
+ doc.add_paragraph("\n", style='Normal')
122
+
123
+ # MDMP Summary
124
+ doc.add_heading("MDMP Summary", level=1)
125
+ mdmp_summary = f"""
126
+ MDMP Step Summary:
127
+ 1. Intelligence requirements derived from all {len(MILITARY_INTEL_TECHNIQUES)} disciplines.
128
+ 2. Threat courses of action evaluated using 5D framework.
129
+ 3. Red / Blue Team comparisons generated for decision support.
130
+ 4. Recommended defensive COAs prioritized for implementation.
131
+ """
132
+ doc.add_paragraph(mdmp_summary, style='Normal')
133
+
134
+ doc.save(filename)
135
+ return filename
136
+
137
+ # -------------------------
138
+ # FULL ANALYSIS ENGINE
139
+ # -------------------------
140
+ def run_full_analysis(problem_text):
141
+ analyses = []
142
+ with concurrent.futures.ThreadPoolExecutor(max_workers=7) as executor:
143
+ futures = {executor.submit(apply_5d_to_technique, tech, problem_text): tech for tech in MILITARY_INTEL_TECHNIQUES}
144
+ for future in concurrent.futures.as_completed(futures):
145
+ analyses.append(future.result())
146
+
147
+ fused = "\n\n".join([
148
+ f"{i+1}. {a.get('technique','Unknown')}\nFindings: {a.get('findings','')}"
149
+ for i, a in enumerate(analyses)
150
+ ])
151
+
152
+ mdmp = f"""
153
+ MDMP Step Summary:
154
+ 1. Intelligence requirements synthesized across all {len(MILITARY_INTEL_TECHNIQUES)} methods.
155
+ 2. Defensive COAs refined via 5D reasoning.
156
+ 3. Enemy indicators and vulnerabilities mapped.
157
+ 4. Final recommendations structured for command review.
158
+ """
159
+ report_text = f"=== Combined Analysis ===\n{fused}\n\n=== MDMP Summary ===\n{mdmp}"
160
+ return report_text, analyses, fused, mdmp
161
+
162
+ # -------------------------
163
+ # GRADIO UI
164
+ # -------------------------
165
+ def analyze_problem(problem_text):
166
+ if not problem_text.strip():
167
+ problem_text = "Default scenario: enemy infiltration risk in forward area; develop full intelligence picture."
168
+ report_text, analyses, fused, mdmp = run_full_analysis(problem_text)
169
+ filename = save_docx(report_text, analyses)
170
+ return filename
171
+
172
+ demo = gr.Interface(
173
+ fn=analyze_problem,
174
+ inputs=gr.Textbox(label="Enter Operational Problem or Training Scenario", lines=10),
175
+ outputs=gr.File(label="Download Intelligence Report"),
176
+ title="ARMYINTEL 5D–MDMP Intelligence Engine",
177
+ description="Enter any enemy or threat-related situation to generate a structured military intelligence report using 21 collection techniques and the 5D + MDMP frameworks."
178
  )
179
 
180
+ if __name__ == "__main__":
181
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=True)