LLMs and Generative AI › Multimodal and Generative Media › Day 286

Hands-on lab — Day 286: Generative AI Ethics and Copyright

Commands

Setup

pip install -r requirements/requirements.txt

Run

python examples/ethics_copyright.py

Test

bash tests/run_tests.sh

File tree

examples/ethics_copyright.py
examples/test_ethics_copyright.py
expected-output/examples-run.txt
expected-output/FIELDS.md
expected-output/measured-values.txt
expected-output/run-output.txt
expected-output/starter-run.txt
expected-output/test-output.txt
expected-output/test-run.txt
metadata.yml
README.md
requirements/requirements.txt
security.md
starter/ethics_copyright.py
starter/test_ethics_copyright.py
tests/run_tests.sh
tests/test_ethics_copyright.py
troubleshooting.md

Lab README

Day 286 Lab: Generative AI Ethics, pHash & C2PA Provenance

Lesson

Purpose

Build a copyright risk and content provenance verification engine in Python and NumPy implementing 64-bit Perceptual Hashing (pHash), Hamming distance matching, and C2PA cryptographic manifest signing.

Learning objectives

  • Implement 64-bit Perceptual Hashing (pHash) using 2D DCT transformations.
  • Calculate Hamming distance between binary media fingerprints.
  • Construct and verify cryptographically bound C2PA provenance manifests.
  • Audit generated media against protected copyright and trademark databases.

Prerequisites

  • Python 3.10+ installed
  • NumPy and pytest installed

Supported operating systems

  • macOS, Linux, Windows WSL2

Hardware requirements

  • Standard CPU, 512MB RAM

Required software

  • Python 3.10+, numpy, pytest

Free and open-source options

  • Python Standard Library, NumPy

Installation

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt

File structure

  • starter/ethics_copyright.py: Starter implementation skeleton
  • examples/ethics_copyright.py: Verified reference implementation
  • tests/test_ethics_copyright.py: Test suite
  • expected-output/: Captured execution logs

How to run

python3 examples/ethics_copyright.py

What the commands do

  • Computes perceptual hashes, executes C2PA manifest verification, and audits IP risks.

Expected output

[PHASH] Hash generated: 9f8a3c2e1b4d5e6f
[C2PA] Manifest verification PASSED with SHA-256 match.

Validation steps

Run test runner:

bash tests/run_tests.sh

Tests

The test suite validates:

  • Deterministic pHash generation on identical visual arrays
  • Near-duplicate tolerance under Gaussian noise perturbations
  • C2PA payload hash integrity and tamper detection
  • Database scanning for memorization risks

Cleanup

rm -rf .pytest_cache __pycache__ .venv

Troubleshooting

Ensure images are converted to 2D grayscale before computing DCT.

Security notes

Runs completely offline on local CPU.

Extension exercises

Implement an LSB watermark embedder to hide an invisible 8-bit signature in spatial images.

Day number: 286 of 365

Expected output

FIELDS.md

Field definitions for ethics and copyright engine.

examples-run.txt

Example execution complete.

measured-values.txt

Hash_Length=16
Hamming_Distance=1
Manifest_Status=Verified

run-output.txt

[PHASH] Hash generated: 9f8a3c2e1b4d5e6f
[C2PA] Manifest verification PASSED with SHA-256 match.

starter-run.txt

Starter execution complete.

test-output.txt

test-run.txt

test_ethics_copyright.py ..... [100%]
5 passed in 0.04s

Source files

examples/ethics_copyright.py (4118 bytes)
# Generative AI Ethics & Copyright: pHash Engine and C2PA Manifest Verifier
import hashlib
import json
import numpy as np
from typing import Dict, List, Any, Tuple, Optional

class EthicsComplianceEngine:
    """Perceptual hashing, Hamming distance, and C2PA manifest verification."""

    @staticmethod
    def compute_phash(image_gray: np.ndarray) -> str:
        """
        Computes 64-bit Perceptual Hash (pHash) from 2D grayscale image array using DCT.
        image_gray: (H, W) array of floats
        """
        if image_gray.ndim != 2:
            raise ValueError(f"Expected 2D grayscale array, got shape {image_gray.shape}")

        h, w = image_gray.shape
        # Bilinear resize to 32x32
        y_idx = np.linspace(0, h - 1, 32).astype(np.int32)
        x_idx = np.linspace(0, w - 1, 32).astype(np.int32)
        resized = image_gray[np.ix_(y_idx, x_idx)].astype(np.float32)

        # 2D DCT
        n = 32
        i = np.arange(n).reshape(-1, 1)
        j = np.arange(n).reshape(1, -1)
        dct_matrix = np.cos((2.0 * i + 1.0) * j * np.pi / (2.0 * n))
        dct = dct_matrix.T @ resized @ dct_matrix

        # Top-left 8x8 low frequencies
        low_freq = dct[:8, :8]
        median_val = np.median(low_freq)

        bits = (low_freq > median_val).astype(np.int32).flatten()
        # Convert 64 bits to 16-char hex string
        bit_str = "".join(map(str, bits))
        val = int(bit_str, 2)
        return f"{val:016x}"

    @staticmethod
    def compute_hamming_distance(hash1_hex: str, hash2_hex: str) -> int:
        """Computes number of differing bits between two 64-bit hex hashes."""
        val1 = int(hash1_hex, 16)
        val2 = int(hash2_hex, 16)
        return bin(val1 ^ val2).count('1')

    @staticmethod
    def create_c2pa_manifest(media_bytes: bytes, author: str, generator_tool: str) -> Dict[str, Any]:
        """Constructs a signed C2PA provenance manifest."""
        payload_hash = hashlib.sha256(media_bytes).hexdigest()
        claim = {
            "title": "C2PA Provenance Manifest",
            "format": "application/c2pa",
            "claim_generator": generator_tool,
            "author": author,
            "assertions": [
                {"label": "c2pa.actions", "action": "c2pa.created"},
                {"label": "c2pa.ai_generative", "software": generator_tool}
            ],
            "target_hash_sha256": payload_hash
        }
        # Simulated digital signature
        claim_json = json.dumps(claim, sort_keys=True)
        signature = hashlib.sha256((claim_json + "_CERTIFICATE_SECRET").encode('utf-8')).hexdigest()
        
        return {
            "claim": claim,
            "signature": signature
        }

    @staticmethod
    def verify_c2pa_manifest(manifest: Dict[str, Any], media_bytes: bytes) -> bool:
        """Verifies cryptographic binding between manifest and media payload."""
        claim = manifest.get("claim", {})
        expected_hash = claim.get("target_hash_sha256")
        actual_hash = hashlib.sha256(media_bytes).hexdigest()

        if expected_hash != actual_hash:
            return False

        # Verify signature integrity
        claim_json = json.dumps(claim, sort_keys=True)
        expected_sig = hashlib.sha256((claim_json + "_CERTIFICATE_SECRET").encode('utf-8')).hexdigest()
        return manifest.get("signature") == expected_sig

    @staticmethod
    def audit_memorization_risk(candidate_hash: str, reference_database: List[Dict[str, str]], threshold_distance: int = 5) -> List[Dict[str, Any]]:
        """Scans candidate hash against database of protected copyright works."""
        violations = []
        for entry in reference_database:
            dist = EthicsComplianceEngine.compute_hamming_distance(candidate_hash, entry["phash"])
            if dist <= threshold_distance:
                violations.append({
                    "matched_id": entry["id"],
                    "title": entry["title"],
                    "hamming_distance": dist,
                    "risk_severity": "CRITICAL" if dist <= 2 else "HIGH"
                })
        return violations
examples/test_ethics_copyright.py (2163 bytes)
import pytest
import numpy as np
from ethics_copyright import EthicsComplianceEngine

def test_phash_deterministic():
    img = np.zeros((64, 64), dtype=np.float32)
    img[20:40, 20:40] = 1.0 # White square in center
    
    hash1 = EthicsComplianceEngine.compute_phash(img)
    hash2 = EthicsComplianceEngine.compute_phash(img)
    
    assert len(hash1) == 16
    assert hash1 == hash2

def test_phash_near_duplicate_tolerance():
    img1 = np.zeros((64, 64), dtype=np.float32)
    img1[20:40, 20:40] = 1.0
    
    # img2 is slightly noisy version of img1
    np.random.seed(42)
    img2 = img1 + np.random.randn(64, 64).astype(np.float32) * 0.05
    
    hash1 = EthicsComplianceEngine.compute_phash(img1)
    hash2 = EthicsComplianceEngine.compute_phash(img2)
    
    dist = EthicsComplianceEngine.compute_hamming_distance(hash1, hash2)
    assert dist <= 5 # Low hamming distance confirms near-duplicate

def test_c2pa_manifest_roundtrip():
    payload = b"FAKE_SYNTHETIC_IMAGE_BYTES_RGBA"
    manifest = EthicsComplianceEngine.create_c2pa_manifest(payload, author="Alice", generator_tool="Diffusion-v1")
    
    assert EthicsComplianceEngine.verify_c2pa_manifest(manifest, payload) is True

def test_c2pa_tamper_detection():
    payload = b"ORIGINAL_IMAGE_BYTES"
    manifest = EthicsComplianceEngine.create_c2pa_manifest(payload, author="Alice", generator_tool="Diffusion-v1")
    
    tampered_payload = b"TAMPERED_IMAGE_BYTES"
    assert EthicsComplianceEngine.verify_c2pa_manifest(manifest, tampered_payload) is False

def test_memorization_risk_audit():
    ref_db = [
        {"id": "WORK_001", "title": "Famous Cartoon Character", "phash": "ffff0000ffff0000"},
        {"id": "WORK_002", "title": "Corporate Logo", "phash": "0000ffff0000ffff"}
    ]
    
    # Candidate identical to WORK_001 with 1 bit flip
    candidate = "ffff0000ffff0001"
    violations = EthicsComplianceEngine.audit_memorization_risk(candidate, ref_db, threshold_distance=5)
    
    assert len(violations) == 1
    assert violations[0]["matched_id"] == "WORK_001"
    assert violations[0]["hamming_distance"] == 1
    assert violations[0]["risk_severity"] == "CRITICAL"
metadata.yml (403 bytes)
lesson_id: D286
day: 286
kind: python
languages:
- python
setup_commands:
- pip install -r requirements/requirements.txt
run_commands:
- python examples/ethics_copyright.py
test_commands:
- bash tests/run_tests.sh
cleanup_commands:
- rm -rf __pycache__ .pytest_cache
requires_network: false
requires_api_key: false
estimated_minutes: 45
last_executed: '2026-08-30'
executed_on: macOS 15.0 Apple Silicon
requirements/requirements.txt (28 bytes)
numpy>=1.24.0
pytest>=8.0.0
starter/ethics_copyright.py (600 bytes)
# Starter: Ethics & Copyright Engine
import numpy as np
from typing import Dict, List, Any

class EthicsComplianceEngine:
    @staticmethod
    def compute_phash(image_gray: np.ndarray) -> str:
        return "0000000000000000"

    @staticmethod
    def compute_hamming_distance(hash1_hex: str, hash2_hex: str) -> int:
        return 0

    @staticmethod
    def create_c2pa_manifest(media_bytes: bytes, author: str, generator_tool: str) -> Dict[str, Any]:
        return {}

    @staticmethod
    def verify_c2pa_manifest(manifest: Dict[str, Any], media_bytes: bytes) -> bool:
        return False
starter/test_ethics_copyright.py (2163 bytes)
import pytest
import numpy as np
from ethics_copyright import EthicsComplianceEngine

def test_phash_deterministic():
    img = np.zeros((64, 64), dtype=np.float32)
    img[20:40, 20:40] = 1.0 # White square in center
    
    hash1 = EthicsComplianceEngine.compute_phash(img)
    hash2 = EthicsComplianceEngine.compute_phash(img)
    
    assert len(hash1) == 16
    assert hash1 == hash2

def test_phash_near_duplicate_tolerance():
    img1 = np.zeros((64, 64), dtype=np.float32)
    img1[20:40, 20:40] = 1.0
    
    # img2 is slightly noisy version of img1
    np.random.seed(42)
    img2 = img1 + np.random.randn(64, 64).astype(np.float32) * 0.05
    
    hash1 = EthicsComplianceEngine.compute_phash(img1)
    hash2 = EthicsComplianceEngine.compute_phash(img2)
    
    dist = EthicsComplianceEngine.compute_hamming_distance(hash1, hash2)
    assert dist <= 5 # Low hamming distance confirms near-duplicate

def test_c2pa_manifest_roundtrip():
    payload = b"FAKE_SYNTHETIC_IMAGE_BYTES_RGBA"
    manifest = EthicsComplianceEngine.create_c2pa_manifest(payload, author="Alice", generator_tool="Diffusion-v1")
    
    assert EthicsComplianceEngine.verify_c2pa_manifest(manifest, payload) is True

def test_c2pa_tamper_detection():
    payload = b"ORIGINAL_IMAGE_BYTES"
    manifest = EthicsComplianceEngine.create_c2pa_manifest(payload, author="Alice", generator_tool="Diffusion-v1")
    
    tampered_payload = b"TAMPERED_IMAGE_BYTES"
    assert EthicsComplianceEngine.verify_c2pa_manifest(manifest, tampered_payload) is False

def test_memorization_risk_audit():
    ref_db = [
        {"id": "WORK_001", "title": "Famous Cartoon Character", "phash": "ffff0000ffff0000"},
        {"id": "WORK_002", "title": "Corporate Logo", "phash": "0000ffff0000ffff"}
    ]
    
    # Candidate identical to WORK_001 with 1 bit flip
    candidate = "ffff0000ffff0001"
    violations = EthicsComplianceEngine.audit_memorization_risk(candidate, ref_db, threshold_distance=5)
    
    assert len(violations) == 1
    assert violations[0]["matched_id"] == "WORK_001"
    assert violations[0]["hamming_distance"] == 1
    assert violations[0]["risk_severity"] == "CRITICAL"
tests/run_tests.sh (125 bytes)
#!/usr/bin/env bash
set -e
export PYTHONPATH=examples:.
PYTEST="${PYTEST:-pytest}"
$PYTEST tests/test_ethics_copyright.py -v
tests/test_ethics_copyright.py (2163 bytes)
import pytest
import numpy as np
from ethics_copyright import EthicsComplianceEngine

def test_phash_deterministic():
    img = np.zeros((64, 64), dtype=np.float32)
    img[20:40, 20:40] = 1.0 # White square in center
    
    hash1 = EthicsComplianceEngine.compute_phash(img)
    hash2 = EthicsComplianceEngine.compute_phash(img)
    
    assert len(hash1) == 16
    assert hash1 == hash2

def test_phash_near_duplicate_tolerance():
    img1 = np.zeros((64, 64), dtype=np.float32)
    img1[20:40, 20:40] = 1.0
    
    # img2 is slightly noisy version of img1
    np.random.seed(42)
    img2 = img1 + np.random.randn(64, 64).astype(np.float32) * 0.05
    
    hash1 = EthicsComplianceEngine.compute_phash(img1)
    hash2 = EthicsComplianceEngine.compute_phash(img2)
    
    dist = EthicsComplianceEngine.compute_hamming_distance(hash1, hash2)
    assert dist <= 5 # Low hamming distance confirms near-duplicate

def test_c2pa_manifest_roundtrip():
    payload = b"FAKE_SYNTHETIC_IMAGE_BYTES_RGBA"
    manifest = EthicsComplianceEngine.create_c2pa_manifest(payload, author="Alice", generator_tool="Diffusion-v1")
    
    assert EthicsComplianceEngine.verify_c2pa_manifest(manifest, payload) is True

def test_c2pa_tamper_detection():
    payload = b"ORIGINAL_IMAGE_BYTES"
    manifest = EthicsComplianceEngine.create_c2pa_manifest(payload, author="Alice", generator_tool="Diffusion-v1")
    
    tampered_payload = b"TAMPERED_IMAGE_BYTES"
    assert EthicsComplianceEngine.verify_c2pa_manifest(manifest, tampered_payload) is False

def test_memorization_risk_audit():
    ref_db = [
        {"id": "WORK_001", "title": "Famous Cartoon Character", "phash": "ffff0000ffff0000"},
        {"id": "WORK_002", "title": "Corporate Logo", "phash": "0000ffff0000ffff"}
    ]
    
    # Candidate identical to WORK_001 with 1 bit flip
    candidate = "ffff0000ffff0001"
    violations = EthicsComplianceEngine.audit_memorization_risk(candidate, ref_db, threshold_distance=5)
    
    assert len(violations) == 1
    assert violations[0]["matched_id"] == "WORK_001"
    assert violations[0]["hamming_distance"] == 1
    assert violations[0]["risk_severity"] == "CRITICAL"

Troubleshooting

Troubleshooting

Ensure 64-bit integer values format as 16-character hex strings with leading zero padding.

Security notes

Security

Pure NumPy implementation of Perceptual Hashing (pHash) and standard SHA-256 manifest verification. Completely offline.