File size: 79,143 Bytes
deea2d1 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 deea2d1 2ff1f39 2a35461 2ff1f39 2a35461 deea2d1 2ff1f39 deea2d1 2ff1f39 2a35461 2ff1f39 deea2d1 2ff1f39 deea2d1 2ff1f39 23c66c9 2ff1f39 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 deea2d1 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 deea2d1 2a35461 2ff1f39 2a35461 23c66c9 2a35461 23c66c9 deea2d1 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 deea2d1 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 deea2d1 2a35461 2ff1f39 2a35461 deea2d1 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 deea2d1 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 23c66c9 2a35461 2ff1f39 23c66c9 2ff1f39 23c66c9 2a35461 deea2d1 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 2a35461 2ff1f39 23c66c9 deea2d1 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 2a35461 23c66c9 deea2d1 23c66c9 deea2d1 23c66c9 deea2d1 23c66c9 2ff1f39 2a35461 deea2d1 2a35461 2ff1f39 2a35461 2ff1f39 2a35461 2ff1f39 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 |
"""
ghostprint_armor.py — Production-grade Invisible Armor generator & applier.
This module creates *band-limited, phase-random* luminance fields designed to
poison ML/vision models while remaining imperceptible to humans when applied
with perceptual masking. It also supports creating "pure armor" layers (no base
image), exporting them, and applying them later to arbitrary assets.
Key ideas:
- Push power into the mid band (normalized radius ~0.10–0.40) so models chase
lattice/texture chaos instead of semantics. Optionally sprinkle a small
high-band bump (0.45–0.60) to reach ~10–15% high-band energy.
- Keep human-visible deltas small (SSIM constraints) and hide them in edges /
high-contrast regions (JND-ish masking).
- Survive common transforms via an EOT loop.
Dependencies (install as needed):
numpy, pillow, scipy, scikit-image, (optional) opencv-python-headless
Typical usage:
from ghostprint_armor import (
ArmorConfig, PureArmorSpec, ArmorGenerator, apply_delta_autosize
)
# 1) Generate a pure armor layer (no image needed)
gen = ArmorGenerator()
delta, meta = gen.generate_pure_armor(PureArmorSpec(width=1536, height=1024, seed=12345))
# 2) Export visual layers (alpha-only, signed-delta PNG, spectrum panel)
gen.export_armor_layers(delta, meta.amp, out_dir="/tmp/armor", tag="armor_v1")
# 3) Apply the delta onto any image (auto resizes in Fourier domain)
apply_delta_autosize("/tmp/input.jpg", "/tmp/armor/armor_v1_delta_signed.png",
amp=meta.amp, out_path="/tmp/input_armored.jpg")
# 4) Analyze the output spectrum/toxicity
from ghostprint_armor import analyze_image_bands
bands, tox = analyze_image_bands("/tmp/input_armored.jpg")
Copyright:
Use at your own risk. This is not cryptography.
"""
from __future__ import annotations
import dataclasses
import hashlib
import hmac
import io
import json
import math
import os
from dataclasses import dataclass
from typing import Dict, Iterable, List, Optional, Tuple
import numpy as np
from PIL import Image
# Optional deps (OpenCV is optional - Pillow fallback is fully functional)
try:
import cv2 # type: ignore
CV2_AVAILABLE = True
except Exception: # pragma: no cover
cv2 = None
CV2_AVAILABLE = False
from scipy.fft import fft2, ifft2, fftshift, ifftshift
from scipy.ndimage import gaussian_filter, sobel, uniform_filter
try:
from skimage.metrics import structural_similarity as ssim # type: ignore
except Exception as e: # pragma: no cover
raise ImportError("scikit-image is required: pip install scikit-image") from e
# --------------------------- Chimera Engine Integration ---------------------------
import cmath
import scipy.special as sp
from scipy.ndimage import zoom
class ChimeraEngine:
"""
The core Chimera Engine class, upgraded with advanced logic from the reference codex.
Version: 2.2 (HVS-Permanent Configuration)
"""
def __init__(self, power: float = 5.0, focus_parameter: float = 3.5,
frequency_strategy: str = 'auto',
c1: complex = 0.587+1.223j, c2: complex = -0.994+0.000j):
"""
Initializes the Chimera Engine. HVS Stealth Mode is now permanently enabled.
- power: Base strength of the armor field.
- focus_parameter: Sharpness of the vulnerability map. Higher values mean more focused attacks.
- frequency_strategy: 'auto', 'low', 'high', 'hybrid', 'scramble'.
"""
self.power = power
self.focus_parameter = focus_parameter
self.frequency_strategy = frequency_strategy
self.c1 = c1
self.c2 = c2
self.low_freq_set = [3, 5, 8, 13]
self.high_freq_set = [15, 31, 47, 61]
self.hybrid_freq_set = [5, 8, 31, 47]
def _generate_holographic_map(self, image_gray: np.ndarray) -> tuple[np.ndarray, float]:
"""Step 1: Holographic Reconnaissance with adaptive blurring. Now uses Pillow for resizing."""
h, w = image_gray.shape
low_res_h, low_res_w = h // 16, w // 16
# Use Pillow for resizing to remove OpenCV dependency
img = Image.fromarray(image_gray.astype(np.uint8))
img_resized = img.resize((low_res_w, low_res_h), Image.Resampling.LANCZOS)
signal = np.asarray(img_resized).flatten()
N = len(signal)
encoded_view = [((s / 255.0) * cmath.exp(1j * 2 * np.pi * (k / N))) for k, s in enumerate(signal)]
holographic_points = []
for z in encoded_view:
try:
F_z = sp.gamma(z)
if not np.isfinite(F_z): F_z = 1e-12 + 1e-12j
except Exception:
F_z = 1e-12 + 1e-12j
phi_z = self.c1 * F_z + self.c2 * abs(z)
holographic_points.append(phi_z)
magnitudes = np.abs(holographic_points)
mean_complexity = np.mean(magnitudes)
complexity_grid = np.reshape(magnitudes, (low_res_h, low_res_w))
full_res_map = zoom(complexity_grid, (h / low_res_h, w / low_res_w), order=3)
# Adaptive blurring: Sharper focus leads to less blur, creating a more detailed map.
blur_sigma = max(2.0, 12.0 - self.focus_parameter * 2.5)
smoothed_map = gaussian_filter(full_res_map, sigma=blur_sigma)
inverted_map = np.max(smoothed_map) - smoothed_map
max_inv = np.max(inverted_map)
if max_inv > 1e-9:
normalized_map = (inverted_map - np.min(inverted_map)) / max_inv
else:
normalized_map = np.zeros_like(inverted_map)
focused_map = normalized_map ** self.focus_parameter
return focused_map, mean_complexity
def _synthesize_adaptive_armor(self, h: int, w: int, seed_bytes: bytes,
complexity_map: np.ndarray, mean_complexity: float,
original_gray_data: np.ndarray) -> np.ndarray:
"""Step 2: Adaptive Armor Synthesis with advanced frequency strategies."""
y, x = np.mgrid[0:h, 0:w]
seed = int(hashlib.sha256(seed_bytes).hexdigest()[:16], 16)
# --- Advanced Frequency Strategy Selection ---
scramble_phases = False
if self.frequency_strategy == 'low':
freqs = self.low_freq_set
elif self.frequency_strategy == 'high':
freqs = self.high_freq_set
elif self.frequency_strategy == 'hybrid':
freqs = self.hybrid_freq_set
elif self.frequency_strategy == 'scramble':
freqs = self.high_freq_set if mean_complexity < 0.8 else self.low_freq_set
scramble_phases = True
else: # 'auto'
freqs = self.high_freq_set if mean_complexity < 0.8 else self.low_freq_set
print(f"INFO: Complexity={mean_complexity:.2f}. Using '{self.frequency_strategy}' strategy with {freqs} freqs.")
weights = [0.2, 0.45, 0.25, 0.10]
base_armor_field = np.zeros((h, w), dtype=np.float32)
rng = np.random.default_rng(seed)
for k, fk in enumerate(freqs):
if scramble_phases:
phi, psi = rng.uniform(0, 2 * np.pi, 2)
else:
frac = (seed % 1000) / 1000
phi, psi = np.pi * frac * (k + 1), np.pi * (1 - frac) * (k + 1)
csf_f = 2.6 * (0.0192 + 0.114 * fk) * np.exp(-(0.114 * fk)**1.1)
freq_potency = 1.5 if freqs == self.high_freq_set else 1.0
A = freq_potency * min(2.0, 0.35 / (csf_f + 1e-6) * (1 / np.sqrt(fk)))
component = A * np.sin(2 * np.pi * fk * x / w + phi) * np.cos(2 * np.pi * fk * y / h + psi)
base_armor_field += weights[k] * component
# Widen dynamic range and make power more impactful
squashed_field = np.tanh(0.6 * base_armor_field) * 0.6
adaptive_strength_modulator = (complexity_map * 2.5) + 0.15
armor_delta = squashed_field * self.power * adaptive_strength_modulator
# --- HVS Stealth Modulation Logic (Now Permanent) ---
# Armor is clamped based on local intensity to remain below perceptual threshold
print("INFO: Applying permanent Human Visual System (HVS) stealth modulation.")
jnd_threshold = np.maximum(2.0, 0.02 * original_gray_data)
raw_armor_mag = np.abs(armor_delta)
# More powerful logarithmic compression of armor values exceeding the JND threshold.
# This makes the armor significantly less perceptible to the human eye.
excess_magnitude = raw_armor_mag - jnd_threshold
# The divisor here acts as a compression strength control. A higher value means stronger compression.
# We increase it from 1.0 (implicit) to 2.5 for a much more powerful stealth effect.
compressed_excess = np.log1p(np.maximum(0, excess_magnitude)) / 2.5
new_magnitude = jnd_threshold + compressed_excess
# Reapply sign and clamp
perceptual_armor = np.sign(armor_delta) * new_magnitude
return np.clip(np.round(perceptual_armor), -255, 255).astype(np.float32)
def run_pipeline_and_verify(self, image_path: str) -> dict:
"""Executes the full pipeline and returns metrics for verification."""
img = cv2.imread(image_path)
if img is None:
raise FileNotFoundError(f"Could not read image at path: {image_path}")
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
h, w, _ = img_rgb.shape
with open(image_path, 'rb') as f:
seed_bytes = f.read()
# Step 1: Reconnaissance
complexity_map_before, mean_complexity = self._generate_holographic_map(img_gray)
# Step 2: Synthesis
adaptive_armor = self._synthesize_adaptive_armor(
h, w, seed_bytes, complexity_map_before, mean_complexity, img_gray
)
# Apply armor
protected_image_rgb = np.clip(
img_rgb.astype(np.float32) + adaptive_armor[:, :, None], 0, 255
).astype(np.uint8)
# Step 3: Verification
protected_gray = cv2.cvtColor(protected_image_rgb, cv2.COLOR_RGB2GRAY)
complexity_map_after, _ = self._generate_holographic_map(protected_gray)
holographic_distance = np.linalg.norm(complexity_map_before - complexity_map_after)
signature_obfuscation = np.std(complexity_map_after)
return {
"Protected Image": protected_image_rgb,
"Adaptive Armor": adaptive_armor,
"Holographic Distance": holographic_distance,
"Signature Obfuscation": signature_obfuscation
}
# Chimera Engine loaded - suppress startup message unless debugging
import os
if os.environ.get('GHOSTPRINT_DEBUG', '').lower() == 'true':
print("✅ Chimera Engine class loaded successfully.")
# --------------------------- Configuration dataclasses ---------------------------
@dataclass
class Ring:
"""Normalized frequency ring (relative to half-diagonal of the image)."""
r1: float = 0.12 # inner radius in [0, 1]
r2: float = 0.35 # outer radius in [0, 1]
weight: float = 1.0 # weight for this ring
def clamp(self) -> "Ring":
r1 = float(np.clip(self.r1, 0.0, 1.0))
r2 = float(np.clip(self.r2, 0.0, 1.0))
if r2 < r1: # swap if needed
r1, r2 = r2, r1
return Ring(r1, r2, self.weight)
@dataclass
class ArmorConfig:
"""
Controls amplitude, ring selection, perceptual masking, determinism, and EOT.
amp: Luminance delta cap in [0..255] (applied after masking).
rings: A list of Rings to compose for the armor field.
mix_edges: 0..1 → weight for edge vs. JND masks (1.0 = only edges).
secret: HMAC secret for deterministic per-asset seeds.
seed: Optional explicit seed (int). If None, code derives it.
eot_iters: Max EOT iterations (robustness tightening).
ssim_floor: Minimum allowed SSIM vs. original when applying armor.
tox_goal: Target toxicity after transforms (≥ this to stop EOT).
amp_step: Amplitude increment during EOT.
max_amp: Upper bound on amplitude during EOT.
band_targets: Optional[Dict[str, float]] = None # e.g. {"low": 0.20, "mid": 0.45, "high": 0.25}
SKIL Defense (Stochastic Key-In-the-Loop Manifold):
server_secret: Optional cryptographic secret for stochastic layer. Reads from
GHOSTPRINT_SERVER_SECRET env var if None and enable_stochastic=True.
enable_stochastic: Enable/disable the SKIL defense layer.
stochastic_alpha: Weight for deterministic armor component (default 0.7).
stochastic_beta: Weight for stochastic mask component (default 0.3).
"""
amp: float = 30.0 # Reduced base for gentler starting point
rings: List[Ring] = dataclasses.field(default_factory=lambda: [
Ring(r1=0.10, r2=0.40, weight=1.0), # Primary mid-band (exact definition)
Ring(r1=0.15, r2=0.35, weight=0.8), # Secondary mid-band (concentrated)
Ring(r1=0.20, r2=0.30, weight=0.6), # Tertiary mid-band (core)
])
mix_edges: float = 0.3 # Reduced to preserve more armor structure
secret: bytes = b"ghostprint-secret"
seed: Optional[int] = None
# EOT (Expectation over Transform) robustness
eot_iters: int = 500 # More iterations to find optimal mid-band
ssim_floor: float = 0.85 # More lenient for mid-band preservation
tox_goal: float = 0.40 # Lower toxicity goal, focus on mid-band
amp_step: float = 1.0 # Smaller steps for finer control (was 2.0)
max_amp: float = 80.0 # Reduced ceiling to prevent overshooting (was 100.0)
# CRITICAL: Mid-band (0.10-0.40 normalized radius) gets 90% of energy for ML disruption
band_targets: Optional[Dict[str, float]] = dataclasses.field(
default_factory=lambda: {"low": 0.05, "mid": 0.90, "high": 0.05}
)
# SKIL Defense - Adds difficulty to autoencoder-based removal attacks
# Note: Effective when attackers lack paired clean/armored training data
# With sufficient paired data, autoencoders can still learn removal patterns
server_secret: Optional[bytes] = None
enable_stochastic: bool = False # Add this line
stochastic_alpha: float = 0.85 # Deterministic component (85%) - primary protection
stochastic_beta: float = 0.15 # Stochastic component (15%)
@dataclass
class PureArmorSpec:
"""Spec for generating a pure armor field (no base image)."""
width: int
height: int
seed: int = 42 # deterministic by default
config: ArmorConfig = dataclasses.field(default_factory=ArmorConfig)
@dataclass
class ArmorMeta:
"""Metadata describing a generated armor field."""
amp: float
rings: List[Ring]
seed: int
bands: Dict[str, float]
toxicity: float
ssim: Optional[float] = None
# --------------------------- Low-level math utilities ---------------------------
def _hann2d(h: int, w: int) -> np.ndarray:
"""2D Hann window to reduce spectral leakage before FFT."""
wy = np.hanning(h)
wx = np.hanning(w)
return np.outer(wy, wx).astype(np.float32)
def _ring_mask(shape: Tuple[int, int], r1: float, r2: float) -> np.ndarray:
"""Boolean mask selecting a normalized frequency ring in the FFT plane."""
h, w = shape
cy, cx = h // 2, w // 2
yy, xx = np.ogrid[:h, :w]
dist = np.sqrt((yy - cy) ** 2 + (xx - cx) ** 2)
maxr = np.sqrt((h / 2) ** 2 + (w / 2) ** 2)
R = dist / maxr
return (R >= r1) & (R <= r2)
def _fft_power(gray: np.ndarray, window: bool = True) -> np.ndarray:
"""Return power spectrum |FFT|^2 of a grayscale image/field."""
g = gray.astype(np.float32, copy=False)
if window:
g = g * _hann2d(*g.shape)
F = fftshift(fft2(g))
return (np.abs(F) ** 2).astype(np.float64)
def _band_energies(power: np.ndarray) -> Dict[str, float]:
"""
Compute energy ratios in low/mid/high bands:
low: 0.00–0.10, mid: 0.10–0.40, high: 0.40–1.00 (radius normalized).
"""
total = float(power.sum() + 1e-12)
low = float(power[_ring_mask(power.shape, 0.00, 0.10)].sum() / total)
mid = float(power[_ring_mask(power.shape, 0.10, 0.40)].sum() / total)
high = float(power[_ring_mask(power.shape, 0.40, 1.00)].sum() / total)
return {"low": low, "mid": mid, "high": high}
def _toxicity(power: np.ndarray) -> float:
"""Energy outside the low-frequency core (radius < 0.10)."""
total = float(power.sum() + 1e-12)
core = float(power[_ring_mask(power.shape, 0.00, 0.10)].sum())
return float(1.0 - core / total)
def _cmt_multi_lens_displacement_field(shape: Tuple[int, int], seed: int,
c1: complex = 0.587+1.223j,
c2: float = -0.994) -> Tuple[np.ndarray, np.ndarray]:
"""
Generate CMT multi-lens displacement fields that create mid-frequency patterns.
Returns (delta_x, delta_y) displacement fields.
"""
h, w = shape
rng = np.random.default_rng(int(seed))
# Create normalized complex coordinate grid
x = np.linspace(-1, 1, w, dtype=np.float32)
y = np.linspace(-1, 1, h, dtype=np.float32)
xx, yy = np.meshgrid(x, y)
Z = xx + 1j * yy
# Import all lens functions
from scipy.special import gamma, airy, j0
# Initialize aggregate displacement fields
delta_x_total = np.zeros(shape, dtype=np.float32)
delta_y_total = np.zeros(shape, dtype=np.float32)
# Lens 1: Gamma function (creates fractal-like patterns)
try:
# Scale Z to avoid overflow in gamma
Z_gamma = Z * (0.5 + rng.random() * 0.3)
F_gamma = gamma(Z_gamma + 1.5) # Shift to avoid singularity at 0
# Handle any infinities
F_gamma = np.where(np.isfinite(F_gamma), F_gamma, 0)
# Apply CMT transform
Phi_gamma = c1 * F_gamma + c2 * np.abs(Z)
delta_x_total += np.real(Phi_gamma)
delta_y_total += np.imag(Phi_gamma)
except:
pass
# Lens 2: Airy function (creates wave interference patterns)
try:
Z_airy = Z * (3.0 + rng.random() * 2.0) # Scale for mid frequencies
F_airy = airy(Z_airy)[0]
F_airy = np.where(np.isfinite(F_airy), F_airy, 0)
Phi_airy = c1 * F_airy + c2 * np.abs(Z)
delta_x_total += np.real(Phi_airy)
delta_y_total += np.imag(Phi_airy)
except:
pass
# Lens 3: Bessel function (creates radial patterns)
try:
Z_bessel = np.abs(Z) * (5.0 + rng.random() * 3.0) # Use magnitude for Bessel
F_bessel = j0(Z_bessel)
# Add phase based on angle
angle = np.angle(Z)
F_bessel_complex = F_bessel * np.exp(1j * angle)
Phi_bessel = c1 * F_bessel_complex + c2 * np.abs(Z)
delta_x_total += np.real(Phi_bessel)
delta_y_total += np.imag(Phi_bessel)
except:
pass
# Lens 4: Sinc function (creates diffraction patterns)
try:
Z_sinc = Z * (10.0 + rng.random() * 5.0)
# Sinc creates strong mid-frequency content
F_sinc = np.sinc(np.real(Z_sinc)) + 1j * np.sinc(np.imag(Z_sinc))
Phi_sinc = c1 * F_sinc + c2 * np.abs(Z)
delta_x_total += np.real(Phi_sinc)
delta_y_total += np.imag(Phi_sinc)
except:
pass
# Normalize to sub-pixel range (0.5 pixels max displacement)
lambda_scale = 0.5 # Maximum displacement in pixels
max_dx = np.max(np.abs(delta_x_total))
max_dy = np.max(np.abs(delta_y_total))
if max_dx > 1e-6:
delta_x_total = lambda_scale * delta_x_total / max_dx
if max_dy > 1e-6:
delta_y_total = lambda_scale * delta_y_total / max_dy
return delta_x_total, delta_y_total
def _apply_cmt_displacement(field: np.ndarray, delta_x: np.ndarray, delta_y: np.ndarray) -> np.ndarray:
"""
Apply CMT displacement field to create mid-frequency perturbations.
Sub-pixel displacements naturally create mid-frequency content.
"""
h, w = field.shape
# Create coordinate grids
y_coords, x_coords = np.meshgrid(np.arange(h), np.arange(w), indexing='ij')
# Apply displacements
x_displaced = x_coords + delta_x
y_displaced = y_coords + delta_y
# Ensure coordinates stay within bounds
x_displaced = np.clip(x_displaced, 0, w - 1)
y_displaced = np.clip(y_displaced, 0, h - 1)
# Use bilinear interpolation for sub-pixel accuracy
from scipy.ndimage import map_coordinates
# Reshape for map_coordinates
coords = np.array([y_displaced.ravel(), x_displaced.ravel()])
# Apply displacement with bilinear interpolation
displaced_field = map_coordinates(field, coords, order=1, mode='reflect')
displaced_field = displaced_field.reshape(h, w)
return displaced_field.astype(np.float32)
def _cmt_lens_field(shape: Tuple[int, int], seed: int) -> np.ndarray:
"""
Enhanced CMT lens field using multi-lens displacement for maximum mid-frequency chaos.
"""
h, w = shape
rng = np.random.default_rng(int(seed))
# Generate CMT displacement fields
delta_x, delta_y = _cmt_multi_lens_displacement_field(shape, seed)
# Create base pattern to be displaced
# Use a combination of patterns that will create mid frequencies when displaced
x = np.linspace(0, 4*np.pi, w)
y = np.linspace(0, 4*np.pi, h)
xx, yy = np.meshgrid(x, y)
# Base pattern with multiple frequencies
base_pattern = (
np.sin(3 * xx) * np.cos(3 * yy) + # Low-mid frequency
0.5 * np.sin(7 * xx) * np.cos(7 * yy) + # Mid frequency
0.3 * np.sin(15 * xx) * np.cos(15 * yy) + # High-mid frequency
0.2 * np.sin(30 * xx) * np.cos(30 * yy) # Very high frequency
)
# Apply CMT displacement to create additional mid frequencies
displaced_pattern = _apply_cmt_displacement(base_pattern, delta_x * 10, delta_y * 10)
# Add LEHI harmonic perturbation
# Frequencies chosen for mid-band: {3, 7, 15, 30} cycles per image
lehi_freqs = [3, 7, 15, 30]
lehi_pattern = np.zeros_like(base_pattern)
for k, freq in enumerate(lehi_freqs):
# Deterministic phases seeded from input
phi_k = rng.random() * 2 * np.pi
psi_k = rng.random() * 2 * np.pi
# Amplitude scaling with CSF
csf = 2.6 * (0.0192 + 0.114 * freq) * np.exp(-(0.114 * freq) ** 1.1)
A_k = min(0.5, 0.1 / csf) # Scale by CSF
# Add harmonic
lehi_pattern += A_k * np.sin(2*np.pi * freq * xx/(4*np.pi) + phi_k) * np.cos(2*np.pi * freq * yy/(4*np.pi) + psi_k)
# Combine all components
combined_field = (
0.4 * displaced_pattern + # CMT displaced patterns
0.3 * lehi_pattern + # LEHI harmonics
0.3 * (delta_x + delta_y) # Direct displacement field contribution
)
# Apply nonlinear transformation to enhance mid frequencies
combined_field = np.tanh(combined_field * 0.5) * 4.0
return combined_field.astype(np.float32)
def _cmt_filtered_field(shape: Tuple[int, int], seed: int, ring: Ring) -> np.ndarray:
"""
Generates a CMT lens field with aggressive mid-band filtering.
Multiple passes ensure maximum energy concentration in target frequencies.
"""
# 1. Generate the base chaotic field from CMT lenses
chaotic_field = _cmt_lens_field(shape, seed)
# 2. Apply multiple filtering passes to concentrate energy in mid-band
field = chaotic_field.copy()
for pass_num in range(3): # Multiple passes to build up mid-band energy
# Transform to frequency domain
F = fftshift(fft2(field))
# Create ring mask
mask = _ring_mask(shape, ring.r1, ring.r2).astype(np.float32)
# Apply progressively stronger filtering
if pass_num == 0:
# First pass: gentle filtering to preserve some structure
F_filtered = F * mask
elif pass_num == 1:
# Second pass: boost mid frequencies
mid_boost = 1.0 + mask * 2.0 # Amplify mid-band by 3x
F_filtered = F * mid_boost
else:
# Final pass: aggressive mid-band isolation
# Suppress everything outside mid-band
F_filtered = F * mask
# Extra boost to mid frequencies
F_filtered *= 2.5
# Back to spatial domain
field = np.real(ifft2(ifftshift(F_filtered))).astype(np.float32)
# Add some of the original chaos back to maintain complexity
if pass_num < 2:
field = 0.7 * field + 0.3 * chaotic_field
# 3. Final normalization with preserved variance
field -= field.mean()
# Ensure strong signal (don't over-normalize)
target_std = 2.0 # Higher standard deviation for more aggressive perturbation
current_std = field.std()
if current_std > 1e-6:
field *= (target_std / current_std)
return field.astype(np.float32)
def _generate_stochastic_mask(
shape: Tuple[int, int],
image_bytes: bytes,
server_secret: bytes,
base_seed: int
) -> np.ndarray:
"""
Generate a cryptographically-keyed stochastic mask for SKIL defense.
This creates a band-limited noise field that is unpredictable without the
server secret, making it impossible for LightShed-style autoencoders to learn
the complete perturbation pattern.
Args:
shape: (height, width) of the output mask
image_bytes: Raw bytes of the image file (for unique per-image keying)
server_secret: Server-side cryptographic secret (512 bits recommended)
base_seed: Base seed from deterministic armor generation
Returns:
Band-limited stochastic field (float32) with mid-band energy concentration
Security Properties:
- Non-reproducible without server_secret (512 bits entropy)
- Unique per-image (incorporates image_bytes)
- Mid-band frequency profile (0.10-0.40 normalized radius)
- Cryptographically secure derivation (SHA-256)
"""
h, w = shape
# Cryptographic seed derivation: combines image data, server secret, and base seed
# This ensures each image gets a unique, unpredictable stochastic component
seed_material = image_bytes + server_secret + base_seed.to_bytes(8, 'big')
stochastic_seed_hash = hashlib.sha256(seed_material).digest()
# Convert hash to integer seed for RNG
stochastic_seed = int.from_bytes(stochastic_seed_hash[:8], 'big', signed=False)
rng = np.random.default_rng(stochastic_seed)
# Generate multi-frequency structured noise (not simple white noise)
# This maintains imperceptibility while adding mid-band chaos
x = np.linspace(0, 20*np.pi, w)
y = np.linspace(0, 20*np.pi, h)
xx, yy = np.meshgrid(x, y)
# Create base pattern with multiple frequency components
# These frequencies are chosen to populate the mid-band (0.10-0.40 normalized radius)
structured_noise = (
rng.normal(0, 0.5, size=shape) + # Random component
0.3 * np.sin(5 * xx + rng.random() * 2*np.pi) * np.cos(5 * yy + rng.random() * 2*np.pi) +
0.2 * np.sin(8 * xx + rng.random() * 2*np.pi) * np.cos(8 * yy + rng.random() * 2*np.pi) +
0.2 * np.sin(12 * xx + rng.random() * 2*np.pi) * np.cos(12 * yy + rng.random() * 2*np.pi) +
0.1 * np.sin(15 * xx + rng.random() * 2*np.pi) * np.cos(15 * yy + rng.random() * 2*np.pi)
).astype(np.float32)
# Apply band-pass filter to concentrate energy in mid-band (0.10-0.40)
# This ensures the stochastic component matches the deterministic armor's frequency profile
F = fftshift(fft2(structured_noise))
mid_band_mask = _ring_mask(shape, 0.10, 0.40).astype(np.float32)
# Apply mask and boost to ensure strong mid-band presence
F_filtered = F * mid_band_mask * 2.0
# Back to spatial domain
stochastic_field = np.real(ifft2(ifftshift(F_filtered))).astype(np.float32)
# Normalize: zero mean, controlled variance
stochastic_field -= stochastic_field.mean()
current_std = stochastic_field.std()
if current_std > 1e-6:
# Target std slightly lower than deterministic armor (we'll scale by beta later)
target_std = 1.5
stochastic_field *= (target_std / current_std)
return stochastic_field
def _phi_en_symbol_mask(h: int, w: int, strength: float = 1.0, seed: Optional[int] = None) -> np.ndarray:
"""
Generates the "Better Armor" perturbation field based on a combination of
five structured masks.
"""
rng = np.random.default_rng(seed)
y, x = np.mgrid[0:h, 0:w]
phi = (1 + np.sqrt(5)) / 2
# 1. Golden Ratio Lattice Mask
G = sum(np.sin(2 * np.pi * (x / phi) / (20 + i * 5) + rng.random() * 2 * np.pi) +
np.cos(2 * np.pi * (y * phi) / (20 + i * 5) + rng.random() * 2 * np.pi)
for i in range(3))
# 2. Fibonacci Phase Harmonics
fibs = [1, 2, 3, 5, 8]
F = sum(0.2 / (k + 1) * (np.sin(f * x / w + rng.random() * 2 * np.pi) +
np.cos(f * y / h + rng.random() * 2 * np.pi))
for k, f in enumerate(fibs))
# 3. Prime Harmonic Grid
primes = [5, 7, 11, 13]
P = sum(0.15 / (i + 1) * (np.sin(p * x / w + rng.random() * 2 * np.pi) +
np.cos(p * y / h + rng.random() * 2 * np.pi))
for i, p in enumerate(primes))
# 4. Irrational Chaos Mask
irr = [(np.pi + i * np.e, np.e + i * np.pi) for i in range(4)]
Q = sum(np.sin(ix * x / w + rng.random() * 2 * np.pi) +
np.cos(iy * y / h + rng.random() * 2 * np.pi)
for ix, iy in irr)
# 5. Homoglyph Phase-Swap Perturbation
swaps = [30, 50]
H = sum(np.sin((x + y) / (h + w) * s + rng.random() * 2 * np.pi)
for s in swaps)
# Combined Mask
M = 0.25 * G + 0.25 * F + 0.20 * P + 0.20 * Q + 0.10 * H
# Normalization
M = np.tanh(0.8 * M) * 0.4
# Perturbation Application
delta = np.clip(np.round(M * strength * 0.6), -2, 2)
return delta.astype(np.float32)
def _band_limited_field(shape: Tuple[int, int], ring: Ring, seed: int) -> np.ndarray:
"""
Create a real band-limited field with aggressive mid-band focus.
Uses structured noise instead of white noise for better mid-band energy.
"""
ring = ring.clamp()
rng = np.random.default_rng(int(seed))
# Start with structured noise that has more mid-frequency content
h, w = shape
x = np.linspace(0, 20*np.pi, w)
y = np.linspace(0, 20*np.pi, h)
xx, yy = np.meshgrid(x, y)
# Create multi-frequency base pattern
structured = (
rng.normal(0, 0.5, size=shape) + # Random component
0.3 * np.sin(5 * xx) * np.cos(5 * yy) + # Mid-frequency waves
0.2 * np.sin(8 * xx + rng.random() * 2*np.pi) +
0.2 * np.cos(8 * yy + rng.random() * 2*np.pi) +
0.1 * np.sin(12 * xx) * np.sin(12 * yy) # Higher frequency
).astype(np.float32)
# Apply band-pass filter
F = fftshift(fft2(structured))
mask = _ring_mask(shape, ring.r1, ring.r2)
F_filtered = F * mask
# Boost the filtered frequencies
F_filtered *= 2.0
field = np.real(ifft2(ifftshift(F_filtered))).astype(np.float32)
field -= float(field.mean())
std = float(field.std() + 1e-6)
if std > 1e-6:
field *= (1.0 / std)
return field
def _decode_signed_delta_png(path: str, amp: float) -> np.ndarray:
"""
Read a signed-delta PNG produced by `export_armor_layers`.
Decoding: delta = (v/255 - 0.5) * (2*amp)
"""
enc = np.asarray(Image.open(path).convert("L")).astype(np.float32)
return ((enc / 255.0) - 0.5) * (2.0 * float(amp))
def _encode_signed_delta_png(delta: np.ndarray, amp: float) -> np.ndarray:
"""
Encode a signed delta to 8-bit grayscale suitable for PNG.
Encoding: v = ((clip(delta, -amp, +amp)/(2*amp)) + 0.5) * 255
"""
enc = ((np.clip(delta, -amp, amp) / (2.0 * float(amp))) + 0.5) * 255.0
return np.clip(enc, 0, 255).astype(np.uint8)
def _fft_resample_field(field: np.ndarray, new_h: int, new_w: int) -> np.ndarray:
"""
Frequency-preserving resize of a band-limited field: crop/pad around the FFT center.
Keeps the ring profile intact, unlike spatial interpolation.
"""
H, W = field.shape
F = fftshift(fft2(field))
out = np.zeros((new_h, new_w), dtype=np.complex64)
hmin = min(H, new_h)
wmin = min(W, new_w)
y0s, y1s = H // 2 - hmin // 2, H // 2 - hmin // 2 + hmin
x0s, x1s = W // 2 - wmin // 2, W // 2 - wmin // 2 + wmin
y0d, y1d = new_h // 2 - hmin // 2, new_h // 2 - hmin // 2 + hmin
x0d, x1d = new_w // 2 - wmin // 2, new_w // 2 - wmin // 2 + wmin
out[y0d:y1d, x0d:x1d] = F[y0s:y1s, x0s:x1s]
resized = np.real(ifft2(ifftshift(out))).astype(np.float32)
# match source variance
if resized.std() > 1e-6 and field.std() > 1e-6:
resized *= (float(field.std()) / float(resized.std()))
return resized
# --------------------------- Perceptual masking ---------------------------
def _jnd_mask(gray: np.ndarray) -> np.ndarray:
"""
Crude JND-like mask: scale deltas by local contrast (std in a window).
Returns values ~[0.5, 1.0] to preserve more armor energy.
"""
mu = uniform_filter(gray, size=7)
mu2 = uniform_filter(gray ** 2, size=7)
local_std = np.sqrt(np.maximum(mu2 - mu ** 2, 1e-6))
m = local_std / (float(local_std.max()) + 1e-6)
# Increased minimum to preserve more armor structure
return (0.5 + 0.5 * m).astype(np.float32)
def _edge_mask(gray: np.ndarray) -> np.ndarray:
"""
Edge emphasis via Sobel gradient magnitude; gamma<1 boosts edges mildly.
"""
gx, gy = sobel(gray, 1), sobel(gray, 0)
mag = np.hypot(gx, gy)
mag /= float(mag.max() + 1e-6)
return (mag ** 0.7).astype(np.float32)
def _content_amplitude_map(gray: np.ndarray, mix_edges: float) -> np.ndarray:
"""
Combine edge and JND masks to decide where to hide energy.
`mix_edges` in [0..1] sets the blend amount.
"""
me = float(np.clip(mix_edges, 0.0, 1.0))
m = me * _edge_mask(gray) + (1.0 - me) * _jnd_mask(gray)
m /= float(m.max() + 1e-6)
return m.astype(np.float32)
# --------------------------- Public API: generation & export ---------------------------
class ArmorGenerator:
"""
Factory for creating and exporting Invisible Armor.
Create once and reuse. All methods are deterministic given seeds.
"""
VERSION: str = "1.0.0"
# --- Pure armor (no base image) ---
def generate_pure_armor(self, spec: PureArmorSpec) -> Tuple[np.ndarray, ArmorMeta]:
"""
Create a pure armor field from a random seed (no base image).
Uses aggressive multi-ring CMT generation to force mid-band energy.
Returns:
delta: 2D float32 array of signed luminance deltas.
meta: ArmorMeta describing amp, bands, toxicity.
"""
cfg = spec.config
shape = (spec.height, spec.width)
# 1. Generate a base chaotic field
base_field = np.zeros(shape, dtype=np.float32)
base_seed = spec.seed
for i, ring in enumerate(cfg.rings):
ring_seed = base_seed + i * 1000
ring_field = _cmt_filtered_field(shape, ring_seed, ring.clamp())
base_field += ring_field * ring.weight
# --- Better Armor Integration ---
better_armor_mask = _phi_en_symbol_mask(spec.height, spec.width, strength=float(cfg.amp), seed=spec.seed)
initial_field = 0.7 * base_field + 0.3 * better_armor_mask * float(cfg.amp)
# 2. Fourier Domain Energy Balancing
# CRITICAL: These are RATIOS that must sum to ~1.0
# Mid-band gets 85%+ of total energy for maximum ML disruption
band_targets = cfg.band_targets or {"low": 0.05, "mid": 0.90, "high": 0.05}
F = fftshift(fft2(initial_field))
mag = np.abs(F)
phase = np.angle(F)
# Define band masks
masks = {
"low": _ring_mask(shape, 0.00, 0.10),
"mid": _ring_mask(shape, 0.10, 0.40),
"high": _ring_mask(shape, 0.40, 1.00),
}
# Calculate current energies
pow2 = mag**2
total_energy = pow2.sum()
if total_energy < 1e-9: # Avoid division by zero for blank fields
total_energy = 1.0
band_energies = {band: pow2[m].sum() for band, m in masks.items()}
# Rescale magnitudes
F_bal = np.zeros_like(F, dtype=complex)
for band, target_ratio in band_targets.items():
if band in masks and band_energies[band] > 0:
mask = masks[band]
current_energy = band_energies[band]
target_energy = target_ratio * total_energy
scale = np.sqrt(target_energy / current_energy)
F_bal[mask] += F[mask] * scale
# 3. Inverse FFT and final processing
balanced_field = np.real(ifft2(ifftshift(F_bal)))
# Normalize, squash, and scale
if balanced_field.std() > 1e-6:
balanced_field = balanced_field / balanced_field.std()
squashed = np.tanh(balanced_field * 0.8) * 0.4
delta = np.clip(np.round(squashed * float(cfg.amp) * 0.6), -float(cfg.amp), float(cfg.amp))
delta = delta.astype(np.float32)
# 4. Final clipping and analysis
delta = np.clip(delta, -float(cfg.amp), float(cfg.amp)).astype(np.float32)
power = _fft_power(delta, window=True)
bands = _band_energies(power)
tox = _toxicity(power)
meta = ArmorMeta(
amp=float(cfg.amp),
rings=cfg.rings,
seed=int(spec.seed),
bands=bands,
toxicity=float(tox),
)
return delta, meta
def export_armor_layers(
self,
delta: np.ndarray,
amp: float,
out_dir: str,
tag: str = "armor",
alpha_gamma: float = 0.6,
) -> Dict[str, str]:
"""
Export armor in multiple representations:
- {tag}_delta_signed.png : reconstructable signed-delta (8-bit L)
decode: delta = (v/255 - 0.5) * (2*amp)
- {tag}_alpha_overlay.png: alpha-only PNG (RGB=0, A=|delta|^gamma)
- {tag}_sign_vis.png: sign-coded visualization (pos=green, neg=magenta)
- {tag}_spectrum.png: full/mid/high spectrum panels with percentages
Returns a dict of absolute file paths.
"""
os.makedirs(out_dir, exist_ok=True)
H, W = delta.shape
amp = float(amp)
# Signed-delta PNG
enc = _encode_signed_delta_png(delta, amp)
p_delta = os.path.join(out_dir, f"{tag}_delta_signed.png")
Image.fromarray(enc).save(p_delta)
# Alpha-only overlay
mag = np.abs(delta) / (amp + 1e-6)
alpha = np.clip((mag ** float(alpha_gamma)) * 255.0, 0, 255).astype(np.uint8)
rgba = np.zeros((H, W, 4), dtype=np.uint8)
rgba[:, :, 3] = alpha
p_alpha = os.path.join(out_dir, f"{tag}_alpha_overlay.png")
Image.fromarray(rgba, mode="RGBA").save(p_alpha)
# Sign visualization
vis = np.zeros((H, W, 4), dtype=np.uint8)
pos = (delta > 0).astype(np.uint8)
neg = 1 - pos
vis[:, :, 1] = pos * 255 # G
vis[:, :, 0] = neg * 255 # R
vis[:, :, 2] = neg * 255 # B
vis[:, :, 3] = alpha
p_vis = os.path.join(out_dir, f"{tag}_sign_vis.png")
Image.fromarray(vis, mode="RGBA").save(p_vis)
# Spectrum panels
p_spec = os.path.join(out_dir, f"{tag}_spectrum.png")
_save_spectrum_panels(delta, p_spec)
return {
"delta_png": p_delta,
"alpha_overlay": p_alpha,
"sign_vis": p_vis,
"spectrum_panel": p_spec,
}
# --- Applying armor to images (content-aware, deterministic, EOT) ---
def derive_seed(self, image_path: str, cfg: ArmorConfig) -> int:
"""
Deterministic per-asset seed: HMAC(secret, sha256(file_bytes)) → uint64.
"""
if cfg.seed is not None:
return int(cfg.seed)
with open(image_path, "rb") as f:
b = f.read()
digest = hashlib.sha256(b).digest()
h = hmac.new(cfg.secret, digest, "sha256").digest()
return int.from_bytes(h[:8], "big", signed=False)
def _extract_low_freq_modulator(self, gray: np.ndarray, cutoff: float = 0.10) -> np.ndarray:
"""Extract low-frequency content to use as modulator for mid-band"""
F = fftshift(fft2(gray))
# Create low-pass mask
low_mask = _ring_mask(F.shape, 0.0, cutoff)
# Extract low frequencies
F_low = F * low_mask
# Back to spatial domain
low_freq = np.real(ifft2(ifftshift(F_low))).astype(np.float32)
# Normalize to [0, 1] range for modulation
low_min, low_max = low_freq.min(), low_freq.max()
if low_max > low_min:
low_freq = (low_freq - low_min) / (low_max - low_min)
else:
low_freq = np.ones_like(low_freq) * 0.5
return low_freq
def _create_frequency_coupled_armor(self, shape: Tuple[int, int], seed: int,
low_freq_modulator: np.ndarray,
cfg: ArmorConfig) -> np.ndarray:
"""Create armor where mid-band energy is driven by low-frequency content"""
h, w = shape
# First, generate strong mid-band base using our proven CMT approach
base_mid_band = np.zeros(shape, dtype=np.float32)
# Use multiple rings to build up mid-band energy
for i, ring in enumerate(cfg.rings):
ring_seed = seed + i * 1000
ring_field = _cmt_filtered_field(shape, ring_seed, ring.clamp())
base_mid_band += ring_field * ring.weight
# Now apply frequency coupling: modulate the mid-band with low-freq content
# This creates a multiplicative relationship between low and mid bands
# Method 1: Direct amplitude modulation
# The low-frequency content acts as an envelope for mid-band carriers
modulation_depth = 25.0 # How strongly low freq modulates mid freq
envelope = 1.0 + modulation_depth * (low_freq_modulator - 0.5)
envelope = np.clip(envelope, 0.1, 3.0) # Prevent zeros and extreme values
# Apply envelope to mid-band content
coupled_armor = base_mid_band * envelope
# Method 2: Frequency modulation (FM synthesis)
# Low frequencies modulate the phase of mid-band content
# This creates sidebands that spread energy across mid-band
x = np.linspace(0, 2*np.pi * 20, w) # 20 cycles across width
y = np.linspace(0, 2*np.pi * 20, h) # 20 cycles across height
xx, yy = np.meshgrid(x, y)
# FM synthesis: carrier + modulator
fm_depth = 5.0 # Modulation index
fm_component = np.sin(xx + fm_depth * low_freq_modulator) * np.cos(yy + fm_depth * low_freq_modulator)
# Combine AM and FM approaches
coupled_armor = 0.7 * coupled_armor + 0.3 * fm_component * cfg.amp
# Method 3: CMT displacement modulation
# Use CMT multi-lens displacement fields modulated by low frequency
delta_x, delta_y = _cmt_multi_lens_displacement_field(shape, seed + 9999)
# Scale displacements by low-frequency content
# Where image has strong low freq, we get stronger displacements
delta_x_mod = delta_x * (1 + 2 * low_freq_modulator)
delta_y_mod = delta_y * (1 + 2 * low_freq_modulator)
# Apply displacement to a mid-frequency grid pattern
grid_x = np.linspace(0, 20*np.pi, w)
grid_y = np.linspace(0, 20*np.pi, h)
grid_xx, grid_yy = np.meshgrid(grid_x, grid_y)
# Create displaced coordinates
displaced_x = grid_xx + delta_x_mod * 5 # Scale displacement effect
displaced_y = grid_yy + delta_y_mod * 5
# Generate pattern at displaced coordinates
# This creates mid-frequency content through the displacement itself
cmt_pattern = np.sin(displaced_x) * np.cos(displaced_y)
coupled_armor += 0.3 * cmt_pattern * cfg.amp
# Method 4: Cross-modulation with LEHI harmonics
# Create interference patterns between low and mid frequencies
rng = np.random.default_rng(seed)
for i in range(3):
# Create mid-band carriers
freq = 15 + i * 10 # 15, 25, 35 cycles
phase = rng.random() * 2 * np.pi
carrier = np.sin(freq * xx / (2*np.pi) + phase)
# Cross-modulate with low frequency
# This creates sum and difference frequencies
cross_mod = carrier * low_freq_modulator * (1 + low_freq_modulator)
coupled_armor += 0.1 * cross_mod * cfg.amp
# Ensure the result is still dominated by mid-band
# Apply band-pass filter to remove any low-freq leakage
F = fftshift(fft2(coupled_armor))
mid_mask = _ring_mask(shape, 0.10, 0.40).astype(np.float32)
# Soft band-pass to preserve some transition
soft_mask = gaussian_filter(mid_mask.astype(np.float32), sigma=5)
F_filtered = F * soft_mask
# Back to spatial domain
coupled_armor = np.real(ifft2(ifftshift(F_filtered))).astype(np.float32)
# Final normalization
coupled_armor -= coupled_armor.mean()
if coupled_armor.std() > 1e-6:
coupled_armor *= (cfg.amp * 0.8 / coupled_armor.std())
return np.clip(coupled_armor, -cfg.amp, cfg.amp).astype(np.float32)
def apply_to_image(
self,
image_path: str,
out_path: str,
cfg: ArmorConfig = ArmorConfig(),
delta_png: Optional[str] = None,
resize_method: str = "fft",
return_metrics: bool = True,
strength: float = 1.0,
focus_parameter: float = 3.5,
frequency_strategy: str = 'auto'
) -> Optional[Dict[str, float]]:
"""
Apply armor to an image with perceptual masking + EOT robustness.
Strength levels:
1.0 - Invisible to humans, moderate AI protection
2.0 - Very subtle, enhanced AI protection
3.0 - Barely visible, strong AI protection
4.0 - Slightly visible, very strong AI protection
5.0 - Visible artifacts allowed, maximum AI confusion
If `delta_png` is provided, that signed-delta map is decoded and (if needed)
frequency-resampled to match the target size. Otherwise, a fresh delta is
generated deterministically from the image bytes.
SKIL Defense (Stochastic Key-In-the-Loop Manifold):
---------------------------------------------------------
This method implements an advanced defense against LightShed-style autoencoder
attacks that attempt to learn and remove perturbation patterns. The defense works
by combining two layers of perturbation:
1. Deterministic Armor (α component): Content-aware, reproducible perturbation
based on CMT, LEHI, and Chimera Engine principles.
2. Stochastic Mask (β component): Non-reproducible perturbation keyed by a
cryptographic server secret (512-bit entropy). This component is unique per
image and cannot be learned by attackers without the secret.
Final perturbation: Δ_final = α·Δ_deterministic + β·M_stochastic
Security Properties:
- Even if attackers learn the deterministic pattern (α component), they cannot
replicate the stochastic component (β component) without the server secret.
- Autoencoder training fails because the stochastic component (70% by default) is
high-entropy random noise that cannot be predicted or modeled.
- Each image gets a unique stochastic mask derived from: image_bytes + server_secret.
Configuration:
- Set cfg.server_secret (bytes) or GHOSTPRINT_SERVER_SECRET environment variable
- Adjust cfg.stochastic_alpha (default 0.3) and cfg.stochastic_beta (default 0.7)
(stochastic-dominant: 70% non-learnable, 30% deterministic)
- Disable with cfg.enable_stochastic = False
- Backward compatible: without server_secret, behaves as original deterministic armor
Args:
image_path: Input image (any format Pillow understands).
out_path: Path to save armored output (PNG/JPEG/etc.).
cfg: ArmorConfig (amp, rings, EOT thresholds, SKIL defense params).
delta_png: Optional path to a signed-delta PNG to apply.
resize_method: "fft" (preferred) or "bicubic" when cv2 unavailable.
return_metrics: If True, returns dict with SSIM, bands, toxicity.
strength: Armor strength from 1.0 to 5.0
Returns:
metrics dict or None.
"""
# Scale all parameters based on strength (now supports 1-10)
strength = np.clip(strength, 1.0, 10.0)
# --- Balanced Strength Scaling Logic ---
# This provides a strong but not overwhelming power curve.
# Use a CUBIC power-law curve (strength^3).
# This scales from 1x at str=1 to 125x at str=5. A significant reduction.
strength_multiplier = strength ** 3
# SSIM floor is restored to a reasonable level, preventing total image destruction.
# Starts at 0.90 and drops to a more moderate 0.60 at strength 5.
ssim_floor = 0.90 - ((strength - 1.0) / 4.0) * 0.30
# CRITICAL: Set hard amplitude ceilings based on strength to prevent SSIM destruction
# These are empirically determined to maintain SSIM > 0.85
# The ceiling is the MAXIMUM the EOT loop can reach, not the starting point
if strength <= 2.0:
hard_amp_ceiling = 30.0 # Very gentle
elif strength <= 2.5:
hard_amp_ceiling = 50.0 # Optimal balance
elif strength <= 3.0:
hard_amp_ceiling = 80.0 # Strong but usable
elif strength <= 4.0:
hard_amp_ceiling = 120.0 # Visible artifacts
elif strength <= 5.0:
hard_amp_ceiling = 200.0 # Maximum chaos
elif strength <= 7.0:
hard_amp_ceiling = 300.0 # Extreme
else:
hard_amp_ceiling = 500.0 # Nuclear (strength 8-10)
# CRITICAL: Apply ceiling to BOTH base amp and max_amp
base_amp = min(cfg.amp * strength_multiplier, hard_amp_ceiling)
print(f"[ARMOR] Strength {strength:.1f}: Hard ceiling={hard_amp_ceiling}, Base amp={base_amp:.2f}, SSIM floor={ssim_floor:.2f}")
adjusted_cfg = ArmorConfig(
amp=base_amp, # Use capped base amp
rings=cfg.rings,
mix_edges=cfg.mix_edges * (1.0 - (strength - 1.0) * 0.2),
band_targets=getattr(cfg, 'band_targets', None),
secret=cfg.secret,
seed=cfg.seed,
eot_iters=cfg.eot_iters + int((strength - 1.0) * 15),
ssim_floor=ssim_floor,
tox_goal=cfg.tox_goal,
amp_step=cfg.amp_step * (1.0 + (strength - 1.0) * 2),
max_amp=hard_amp_ceiling, # Use hard ceiling directly
# SKIL Defense parameters (critical: must copy from cfg!)
server_secret=cfg.server_secret,
enable_stochastic=cfg.enable_stochastic,
stochastic_alpha=cfg.stochastic_alpha,
stochastic_beta=cfg.stochastic_beta,
)
arr = _load_rgb(image_path)
gray = _rgb_to_gray(arr)
# --- Configure the Upgraded Chimera Engine based on Strength ---
# At high strengths, use more chaotic frequency strategies
if strength >= 4.5:
freq_strategy = 'scramble'
elif strength >= 3.0:
freq_strategy = 'hybrid'
else:
freq_strategy = 'auto'
# Focus sharpens dramatically with strength
focus = 2.5 + (strength - 1.0) * 1.5 # Scales from 2.5 to 8.5
chimera = ChimeraEngine(
power=adjusted_cfg.amp,
focus_parameter=focus,
frequency_strategy=freq_strategy
)
# --- Generate Base Armor with Mid-Band Targeting ---
# The Chimera Engine is great for adaptive strength, but we need to ensure
# the frequency content is in the mid-band (0.10-0.40 normalized radius)
seed = self.derive_seed(image_path, adjusted_cfg)
# Generate multi-ring CMT armor with aggressive mid-band filtering
base_delta = np.zeros(gray.shape, dtype=np.float32)
for i, ring in enumerate(adjusted_cfg.rings):
ring_seed = seed + i * 1000
ring_field = _cmt_filtered_field(gray.shape, ring_seed, ring.clamp())
base_delta += ring_field * ring.weight
# Apply Fourier domain energy balancing to force mid-band concentration
F = fftshift(fft2(base_delta))
mag = np.abs(F)
phase = np.angle(F)
# Define band masks
masks = {
"low": _ring_mask(gray.shape, 0.00, 0.10),
"mid": _ring_mask(gray.shape, 0.10, 0.40),
"high": _ring_mask(gray.shape, 0.40, 1.00),
}
# Target distribution based on strength
if strength >= 4.5:
band_targets = {"low": 0.03, "mid": 0.92, "high": 0.05}
elif strength >= 3.0:
band_targets = {"low": 0.05, "mid": 0.85, "high": 0.10}
else:
band_targets = {"low": 0.10, "mid": 0.75, "high": 0.15}
# Calculate current energies
pow2 = mag**2
total_energy = pow2.sum()
if total_energy < 1e-9:
total_energy = 1.0
band_energies = {band: pow2[m].sum() for band, m in masks.items()}
# Rescale magnitudes to hit targets
F_bal = np.zeros_like(F, dtype=complex)
for band, target_ratio in band_targets.items():
if band in masks and band_energies[band] > 0:
mask = masks[band]
current_energy = band_energies[band]
target_energy = target_ratio * total_energy
scale = np.sqrt(target_energy / current_energy)
F_bal[mask] += F[mask] * scale
# Back to spatial domain
balanced_delta = np.real(ifft2(ifftshift(F_bal))).astype(np.float32)
# Normalize
if balanced_delta.std() > 1e-6:
balanced_delta = balanced_delta / balanced_delta.std()
# Now apply perceptual masking and Chimera adaptive modulation
holographic_map, mean_complexity = chimera._generate_holographic_map(gray)
# CRITICAL: Apply content-aware amplitude mapping for human invisibility
# This hides the armor in edges and high-contrast regions
content_mask = _content_amplitude_map(gray, adjusted_cfg.mix_edges)
# Combine holographic vulnerability map with perceptual masking
# Holographic map tells us WHERE to attack, content mask tells us HOW MUCH humans can tolerate
adaptive_strength_modulator = (holographic_map * 1.5 + 0.3) * content_mask
# Scale the balanced delta (which has correct frequency distribution)
delta_masked = balanced_delta * adaptive_strength_modulator * float(adjusted_cfg.amp)
# ============================================================================
# SKIL DEFENSE: Stochastic Key-In-the-Loop Manifold
# ============================================================================
# This layer defeats LightShed-style autoencoder attacks by adding a
# non-deterministic perturbation component that requires the server secret.
# Even if an attacker learns the deterministic armor pattern, they cannot
# replicate the stochastic component, leaving their training data poisoned.
#
# Security: 512-bit entropy from server_secret makes brute-force infeasible.
# The stochastic mask is unique per image (keyed by image bytes + secret).
# ============================================================================
final_delta = delta_masked # Default: use only deterministic armor
if adjusted_cfg.enable_stochastic:
server_secret = adjusted_cfg.server_secret
# Try to load server secret from environment if not explicitly provided
if server_secret is None:
env_secret = os.environ.get('GHOSTPRINT_SERVER_SECRET')
if env_secret:
server_secret = env_secret.encode('utf-8')
if server_secret:
# Read image bytes for cryptographic keying
with open(image_path, 'rb') as f:
image_bytes = f.read()
# Generate the stochastic mask (non-reproducible without server_secret)
stochastic_mask = _generate_stochastic_mask(
gray.shape, image_bytes, server_secret, seed
)
# Apply the same perceptual masking to the stochastic component
# This ensures it respects human visibility constraints
stochastic_masked = stochastic_mask * adaptive_strength_modulator * float(adjusted_cfg.amp)
# Blend deterministic and stochastic components using weighted sum
alpha = adjusted_cfg.stochastic_alpha # Weight for deterministic armor
beta = adjusted_cfg.stochastic_beta # Weight for stochastic mask
final_delta = alpha * delta_masked + beta * stochastic_masked
print(f"[ARMOR] SKIL defense ACTIVE: α={alpha:.2f} (deterministic), β={beta:.2f} (stochastic)")
print(f"[ARMOR] Server secret: {len(server_secret)} bytes, Image: {len(image_bytes)} bytes")
else:
print("[ARMOR] SKIL defense DISABLED: no server secret available (set GHOSTPRINT_SERVER_SECRET)")
# Start with a VERY conservative amplitude and let EOT find the sweet spot
# We want high mid-band but also good SSIM
amp_used = float(adjusted_cfg.amp)
# Conservative initial scale to preserve image quality
# The frequency distribution is already correct, we just need the right amplitude
# Start small and let EOT ramp up to the ceiling
initial_scale = 0.02 + (strength - 1.0) * 0.03 # Scales from 0.02x to 0.14x
out = _apply_delta_luma(arr, final_delta, amp_scale=initial_scale)
amp_used *= initial_scale
# SSIM check - ensure we start with acceptable quality
s = _ssim(arr, out)
# More strict SSIM requirements to keep image usable
if strength >= 4.5:
min_acceptable_ssim = 0.65 # Visible artifacts allowed at max strength
elif strength >= 3.0:
min_acceptable_ssim = 0.80 # Barely visible at high strength
else:
min_acceptable_ssim = 0.90 # Invisible at normal strength
if s < min_acceptable_ssim:
# Scale back to meet SSIM requirement
scale_back_factor = max(0.5, s / min_acceptable_ssim)
out = _apply_delta_luma(arr, final_delta, amp_scale=initial_scale * scale_back_factor)
amp_used *= scale_back_factor
s = _ssim(arr, out)
print(f"[ARMOR] Scaled back to SSIM {s:.3f} (target: {min_acceptable_ssim:.3f})")
# Track best result for mid-band
best_out = out.copy()
best_mid_band = 0.0
# Initialize best_metrics with current state to avoid None errors
delta_bands_init, _ = analyze_array_bands(final_delta)
best_metrics = (_ssim(arr, out), delta_bands_init, 0.0, amp_used)
# CRITICAL: Target 70%+ mid-band energy for maximum ML disruption
# At higher strengths, we can push even harder
if strength >= 4.5:
target_mid_band = 0.85 # 85% mid-band at max strength
elif strength >= 3.0:
target_mid_band = 0.75 # 75% mid-band at high strength
else:
target_mid_band = 0.70 # 70% mid-band at normal strength
for i in range(int(adjusted_cfg.eot_iters)):
ok, worst_tox, worst_ssim = _survival_ok(out, arr, adjusted_cfg)
# CRITICAL: Check current SSIM against original (not transformed)
current_ssim = _ssim(arr, out)
# CRITICAL: Check mid-band energy of the ARMOR DELTA, not the final image
delta_bands, _ = analyze_array_bands(final_delta)
current_mid = delta_bands["mid"] # This is what we're optimizing for
# Track best mid-band result
min_ssim_for_best = adjusted_cfg.ssim_floor * (0.85 - (strength - 1.0) * 0.05)
if current_mid > best_mid_band and current_ssim >= min_ssim_for_best:
best_mid_band = current_mid
best_out = out.copy()
best_metrics = (current_ssim, delta_bands, worst_tox, amp_used)
# CRITICAL: Stop immediately if SSIM drops below floor
# BUT: Only revert if the best result has decent mid-band (>50% of target)
if current_ssim < min_acceptable_ssim:
if best_metrics and best_metrics[1]["mid"] >= target_mid_band * 0.5:
print(f"[ARMOR] SSIM dropped to {current_ssim:.3f}, reverting to best (SSIM={best_metrics[0]:.3f}, mid={best_metrics[1]['mid']:.1%})")
out = best_out
amp_used = best_metrics[3]
break
else:
# Best result has poor mid-band, keep trying with lower amplitude
print(f"[ARMOR] SSIM dropped to {current_ssim:.3f}, but best has poor mid-band ({best_metrics[1]['mid']:.1%}), continuing...")
# Reduce amplitude slightly and continue
amp_used *= 0.95
out = _apply_delta_luma(arr, final_delta, amp_scale=(amp_used / float(adjusted_cfg.amp)))
# Success criteria depends on strength
# CRITICAL: We're optimizing for MID-BAND energy (0.10-0.40 normalized radius)
# This is where CNNs are most vulnerable - it disrupts feature extraction
if strength >= 4.5:
# At max strength, accept very high mid-band (85%+)
if current_mid >= 0.75: # Raised from 0.25
break
else:
# Normal criteria: hit target mid-band while maintaining quality
if ok and current_mid >= target_mid_band:
break
# SSIM tolerance - use our stricter requirements
if worst_ssim < min_acceptable_ssim * 0.95 and strength < 4.5:
# We've degraded quality too much, use best result
if best_metrics:
out = best_out
amp_used = best_metrics[3]
print(f"[ARMOR] SSIM too low ({worst_ssim:.3f}), using best result")
break
# At strength 5, ignore SSIM limits
if strength >= 4.5 and worst_ssim < 0.60:
# Too degraded even for strength 5
if best_metrics:
out = best_out
amp_used = best_metrics[3]
break
# Max amplitude check - use the hard ceiling
if amp_used >= adjusted_cfg.max_amp:
print(f"[ARMOR] Hit amplitude ceiling: {adjusted_cfg.max_amp:.2f}")
if best_metrics:
out = best_out
amp_used = best_metrics[3]
break
# Gradual amplitude increase to preserve SSIM while reaching target mid-band
# We already have the right frequency distribution, just need the right amplitude
strength_multiplier = 0.8 + (strength - 1.0) * 0.4 # Scales from 0.8x to 2.4x
# Adaptive step size based on how far we are from target
mid_band_deficit = target_mid_band - current_mid
if current_mid < 0.10:
# Very low mid-band, need aggressive increase
amp_step = adjusted_cfg.amp_step * 2.0 * strength_multiplier
elif mid_band_deficit > 0.30:
# Far from target (30%+ deficit), increase moderately
amp_step = adjusted_cfg.amp_step * 1.5 * strength_multiplier
elif mid_band_deficit > 0.10:
# Getting closer (10-30% deficit), gentle increase
amp_step = adjusted_cfg.amp_step * 1.0 * strength_multiplier
else:
# Near target (<10% deficit), very gentle
amp_step = adjusted_cfg.amp_step * 0.5 * strength_multiplier
# Check SSIM before applying increase
test_amp = amp_used + amp_step
test_out = _apply_delta_luma(arr, final_delta, amp_scale=(test_amp / float(adjusted_cfg.amp)))
test_ssim = _ssim(arr, test_out)
# Adaptive SSIM tolerance based on mid-band deficit
# If we're far from target mid-band, allow more SSIM degradation
if mid_band_deficit > 0.30:
ssim_tolerance = 0.85 # Allow more degradation when far from target
elif mid_band_deficit > 0.10:
ssim_tolerance = 0.92 # Moderate tolerance
else:
ssim_tolerance = 0.95 # Strict tolerance when near target
# Only increase if SSIM stays acceptable
if test_ssim >= min_acceptable_ssim * ssim_tolerance:
amp_used = test_amp
out = test_out
else:
# SSIM would drop too much, stop increasing
print(f"[ARMOR] Stopping at amp={amp_used:.2f}, SSIM would drop to {test_ssim:.3f} (mid-band: {current_mid:.1%})")
break
# CRITICAL FIX: The issue is that we're measuring the armor delta BEFORE applying amplitude
# But the EOT loop modifies amplitude, which doesn't change frequency distribution
# The frequency distribution is set during generation, not during amplitude scaling
# So we need to verify the GENERATION was correct, not the final scaled result
# The real issue: If best_out has low mid-band, we need to regenerate with more aggressive targeting
final_delta_bands, _ = analyze_array_bands(final_delta)
print(f"[ARMOR] Final armor delta bands - Low: {final_delta_bands['low']:.1%}, Mid: {final_delta_bands['mid']:.1%}, High: {final_delta_bands['high']:.1%}")
# If we ended up with poor mid-band, it means the generation phase failed
# This can happen with certain images - we need to force it
if final_delta_bands['mid'] < target_mid_band * 0.5: # Less than 50% of target
print(f"[ARMOR] Mid-band critically low ({final_delta_bands['mid']:.1%} < {target_mid_band * 0.5:.1%}), forcing aggressive rebalancing...")
# NUCLEAR OPTION: Completely regenerate the armor with pure mid-band focus
# Use ONLY the mid-band ring, no multi-ring composition
mid_ring = Ring(r1=0.10, r2=0.40, weight=1.0)
pure_mid_field = _cmt_filtered_field(gray.shape, seed + 99999, mid_ring)
# Apply extreme frequency domain filtering
F = fftshift(fft2(pure_mid_field))
mid_mask = _ring_mask(gray.shape, 0.10, 0.40).astype(np.float32)
# ONLY keep mid-band, zero everything else
F_pure_mid = F * mid_mask
# Boost it significantly
F_pure_mid *= 3.0
# Back to spatial
pure_mid_delta = np.real(ifft2(ifftshift(F_pure_mid))).astype(np.float32)
# Normalize
if pure_mid_delta.std() > 1e-6:
pure_mid_delta = pure_mid_delta / pure_mid_delta.std()
# Replace the delta with this pure mid-band version
# Keep the same perceptual masking
# Note: In nuclear rebalancing, we regenerate without SKIL defense
# This is a last-resort fallback for problematic images
final_delta = pure_mid_delta * adaptive_strength_modulator * float(adjusted_cfg.amp)
# Reapply with current amplitude
out = _apply_delta_luma(arr, final_delta, amp_scale=(amp_used / float(adjusted_cfg.amp)))
# Verify it worked
verify_bands, _ = analyze_array_bands(final_delta)
print(f"[ARMOR] After nuclear rebalancing - Mid: {verify_bands['mid']:.1%}")
Image.fromarray(out.astype(np.uint8)).save(out_path)
if return_metrics:
# CRITICAL FIX: Analyze the DELTA (armor) itself, not the final image
# The final image is dominated by the original's low-band content
# We need to measure the armor's frequency distribution
delta_bands, delta_tox = analyze_array_bands(final_delta)
# Also provide final image metrics for SSIM
final_bands, final_tox = analyze_array_bands(_rgb_to_gray(out))
final_ssim = _ssim(arr, out)
return {
"ssim": final_ssim,
# Armor delta frequency distribution (what we actually control)
"armor_bands_low": delta_bands["low"],
"armor_bands_mid": delta_bands["mid"],
"armor_bands_high": delta_bands["high"],
"armor_toxicity": delta_tox,
# Final image metrics (for reference)
"bands_low": final_bands["low"],
"bands_mid": final_bands["mid"],
"bands_high": final_bands["high"],
"toxicity": final_tox,
"amp_used": amp_used,
}
return None
# --------------------------- Analysis & transforms ---------------------------
def analyze_image_bands(path: str) -> Tuple[Dict[str, float], float]:
"""
FFT band energy (low/mid/high) + toxicity of an image at path.
Useful for reporting and regression tests.
"""
arr = _load_rgb(path)
return analyze_array_bands(_rgb_to_gray(arr))
def analyze_array_bands(gray: np.ndarray) -> Tuple[Dict[str, float], float]:
"""FFT band energy (low/mid/high) + toxicity of a grayscale array."""
P = _fft_power(gray, window=True)
return _band_energies(P), _toxicity(P)
def _save_spectrum_panels(gray_like: np.ndarray, out_png: str) -> None:
"""
Save a 1x4 panel of (full, low, mid, high) log-spectra with percentages.
Accepts either a grayscale image or a delta field.
"""
import matplotlib.pyplot as plt
if gray_like.ndim == 3:
gray = _rgb_to_gray(gray_like)
else:
gray = gray_like
P = _fft_power(gray, window=True)
lowM = _ring_mask(P.shape, 0.00, 0.10)
midM = _ring_mask(P.shape, 0.10, 0.40)
highM = _ring_mask(P.shape, 0.40, 1.00)
bands = _band_energies(P)
plt.figure(figsize=(20, 5))
plt.subplot(1, 4, 1); plt.imshow(np.log1p(P), cmap="magma"); plt.title("Full Spectrum (log)"); plt.axis("off")
plt.subplot(1, 4, 2); plt.imshow(np.log1p(P * lowM), cmap="magma"); plt.title(f"Low {bands['low']*100:.2f}%"); plt.axis("off")
plt.subplot(1, 4, 3); plt.imshow(np.log1p(P * midM), cmap="magma"); plt.title(f"Mid {bands['mid']*100:.2f}%"); plt.axis("off")
plt.subplot(1, 4, 4); plt.imshow(np.log1p(P * highM), cmap="magma"); plt.title(f"High {bands['high']*100:.2f}%"); plt.axis("off")
plt.tight_layout()
plt.savefig(out_png, dpi=150)
plt.close()
# --------------------------- Internals: transforms & EOT ---------------------------
def _load_rgb(path: str) -> np.ndarray:
"""Load an image as float32 RGB in [0,255]."""
img = Image.open(path)
if img is None:
raise FileNotFoundError(f"Failed to load image at path: {path}. The file may be corrupt or not a valid image.")
return np.asarray(img.convert("RGB")).astype(np.float32)
def _rgb_to_gray(arr: np.ndarray) -> np.ndarray:
"""Convert RGB to luminance (BT.601-ish)."""
return np.dot(arr, [0.2989, 0.5870, 0.1140]).astype(np.float32)
def _ssim(a_rgb: np.ndarray, b_rgb: np.ndarray) -> float:
"""SSIM computed on luminance; returns 0..1 (higher is more similar)."""
a = _rgb_to_gray(a_rgb)
b = _rgb_to_gray(b_rgb)
return float(ssim(a, b, data_range=255))
def _jpeg_roundtrip(arr: np.ndarray, quality: int) -> np.ndarray:
"""JPEG encode/decode in-memory with Pillow."""
im = Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8))
buf = io.BytesIO()
im.save(buf, format="JPEG", quality=int(quality), optimize=True)
buf.seek(0)
return np.asarray(Image.open(buf).convert("RGB")).astype(np.float32)
def _resize_roundtrip(arr: np.ndarray, scale: float) -> np.ndarray:
"""Resize down/up with bicubic to original size."""
H, W = arr.shape[:2]
if cv2 is None:
# Pillow fallback (slower)
im = Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8))
a = im.resize((int(W * scale), int(H * scale)), Image.BICUBIC)
b = a.resize((W, H), Image.BICUBIC)
return np.asarray(b).astype(np.float32)
out = cv2.resize(arr, (int(W * scale), int(H * scale)), interpolation=cv2.INTER_CUBIC)
out = cv2.resize(out, (W, H), interpolation=cv2.INTER_CUBIC)
return out.astype(np.float32)
def _gauss_blur(arr: np.ndarray, sigma: float) -> np.ndarray:
"""Apply per-channel Gaussian blur."""
out = np.zeros_like(arr)
for c in range(3):
out[:, :, c] = gaussian_filter(arr[:, :, c], sigma)
return out
def _survival_ok(armored_img: np.ndarray, original_img: np.ndarray, cfg: ArmorConfig) -> Tuple[bool, float, float]:
"""
Check robustness across a set of transforms. We apply transforms to the *armored*
image to simulate CDN / user edits and ensure toxicity survives.
The SSIM is always calculated against the pristine original image.
Returns:
(ok, worst_toxicity, worst_ssim)
"""
transforms: List[np.ndarray] = [
_jpeg_roundtrip(armored_img, 85),
_jpeg_roundtrip(armored_img, 75),
_resize_roundtrip(armored_img, 0.75),
_resize_roundtrip(armored_img, 1.25),
_gauss_blur(armored_img, 0.4),
_gauss_blur(armored_img, 0.8),
]
worst_tox = 1.0
worst_ssim = 1.0
passed_count = 0
for transformed_img in transforms:
# Toxicity of the transformed image
_bands, tox = analyze_array_bands(_rgb_to_gray(transformed_img))
# SSIM of transformed vs. original
s = _ssim(original_img, transformed_img)
worst_tox = min(worst_tox, tox)
worst_ssim = min(worst_ssim, s)
# A transform passes if toxicity and SSIM are within goals
if tox >= cfg.tox_goal and s >= cfg.ssim_floor:
passed_count += 1
# The armor is considered "ok" if a majority of transforms pass
is_ok = passed_count >= (len(transforms) // 2 + 1)
return is_ok, worst_tox, worst_ssim
def _to_uint8(arr: np.ndarray) -> np.ndarray:
return np.clip(arr, 0, 255).astype(np.uint8)
def _apply_delta_luma(arr_rgb: np.ndarray, delta_masked: np.ndarray, amp_scale: float = 1.0) -> np.ndarray:
"""
Apply a luminance delta to RGB by adding the same delta to all channels.
Enhanced to preserve mid-band frequency content better.
"""
delta = delta_masked * float(amp_scale)
# Apply delta to all channels
out = arr_rgb.astype(np.float32) + delta[..., None]
# Apply soft clipping to preserve more detail instead of hard clipping
# This helps maintain frequency content
out = np.where(out > 255, 255 + np.tanh((out - 255) / 50) * 50, out)
out = np.where(out < 0, np.tanh(out / 50) * 50, out)
return _to_uint8(out)
def _resize_field(field: np.ndarray, target_shape: Tuple[int, int], method: str) -> np.ndarray:
if field.shape == target_shape:
return field
H, W = target_shape
if method == "fft":
return _fft_resample_field(field, H, W)
else:
# Bicubic fallback (not spectrally faithful)
if cv2 is None:
im = Image.fromarray(field.astype(np.float32))
return np.asarray(im.resize((W, H), Image.BICUBIC)).astype(np.float32)
return cv2.resize(field, (W, H), interpolation=cv2.INTER_CUBIC).astype(np.float32)
# --------------------------- Convenience: apply from delta PNG ---------------------------
def apply_delta_autosize(
base_path: str,
delta_png_path: str,
amp: float,
out_path: str,
resize_method: str = "fft",
) -> Dict[str, float]:
"""
Apply a signed-delta PNG to any base image.
The delta is decoded and resized **in the frequency domain** (default) to
preserve its ring profile, then added uniformly to all channels.
Returns: metrics dict with SSIM, band energies, and toxicity.
"""
base = _load_rgb(base_path)
gray_base = _rgb_to_gray(base)
delta = _decode_signed_delta_png(delta_png_path, amp)
if delta.shape != gray_base.shape:
delta = _resize_field(delta, gray_base.shape, method=resize_method)
out = _apply_delta_luma(base, delta, amp_scale=1.0)
Image.fromarray(out.astype(np.uint8)).save(out_path)
bands, tox = analyze_array_bands(_rgb_to_gray(out))
return {
"ssim": _ssim(base, out),
"bands_low": bands["low"],
"bands_mid": bands["mid"],
"bands_high": bands["high"],
"toxicity": tox,
}
# --------------------------- __all__ ---------------------------
__all__ = [
"Ring",
"ArmorConfig",
"PureArmorSpec",
"ArmorMeta",
"ArmorGenerator",
"apply_delta_autosize",
"analyze_image_bands",
"analyze_array_bands",
]
|