Files
jwxt/app/watermark_util.py
T

220 lines
7.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
盲水印工具模块 — 截图表溯源
使用 blind-watermark (DWT-DCT-SVD) 在极弱噪点纹理中嵌入用户ID,
页面作为 CSS 背景平铺。用户肉眼不可见,但截图包含水印,可解码溯源。
工作流:
嵌入: 生成噪点纹理 -> 嵌入 "uid=xxx|ts=..." -> 返回 PNG 字节
解码: 截图(PNG/JPG) -> extract -> 解析 uid
"""
import io
import os
import time
from datetime import datetime
import numpy as np
import cv2
from blind_watermark import WaterMark, bw_notes
bw_notes.close()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CARRIER_PATH = os.path.join(BASE_DIR, "static", "carrier.png")
CARRIER_DARK_PATH = os.path.join(BASE_DIR, "static", "carrier_dark.png")
CARRIER_SIZE = 256 # 纹理尺寸
# 浅色载体:匹配 bg-gray-50 (#f9fafb ≈ 250)
CARRIER_BASE = 248
# 暗色载体:匹配 dark mode 背景 (#0a0a0a ≈ 10)
CARRIER_BASE_DARK = 12
# 噪点范围(±4,单像素差异 ≤1.5%,肉眼完全不可分辨)
CARRIER_NOISE_RANGE = 4
WM_BYTES = 96 # 水印最大字节数(UTF-8 编码后)
WM_BITS = WM_BYTES * 8 # 768 bit — 使用 mode='bit' 精确编码,每字节固定 8 bit
WM_SHAPE = WM_BITS # 兼容旧代码的引用名
# ==================== 纹理生成 ====================
def _generate_noise_carrier(path: str, base: int, noise_range: int, seed: int = 42) -> str:
"""内部:生成噪点纹理载体图。"""
np.random.seed(seed)
half_range = noise_range
noise = np.random.randint(
base - half_range, base + half_range + 1,
(CARRIER_SIZE, CARRIER_SIZE), dtype=np.uint8
)
noise_rgb = cv2.cvtColor(noise, cv2.COLOR_GRAY2BGR)
os.makedirs(os.path.dirname(path), exist_ok=True)
cv2.imwrite(path, noise_rgb)
return path
def generate_carrier(path: str = None) -> str:
"""生成浅色噪点纹理载体图(匹配 bg-gray-50 ≈ 250)。"""
if path is None:
path = CARRIER_PATH
return _generate_noise_carrier(path, CARRIER_BASE, CARRIER_NOISE_RANGE)
def generate_carrier_dark(path: str = None) -> str:
"""生成暗色噪点纹理载体图(匹配 dark mode 背景 #0a0a0a ≈ 10)。"""
if path is None:
path = CARRIER_DARK_PATH
return _generate_noise_carrier(path, CARRIER_BASE_DARK, CARRIER_NOISE_RANGE, seed=43)
def ensure_carrier() -> str:
"""确保浅色载体图存在,不存在则生成。"""
if not os.path.exists(CARRIER_PATH):
generate_carrier(CARRIER_PATH)
return CARRIER_PATH
def ensure_carrier_dark() -> str:
"""确保暗色载体图存在,不存在则生成。"""
if not os.path.exists(CARRIER_DARK_PATH):
generate_carrier_dark(CARRIER_DARK_PATH)
return CARRIER_DARK_PATH
# ==================== 比特编解码(mode='bit') ====================
def _str_to_bits(s: str, num_bits: int = None) -> np.ndarray:
"""字符串 → 固定宽度比特数组(UTF-8 编码,每字节精确 8 bit)。
与 blind-watermark mode='str' 不同,mode='str' 使用
bin(int(hex(utf8_bytes))) 丢弃前导零,导致可变比特宽度;
本函数保证每字节固定 8 bit,中文/ASCII 统一对待。
"""
if num_bits is None:
num_bits = WM_BITS
content_bytes = s.encode('utf-8')
max_bytes = num_bits // 8
if len(content_bytes) > max_bytes:
# 截断:留最后一字节给截断标记
content_bytes = content_bytes[:max_bytes - 1] + b'.'
content_bytes = content_bytes.ljust(max_bytes, b'\x00')
bits = []
for b in content_bytes:
bits.extend(int(bit) for bit in format(b, '08b'))
return np.array(bits[:num_bits], dtype=bool)
def _bits_to_str(bits: np.ndarray) -> str:
"""比特数组 → UTF-8 字符串(去尾部空字节)。"""
byte_vals = []
for i in range(0, len(bits), 8):
byte_bits = bits[i:i + 8]
if len(byte_bits) < 8:
break
val = int(''.join(str(int(b)) for b in byte_bits), 2)
byte_vals.append(val)
return bytes(byte_vals).decode('utf-8', errors='replace').rstrip('\x00')
# ==================== 嵌入 ====================
def _embed_into_carrier(user_identifier: str, carrier_path: str,
password_img: int = 1, password_wm: int = 1) -> bytes:
"""内部:将水印嵌入指定载体(使用 mode='bit' 避免中文乱码)。"""
bits = _str_to_bits(user_identifier, WM_BITS)
bwm = WaterMark(password_img=password_img, password_wm=password_wm)
bwm.read_img(carrier_path)
bwm.read_wm(bits, mode="bit")
tmp_path = os.path.join(os.path.dirname(carrier_path), "_wm_tmp.png")
bwm.embed(tmp_path)
img = cv2.imread(tmp_path)
compact_path = tmp_path + ".compact.png"
cv2.imwrite(compact_path, img, [cv2.IMWRITE_PNG_COMPRESSION, 9])
with open(compact_path, "rb") as f:
data = f.read()
return data
def embed_watermark(user_identifier: str, password_img: int = 1, password_wm: int = 1) -> bytes:
"""将用户标识嵌入浅色载体纹理,返回带水印的 PNG 字节。"""
return _embed_into_carrier(user_identifier, ensure_carrier(),
password_img, password_wm)
def embed_watermark_dark(user_identifier: str, password_img: int = 1, password_wm: int = 1) -> bytes:
"""将用户标识嵌入暗色载体纹理,返回带水印的 PNG 字节。"""
return _embed_into_carrier(user_identifier, ensure_carrier_dark(),
password_img, password_wm)
# ==================== 解码 ====================
def extract_watermark(screenshot_path: str, password_img: int = 1, password_wm: int = 1) -> dict:
"""从截图中提取盲水印(使用 mode='bit' 支持中文)。
Args:
screenshot_path: 截图文件路径
password_img: 图片密钥
password_wm: 水印密钥
Returns:
dict:
success: bool
raw: 提取到的原始字符串(去尾部空字节)
info: 解析后的 dict (u, n, m, j, t, i 等字段)
"""
try:
result = {"success": False, "raw": "", "info": {}}
img = cv2.imread(screenshot_path)
if img is None:
result["raw"] = f"无法读取图片: {screenshot_path}"
return result
h, w = img.shape[:2]
# 从截图边角裁出多个 CARRIER_SIZE×CARRIER_SIZE 块尝试解码
corners = [
("top_left", 0, 0),
("top_right", max(0, w - CARRIER_SIZE), 0),
("bottom_left", 0, max(0, h - CARRIER_SIZE)),
("bottom_right", max(0, w - CARRIER_SIZE), max(0, h - CARRIER_SIZE)),
]
for label, x, y in corners:
if x + CARRIER_SIZE > w or y + CARRIER_SIZE > h:
continue
crop = img[y:y + CARRIER_SIZE, x:x + CARRIER_SIZE]
tmp = os.path.join(os.path.dirname(CARRIER_PATH), f"_decode_{label}.png")
cv2.imwrite(tmp, crop)
try:
bwm = WaterMark(password_img=password_img, password_wm=password_wm)
extracted_bits = bwm.extract(tmp, wm_shape=WM_BITS, mode="bit")
raw = _bits_to_str(extracted_bits)
if raw and len(raw.strip()) >= 2:
result["success"] = True
result["raw"] = raw.strip()
break
except Exception:
continue
# 解析 key=value|key=value 格式
for part in result["raw"].split("|"):
if "=" in part:
k, v = part.split("=", 1)
result["info"][k.strip()] = v.strip()
return result
except Exception as e:
return {"success": False, "raw": str(e), "info": {}}
# ==================== 首次导入时确保载体存在 ====================
ensure_carrier()
ensure_carrier_dark()