test_dark_features.py 10 KB
"""Exercise the production feature, indexing, and FastAPI startup paths offline."""
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import os
from pathlib import Path
import threading

import cv2
from fastapi.testclient import TestClient
import numpy as np
from PIL import Image
import pytest
import torch

from app import create_app
from core import feature_extractor as feature_module
from core.feature_extractor import FeatureExtractor
from core.search_engine import ImageSearchEngine
from data_sync import DesignDataSync
from database import DatabaseManager
from tools.feature_consistency import compare_features, load_v3

FIXTURES = Path(__file__).with_name('fixtures')
RING = FIXTURES / 'dark-ring-00.jpg'


@pytest.fixture(scope='module', autouse=True)
def inference_threads():
    previous = torch.get_num_threads()
    torch.set_num_threads(1)
    yield
    torch.set_num_threads(previous)


@pytest.fixture(scope='module')
def extractor():
    return FeatureExtractor()


def config_for(tmp_path, dimension=1152):
    return {
        'database': {'sqlite': {'path': tmp_path / 'features.db'}},
        'feature_extractor': {'cnn': {'vector_dim': dimension}},
        'mysql': {},
    }


def design_record():
    return {'id': 1, 'eps_id': 2, 'design_no': 'D1', 'images': ['https://offline.test/image'],
            'utc_modified': datetime(2026, 11, 18)}


def test_dual_vector_order_and_norm(monkeypatch, extractor):
    with Image.open(RING) as image:
        rgb = np.array(image.convert('RGB'))
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    lab = cv2.cvtColor(rgb, cv2.COLOR_RGB2LAB)
    lab[:, :, 0] = clahe.apply(lab[:, :, 0])
    color = cv2.cvtColor(lab, cv2.COLOR_LAB2RGB)
    gray = clahe.apply(cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY))
    edges = cv2.cvtColor(cv2.Canny(gray, 50, 150), cv2.COLOR_GRAY2RGB)
    cnn_inputs = []
    cnn = extractor._cnn_vector

    def record(image):
        cnn_inputs.append(np.asarray(image).copy())
        return cnn(image)

    monkeypatch.setattr(extractor, '_cnn_vector', record)
    actual = extractor.extract_all_features(RING)['cnn_vector']
    assert actual.shape == (1152,) and actual.dtype == np.float32
    assert np.linalg.norm(actual) == pytest.approx(1.0, abs=1e-7)
    assert len(cnn_inputs) == 2
    np.testing.assert_array_equal(cnn_inputs[0], color)
    np.testing.assert_array_equal(cnn_inputs[1], edges)
    expected = np.concatenate((cnn(Image.fromarray(color)), cnn(Image.fromarray(edges))))
    np.testing.assert_array_equal(actual, expected / (np.linalg.norm(expected) + 1e-8))
    np.testing.assert_array_equal(extractor.extract_cnn_feature(RING), actual)


@pytest.mark.parametrize('name', ['zero_cnn', 'blank'])
def test_zero_cnn_or_blank_is_not_written(monkeypatch, extractor, tmp_path, name):
    path = tmp_path / 'main.jpg'
    if name == 'zero_cnn':
        path.write_bytes(RING.read_bytes())
        # A zero branch must fail even if the other branch is non-zero.
        outputs = iter((torch.ones((1, 576)), torch.zeros((1, 576))))
        monkeypatch.setattr(feature_module, '_torch_model', lambda tensor: next(outputs))
    else:
        Image.new('RGB', (64, 64), 'black').save(path)
        features = extractor.extract_all_features(path)
        assert features['orb_kp'] is None and features['orb_desc'] is None
        assert np.linalg.norm(features['cnn_vector']) == pytest.approx(1)
    sync = DesignDataSync(config_for(tmp_path), source=object(), downloader=lambda url: path, extractor=extractor)
    assert sync._process_design(design_record()) is False
    assert sync.db_manager.health_stats()['total_images'] == 0
    assert sync.index.stats()['total_vectors'] == 0
    assert sync.db_manager.max_feat_version() == 0


def test_nonuniform_orbless_image_can_be_written(extractor, tmp_path):
    path = tmp_path / 'main.png'
    image = Image.new('RGB', (16, 16), 'white')
    image.putpixel((4, 4), (0, 0, 0))
    image.save(path)
    features = extractor.extract_all_features(path)
    assert features['orb_kp'] is None and features['orb_desc'] is None
    sync = DesignDataSync(config_for(tmp_path), source=object(), downloader=lambda url: path, extractor=extractor)
    assert sync._process_design(design_record())
    assert sync.index.stats()['total_vectors'] == 1


def test_concurrent_extraction_is_thread_local_and_stable(extractor):
    workers = 3
    barrier = threading.Barrier(workers, timeout=10)
    paths = sorted(FIXTURES.glob('dark-ring-*.jpg'))[:workers]
    expected = [extractor.extract_all_features(path) for path in paths]

    def extract(path):
        operators = extractor.clahe, extractor.orb
        barrier.wait()
        actual = extractor.extract_all_features(path)
        assert operators == (extractor.clahe, extractor.orb)
        return operators, actual

    with ThreadPoolExecutor(max_workers=workers) as pool:
        runs = list(pool.map(extract, paths))
    for position in (0, 1):
        assert len({id(run[0][position]) for run in runs}) == workers
    for (_, actual), reference in zip(runs, expected):
        np.testing.assert_allclose(actual['cnn_vector'], reference['cnn_vector'], atol=1e-7)
        for key in ('orb_desc', 'orb_kp'):
            assert actual[key].tobytes() == reference[key].tobytes()


@pytest.mark.parametrize(('width', 'height', 'expected'), [
    (1313, 717, (559, 1024)), (1024, 405, (405, 1024)), (420, 320, (320, 420)),
])
def test_resize_only_orb_after_clahe(width, height, expected, monkeypatch, extractor):
    image = Image.new('RGB', (width, height), (15, 100, 200))
    raw = np.array(image)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    enhanced = clahe.apply(cv2.cvtColor(raw, cv2.COLOR_RGB2GRAY))
    if enhanced.shape != expected:
        expected_orb = cv2.resize(enhanced, expected[::-1], interpolation=cv2.INTER_AREA)
    else:
        expected_orb = enhanced
    canny = cv2.Canny
    observed = []

    def record_canny(gray, low, high):
        np.testing.assert_array_equal(gray, enhanced)
        assert (low, high) == (50, 150)
        observed.append('canny')
        return canny(gray, low, high)

    class Detector:
        def detectAndCompute(self, gray, mask):
            np.testing.assert_array_equal(gray, expected_orb)
            observed.append('orb')
            return (), None

    monkeypatch.setattr(cv2, 'Canny', record_canny)
    monkeypatch.setattr(extractor._local, 'orb', Detector())
    features = extractor.extract_all_features(image)
    assert observed == ['canny', 'orb']
    assert features['orb_kp'] is None and features['orb_desc'] is None


def test_same_image_search_ransac(extractor, tmp_path):
    config = config_for(tmp_path)
    sync = DesignDataSync(config, source=object(), downloader=lambda url: RING, extractor=extractor)
    assert sync._process_design(design_record())
    engine = ImageSearchEngine(config=config, index=sync.index, db_manager=sync.db_manager, extractor=extractor)
    result, = engine.search(RING, eps_id=2)
    assert result['img_id'] == 1
    assert result['details']['ransac_inliers'] > 50
    print(f"Same-image RANSAC inliers: {result['details']['ransac_inliers']}")


def test_even_number_of_old_vectors_refuses_startup(tmp_path):
    config = config_for(tmp_path)
    db = DatabaseManager(config['database']['sqlite']['path'])
    for design_id in (1, 2):
        db.upsert(design_id, 2, 'D', 'https://offline.test/image',
                  {'cnn_vector': np.ones(576, np.float32)}, design_id, None)
    app = create_app(config)
    with pytest.raises(ValueError, match=r'design 1.*1152.*576'), TestClient(app):
        pytest.fail('Started with a 576-dimensional store')
    assert app.state.sync_thread is None


def test_empty_db_wrong_config_refuses_startup(tmp_path):
    app = create_app(config_for(tmp_path, 576))
    with pytest.raises(RuntimeError, match='index=576, config=576, probe=1152'), TestClient(app):
        pytest.fail('Started with a dimension mismatch')
    assert app.state.sync_thread is None


@pytest.mark.parametrize('vector', [None, np.zeros(1152, np.float32), np.full(1152, np.inf, np.float32),
                                     np.ones(1152, np.float64), np.ones(576, np.float32)])
def test_startup_self_check_rejects_failed_probe(tmp_path, monkeypatch, vector):
    monkeypatch.setattr(FeatureExtractor, 'extract_all_features', lambda self, path: {'cnn_vector': vector})
    app = create_app(config_for(tmp_path))
    with pytest.raises(RuntimeError, match='Feature self-check failed'), TestClient(app):
        pytest.fail('Started after a failed feature self-check')
    assert app.state.sync_thread is None


def test_startup_logs_versions_and_weights_digest(tmp_path, monkeypatch, caplog):
    monkeypatch.setattr(DesignDataSync, 'run_forever', lambda sync: sync.stop_event.wait(5))
    app = create_app(config_for(tmp_path))
    with caplog.at_level('INFO'), TestClient(app) as client:
        assert client.get('/health').status_code == 200
    assert 'torch=2.0.1+cpu torchvision=0.15.2+cpu cv2=4.8.1 Pillow=10.1.0 AVIF=1.6.0 numpy=1.24.3' in caplog.text
    digest = caplog.text.split('weights sha256=', 1)[1].split()[0]
    assert len(digest) == 64 and int(digest, 16)


def test_v3_working_tree_equivalence(extractor):
    source_path = os.environ.get('DIS_V3_FEATURE_EXTRACTOR')
    if not source_path:
        pytest.skip('Set DIS_V3_FEATURE_EXTRACTOR to the V3 working-tree feature_extractor.py path')
    paths = sorted(path for path in FIXTURES.iterdir() if path.suffix in ('.jpg', '.avif'))
    assert len(paths) >= 20
    assert sum(path.stat().st_size for path in paths) < 2_000_000
    with Image.open(FIXTURES / 'dark-ring.avif') as image:
        assert image.format == 'AVIF'
    with Image.open(RING) as image:
        assert max(image.size) > 1024
    reference, digest = load_v3(Path(source_path))
    summary, results = compare_features(paths, extractor.extract_all_features, reference)
    print(f'V3 source sha256: {digest}\nV3 comparison: {summary}')
    assert summary['cnn_mismatches'] == 0, results
    assert summary['orb_descriptor_mismatches'] == 0, results
    assert summary['orb_coordinate_mismatches'] == 0, results