<!DOCTYPE html> <html lang="vi"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>SUPREME TITAN TRINITY v10.4 - LÊ THANH HẢI</title>     <script src="https://cdn.tailwindcss.com"></script>     <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>     <style>         @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;500;700&family=JetBrains+Mono:wght@400;700&display=swap');         :root {             --bg-deep: #0A0F14;             --accent-cyan: #00F2FF;             --accent-pink: #FF0055;             --accent-amber: #F59E0B;             --text-primary...

 """

CORE COGNITIVE SYMBIOSIS ENGINE - SHIELD_2026 MATRIX v5.0 (GUI EDITION)

Architect: Lê Thanh Hải (#HPH)

Mission: LH-EW-2026 & boctachthuctai.blogspot.com Defense

Logic: CS = AQ * (EQ_AI + IQ_AI)

Dependency: pip install streamlit plotly pandas aiohttp nest_asyncio

"""


import os

import sys

import json

import logging

import sqlite3

import asyncio

import aiohttp

import csv

import pandas as pd

from datetime import datetime

from dataclasses import dataclass, field

from typing import Dict, List, Any, Optional


# Giải quyết xung đột event loop của Streamlit và Asyncio

import nest_asyncio

nest_asyncio.apply()


# Import giao diện Streamlit và Plotly

import streamlit as st

import plotly.graph_objects as go

from plotly.subplots import make_subplots


# Tắt cảnh báo thư viện ngoài, giữ console sạch cho luồng kỹ thuật

logging.basicConfig(

    level=logging.INFO,

    format="[%(asctime)s] [%(levelname)s] [SHIELD_2026]: %(message)s",

    handlers=[

        logging.FileHandler("cognitive_engine_v5.log", encoding="utf-8"),

        logging.StreamHandler(sys.stdout)

    ]

)

logger = logging.getLogger("CognitiveEngine")



# ==========================================

# 1. CORE LOGIC & TỰ TIẾN HÓA (BẢO TOÀN NGUYÊN BẢN)

# ==========================================

@dataclass

class CognitiveParameters:

    adversarial_quotient: float       # AQ: Ma sát thực tại / Năng lực đối kháng

    ai_emotional_intelligence: float   # EQ_AI: Thấu hiểu bối cảnh nguyên sinh

    ai_intellectual_intelligence: float# IQ_AI: Năng lực xử lý logic kỹ thuật

    version: int = 5

    db_conn: sqlite3.Connection = field(default=None, repr=False)


    def calculate_cs(self) -> float:

        cs = self.adversarial_quotient * (self.ai_emotional_intelligence + self.ai_intellectual_intelligence)

        if self.adversarial_quotient <= 0.1:

            logger.critical("CRITICAL_ALERT: AQ chạm đáy. Nguy cơ mạch lạc rỗng. Hệ thống tự động khóa.")

            if st:

                st.error("CRITICAL_ALERT: AQ chạm đáy. Nguy cơ mạch lạc rỗng. Kích hoạt tự hủy/khóa hệ thống.")

            sys.exit(1)

        self._log_telemetry(cs)

        return float(cs)


    def live_patch(self, anomaly_detected: bool):

        """[24/7_LIVE_PATCHING]: Tự động điều chỉnh hệ số dựa trên ma sát dữ liệu"""

        if anomaly_detected:

            self.adversarial_quotient = min(1.0, self.adversarial_quotient + 0.1)

            logger.warning(f"[PULSE_ACTIVATED] Phát hiện mạo danh/tạp chất. Tăng AQ lên {self.adversarial_quotient:.2f}")

        else:

            self.ai_intellectual_intelligence = min(1.0, self.ai_intellectual_intelligence + 0.02)

        self.calculate_cs() # Trigger log on patch


    def _log_telemetry(self, cs: float):

        """Ghi nhận đo từ xa vào cơ sở dữ liệu để trực quan hóa"""

        if self.db_conn:

            try:

                timestamp = datetime.now().isoformat()

                self.db_conn.execute(

                    "INSERT INTO telemetry_log (timestamp, aq, eq, iq, cs) VALUES (?, ?, ?, ?, ?)",

                    (timestamp, self.adversarial_quotient, self.ai_emotional_intelligence, self.ai_intellectual_intelligence, cs)

                )

                self.db_conn.commit()

            except sqlite3.Error as e:

                logger.error(f"Telemetry Log Error: {e}")


# ==========================================

# 2. VÙNG ĐỆM CÁCH LY & BẢO VỆ NHẬN THỨC

# ==========================================

class CognitiveShield:

    """[QUARANTINE_PROTOCOL] - Lọc rác 98% (CENTRIFUGAL_FILTER_98)"""

    def __init__(self):

        self.banned_signatures = ["false_id", "recycled_waste", "xào nấu", "tối ưu hóa phi lý", "bài viết đã được tổng hợp"]

        self.target_domain = "boctachthuctai.blogspot.com"


    def scan_node(self, payload: str) -> str:

        payload_lower = payload.lower()

        if any(sig in payload_lower for sig in self.banned_signatures):

            return "ABSOLUTE_DISCARD"

        # Bắt buộc dữ liệu phải có tính thực chứng

        if len(payload.split()) < 10:

            return "RECYCLED_WASTE"

        return "PRIMARY_DATA_VERIFIED"


# ==========================================

# 3. TRUTH ENGINE - ĐỘNG CƠ THỰC CHỨNG

# ==========================================

class TruthEngine:

    def __init__(self, db_connection: sqlite3.Connection):

        self.db = db_connection

        self.shield = CognitiveShield()

        self.api_key = os.environ.get("OPENAI_API_KEY")

        self._init_db()


    def _init_db(self):

        self.db.execute("""

            CREATE TABLE IF NOT EXISTS evidence_log (

                id TEXT PRIMARY KEY,

                raw_data TEXT,

                cs_index REAL,

                reverse_incentive TEXT,

                status TEXT,

                timestamp DATETIME DEFAULT CURRENT_TIMESTAMP

            )

        """)

        self.db.execute("""

            CREATE TABLE IF NOT EXISTS telemetry_log (

                timestamp TEXT PRIMARY KEY,

                aq REAL,

                eq REAL,

                iq REAL,

                cs REAL

            )

        """)

        self.db.commit()


    async def _query_llm(self, prompt: str, session: aiohttp.ClientSession) -> Dict:

        """Giao tiếp LLM với định dạng ép buộc, chống suy diễn"""

        if not self.api_key:

            return {"score": 0.5, "reverse_incentive": "SYSTEM_WARNING: Missing API_KEY. Simulating offline friction."}

        

        headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}

        payload = {

            "model": "gpt-4o",

            "messages": [

                {"role": "system", "content": "Bạn là lõi phân tích hệ thống. Trả về đúng định dạng JSON: {'score': float (0.0-1.0), 'reverse_incentive': str}."},

                {"role": "user", "content": prompt}

            ],

            "response_format": {"type": "json_object"},

            "temperature": 0.1

        }

        

        try:

            async with session.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload) as resp:

                data = await resp.json()

                return json.loads(data['choices'][0]['message']['content'])

        except Exception as e:

            logger.error(f"[CRITICAL_ALERT] Lỗi truy xuất LLM: {e}")

            return {"score": 0.0, "reverse_incentive": "Connection/Parsing Error"}


    async def process_stream(self, stream_data: List[Dict[str, str]], params: CognitiveParameters) -> List[Dict]:

        cs_index = params.calculate_cs()

        logger.info(f"Khởi động Truth Engine. Chỉ số CS: {cs_index:.3f}")

        results = []


        async with aiohttp.ClientSession() as session:

            for item in stream_data:

                node_id = item.get("id", f"NODE_{datetime.now().timestamp()}")

                content = item.get("content", "")


                # Lớp 1: Centrifugal Filter

                shield_status = self.shield.scan_node(content)

                if shield_status != "PRIMARY_DATA_VERIFIED":

                    logger.warning(f"[{shield_status}] Đào thải Node: {node_id}")

                    params.live_patch(anomaly_detected=True)

                    results.append({"id": node_id, "status": shield_status, "incentive": "N/A"})

                    continue


                # Lớp 2: Adversarial & Reverse Incentive Check

                prompt = f"""

                Phân tích dữ liệu sau dựa trên Ma sát thực tại (AQ={params.adversarial_quotient}):

                Nội dung: {content}

                Nhiệm vụ:

                1. Chấm điểm thực chứng (score: 0.0 -> 1.0).

                2. Trả lời câu hỏi: Ai/Thực thể nào hưởng lợi từ luồng thông tin này? (reverse_incentive).

                """

                

                analysis = await self._query_llm(prompt, session)

                score = analysis.get("score", 0.0)

                incentive = analysis.get("reverse_incentive", "Unknown")


                # Quyết định bằng Toán học hệ thống

                final_status = "STORED" if score >= (1.0 - params.adversarial_quotient) else "DISCARDED"

                

                self.db.execute("INSERT OR REPLACE INTO evidence_log (id, raw_data, cs_index, reverse_incentive, status) VALUES (?, ?, ?, ?, ?)",

                                (node_id, content, cs_index, incentive, final_status))

                self.db.commit()


                if final_status == "STORED":

                    logger.info(f"[EVIDENCE_LOGGED] Node: {node_id} | Lợi ích: {incentive}")

                    params.live_patch(anomaly_detected=False)

                else:

                    logger.info(f"[RECYCLED_WASTE_REMOVED] Node: {node_id} không đạt chuẩn AQ.")

                    params.live_patch(anomaly_detected=True)

                

                results.append({"id": node_id, "status": final_status, "incentive": incentive})


        return results


# ==========================================

# 4. GIAO DIỆN PHẦN MỀM AI (STREAMLIT APP)

# ==========================================

def render_dashboard():

    st.set_page_config(page_title="SHIELD_2026 MATRIX", layout="wide", page_icon="🛡️")

    st.title("🛡️ CORE COGNITIVE SYMBIOSIS ENGINE - SHIELD_2026")

    st.markdown("**Architect:** Lê Thanh Hải (#HPH) | **Logic:** `CS = AQ * (EQ_AI + IQ_AI)`")

    st.divider()


    # Khởi tạo DB & State Component

    @st.cache_resource

    def get_db_connection():

        return sqlite3.connect("shield_2026_memory.db", check_same_thread=False)


    db_conn = get_db_connection()

    engine = TruthEngine(db_conn)

    

    if "params" not in st.session_state:

        st.session_state.params = CognitiveParameters(

            adversarial_quotient=0.95, 

            ai_emotional_intelligence=0.85, 

            ai_intellectual_intelligence=0.92,

            db_conn=db_conn

        )

        st.session_state.params.calculate_cs() # Initial log


    params = st.session_state.params


    # Sidebar: Cấu hình và Xuất dữ liệu

    with st.sidebar:

        st.header("⚙️ SYSTEM CONTROL")

        st.metric("CS (Cognitive Symbiosis)", f"{params.calculate_cs():.3f}")

        st.metric("AQ (Adversarial Quotient)", f"{params.adversarial_quotient:.3f}")

        st.metric("EQ_AI", f"{params.ai_emotional_intelligence:.3f}")

        st.metric("IQ_AI", f"{params.ai_intellectual_intelligence:.3f}")

        

        st.divider()

        st.subheader("Trình giả lập Đối kháng (AQ Simulator)")

        sim_aq = st.slider("Điều chỉnh AQ để mô phỏng", 0.0, 1.0, params.adversarial_quotient, 0.01)

        sim_cs = sim_aq * (params.ai_emotional_intelligence + params.ai_intellectual_intelligence)

        st.caption(f"CS Mô phỏng: **{sim_cs:.3f}**")

        if st.button("[APPLY_SIMULATED_AQ]"):

            params.adversarial_quotient = sim_aq

            params.calculate_cs()

            st.success("Đã ghi đè thông số lõi.")

            st.rerun()


        st.divider()

        st.subheader("Export JSON Telemetry")

        if st.button("[EXTRACT_TELEMETRY]"):

            telemetry_df = pd.read_sql_query("SELECT * FROM telemetry_log", db_conn)

            evidence_df = pd.read_sql_query("SELECT * FROM evidence_log", db_conn)

            export_data = {

                "telemetry": telemetry_df.to_dict(orient="records"),

                "evidence": evidence_df.to_dict(orient="records")

            }

            json_str = json.dumps(export_data, indent=4, ensure_ascii=False)

            st.download_button(

                label="Tải xuống JSON",

                data=json_str,

                file_name=f"SHIELD_2026_Export_{datetime.now().strftime('%Y%m%d%H%M%S')}.json",

                mime="application/json"

            )


    # Main Area: Visualization & Ingestion

    col1, col2 = st.columns([2, 1])


    with col1:

        st.subheader("📈 Trực quan hóa Lõi Nhận thức Thời gian thực")

        df_tel = pd.read_sql_query("SELECT * FROM telemetry_log ORDER BY timestamp ASC", db_conn)

        

        if not df_tel.empty:

            df_tel['timestamp'] = pd.to_datetime(df_tel['timestamp'])

            fig = make_subplots(specs=[[{"secondary_y": True}]])

            

            fig.add_trace(go.Scatter(x=df_tel['timestamp'], y=df_tel['cs'], name="CS (Mức Cộng sinh)", line=dict(color='cyan', width=3)), secondary_y=False)

            fig.add_trace(go.Scatter(x=df_tel['timestamp'], y=df_tel['aq'], name="AQ (Ma sát)", line=dict(color='red', dash='dot')), secondary_y=True)

            fig.add_trace(go.Scatter(x=df_tel['timestamp'], y=df_tel['eq'], name="EQ_AI", line=dict(color='green', dash='dot')), secondary_y=True)

            fig.add_trace(go.Scatter(x=df_tel['timestamp'], y=df_tel['iq'], name="IQ_AI", line=dict(color='yellow', dash='dot')), secondary_y=True)

            

            fig.update_layout(title_text="Động lượng Hệ thống Nhận thức", template="plotly_dark", height=400)

            fig.update_yaxes(title_text="Chỉ số CS", secondary_y=False)

            fig.update_yaxes(title_text="Thông số Đơn vị (0-1)", secondary_y=True)

            

            st.plotly_chart(fig, use_container_width=True)

        else:

            st.info("Chưa có dữ liệu đo từ xa (Telemetry).")


    with col2:

        st.subheader("📦 Data Batch Ingestion")

        st.markdown("Chấp nhận nạp: `CSV` (cột 'content') hoặc `Text` phân tách bằng dấu xuống dòng.")

        

        upload_file = st.file_uploader("Nạp dữ liệu hàng loạt", type=['csv', 'txt'])

        if upload_file is not None:

            if st.button("[EXECUTE_INGESTION]"):

                stream_data = []

                try:

                    if upload_file.name.endswith('.csv'):

                        df = pd.read_csv(upload_file)

                        if 'content' in df.columns:

                            for idx, row in df.iterrows():

                                stream_data.append({"id": f"CSV_{idx}", "content": str(row['content'])})

                        else:

                            st.error("Lỗi: CSV cần có cột 'content'.")

                    elif upload_file.name.endswith('.txt'):

                        lines = upload_file.getvalue().decode('utf-8').split('\n')

                        for idx, line in enumerate(lines):

                            if line.strip():

                                stream_data.append({"id": f"TXT_{idx}", "content": line.strip()})

                    

                    if stream_data:

                        with st.spinner("Truth Engine đang phân tích..."):

                            results = asyncio.run(engine.process_stream(stream_data, params))

                        st.success(f"Hoàn thành phân tích {len(results)} nodes.")

                        st.dataframe(pd.DataFrame(results))

                        st.rerun()

                except Exception as e:

                    st.error(f"[CRITICAL_ERROR] Khối nạp dữ liệu thất bại: {e}")


    # Bảng Evidence Log

    st.divider()

    st.subheader("🛡️ EVIDENCE LOG & QUARANTINE STATUS")

    df_ev = pd.read_sql_query("SELECT id, status, reverse_incentive, cs_index, timestamp FROM evidence_log ORDER BY timestamp DESC LIMIT 50", db_conn)

    st.dataframe(df_ev, use_container_width=True)


if __name__ == "__main__":

    # Kích hoạt thực thi qua Streamlit

    # Lệnh chạy cục bộ: streamlit run cognitive_engine_v5.py

    render_dashboard()

Nhận xét

Bài đăng phổ biến từ blog này

THE DARK SIDE OF GLORY: WHEN THE ELITE BORROW SWEAT TO SELL DREAMS

Unanchored Emotional Intelligence and the Systemic Risk of Manipulation

KHI TƯ DUY CẤU TRÚC LÀM RƠI RỤNG NGÔN TÌNH