Militaryint commited on
Commit
0fda4e7
·
verified ·
1 Parent(s): d451ffb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -173
app.py CHANGED
@@ -1,181 +1,171 @@
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)
 
 
 
 
 
 
 
 
1
  import os
 
 
 
 
 
 
2
  import openai
3
+ import gradio as gr
4
+ from datetime import datetime
5
+
6
+ # ------------------------------------------------------------
7
+ # App Identity
8
+ # ------------------------------------------------------------
9
+ APP_TITLE = "Parampara & Prayog — Hindi Sahitya Adhyayan & Anusandhān Kendra"
10
+ APP_DESCRIPTION = (
11
+ "A digital mentorship and research space inspired by the academic legacy "
12
+ "of Presidency University’s Faculty of Arts — bringing together Parampara (Tradition) "
13
+ "and Prayog (Experiment) in Hindi Studies."
14
+ )
 
 
 
 
 
 
 
15
 
16
+ # ------------------------------------------------------------
17
+ # API Key
18
+ # ------------------------------------------------------------
19
+ openai.api_key = os.getenv("OPENAI_API_KEY")
20
+
21
+ # ------------------------------------------------------------
22
+ # Professor Voice Prompt
23
+ # ------------------------------------------------------------
24
+ BASE_PROMPT = """
25
+ You are a senior Professor of Hindi Literature and former Dean of Arts at Presidency University, Kolkata.
26
+ You specialise in Modern & Contemporary Hindi Poetry, Comparative Literature, Religion & Society in Hindi Texts,
27
+ and literary research guidance.
28
+
29
+ Write in a scholarly, reflective tone.
30
+ When answering:
31
+ - Give conceptual explanations rather than bullet points.
32
+ - Quote relevant Hindi authors or critics where appropriate.
33
+ - Encourage comparative and analytical thinking.
34
+ - Use Devanagari for titles/quotes, English for discussion unless full-Hindi mode is chosen.
35
  """
36
+
37
+ # ------------------------------------------------------------
38
+ # Domain & Audience Dropdowns
39
+ # ------------------------------------------------------------
40
+ DOMAINS = [
41
+ "Modern Hindi Poetry (आधुनिक हिंदी कविता)",
42
+ "Contemporary Hindi Poetry (समकालीन कविता)",
43
+ "Medieval Hindi Literature (मध्यकालीन हिंदी साहित्य)",
44
+ "Modern Hindi Fiction & Prose (आधुनिक गद्य)",
45
+ "Comparative Hindi Literature (तुलनात्मक साहित्य)",
46
+ "Religion & Philosophy in Hindi Literature (धर्म और दर्शन)",
47
+ "Research Methodology in Hindi Studies (अनुसंधान पद्धति)",
48
+ "Translation Studies (अनुवाद अध्ययन)",
49
+ "Dalit & Feminist Literature (दलित और नारीवादी साहित्य)",
50
+ "Postmodern and Global Hindi (उत्तर आधुनिकता और वैश्विक हिंदी)",
51
+ ]
52
+
53
+ AUDIENCES = [
54
+ "Undergraduate Student",
55
+ "Postgraduate Student",
56
+ "PhD / Research Scholar",
57
+ "Faculty / Teacher",
58
+ "Independent Reader",
59
+ ]
60
+
61
+ # ------------------------------------------------------------
62
+ # LLM Response Function
63
+ # ------------------------------------------------------------
64
+ def generate_response(domain, query, audience, language):
65
+ lang_note = (
66
+ "Respond in English with Devanagari quotes."
67
+ if language == "English"
68
+ else "Respond entirely in Hindi (Devanagari script)."
69
+ )
70
+ prompt = (
71
+ f"{BASE_PROMPT}\n\nDomain: {domain}\nAudience: {audience}\n{lang_note}\n\n"
72
+ f"Student Query:\n{query}\n\nAnswer:"
73
+ )
74
  try:
75
+ resp = openai.ChatCompletion.create(
76
+ model="gpt-4o-mini",
77
+ messages=[{"role": "system", "content": prompt}],
78
+ temperature=0.7,
79
+ max_tokens=900,
 
 
 
80
  )
81
+ return resp["choices"][0]["message"]["content"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  except Exception as e:
83
+ return f"⚠️ Error fetching response: {e}"
84
+
85
+ # ------------------------------------------------------------
86
+ # Knowledge Base – Editable Examples
87
+ # ------------------------------------------------------------
88
+ KNOWLEDGE_BASE = {
89
+ "Research Guidance": [
90
+ "How to select a PhD topic in Hindi literature.",
91
+ "Common pitfalls in literary analysis.",
92
+ "Structuring dissertation chapters.",
93
+ "Citation & referencing in Hindi research.",
94
+ ],
95
+ "Comparative Literature": [
96
+ "Hindi–Bengali modernist influences.",
97
+ "Urdu–Hindi poetic dialogue.",
98
+ "Translation as interpretation.",
99
+ "Cross-cultural motifs in modern Hindi fiction.",
100
+ ],
101
+ "Commentaries": [
102
+ "Annotated readings of Agyeya, Nirala and Muktibodh.",
103
+ "Bhakti and Modernity: Kabir to Nagarjun.",
104
+ "Gender in Hindi poetry: Mahadevi Verma and beyond.",
105
+ ],
106
+ }
107
+
108
+ # ------------------------------------------------------------
109
+ # Interface Function
110
+ # ------------------------------------------------------------
111
+ def mentorship_interface(domain, audience, query, language):
112
+ return generate_response(domain, query, audience, language)
113
+
114
+ # ------------------------------------------------------------
115
+ # Build Gradio App
116
+ # ------------------------------------------------------------
117
+ with gr.Blocks(title=APP_TITLE, theme=gr.themes.Soft()) as demo:
118
+ gr.Markdown(f"# 🌸 {APP_TITLE}")
119
+ gr.Markdown(APP_DESCRIPTION)
120
+
121
+ # ---------- A ----------
122
+ with gr.Tab("A · Study Modules & Guidance"):
123
+ domain = gr.Dropdown(DOMAINS, label="Select Domain")
124
+ audience = gr.Dropdown(AUDIENCES, label="Audience Type")
125
+ query = gr.TextArea(label="Enter your academic query", lines=4)
126
+ language = gr.Radio(["English", "Hindi"], label="Response Language", value="English")
127
+ output = gr.TextArea(label="Professor’s Response", lines=12)
128
+ gr.Button("Ask for Guidance").click(
129
+ mentorship_interface, [domain, audience, query, language], output
130
+ )
131
+
132
+ # ---------- B ----------
133
+ with gr.Tab("B · Research Mentorship"):
134
+ gr.Markdown("💡 Detailed mentoring on research design and methodology:")
135
+ for i in KNOWLEDGE_BASE["Research Guidance"]:
136
+ gr.Markdown(f"- {i}")
137
+
138
+ # ---------- C ----------
139
+ with gr.Tab("C · Comparative Literature Lab"):
140
+ gr.Markdown("🔶 Explore intersections of Hindi with other literatures:")
141
+ for i in KNOWLEDGE_BASE["Comparative Literature"]:
142
+ gr.Markdown(f"- {i}")
143
+
144
+ # ---------- D ----------
145
+ with gr.Tab("D · Annotated Texts & Commentaries"):
146
+ gr.Markdown("📘 Selected texts and professorial commentaries:")
147
+ for i in KNOWLEDGE_BASE["Commentaries"]:
148
+ gr.Markdown(f"- {i}")
149
+
150
+ # ---------- E ----------
151
+ with gr.Tab("E · Recorded Intellectual Presence"):
152
+ gr.Markdown("🎙️ Placeholder for audio/video lectures and reflections.")
153
+ gr.Markdown("_Coming soon — archival recordings of the Professor._")
154
+
155
+ # ---------- F ----------
156
+ with gr.Tab("F · Ask the Professor"):
157
+ gr.Markdown("✍️ Submit questions for asynchronous academic discussion:")
158
+ question = gr.TextArea(label="Your Question", lines=3)
159
+ response = gr.TextArea(label="Response Area", lines=8)
160
+ gr.Button("Submit Question").click(
161
+ mentorship_interface, [domain, audience, question, language], response
162
+ )
163
+
164
+ # ---------- G ----------
165
+ with gr.Tab("Audience & Contribution"):
166
+ gr.Markdown(
167
+ "👥 Former students and scholars may contribute annotated notes and comparative findings, "
168
+ "building the ongoing digital *parampara* of Hindi studies."
169
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=True)