test_equivalence.py 4.87 KB
"""Production HEAD reference modules are frozen verbatim alongside these tests."""
import ast
from pathlib import Path
from types import SimpleNamespace

import cv2
import numpy as np
import pytest

from core.feature_extractor import FeatureExtractor
from core.search_engine import ImageSearchEngine
from core.vector_index import VectorIndex
from database import DatabaseManager


def reference_class(module, name):
    # Compile only the original class, avoiding its obsolete dependency imports.
    tree = ast.parse(Path(__file__).with_name('reference_' + module + '.py').read_text(encoding='utf-8'))
    cls = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == name)
    scope = {'np': np, 'cv2': cv2, 'logger': __import__('logging').getLogger('reference')}
    exec(compile(ast.Module(body=[cls], type_ignores=[]), module, 'exec'), scope)
    return scope[name]


@pytest.mark.parametrize('weights', [{}, {'cnn': 0.37, 'ransac': 0.63}])
def test_scores_and_confidence_match_production(tmp_path, weights):
    old_cls = reference_class('search_engine', 'ImageSearchEngine')
    old = old_cls.__new__(old_cls)
    old.weights = {'cnn': weights.get('cnn', .2) * 100, 'ransac': weights.get('ransac', .8) * 100}
    old.max_candidates = old.cnn_top_k = 20
    old.top_results = 20
    sims = [.9, .81, .8, .75, .71, .7, .5]
    inliers = [18, 15, 16, 8, 7, 20, 0]
    query = {'cnn_vector': np.eye(1, 1152, dtype=np.float32)[0],
             'orb_kp': np.zeros((20, 2), np.float32), 'orb_desc': np.zeros((20, 32), np.uint8)}
    index = VectorIndex()
    db = DatabaseManager(tmp_path / 'features.db')
    for i, sim in enumerate(sims, 1):
        vector = np.zeros(1152, np.float32)
        vector[:2] = [sim, np.sqrt(1 - sim * sim)]
        features = dict(query, cnn_vector=vector,
                        orb_desc=np.full((20, 32), i, np.uint8))
        db.upsert(i, 2, str(i), 'https://image/' + str(i), features, i, None)
        index.upsert(i, 2, vector, i)
    recalled = index.search(query['cnn_vector'], 2, 20)
    old.faiss_manager = SimpleNamespace(search=lambda *a, **kw: [(i, sim) for i, sim, _ in recalled])
    old.memory_index = SimpleNamespace(img_metadata={str(i): {'path': str(i)} for i in range(1, 8)})
    old.extractor = SimpleNamespace(extract_all_features=lambda path: query)
    old._ransac_verify_single = lambda i, *args: inliers[i - 1]
    options = {'min_inliers': 11, 'reproj_threshold': 3.5, 'confidence': .98}
    calls = []
    def ransac(q, candidate, **kwargs):
        calls.append(kwargs)
        return inliers[int(candidate[1][0, 0]) - 1]
    extractor = SimpleNamespace(extract_all_features=lambda path: query, compute_orb_ransac_score=ransac)
    new = ImageSearchEngine(config={'search': {'fusion_weights': weights, 'ransac': options}},
                            index=index, db_manager=db, extractor=extractor)
    actual, expected = new.search('query', 2), old.search('query')
    assert [(r['img_id'], r['score'], r['confidence'], r['details']) for r in actual] == [
        (r['img_id'], r['score'], r['confidence'], r['details']) for r in expected]
    assert calls == [{'min_inliers': 11, 'ransac_thresh': 3.5, 'confidence': .98}] * 7


@pytest.mark.parametrize('scale,min_inliers', [(1., 15), (1., 33), (.2, 15), (4., 15)])
def test_array_ransac_matches_original_keypoints(scale, min_inliers):
    old_cls = reference_class('feature_extractor', 'FeatureExtractor')
    old = old_cls.__new__(old_cls)
    new = FeatureExtractor(cnn_enabled=False)
    rng = np.random.RandomState(42)
    points = rng.uniform(0, 200, (32, 2)).astype(np.float32)
    target = points * scale + 7
    desc = rng.randint(0, 256, (32, 32), dtype=np.uint8)
    kp1 = [cv2.KeyPoint(float(x), float(y), 1) for x, y in points]
    kp2 = [cv2.KeyPoint(float(x), float(y), 1) for x, y in target]
    cv2.setRNGSeed(42)
    expected = old.compute_orb_ransac_score((kp1, desc), (kp2, desc), min_inliers=min_inliers)
    cv2.setRNGSeed(42)
    actual = new.compute_orb_ransac_score((points, desc), (target, desc), min_inliers=min_inliers)
    assert actual == expected
    assert actual == (32 if scale == 1 and min_inliers <= 32 else 0)


def test_orb_detector_is_thread_local_and_points_float32(tmp_path):
    import threading
    from PIL import Image
    rng = np.random.RandomState(42)
    path = tmp_path / 'noise.png'
    Image.fromarray(rng.randint(0, 256, (256, 256), dtype=np.uint8)).save(path)
    extractor = FeatureExtractor(cnn_enabled=False)
    first = extractor.orb
    others = []
    worker = threading.Thread(target=lambda: others.append(extractor.orb))
    worker.start()
    worker.join()
    assert first is extractor.orb and first is not others[0]
    points, desc = extractor.compute_orb_with_keypoints(str(path))
    assert points.dtype == np.float32 and points.shape == (len(desc), 2)
    features = extractor.extract_all_features(str(path))
    np.testing.assert_array_equal(features['orb_kp'], points)