"""AI-BioSecure Morphic Simulation Engine Gray-Scott reaction-diffusion parameterized by cumulative audit data. Palette: governance blue, biosafety cyan, biosecurity crimson, AI safety emerald, compliance gold, ethics violet, dual-use orange. """ from __future__ import annotations import io import numpy as np from PIL import Image, ImageDraw, ImageFilter, ImageFont # ── Audit color palette ──────────────────────────────────────────────────── _BLACK = np.array([5, 5, 10], dtype=np.float32) _SLATE = np.array([15, 20, 35], dtype=np.float32) _BLUE = np.array([40, 90, 210], dtype=np.float32) # governance royal blue _CYAN = np.array([0, 190, 200], dtype=np.float32) # biosafety cyan _TEAL = np.array([0, 140, 150], dtype=np.float32) _CRIMSON = np.array([200, 30, 50], dtype=np.float32) # biosecurity crimson _CHAR = np.array([40, 20, 25], dtype=np.float32) _EMERALD = np.array([20, 190, 110], dtype=np.float32) # AI safety emerald _AMBER = np.array([245, 165, 15], dtype=np.float32) _GOLD = np.array([230, 180, 20], dtype=np.float32) # compliance gold _CREAM = np.array([240, 225, 190], dtype=np.float32) _VIOLET = np.array([140, 60, 220], dtype=np.float32) # ethics violet _MAGENTA = np.array([210, 40, 170], dtype=np.float32) _ORANGE = np.array([245, 120, 20], dtype=np.float32) # dual-use orange _DEEPRED = np.array([170, 20, 20], dtype=np.float32) _WHITE = np.array([235, 240, 255], dtype=np.float32) DOMAIN_PALETTES: dict[str, tuple[np.ndarray, np.ndarray, np.ndarray]] = { "governance": (_BLUE, _SLATE, _WHITE), "biosafety": (_CYAN, _TEAL, _WHITE), "biosecurity": (_CRIMSON, _CHAR, _WHITE), "ai_safety": (_EMERALD, _AMBER, _WHITE), "compliance": (_GOLD, _CREAM, _WHITE), "ethics": (_VIOLET, _MAGENTA, _WHITE), "dual_use": (_ORANGE, _DEEPRED, _WHITE), "default": (_CYAN, _BLUE, _WHITE), } # Domain -> Gray-Scott parameters. # Governance/biosecurity/dual-use (highest-stakes) -> low f, complex labyrinthine. # Compliance/biosafety (procedural) -> higher f, spotted/defined. DOMAIN_PARAMS: dict[str, tuple[float, float]] = { "governance": (0.026, 0.053), "biosafety": (0.037, 0.061), "biosecurity": (0.024, 0.055), "ai_safety": (0.033, 0.058), "compliance": (0.040, 0.062), "ethics": (0.029, 0.057), "dual_use": (0.023, 0.054), "default": (0.037, 0.060), } # ── Color LUT builder ───────────────────────────────────────────────────────── def build_lut(c1: np.ndarray, c2: np.ndarray, c3: np.ndarray) -> np.ndarray: """Build 256x3 uint8 LUT: black -> slate -> c1 -> c2 -> c3 -> white.""" stops = [ (0, _BLACK), (45, _SLATE), (90, c1 * 0.5), (130, c1), (170, c2), (210, c3 * 0.9), (245, c3), (255, _WHITE), ] lut = np.zeros((256, 3), dtype=np.float32) for i in range(len(stops) - 1): i0, a = stops[i] i1, b = stops[i + 1] span = i1 - i0 for j in range(i0, i1): t = (j - i0) / span lut[j] = a * (1 - t) + b * t lut[255] = _WHITE return np.clip(lut, 0, 255).astype(np.uint8) # ── Gray-Scott engine ───────────────────────────────────────────────────────── def _laplacian(z: np.ndarray) -> np.ndarray: return ( np.roll(z, 1, 0) + np.roll(z, -1, 0) + np.roll(z, 1, 1) + np.roll(z, -1, 1) - 4.0 * z ) def run_gray_scott( w: int, h: int, iters: int, feed: float, kill: float, seed: int, n_patches: int, ) -> np.ndarray: rng = np.random.default_rng(seed) u = np.ones((h, w), dtype=np.float32) v = np.zeros((h, w), dtype=np.float32) r = max(5, min(w, h) // 16) for _ in range(n_patches): cx = int(rng.integers(r, w - r)) cy = int(rng.integers(r, h - r)) noise = 0.05 * rng.random((2*r, 2*r)).astype(np.float32) u[cy-r:cy+r, cx-r:cx+r] = 0.50 + noise v[cy-r:cy+r, cx-r:cx+r] = 0.25 + noise Du, Dv = 0.16, 0.08 for _ in range(iters): uvv = u * v * v u += Du * _laplacian(u) - uvv + feed * (1.0 - u) v += Dv * _laplacian(v) + uvv - (feed + kill) * v np.clip(u, 0.0, 1.0, out=u) np.clip(v, 0.0, 1.0, out=v) return v # ── Renderer ────────────────────────────────────────────────────────────────── _FONT = None def _font(size=11): global _FONT if _FONT is None: try: _FONT = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", size) except Exception: _FONT = ImageFont.load_default() return _FONT def _render(v: np.ndarray, lut: np.ndarray, size: int) -> Image.Image: vn = (v - v.min()) / (v.max() - v.min() + 1e-9) vs = np.clip(vn * 1.9 - 0.1, 0.0, 1.0) idx = (vs * 255).astype(np.uint8) rgb = lut[idx] img = Image.fromarray(rgb, "RGB").resize((size, size), Image.BILINEAR) glow = img.filter(ImageFilter.GaussianBlur(3)) return Image.blend(img, glow, 0.3) def _hud(img: Image.Image, domain: str, generation: int, label: str, feed: float, kill: float) -> Image.Image: w, h = img.size draw = ImageDraw.Draw(img, "RGBA") font = _font(11) bracket = (0, 190, 200, 160) blen = 22 for bx, by in [(6, 6), (w-6, 6), (6, h-6), (w-6, h-6)]: sx = 1 if bx < w//2 else -1 sy = 1 if by < h//2 else -1 draw.line([(bx, by), (bx + sx*blen, by)], fill=bracket, width=2) draw.line([(bx, by), (bx, by + sy*blen)], fill=bracket, width=2) draw.rectangle([(0, 0), (w, 26)], fill=(5, 5, 15, 210)) draw.text((10, 6), "AI-BIOSECURE · 2ND BRAIN", fill=(0, 190, 200, 220), font=font) draw.text((w - 72, 6), f"GEN {generation:03d}", fill=(140, 60, 220, 200), font=font) draw.rectangle([(0, h-26), (w, h)], fill=(5, 5, 15, 210)) draw.text((10, h-19), label, fill=(180, 200, 230, 200), font=font) draw.text((w-130, h-19), f"f={feed:.4f} k={kill:.4f}", fill=(80, 120, 180, 160), font=font) domain_colors = { "governance": (40, 90, 210), "biosafety": (0, 190, 200), "biosecurity": (200, 30, 50), "ai_safety": (20, 190, 110), "compliance": (230, 180, 20), "ethics": (140, 60, 220), "dual_use": (245, 120, 20), "default": (100, 140, 255), } dc = domain_colors.get(domain, (100, 140, 255)) draw.rectangle([(w-105, 28), (w-6, 48)], fill=(*dc, 180)) draw.text((w-100, 32), domain[:13].upper(), fill=(255, 255, 255, 230), font=font) return img def generate_audit_image( dominant_domain: str = "default", trust_score: float = 0.70, session_count: int = 1, pattern_generation: int = 1, risk_turbulence: float = 0.5, out_size: int = 512, grid: int = 220, iterations: int = 900, ) -> bytes: base_f, base_k = DOMAIN_PARAMS.get(dominant_domain, DOMAIN_PARAMS["default"]) trust_norm = max(0.0, min(1.0, trust_score)) turb_norm = max(0.0, min(1.0, risk_turbulence)) feed = round(base_f + turb_norm * 0.008, 5) kill = round(base_k + trust_norm * 0.006, 5) seed = (session_count * 17 + pattern_generation * 11 + 7) % (2**31) n_patches = min(2 + session_count // 6, 14) v = run_gray_scott(grid, grid, iterations, feed, kill, seed, n_patches) c1, c2, c3 = DOMAIN_PALETTES.get(dominant_domain, DOMAIN_PALETTES["default"]) lut = build_lut(c1, c2, c3) img = _render(v, lut, out_size) label = f"{dominant_domain} · trust {trust_score:.2f} · turbulence {risk_turbulence:.2f}" img = _hud(img, dominant_domain, pattern_generation, label, feed, kill) buf = io.BytesIO() img.save(buf, "PNG", optimize=True) return buf.getvalue() def generate_audit_heatmap( trust_score_history: list[float], domain_frequency: dict[str, int], out_size: int = 512, ) -> bytes: img = Image.new("RGB", (out_size, out_size), (5, 5, 15)) draw = ImageDraw.Draw(img) font = _font(11) w, h = out_size, out_size draw.rectangle([(0, 0), (w, 30)], fill=(10, 20, 50)) draw.text((10, 8), "AI-BIOSECURE 2ND BRAIN — AUDIT INTELLIGENCE MAP", fill=(0, 190, 200), font=font) pw = w // 2 - 10 strip_top, strip_bot = 50, h - 60 strip_h = strip_bot - strip_top draw.text((10, 36), "TRUST SCORE HISTORY", fill=(80, 140, 220), font=font) hist = trust_score_history[-pw:] if len(trust_score_history) > pw else trust_score_history for i, tv in enumerate(hist): t = max(0.0, min(1.0, tv)) r = int(200 - (200 - 30) * t) g = int(80 + (190 - 80) * t) b = int(80 + (200 - 80) * t) bh = int(strip_h * t) draw.line([(10+i, strip_bot), (10+i, strip_bot - bh)], fill=(r, g, b)) draw.rectangle([(8, strip_top), (10+pw, strip_bot)], outline=(30, 50, 100), width=1) rx = w // 2 + 5 draw.text((rx, 36), "DOMAIN ACTIVITY", fill=(80, 140, 220), font=font) domain_colors_map = { "governance": (40, 90, 210), "biosafety": (0, 190, 200), "biosecurity": (200, 30, 50), "ai_safety": (20, 190, 110), "compliance": (230, 180, 20), "ethics": (140, 60, 220), "dual_use": (245, 120, 20), } mx = max(domain_frequency.values()) if domain_frequency else 1 bw = (w - rx - 15) // max(len(domain_frequency), 1) bx = rx + 5 for domain, n in domain_frequency.items(): ratio = n / max(mx, 1) bh = int((strip_h - 20) * ratio) col = domain_colors_map.get(domain, (100, 140, 220)) draw.rectangle([(bx, strip_bot-bh), (bx+bw-5, strip_bot)], fill=col) draw.text((bx, strip_bot+4), domain[:8], fill=(160, 190, 230), font=font) draw.text((bx, strip_bot-bh-14), str(n), fill=(210, 220, 240), font=font) bx += bw bt = h - 56 draw.text((10, bt-16), "TRUST TREND", fill=(80, 140, 220), font=font) scores = trust_score_history[-(w-20):] if len(trust_score_history) > w-20 else trust_score_history if len(scores) > 1: pts = [(10 + int(i*(w-20)/len(scores)), bt + int((1-s)*40)) for i, s in enumerate(scores)] for i in range(len(pts)-1): draw.line([pts[i], pts[i+1]], fill=(0, 190, 200), width=2) draw.rectangle([(8, bt), (w-8, h-12)], outline=(30, 50, 100), width=1) buf = io.BytesIO() img.save(buf, "PNG", optimize=True) return buf.getvalue()