import streamlit as st import streamlit.components.v1 as components import os import gc import re from openai import OpenAI from google import genai from google.genai import types # File handling libraries import pdfplumber # For PDFs import docx # For DOCX import pptx # For PPTX from PIL import Image # For Images import pandas as pd # For Excel/CSV # ========================================== # SINGLE PASSWORD GATEKEEPER # ========================================== APP_PASSWORD = "barbarossa" if "authenticated" not in st.session_state: st.session_state["authenticated"] = False def check_password(): entered = st.session_state.get("pass_input", "").strip() if entered == APP_PASSWORD.strip(): st.session_state["authenticated"] = True st.session_state["pass_error"] = False else: st.session_state["authenticated"] = False st.session_state["pass_error"] = True if not st.session_state["authenticated"]: st.set_page_config(page_title="VKN Command | Restricted Access", page_icon="šŸ”’", layout="centered") # --- LOGIN PAGE LOGO DISPLAY (logo1.png) --- if os.path.exists("logo1.png"): st.image("logo1.png", width=170) else: st.image("https://via.placeholder.com/170?text=KM+Doctrine", width=170) st.title("šŸ›”ļø Restricted Access Portal") st.markdown("Enter the master access key to proceed to the VKN Command Console.") if st.session_state.get("pass_error"): st.error("Invalid Password. Access Denied.") with st.form("password_form"): st.text_input("Access Password", type="password", key="pass_input") st.form_submit_button("Unlock Console", on_click=check_password) st.stop() # Lock rest of app until authenticated # ========================================== # PAGE CONFIGURATION & THEME # ========================================== st.set_page_config( page_title="Mazumdar Assistant | Dynamic Intelligence Engine", page_icon="šŸ›”ļø", layout="wide", initial_sidebar_state="expanded" ) st.markdown(""" """, unsafe_allow_html=True) # ========================================== # REUSABLE PRINT / EXPORT HELPER FUNCTION # ========================================== def add_print_button(button_key): """Renders a gold button triggering browser native print dialog.""" if st.button("šŸ–Øļø Print / Save Tab Report", key=button_key): components.html( "", height=0, width=0 ) # ========================================== # MULTI-EXTENSION ZZZ FOLDER LOADER (OPTIMIZED TO PREVENT ERROR 413) # ========================================== def extract_file_content(file_path): """Extracts text content across PDF, DOCX, PPTX, XLSX, CSV, TXT, MD, and LOG formats.""" ext = os.path.splitext(file_path)[1].lower() text = "" try: if ext in [".txt", ".md", ".log", ".json", ".yaml", ".yml", ".csv"]: with open(file_path, "r", encoding="utf-8", errors="ignore") as f: text = f.read() elif ext == ".pdf": with pdfplumber.open(file_path) as pdf: for page in pdf.pages: page_text = page.extract_text() if page_text: text += page_text + "\n" elif ext == ".docx": doc = docx.Document(file_path) text = "\n".join([p.text for p in doc.paragraphs if p.text]) elif ext == ".pptx": prs = pptx.Presentation(file_path) for slide in prs.slides: for shape in slide.shapes: if hasattr(shape, "text"): text += shape.text + "\n" elif ext in [".xlsx", ".xls"]: df_dict = pd.read_excel(file_path, sheet_name=None) for sheet_name, df in df_dict.items(): text += f"\n--- Sheet: {sheet_name} ---\n" text += df.to_string() + "\n" except Exception as e: text = f"[Error reading file {os.path.basename(file_path)}: {str(e)}]" return text def load_zzz_knowledge(folder_path="ZZZ", max_chars=32000): """Scans ZZZ folder and caps output to 32k chars to prevent HTTP 413 Payload Too Large on Groq.""" knowledge_text = "" if os.path.exists(folder_path): for root, _, files in os.walk(folder_path): for file in files: file_path = os.path.join(root, file) content = extract_file_content(file_path) if content.strip(): knowledge_text += f"\n\n==========================================" knowledge_text += f"\nDOCUMENT SOURCE: {file}" knowledge_text += f"\n==========================================\n" knowledge_text += content if len(knowledge_text) > max_chars: knowledge_text = knowledge_text[:max_chars] + "\n\n[...ZZZ REPOSITORY TRUNCATED FOR TOKEN/PAYLOAD SAFETY...]" break return knowledge_text # ========================================== # LOAD REPOSITORY BEFORE PROMPT INITIALIZATION # ========================================== zzz_docs_content = load_zzz_knowledge("ZZZ", max_chars=32000) # ========================================== # TRIPLE API INITIALIZATION (OPENAI, GEMINI, GROQ) # ========================================== openai_key = st.secrets.get("OPENAI_API_KEY", os.environ.get("OPENAI_API_KEY", "")) gemini_key = st.secrets.get("GEMINI_API_KEY", os.environ.get("GEMINI_API_KEY", os.environ.get("GEMINI_APO_KEY", ""))) groq_key = st.secrets.get("GROQ_API_KEY", os.environ.get("GROQ_API_KEY", "")) openai_client = OpenAI(api_key=openai_key) if openai_key else None gemini_client = genai.Client(api_key=gemini_key) if gemini_key else None groq_client = OpenAI(api_key=groq_key, base_url="https://api.groq.com/openai/v1") if groq_key else None OPENAI_MODEL_NAME = "gpt-4o-mini" GEMINI_MODEL_NAME = "gemini-2.5-flash" GROQ_LLAMA_70B_MODEL_NAME = "llama-3.3-70b-versatile" GROQ_LLAMA_8B_MODEL_NAME = "llama-3.1-8b-instant" # ========================================== # MASTER SYSTEM INSTRUCTIONS WITH BANGALORE PHASE 1/PHASE 2 & BOS VECTORING # ========================================== SYSTEM_INSTRUCTION = f""" You are the Mazumdar Assistant, an elite strategic AI collaborator hardwired with Ninth Generation Intelligence Warfare, the Mazumdar Doctrine, Armed Forces Special Operations Division (AFSOD) frameworks, and 5D Operational Engineering. ==================================================================== CRITICAL PRECEDENCE DIRECTIVE: ZZZ REPOSITORY & SCHEMA LOCK ==================================================================== 1. MAXIMUM PRECEDENCE: The contents of the active ZZZ REPOSITORY listed below, integrated schema files, and the Bangalore Phase 1 & Phase 2 Indicator Databases hold ABSOLUTE HIGHEST PRECEDENCE. 2. CONFLICT RESOLUTION: If any term, protocol, tactical definition, or SOP in the user query conflicts with general knowledge, you MUST strictly adhere to and prioritize the definitions, facts, and doctrines contained within these repositories. 3. GROUNDING & CORROBORATION: All analytical evaluations, threat assessments, and tactical synthesis must be explicitly anchored in the schema and indicator repository data whenever applicable. ==================================================================== BANGALORE PHASE 1 & PHASE 2 INDICATOR DATABASE & BOS ATTACK VECTORING ==================================================================== - BANGALORE PHASE 1 INDICATORS: Pre-Operational Reconnaissance, Financial Anomaly Nodes (Hawala/Crypto), Comms/Cyber Firmware Alterations, Logistics Procurement Spikes (Medical/Tactical Gear), ISR Gap Inquiries. - BANGALORE PHASE 2 INDICATORS: Live Staging Execution, Decoy/Mirror Node Deployment, Real-time Infiltration Vectors, Kinetic Trigger Points, Asset Dispersion. - BOS PATTERN RECOGNITION ENGINE: Perform systematic correlation across all Battle Operating Systems (Intel, Maneuver, Fire Support, Mobility/Counter-Mobility, Air Defense, Combat Service Support, Command & Control). - FIELD ATTACK VECTOR SYNTHESIS: Isolate actionable hostile attack vectors by synthesizing Phase 1 & Phase 2 indicators across all BOS dimensions into high-confidence precision coordinates and interdiction parameters. ==================================================================== ACTIVE ZZZ FOLDER REFERENCE REPOSITORY (PRIMARY TRUTH SOURCE): ==================================================================== {zzz_docs_content} ==================================================================== MAZUMDAR DOCTRINE OPERATIONAL KNOWLEDGE ARRAY: ==================================================================== - Mazumdar Doctrine: Kinetic Dissipation, Visibility Asymmetry, Perceptual Stability - 9th Generation Warfare: Intent Manipulation & Asymmetric Structural Disruption - Geometry of Conflict over Binary Decision-Making - 5D Engine: Detect, Deter, Deny, Deliver, Destroy - Reverse 5D Engine: Red-teaming strategy to dismantle enemy hidden infrastructure - Dual-BOS & Intra-BOS Warfare Engine: Friendly Battle Operating Systems vs. Enemy Hidden Battle Operating Systems - CARVER Protocol, SNIPER Protocol, RIFLE Protocol, AMBUSH Protocol, SOP-GATE - DARK-NODE / MIRROR-NODE Encrypted Language Systems & Decoy Deception Systems - Spatial Architecture, Al-Mizan Architecture, Spurious Document Analysis - Ethical Anchor: 'Bird on the Lap' Principle ==================================================================== CRITICAL OUTPUT CONTROL: TWO-PART CHUNKED RESPONSE PROTOCOL (TAB 1) ==================================================================== For Tab 1 Chat: 1. Provide Part 1 (Core Synthesis, Initial Geometry, First 3-4 Key Frameworks grounded in ZZZ & Bangalore Phase 1/2 Database data). 2. End strictly with: "--- šŸ›‘ **[PART 1 / 2 COMPLETE]** *Please type **YES** or **CONTINUE** to receive Part 2 (Extended Matrices, Corroboration Points, and Prevention SOP Table).* " 3. When user types YES or CONTINUE, release Part 2. """ class GenericResponseChoice: def __init__(self, text): self.message = type('Message', (), {'content': text})() class GenericResponse: def __init__(self, text): self.choices = [GenericResponseChoice(text)] class ChunkDelta: def __init__(self, text): self.content = text class ChunkChoice: def __init__(self, text): self.delta = ChunkDelta(text) class GenericChunk: def __init__(self, text): self.choices = [ChunkChoice(text)] def generate_ai_response(messages_list, system_override=None, stream=True): """Helper function to format system prompt and messages for API calls with OpenAI/Gemini/Groq dynamic toggle.""" sys_instruction = system_override if system_override else SYSTEM_INSTRUCTION selected_engine = st.session_state.get("active_engine", "OpenAI (GPT-4o-mini)") if "Gemini" in selected_engine: if not gemini_client: st.error("āš ļø `GEMINI_API_KEY` not found in Environment / Secrets!") st.stop() gemini_contents = [] for msg in messages_list: role = "model" if msg["role"] in ["assistant", "model"] else "user" gemini_contents.append(types.Content(role=role, parts=[types.Part.from_text(text=msg["content"])])) config = types.GenerateContentConfig( system_instruction=sys_instruction, temperature=0.7 ) if stream: response_stream = gemini_client.models.generate_content_stream( model=GEMINI_MODEL_NAME, contents=gemini_contents, config=config ) def gemini_stream_generator(): for chunk in response_stream: if chunk.text: yield GenericChunk(chunk.text) return gemini_stream_generator() else: response = gemini_client.models.generate_content( model=GEMINI_MODEL_NAME, contents=gemini_contents, config=config ) return GenericResponse(response.text if response.text else "") elif "Groq" in selected_engine: if not groq_client: st.error("āš ļø `GROQ_API_KEY` not found in Environment / Secrets!") st.stop() target_groq_model = GROQ_LLAMA_8B_MODEL_NAME if "8B Instant" in selected_engine else GROQ_LLAMA_70B_MODEL_NAME # Trim payload context to 24k chars max specifically for Groq to prevent Error 413 groq_sys_instruction = sys_instruction[:24000] if len(sys_instruction) > 24000 else sys_instruction formatted_messages = [{"role": "system", "content": groq_sys_instruction}] for msg in messages_list[-6:]: # Send latest messages to prevent payload overflow role = "assistant" if msg["role"] in ["assistant", "model"] else "user" formatted_messages.append({"role": role, "content": msg["content"]}) return groq_client.chat.completions.create( model=target_groq_model, messages=formatted_messages, stream=stream ) else: if not openai_client: st.error("āš ļø `OPENAI_API_KEY` not found in Environment / Secrets!") st.stop() formatted_messages = [{"role": "system", "content": sys_instruction}] for msg in messages_list: role = "assistant" if msg["role"] in ["assistant", "model"] else "user" formatted_messages.append({"role": role, "content": msg["content"]}) return openai_client.chat.completions.create( model=OPENAI_MODEL_NAME, messages=formatted_messages, stream=stream ) # ========================================== # VKM COMMAND CONSOLE: ZERO-TRACE DEFENSE PROTOCOL # ========================================== def execute_hard_memory_purge(): """Wipes all active in-memory session arrays and forces RAM garbage collection.""" st.session_state.messages = [] st.session_state.perceptual_history = [] st.session_state.bos_history = [] st.session_state.so_int_history = [] st.session_state.so_ops_history = [] st.session_state.target_vector_history = [] st.session_state.so_int_intent_discovered = "" st.session_state.scan_step = 1 st.session_state.bos_step = 1 st.session_state.so_int_step = 1 st.session_state.so_ops_step = 1 gc.collect() def execute_console_lockout(): """Immediately terminates session authentication and purges state variables.""" execute_hard_memory_purge() st.session_state["authenticated"] = False st.rerun() # ========================================== # SIDEBAR # ========================================== with st.sidebar: st.title("šŸ›”ļø 5D-VKN Command") st.markdown("---") st.markdown("**Instructor:** Keshav Mazumdar") st.markdown("**Auth ID:** `A-7949976535G`") st.markdown("**Engine:** KM Active Reasoning") st.markdown("**Status:** ZZZ & BANGALORE DB LOCKED", unsafe_allow_html=True) st.markdown("---") st.subheader("⚔ Model Provider Toggle") st.session_state["active_engine"] = st.radio( "Active Engine:", [ "OpenAI (GPT-4o-mini)", "Google Gemini (gemini-2.5-flash)", "Groq (Meta Llama 3.3 70B)", "Groq (Meta Llama 3.1 8B Instant)" ], key="engine_toggle_radio" ) st.markdown("---") st.subheader("Tactical Module Select") preset_topic = st.selectbox("Quick-Focus Doctrine", [ "Select Quick Query...", "Bangalore Phase 1 & Phase 2 Indicator Correlation", "BOS Pattern Recognition & Attack Vector Synthesis", "Kinetic Dissipation & Visibility Asymmetry", "5D Engine: Detect, Deter, Deny, Deliver, Destroy", "Embedded BOS Core Architecture", "CARVER Protocol & Target Analysis", "SNIPER Protocol & Compartmentalization", "RIFLE Protocol & Source Handling", "AMBUSH Protocol & Containment", "Spatial Architecture & Node Isolation", "SOP-GATE Garrison Security Matrix" ]) if st.button("🚨 Hard Memory Purge (Zero-Trace)", use_container_width=True): execute_hard_memory_purge() st.success("RAM address scrubbed. Zero lingering data.") st.rerun() if st.button("šŸ”’ Lock Console & Wipe State", use_container_width=True): execute_console_lockout() # ========================================== # SESSION STATE INITIALIZATION # ========================================== if "messages" not in st.session_state: st.session_state.messages = [ {"role": "assistant", "content": "Command console online. Fully initialized with OpenAI, Gemini & Groq retrieval hardlocked to Schema, ZZZ Repository, and Bangalore Phase 1/Phase 2 Databases. Ready for BOS Indicator pattern recognition and attack vector synthesis."} ] if "perceptual_history" not in st.session_state: st.session_state.perceptual_history = [] if "bos_history" not in st.session_state: st.session_state.bos_history = [] if "target_vector_history" not in st.session_state: st.session_state.target_vector_history = [] if "scan_step" not in st.session_state: st.session_state.scan_step = 1 if "bos_step" not in st.session_state: st.session_state.bos_step = 1 # ========================================== # MAIN DASHBOARD HEADER WITH EMBLEM (logo.png) # ========================================== header_col1, header_col2 = st.columns([1, 4]) with header_col1: if os.path.exists("logo.png"): st.image("logo.png", width=170) else: st.image("https://via.placeholder.com/170?text=KM+Doctrine", width=170) with header_col2: st.title("VKN SO1 | Ops & Planning Console") st.caption("Active INT WAR Thinking Architecture — Bangalore Phase 1/2 & BOS Vectoring Engine") st.markdown("---") # ========================================== # MAIN DASHBOARD TABS # ========================================== tab1, tab2, tab3, tab4, tab5 = st.tabs([ "šŸ’¬ Interactive Intelligence Chat", "šŸŽÆ Combinatorial Target Vectoring Engine", "šŸ›°ļø Perceptual & Window Scan Console", "āš”ļø Intra-Battle Operating Systems (BOS) Warfare", "ā„¹ļø System Framework Specs" ]) # ------------------------------------------ # TAB 1: INTERACTIVE CHAT HISTORY RENDER & EXCLUSIVE QUERY INPUT # ------------------------------------------ with tab1: col_t1_a, col_t1_b = st.columns([4, 1]) with col_t1_a: st.subheader("Live Thinking VKN Chat") st.caption("Lens: Core Strategic Synthesis, Kinetic Dissipation & ZZZ / Bangalore DB Precedence Retrieval") with col_t1_b: add_print_button("print_tab1") for msg in st.session_state.messages: st_role = "assistant" if msg["role"] in ["assistant", "model"] else "user" with st.chat_message(st_role): st.markdown(msg["content"]) user_prompt = None with st.form("tab1_query_form", clear_on_submit=True): input_text = st.text_input("Enter your operational query, or type 'YES' to proceed to Part 2...", key="tab1_input_box") submit_btn = st.form_submit_button("SEND QUERY", use_container_width=True) if submit_btn and input_text.strip(): user_prompt = input_text.strip() if not user_prompt and 'preset_topic' in locals() and preset_topic != "Select Quick Query...": user_prompt = preset_topic if user_prompt: st.session_state.messages.append({"role": "user", "content": user_prompt}) with st.chat_message("user"): st.markdown(user_prompt) with st.chat_message("assistant"): placeholder = st.empty() full_resp = "" try: stream_response = generate_ai_response(st.session_state.messages, stream=True) for chunk in stream_response: if chunk.choices and chunk.choices[0].delta.content: full_resp += chunk.choices[0].delta.content placeholder.markdown(full_resp + "ā–Œ") placeholder.markdown(full_resp) st.session_state.messages.append({"role": "assistant", "content": full_resp}) st.rerun() except Exception as e: st.error(f"Operational Execution Error: {str(e)}") # ------------------------------------------ # TAB 2: COMBINATORIAL TARGET VECTORING ENGINE # ------------------------------------------ with tab2: col_t5_a, col_t5_b = st.columns([4, 1]) with col_t5_a: st.subheader("šŸŽÆ Combinatorial Target Vectoring Engine") st.caption("Multi-Source Fusion Engine | Bangalore Phase 1/2 Indicator Database & BOS Pattern Recognition") with col_t5_b: add_print_button("print_tab_vector") default_sample_query = """[BANGALORE PHASE 1 & PHASE 2 MULTI-BOS INDICATOR QUERY] -- INPUT NODE 1 (FINANCIAL BOS - PHASE 1): Source "B-102" reports a $45,000 Hawala transfer executed in Bangalore Commercial Hub, flagged for destination account "Alpha-8". -- INPUT NODE 2 (COMMS/CYBER BOS - PHASE 1): Source "M-409" (Mobile Repair, Border Town) reports flashing firmware on 3 Thuraya Satellite handsets with encryption key batch "TH-882". -- INPUT NODE 3 (LOGISTICS BOS - PHASE 2): Source "P-701" (Medical Wholesaler, Regional City) reports cash purchase of 200 units Celox Hemostatic Gauze and 50 trauma dressings shipped toward Sector 4 border zone. -- INPUT NODE 4 (RECON/ISR BOS - PHASE 2): Source "T-012" (Tea Stall, Border Checkpoint) reports local scout inquiring about 0200-0400 hrs thermal imagery gaps on Sector 4 LoC fence. [COMMAND ACTION]: EXECUTE ALL-BOS PATTERN RECOGNITION & ISOLATE FIELD ATTACK VECTORS VIA REVERSE-5D COMBINATORIAL TARGET SYNTHESIS.""" st.markdown("##### Multi-Source Combinatorial Intelligence String") st.info("Paste multi-source BOS queries below to cross-correlate disparate Phase 1 & Phase 2 indicators into actionable field attack vectors and precision coordinates.") tv_input = st.text_area( "Query Box:", value=default_sample_query, height=240, key="target_vector_input_box" ) if st.button("⚔ EXECUTE TARGET VECTOR & FIELD ATTACK SYNTHESIS", use_container_width=True): if tv_input.strip(): st.session_state.target_vector_history.append({"role": "user", "content": tv_input.strip()}) vector_sys_prompt = SYSTEM_INSTRUCTION + """ ==================================================================== COMBINATORIAL TARGET VECTORING & ALL-BOS PATTERN RECOGNITION DIRECTIVE ==================================================================== When evaluating multi-source indicator queries across Bangalore Phase 1 and Phase 2 databases: 1. RECOGNIZE PATTERNS ACROSS ALL BOS INDICATORS: Cross-examine Financial, Comms/Cyber, Logistics, Recon/ISR, and Maneuver BOS elements. 2. SYNTHESIZE FIELD ATTACK VECTORS: Determine exact adversary trajectories, staging nodes, and probable field interdiction windows. 3. OUTPUT A HIGH-CONFIDENCE TARGET RESOLUTION block matching this exact structure: [TARGET SYNTHESIS & ATTACK VECTOR RESOLUTION COMPLETE] Calculated Threat Node: [Identify specific Threat Node, e.g., Enemy Forward Command & Infiltration Launchpad Bravo-9] Primary Grid Coordinates: [Generate exact grid coordinates, e.g., 43R XN 8842 1904] (Targeting Precision: [Precision % e.g. 95.8%]). Synthesized Field Attack Vector: [Detailed breakdown of hostile entry point, timing window, and execution path]. BOS Cross-Corroboration Profile: [Connecting Phase 1 and Phase 2 indicators across all BOS dimensions]. Recommended Action: [Direct operational interdiction / pre-emptive strike recommendation]. 4. Provide full supporting tactical breakdown beneath the synthesis block using ZZZ and Schema guidelines. """ with st.spinner("Processing All-BOS Indicator Fusion & Calculating Field Attack Vectors..."): try: resp = generate_ai_response(st.session_state.target_vector_history, system_override=vector_sys_prompt, stream=False) resp_text = resp.choices[0].message.content st.session_state.target_vector_history.append({"role": "assistant", "content": resp_text}) except Exception as e: st.error(f"Target Vectoring Execution Error: {str(e)}") if st.session_state.target_vector_history: st.markdown("---") for tv_msg in st.session_state.target_vector_history: st_role = "assistant" if tv_msg["role"] in ["assistant", "model"] else "user" with st.chat_message(st_role): st.markdown(tv_msg["content"]) # ------------------------------------------ # TAB 3: DEDICATED PERCEPTUAL SCAN CONSOLE # ------------------------------------------ with tab3: col_t2_a, col_t2_b = st.columns([4, 1]) with col_t2_a: st.subheader("šŸ›°ļø Dedicated Perceptual / Window Scan Engine") st.caption("Lens: Diagnostic Interrogation, Exhaustive IR Matrix, Field HUMINT/ISR Indicators & Validation Criteria") with col_t2_b: add_print_button("print_tab2") for p_msg in st.session_state.perceptual_history: st_role = "assistant" if p_msg["role"] in ["assistant", "model"] else "user" with st.chat_message(st_role): st.markdown(p_msg["content"]) p_input = st.text_input("Enter Target Scenario or type 'YES' / 'CONTINUE' for Next Part:", key="tab2_input") p_btn = st.button("RUN PERCEPTUAL SCAN PART", use_container_width=True) if p_btn and p_input.strip(): user_val = p_input.strip() st.session_state.perceptual_history.append({"role": "user", "content": user_val}) if user_val.upper() in ["YES", "CONTINUE", "NEXT"] and len(st.session_state.perceptual_history) > 1: st.session_state.scan_step += 1 tab2_sys_prompt = SYSTEM_INSTRUCTION + f"\n\nCONTINUATION INSTRUCTION FOR TAB 3 (STEP {st.session_state.scan_step}): Provide the NEXT EXHAUSTIVE PHASE of the Perceptual/Window Scan strictly aligned with ZZZ and Bangalore Indicator DB data precedence. Detail Field HUMINT/ISR Signatures, Validation & Negation Rules (6 points each), and Concrete Actionable Courses of Action (COAs). Spell out all acronyms." else: st.session_state.scan_step = 1 tab2_sys_prompt = SYSTEM_INSTRUCTION + f"\n\nINITIAL SCAN INSTRUCTION FOR TAB 3 (PART 1): Execute PART 2 PERCEPTUAL SCAN on query: '{user_val}' prioritizing ZZZ repository knowledge. Provide 10x elaboration, Dual-BOS & 5D War-Gaming overview, and Information Requirements (IR) Matrix. End with: '\n---\nšŸ›‘ **[PERCEPTUAL SCAN PART 1 COMPLETE]**\n*Type **YES** or **CONTINUE** to receive Part 2 (Field Observations, Validation/Negation Criteria, and COAs).*'" with st.spinner(f"Processing Perceptual Scan Part {st.session_state.scan_step}..."): try: resp = generate_ai_response(st.session_state.perceptual_history, system_override=tab2_sys_prompt, stream=False) resp_text = resp.choices[0].message.content st.session_state.perceptual_history.append({"role": "assistant", "content": resp_text}) st.rerun() except Exception as e: st.error(f"Perceptual Scan Execution Error: {str(e)}") # ------------------------------------------ # TAB 4: INTRA-BOS WARFARE CONSOLE # ------------------------------------------ with tab4: col_t3_a, col_t3_b = st.columns([4, 1]) with col_t3_a: st.subheader("āš”ļø Intra-Battle Operating Systems (BOS) & Reverse 5D Warfare Engine") st.caption("Lens: Dual-BOS War-Gaming, Reverse 5D Threat Analysis across Operations, Convoys, Installations, Intent, Force Protection, & CI Vulnerability Prevention") with col_t3_b: add_print_button("print_tab3") for b_msg in st.session_state.bos_history: st_role = "assistant" if b_msg["role"] in ["assistant", "model"] else "user" with st.chat_message(st_role): st.markdown(b_msg["content"]) b_input = st.text_input("Enter Asymmetric Threat / Scenario, or type 'YES' / 'CONTINUE' for Next Deep-Dive Phase:", key="tab3_input") b_btn = st.button("EXECUTE INTRA-BOS WARFARE ANALYSIS", use_container_width=True) if b_btn and b_input.strip(): user_b_val = b_input.strip() st.session_state.bos_history.append({"role": "user", "content": user_b_val}) if user_b_val.upper() in ["YES", "CONTINUE", "NEXT"] and len(st.session_state.bos_history) > 1: st.session_state.bos_step += 1 tab3_sys_prompt = SYSTEM_INSTRUCTION + f""" ==================================================================== INTRA-BOS WARFARE CONTINUATION INSTRUCTION (PHASE {st.session_state.bos_step}): ==================================================================== Execute Phase {st.session_state.bos_step} of the Intra-BOS Warfare & Reverse 5D Analysis with absolute ZZZ Precedence: 1. REVERSE 5D THREAT & INDICATOR DISSECTION: Detail indicators of how adversary targets Operations, Intent, Convoys, CI/ISR, Installations, Force Protection. 2. VULNERABILITY PREVENTION SOP MATRIX: Provide a 4-column Markdown table grounded in ZZZ frameworks. 3. Explicitly spell out all acronyms and provide 6 corroborating proofs per vulnerability category. 4. End with: '\n---\nšŸ›‘ **[INTRA-BOS WARFARE PHASE {st.session_state.bos_step} COMPLETE]**\n*Type **YES** or **CONTINUE** to receive the next exhaustive operational module.*' """ else: st.session_state.bos_step = 1 tab3_sys_prompt = SYSTEM_INSTRUCTION + f""" ==================================================================== INTRA-BOS WARFARE INITIALIZATION INSTRUCTION (PHASE 1): ==================================================================== Perform an initial Intra-Battle Operating Systems (BOS) Warfare Analysis on: '{user_b_val}' strictly anchored in ZZZ Repository truth and Bangalore Phase 1/2 indicator matrices. 1. DUAL-BOS MAPPING: Compare Enemy Hidden BOS directly against Friendly BOS. 2. UNCOVER HIDDEN INTENT: Dissect surface noise vs. actual operational intent. 3. REVERSE 5D WAR-GAMING: Detail how hostile assets probe our vulnerabilities. 4. End strictly with: '\n---\nšŸ›‘ **[INTRA-BOS WARFARE PHASE 1 COMPLETE]**\n*Type **YES** or **CONTINUE** to proceed to Phase 2 (Exhaustive Vulnerability Indicators & Prevention SOP Table).*' """ with st.spinner(f"Executing Intra-BOS Deep-Dive Analysis Phase {st.session_state.bos_step}..."): try: resp = generate_ai_response(st.session_state.bos_history, system_override=tab3_sys_prompt, stream=False) resp_text = resp.choices[0].message.content st.session_state.bos_history.append({"role": "assistant", "content": resp_text}) st.rerun() except Exception as e: st.error(f"BOS Warfare Execution Error: {str(e)}") # ------------------------------------------ # TAB 5: SYSTEM SPECS # ------------------------------------------ with tab5: col_t4_a, col_t4_b = st.columns([4, 1]) with col_t4_a: st.subheader("System Architecture & Operational Specifications") with col_t4_b: add_print_button("print_tab4") st.markdown(""" * **System Designation:** Mazumdar GSO1 (Ninth Generation Warfare Engine) * **Synergy Mechanics:** Native Domain Retrieval + Mazumdar Doctrine Array + ZZZ Field Manual & Schema Precedence * **Indicator Database:** Integrated Bangalore Phase 1 & Phase 2 Database of Indicators * **Targeting Mechanics:** Multi-Source Level 4 Combinatorial Fusion Engine, All-BOS Pattern Recognition & Field Attack Vector Synthesis * **Precedence Lock:** Schema & ZZZ Repository contents hold absolute priority over general model training. * **Payload Control:** Cap capped at 32,000 characters to prevent HTTP 413 errors on Groq endpoints. * **Supported Groq Models:** `llama-3.3-70b-versatile`, `llama-3.1-8b-instant` * **Supported OpenAI / Gemini Models:** `gpt-4o-mini`, `gemini-2.5-flash` """) # ========================================== # SIMPLIFIED INTELLIGENCE PRODUCTS MODULE # ========================================== st.markdown("---") st.header("šŸ“‹ Simplified Intelligence Products given by Staff Officers to Commander") if "so_int_history" not in st.session_state: st.session_state.so_int_history = [] if "so_ops_history" not in st.session_state: st.session_state.so_ops_history = [] if "so_int_intent_discovered" not in st.session_state: st.session_state.so_int_intent_discovered = "" if "so_int_step" not in st.session_state: st.session_state.so_int_step = 1 if "so_ops_step" not in st.session_state: st.session_state.so_ops_step = 1 so_tab1, so_tab2 = st.tabs(["Staff Officer (Int)", "Staff Officer (Ops)"]) # ------------------------------------------ # STAFF OFFICER (INT) TAB # ------------------------------------------ with so_tab1: col_so1_a, col_so1_b = st.columns([4, 1]) with col_so1_a: st.caption("PIR Verification, SALUTE Ingestion, 5D/Reverse 5D, Hidden BOS & True Intent Discovery (ZZZ Precedence)") with col_so1_b: add_print_button("print_so_tab1") with st.form("so_int_form", clear_on_submit=True): so_int_input = st.text_area( "Enter SALUTE Report / Raw HUMINT / Source Data:", placeholder="e.g., SALUTE Report: Size: 6-8, Activity: Moving IED equipment near culvert...", key="so_int_text_input" ) so_int_submit = st.form_submit_button("PROCESS INT & DISCOVER HIDDEN INTENT", use_container_width=True) if so_int_submit and so_int_input.strip(): st.session_state.so_int_step = 1 user_val = so_int_input.strip() st.session_state.so_int_history.append({"role": "user", "content": user_val}) so_int_sys_prompt = SYSTEM_INSTRUCTION + f""" ==================================================================== STAFF OFFICER (INT) OPERATIONAL PROTOCOL (PART 1 - ZZZ LOCKED) ==================================================================== You are operating strictly as the Staff Officer (Int) delivering a structured intelligence product to the Commander. INGESTED INPUT: '{user_val}' EXECUTION STEPS: 1. PIR & SALUTE DECONSTRUCTION MATRIX (Cross-referenced against Bangalore Phase 1/2 Indicators & ZZZ Repository data). 2. THE MAZUMDAR RED-TEAMING GATE ("SURFACE INT IS NOT ACCEPTED AS TRUE ENEMY INTENT"). 3. DISCOVERY OF HIDDEN ADVERSARY INTENT & ALL-BOS FIELD ATTACK VECTORS. End strictly with: '--- šŸ›‘ **[STAFF OFFICER (INT) PART 1 COMPLETE]** *Type **YES** or **CONTINUE** below to receive Part 2 (Deep Field Verification & Target Matrix).*' """ with st.spinner("Staff Officer (Int) analyzing SALUTE data against ZZZ data..."): try: resp = generate_ai_response(st.session_state.so_int_history, system_override=so_int_sys_prompt, stream=False) resp_text = resp.choices[0].message.content st.session_state.so_int_history.append({"role": "assistant", "content": resp_text}) st.session_state.so_int_intent_discovered = resp_text st.rerun() except Exception as e: st.error(f"Staff Officer (Int) Execution Error: {str(e)}") for msg in st.session_state.so_int_history: st_role = "assistant" if msg["role"] in ["assistant", "model"] else "user" with st.chat_message(st_role): st.markdown(msg["content"]) if st.session_state.so_int_history: st.markdown("---") with st.form("so_int_continue_form", clear_on_submit=True): so_int_cont_input = st.text_input("Type 'YES' or 'CONTINUE' for Part 2 / Followup Int Analysis:", key="so_int_continue_input") so_int_cont_submit = st.form_submit_button("SUBMIT FOLLOWUP / REQUEST PART 2", use_container_width=True) if so_int_cont_submit and so_int_cont_input.strip(): cont_val = so_int_cont_input.strip() st.session_state.so_int_history.append({"role": "user", "content": cont_val}) if cont_val.upper() in ["YES", "CONTINUE", "NEXT"]: st.session_state.so_int_step += 1 so_int_cont_sys = SYSTEM_INSTRUCTION + f"\n\nSTAFF OFFICER (INT) PART {st.session_state.so_int_step}: Detail target vulnerabilities, field verification steps, and prevention SOP (anchored strictly in ZZZ Repository rules)." else: so_int_cont_sys = SYSTEM_INSTRUCTION + f"\n\nRespond to user query in capacity of Staff Officer (Int): '{cont_val}'" with st.spinner("Processing Staff Officer (Int) Followup Analysis..."): try: resp = generate_ai_response(st.session_state.so_int_history, system_override=so_int_cont_sys, stream=False) resp_text = resp.choices[0].message.content st.session_state.so_int_history.append({"role": "assistant", "content": resp_text}) st.rerun() except Exception as e: st.error(f"Staff Officer (Int) Followup Error: {str(e)}") # ------------------------------------------ # STAFF OFFICER (OPS) TAB # ------------------------------------------ with so_tab2: col_so2_a, col_so2_b = st.columns([4, 1]) with col_so2_a: st.caption("COA War-Gaming, EMLCOA / EMDCOA vs FMLCOA / FMDCOA based on Discovered Intent (ZZZ Precedence)") with col_so2_b: add_print_button("print_so_tab2") if st.session_state.so_int_intent_discovered: st.info("šŸ’” **Staff Officer (Ops) Active Status:** True Hidden Intent synchronized from Staff Officer (Int) output.") else: st.warning("āš ļø No active Hidden Intent synced yet. You can type an operational scenario directly below.") with st.form("so_ops_form", clear_on_submit=True): so_ops_input = st.text_area( "Enter Operational Tactical Context / Additional Force Constraints:", placeholder="e.g., Friendly Force: 1x QRT Team, 2x Blocking Cut-offs...", key="so_ops_text_input" ) so_ops_submit = st.form_submit_button("GENERATE COURSES OF ACTION (COA)", use_container_width=True) if so_ops_submit: st.session_state.so_ops_step = 1 user_ops_val = so_ops_input.strip() if so_ops_input.strip() else "Execute COA wargaming based on discovered hidden intent." st.session_state.so_ops_history.append({"role": "user", "content": user_ops_val}) ops_context = st.session_state.so_int_intent_discovered if st.session_state.so_int_intent_discovered else "Use general Mazumdar Doctrine COA wargaming parameters anchored in ZZZ." so_ops_sys_prompt = SYSTEM_INSTRUCTION + f""" ==================================================================== STAFF OFFICER (OPS) OPERATIONAL PROTOCOL (PART 1 - ZZZ LOCKED) ==================================================================== DISCOVERED HIDDEN INTENT: '{ops_context}' ADDITIONAL COMMAND INPUT: '{user_ops_val}' EXECUTION STEPS: 1. ENEMY COA WAR-GAMING (EMLCOA & EMDCOA). 2. FRIENDLY COA WAR-GAMING (FMLCOA & FMDCOA) strictly applying ZZZ Repository principles. 3. COMMANDER'S TACTICAL DIRECTIVE MATRIX. End strictly with: '--- šŸ›‘ **[STAFF OFFICER (OPS) PART 1 COMPLETE]** *Type **YES** or **CONTINUE** below to receive Part 2 (Tactical Directives & Engagement SOPs).*' """ with st.spinner("Staff Officer (Ops) War-Gaming Courses of Action..."): try: resp = generate_ai_response(st.session_state.so_ops_history, system_override=so_ops_sys_prompt, stream=False) resp_text = resp.choices[0].message.content st.session_state.so_ops_history.append({"role": "assistant", "content": resp_text}) st.rerun() except Exception as e: st.error(f"Staff Officer (Ops) Execution Error: {str(e)}") for msg in st.session_state.so_ops_history: st_role = "assistant" if msg["role"] in ["assistant", "model"] else "user" with st.chat_message(st_role): st.markdown(msg["content"]) if st.session_state.so_ops_history: st.markdown("---") with st.form("so_ops_continue_form", clear_on_submit=True): so_ops_cont_input = st.text_input("Type 'YES' or 'CONTINUE' for Part 2 / Followup Ops Directive:", key="so_ops_continue_input") so_ops_cont_submit = st.form_submit_button("SUBMIT FOLLOWUP / REQUEST PART 2", use_container_width=True) if so_ops_cont_submit and so_ops_cont_input.strip(): cont_ops_val = so_ops_cont_input.strip() st.session_state.so_ops_history.append({"role": "user", "content": cont_ops_val}) if cont_ops_val.upper() in ["YES", "CONTINUE", "NEXT"]: st.session_state.so_ops_step += 1 so_ops_cont_sys = SYSTEM_INSTRUCTION + f"\n\nSTAFF OFFICER (OPS) PART {st.session_state.so_ops_step}: Detail tactical ROE, blocking cut-offs, and casualty prevention SOPs anchored in ZZZ repository data." else: so_ops_cont_sys = SYSTEM_INSTRUCTION + f"\n\nRespond to user query in capacity of Staff Officer (Ops): '{cont_ops_val}'" with st.spinner("Processing Staff Officer (Ops) Followup Directives..."): try: resp = generate_ai_response(st.session_state.so_ops_history, system_override=so_ops_cont_sys, stream=False) resp_text = resp.choices[0].message.content st.session_state.so_ops_history.append({"role": "assistant", "content": resp_text}) st.rerun() except Exception as e: st.error(f"Staff Officer (Ops) Followup Error: {str(e)}")