fix: 索引正确性、同步收敛与企业隔离通路
线上实测(2025-12-19 启动后未重启的实例):启动后新增的款式搜不到、 改图后旧向量残留、已删款式不移除、搜索阻塞事件循环。 - 索引:去掉 HNSW/墓碑/pickle 映射/双 FAISS 实例,改为进程内单一精确索引, SQLite 为唯一持久化事实源,启动时批量加载 - 存储:新 schema(整数 id、eps_id、关键点只存坐标、特征版本),拒绝旧库 - 同步:重叠窗口 + 键集分页,按状态写入或移除,按内容定时对账, 所有同步入口共用一把互斥锁,重建在后台执行 - 搜索:eps_id 只取自 JWT,召回前按企业过滤;候选特征批量加载并做版本校验; 同分按 id 升序;打分公式与置信度规则不变 - 接口:搜索改同步函数进线程池并限并发,/health 保持协程不占工作线程 设计与验收:saasProject openspec/changes/fix-image-search-index-integrity
Showing
53 changed files
with
244 additions
and
172 deletions
This diff is collapsed.
Click to expand it.
| ... | @@ -3,35 +3,23 @@ | ... | @@ -3,35 +3,23 @@ |
| 3 | 3 | ||
| 4 | # Server Settings | 4 | # Server Settings |
| 5 | server: | 5 | server: |
| 6 | host: "127.0.0.1" | 6 | host: "0.0.0.0" |
| 7 | port: 5088 | 7 | port: 5088 |
| 8 | workers: 1 | 8 | workers: 1 |
| 9 | 9 | ||
| 10 | # Database Settings | 10 | # Database Settings |
| 11 | database: | 11 | database: |
| 12 | sqlite: | 12 | sqlite: |
| 13 | path: "./data/design_images.db" | 13 | path: "./data/design_images_v2.db" |
| 14 | 14 | ||
| 15 | mysql: | 15 | mysql: |
| 16 | host: "${MYSQL_HOST:localhost}" | 16 | host: "${MYSQL_HOST:localhost}" |
| 17 | port: 3306 | 17 | port: "${MYSQL_PORT:3306}" |
| 18 | database: "${MYSQL_DB:saas_design}" | 18 | database: "${MYSQL_DB:saas_design}" |
| 19 | username: "${MYSQL_USER:root}" | 19 | username: "${MYSQL_USER:root}" |
| 20 | password: "${MYSQL_PASSWORD}" | 20 | password: "${MYSQL_PASSWORD}" |
| 21 | charset: "utf8mb4" | 21 | charset: "utf8mb4" |
| 22 | 22 | ||
| 23 | # FAISS Settings | ||
| 24 | faiss: | ||
| 25 | index_path: "./data/faiss_cnn.index" | ||
| 26 | mapping_path: "./data/faiss_id_mapping.pkl" | ||
| 27 | tombstone_path: "./data/faiss_tombstones.pkl" | ||
| 28 | vector_dim: 576 # MobileNetV3-Small output dimension | ||
| 29 | metric: "cosine" # cosine or L2 | ||
| 30 | hnsw: | ||
| 31 | M: 32 # HNSW connections | ||
| 32 | efConstruction: 200 # Build-time search depth | ||
| 33 | efSearch: 400 # Search-time depth (dynamic) | ||
| 34 | |||
| 35 | # Feature Extraction | 23 | # Feature Extraction |
| 36 | feature_extractor: | 24 | feature_extractor: |
| 37 | orb: | 25 | orb: |
| ... | @@ -42,7 +30,8 @@ feature_extractor: | ... | @@ -42,7 +30,8 @@ feature_extractor: |
| 42 | 30 | ||
| 43 | # Search Engine | 31 | # Search Engine |
| 44 | search: | 32 | search: |
| 45 | cnn_top_k: 5000 # CNN coarse recall | 33 | max_candidates: 200 |
| 34 | max_concurrent: 2 | ||
| 46 | ransac_top_k: 100 # RANSAC fine ranking | 35 | ransac_top_k: 100 # RANSAC fine ranking |
| 47 | fusion_weights: | 36 | fusion_weights: |
| 48 | cnn: 0.2 # 20% | 37 | cnn: 0.2 # 20% |
| ... | @@ -55,6 +44,9 @@ search: | ... | @@ -55,6 +44,9 @@ search: |
| 55 | 44 | ||
| 56 | # Data Sync | 45 | # Data Sync |
| 57 | sync: | 46 | sync: |
| 47 | eps_ids: [2] | ||
| 48 | overlap_seconds: 120 | ||
| 49 | reconcile_hour: 18 # Container clock is UTC: 18:00 UTC = 02:00 Beijing time next day. | ||
| 58 | interval_seconds: 60 # Sync every minute | 50 | interval_seconds: 60 # Sync every minute |
| 59 | batch_size: 500 # Process 500 records per batch | 51 | batch_size: 500 # Process 500 records per batch |
| 60 | image_download_timeout: 30 # seconds | 52 | image_download_timeout: 30 # seconds |
| ... | @@ -90,4 +82,4 @@ cors: | ... | @@ -90,4 +82,4 @@ cors: |
| 90 | - "POST" | 82 | - "POST" |
| 91 | - "GET" | 83 | - "GET" |
| 92 | headers: | 84 | headers: |
| 93 | - "*" | ||
| ... | \ No newline at end of file | ... | \ No newline at end of file |
| 85 | - "*" | ... | ... |
core/faiss_manager.py
deleted
100644 → 0
This diff is collapsed.
Click to expand it.
| ... | @@ -4,6 +4,7 @@ | ... | @@ -4,6 +4,7 @@ |
| 4 | - ORB特征: 保留关键点,支持RANSAC | 4 | - ORB特征: 保留关键点,支持RANSAC |
| 5 | """ | 5 | """ |
| 6 | 6 | ||
| 7 | import threading | ||
| 7 | import logging | 8 | import logging |
| 8 | import cv2 | 9 | import cv2 |
| 9 | import numpy as np | 10 | import numpy as np |
| ... | @@ -32,7 +33,7 @@ class FeatureExtractor: | ... | @@ -32,7 +33,7 @@ class FeatureExtractor: |
| 32 | self.cnn_enabled = cnn_enabled | 33 | self.cnn_enabled = cnn_enabled |
| 33 | 34 | ||
| 34 | # 初始化ORB检测器 | 35 | # 初始化ORB检测器 |
| 35 | self.orb = cv2.ORB_create(nfeatures=orb_max_features) | 36 | self._orb_local = threading.local() |
| 36 | 37 | ||
| 37 | # 延迟加载CNN模型 | 38 | # 延迟加载CNN模型 |
| 38 | if self.cnn_enabled: | 39 | if self.cnn_enabled: |
| ... | @@ -40,6 +41,13 @@ class FeatureExtractor: | ... | @@ -40,6 +41,13 @@ class FeatureExtractor: |
| 40 | 41 | ||
| 41 | logger.info(f"特征提取器初始化完成: ORB={orb_max_features}, CNN={cnn_enabled}") | 42 | logger.info(f"特征提取器初始化完成: ORB={orb_max_features}, CNN={cnn_enabled}") |
| 42 | 43 | ||
| 44 | @property | ||
| 45 | def orb(self): | ||
| 46 | """Each worker owns its detector; parameters remain unchanged.""" | ||
| 47 | if not hasattr(self._orb_local, 'detector'): | ||
| 48 | self._orb_local.detector = cv2.ORB_create(nfeatures=self.orb_max_features) | ||
| 49 | return self._orb_local.detector | ||
| 50 | |||
| 43 | def _init_cnn_model(self): | 51 | def _init_cnn_model(self): |
| 44 | """延迟初始化CNN模型(只在需要时加载)""" | 52 | """延迟初始化CNN模型(只在需要时加载)""" |
| 45 | global _torch_model, _torch_transforms | 53 | global _torch_model, _torch_transforms |
| ... | @@ -128,7 +136,7 @@ class FeatureExtractor: | ... | @@ -128,7 +136,7 @@ class FeatureExtractor: |
| 128 | 136 | ||
| 129 | Returns: | 137 | Returns: |
| 130 | tuple: (keypoints, descriptors) 或 (None, None) | 138 | tuple: (keypoints, descriptors) 或 (None, None) |
| 131 | - keypoints: list of cv2.KeyPoint | 139 | - keypoints: float32 array (N x 2) |
| 132 | - descriptors: numpy.ndarray (N x 32, uint8) | 140 | - descriptors: numpy.ndarray (N x 32, uint8) |
| 133 | """ | 141 | """ |
| 134 | try: | 142 | try: |
| ... | @@ -150,7 +158,7 @@ class FeatureExtractor: | ... | @@ -150,7 +158,7 @@ class FeatureExtractor: |
| 150 | logger.warning(f"图片无ORB特征 {img_path}") | 158 | logger.warning(f"图片无ORB特征 {img_path}") |
| 151 | return None, None | 159 | return None, None |
| 152 | 160 | ||
| 153 | return keypoints, descriptors | 161 | return np.float32([kp.pt for kp in keypoints]).reshape(-1, 2), descriptors |
| 154 | 162 | ||
| 155 | except Exception as e: | 163 | except Exception as e: |
| 156 | logger.error(f"计算ORB失败 {img_path}: {e}") | 164 | logger.error(f"计算ORB失败 {img_path}: {e}") |
| ... | @@ -205,8 +213,8 @@ class FeatureExtractor: | ... | @@ -205,8 +213,8 @@ class FeatureExtractor: |
| 205 | return 0 | 213 | return 0 |
| 206 | 214 | ||
| 207 | # Step 3: 提取匹配点坐标 | 215 | # Step 3: 提取匹配点坐标 |
| 208 | pts1 = np.float32([kp1[m.queryIdx].pt for m in good_matches]) | 216 | pts1 = np.float32([kp1[m.queryIdx] for m in good_matches]) |
| 209 | pts2 = np.float32([kp2[m.trainIdx].pt for m in good_matches]) | 217 | pts2 = np.float32([kp2[m.trainIdx] for m in good_matches]) |
| 210 | 218 | ||
| 211 | # Step 4: RANSAC估计单应性矩阵 | 219 | # Step 4: RANSAC估计单应性矩阵 |
| 212 | try: | 220 | try: |
| ... | @@ -247,7 +255,7 @@ class FeatureExtractor: | ... | @@ -247,7 +255,7 @@ class FeatureExtractor: |
| 247 | Returns: | 255 | Returns: |
| 248 | dict: { | 256 | dict: { |
| 249 | "cnn_vector": np.ndarray, # CNN向量(576维) | 257 | "cnn_vector": np.ndarray, # CNN向量(576维) |
| 250 | "orb_kp": list, # ORB关键点 | 258 | "orb_kp": np.ndarray, # ORB关键点 |
| 251 | "orb_desc": np.ndarray # ORB描述子 | 259 | "orb_desc": np.ndarray # ORB描述子 |
| 252 | } 或 None | 260 | } 或 None |
| 253 | """ | 261 | """ |
| ... | @@ -288,7 +296,7 @@ class FeatureExtractor: | ... | @@ -288,7 +296,7 @@ class FeatureExtractor: |
| 288 | 296 | ||
| 289 | return { | 297 | return { |
| 290 | "cnn_vector": cnn_vector, | 298 | "cnn_vector": cnn_vector, |
| 291 | "orb_kp": keypoints, | 299 | "orb_kp": None if keypoints is None else np.float32([kp.pt for kp in keypoints]).reshape(-1, 2), |
| 292 | "orb_desc": descriptors | 300 | "orb_desc": descriptors |
| 293 | } | 301 | } |
| 294 | 302 | ... | ... |
core/memory_index.py
deleted
100644 → 0
| 1 | """ | ||
| 2 | 内存索引模块 | ||
| 3 | 将图片元数据加载到内存,支持快速元数据查询 | ||
| 4 | """ | ||
| 5 | |||
| 6 | import logging | ||
| 7 | import sqlite3 | ||
| 8 | import threading | ||
| 9 | |||
| 10 | logging.basicConfig(level=logging.INFO) | ||
| 11 | logger = logging.getLogger(__name__) | ||
| 12 | |||
| 13 | |||
| 14 | class InMemoryIndex: | ||
| 15 | """内存索引(支持快速元数据查询和线程安全更新)""" | ||
| 16 | |||
| 17 | def __init__(self): | ||
| 18 | """初始化空索引""" | ||
| 19 | # 图片元数据 {img_id: {"path": ..., "design_no": ..., "image_url": ...}} | ||
| 20 | self.img_metadata = {} | ||
| 21 | # 线程锁(支持并发读写) | ||
| 22 | self._lock = threading.RLock() | ||
| 23 | |||
| 24 | def load_from_db(self, db_path): | ||
| 25 | """ | ||
| 26 | 从SQLite数据库加载索引到内存 | ||
| 27 | |||
| 28 | Args: | ||
| 29 | db_path: 数据库路径 | ||
| 30 | |||
| 31 | Returns: | ||
| 32 | bool: 是否成功 | ||
| 33 | """ | ||
| 34 | try: | ||
| 35 | import time | ||
| 36 | start = time.time() | ||
| 37 | |||
| 38 | conn = sqlite3.connect(db_path) | ||
| 39 | |||
| 40 | # 加载元数据 | ||
| 41 | logger.info("加载图片元数据到内存...") | ||
| 42 | cursor = conn.execute( | ||
| 43 | "SELECT id, path, design_no, image_url FROM images" | ||
| 44 | ) | ||
| 45 | |||
| 46 | with self._lock: | ||
| 47 | for row in cursor: | ||
| 48 | img_id, path, design_no, image_url = row | ||
| 49 | self.img_metadata[img_id] = { | ||
| 50 | "id": img_id, | ||
| 51 | "path": image_url if image_url else path, # 优先使用image_url | ||
| 52 | "design_no": design_no, | ||
| 53 | "image_url": image_url | ||
| 54 | } | ||
| 55 | |||
| 56 | logger.info(f"✓ 已加载 {len(self.img_metadata)} 条元数据") | ||
| 57 | |||
| 58 | conn.close() | ||
| 59 | |||
| 60 | elapsed = time.time() - start | ||
| 61 | logger.info(f"内存索引加载完成,耗时 {elapsed:.2f}秒") | ||
| 62 | logger.info(f"内存占用估算: {self.estimate_memory_usage():.1f}MB") | ||
| 63 | |||
| 64 | return True | ||
| 65 | |||
| 66 | except Exception as e: | ||
| 67 | logger.error(f"加载内存索引失败: {e}", exc_info=True) | ||
| 68 | return False | ||
| 69 | |||
| 70 | def add_or_update(self, img_id, design_no, image_url, image_path=None): | ||
| 71 | """ | ||
| 72 | 增量添加或更新元数据(线程安全) | ||
| 73 | |||
| 74 | Args: | ||
| 75 | img_id: 图片ID (design_id) | ||
| 76 | design_no: 设计款号 | ||
| 77 | image_url: 图片URL | ||
| 78 | image_path: 本地路径(可选) | ||
| 79 | """ | ||
| 80 | with self._lock: | ||
| 81 | self.img_metadata[img_id] = { | ||
| 82 | "id": img_id, | ||
| 83 | "path": image_url if image_url else image_path, | ||
| 84 | "design_no": design_no, | ||
| 85 | "image_url": image_url | ||
| 86 | } | ||
| 87 | logger.debug(f"内存索引已更新: img_id={img_id}") | ||
| 88 | |||
| 89 | def remove(self, img_id): | ||
| 90 | """ | ||
| 91 | 删除元数据(线程安全) | ||
| 92 | |||
| 93 | Args: | ||
| 94 | img_id: 图片ID | ||
| 95 | """ | ||
| 96 | with self._lock: | ||
| 97 | if img_id in self.img_metadata: | ||
| 98 | del self.img_metadata[img_id] | ||
| 99 | logger.debug(f"内存索引已删除: img_id={img_id}") | ||
| 100 | |||
| 101 | def estimate_memory_usage(self): | ||
| 102 | """估算内存占用(MB)""" | ||
| 103 | # img_metadata: 每条约200字节(路径字符串 + design_no) | ||
| 104 | size = len(self.img_metadata) * 200 | ||
| 105 | return size / 1024 / 1024 | ||
| 106 | |||
| 107 | def get_metadata(self, img_id): | ||
| 108 | """ | ||
| 109 | 获取图片元数据(线程安全,兼容int/str类型) | ||
| 110 | |||
| 111 | Args: | ||
| 112 | img_id: 图片ID(int或str) | ||
| 113 | |||
| 114 | Returns: | ||
| 115 | dict or None: 元数据字典 | ||
| 116 | """ | ||
| 117 | with self._lock: | ||
| 118 | # 尝试原始类型 | ||
| 119 | metadata = self.img_metadata.get(img_id) | ||
| 120 | if metadata: | ||
| 121 | return metadata | ||
| 122 | |||
| 123 | # 尝试字符串类型(兼容FAISS返回int但SQLite存str的情况) | ||
| 124 | metadata = self.img_metadata.get(str(img_id)) | ||
| 125 | if metadata: | ||
| 126 | return metadata | ||
| 127 | |||
| 128 | # 尝试int类型(兼容反向情况) | ||
| 129 | if isinstance(img_id, str) and img_id.isdigit(): | ||
| 130 | metadata = self.img_metadata.get(int(img_id)) | ||
| 131 | if metadata: | ||
| 132 | return metadata | ||
| 133 | |||
| 134 | return None | ||
| 135 | |||
| 136 | def get_stats(self): | ||
| 137 | """获取索引统计信息""" | ||
| 138 | with self._lock: | ||
| 139 | return { | ||
| 140 | "total_images": len(self.img_metadata), | ||
| 141 | "memory_mb": self.estimate_memory_usage() | ||
| 142 | } |
This diff is collapsed.
Click to expand it.
core/vector_index.py
0 → 100644
| 1 | """Exact, tenant-filtered recall. SQLite is the only persistent state.""" | ||
| 2 | import threading | ||
| 3 | |||
| 4 | import numpy as np | ||
| 5 | |||
| 6 | |||
| 7 | class VectorIndex: | ||
| 8 | def __init__(self, dimension=576): | ||
| 9 | self.dimension = dimension | ||
| 10 | self.lock = threading.RLock() | ||
| 11 | self.vectors = np.empty((0, dimension), dtype=np.float32) | ||
| 12 | self.ids = np.empty(0, dtype=np.int64) | ||
| 13 | self.eps_ids = np.empty(0, dtype=np.int64) | ||
| 14 | self.versions = np.empty(0, dtype=np.int64) | ||
| 15 | self.rows = {} | ||
| 16 | self._size = 0 | ||
| 17 | |||
| 18 | def bulk_load(self, rows): | ||
| 19 | """Replace the index from a single pass over SQLite's vector-only rows.""" | ||
| 20 | rows = list(rows) | ||
| 21 | ids = np.array([row['id'] for row in rows], dtype=np.int64) | ||
| 22 | positions = {int(design_id): i for i, design_id in enumerate(ids)} | ||
| 23 | if len(positions) != len(rows): | ||
| 24 | raise ValueError('Duplicate design id in bulk load') | ||
| 25 | vectors = np.array([row['cnn_vector'] for row in rows], dtype=np.float32).reshape(-1, self.dimension) | ||
| 26 | norms = np.linalg.norm(vectors, axis=1) | ||
| 27 | if not np.isfinite(vectors).all() or np.any(norms == 0): | ||
| 28 | raise ValueError('Invalid CNN vector') | ||
| 29 | vectors /= norms[:, None] | ||
| 30 | eps_ids = np.array([row['eps_id'] for row in rows], dtype=np.int64) | ||
| 31 | versions = np.array([row['feat_version'] for row in rows], dtype=np.int64) | ||
| 32 | with self.lock: | ||
| 33 | self.vectors, self.ids = vectors, ids | ||
| 34 | self.eps_ids, self.versions = eps_ids, versions | ||
| 35 | self.rows = positions | ||
| 36 | self._size = len(rows) | ||
| 37 | |||
| 38 | def _grow(self): | ||
| 39 | """Double storage only when full, making incremental appends amortized.""" | ||
| 40 | capacity = max(1, len(self.ids) * 2) | ||
| 41 | vectors = np.empty((capacity, self.dimension), dtype=np.float32) | ||
| 42 | ids = np.empty(capacity, dtype=np.int64) | ||
| 43 | eps_ids = np.empty(capacity, dtype=np.int64) | ||
| 44 | versions = np.empty(capacity, dtype=np.int64) | ||
| 45 | for target, source in zip((vectors, ids, eps_ids, versions), | ||
| 46 | (self.vectors, self.ids, self.eps_ids, self.versions)): | ||
| 47 | target[:self._size] = source[:self._size] | ||
| 48 | self.vectors, self.ids = vectors, ids | ||
| 49 | self.eps_ids, self.versions = eps_ids, versions | ||
| 50 | |||
| 51 | def upsert(self, design_id, eps_id, vector, feat_version): | ||
| 52 | vector = np.asarray(vector, dtype=np.float32).reshape(self.dimension) | ||
| 53 | norm = np.linalg.norm(vector) | ||
| 54 | if not np.isfinite(vector).all() or norm == 0: | ||
| 55 | raise ValueError('Invalid CNN vector') | ||
| 56 | vector = vector / norm | ||
| 57 | with self.lock: | ||
| 58 | row = self.rows.get(int(design_id)) | ||
| 59 | if row is None: | ||
| 60 | if self._size == len(self.ids): | ||
| 61 | self._grow() | ||
| 62 | row = self._size | ||
| 63 | self.rows[int(design_id)] = row | ||
| 64 | self.ids[row] = design_id | ||
| 65 | self._size += 1 | ||
| 66 | self.vectors[row] = vector | ||
| 67 | self.eps_ids[row] = eps_id | ||
| 68 | self.versions[row] = feat_version | ||
| 69 | |||
| 70 | def remove(self, design_id): | ||
| 71 | with self.lock: | ||
| 72 | row = self.rows.pop(int(design_id), None) | ||
| 73 | if row is None: | ||
| 74 | return | ||
| 75 | last = self._size - 1 | ||
| 76 | if row != last: | ||
| 77 | for array in (self.vectors, self.ids, self.eps_ids, self.versions): | ||
| 78 | array[row] = array[last] | ||
| 79 | self.rows[int(self.ids[row])] = row | ||
| 80 | self._size -= 1 | ||
| 81 | |||
| 82 | def search(self, vector, eps_id, k): | ||
| 83 | vector = np.asarray(vector, dtype=np.float32).reshape(self.dimension) | ||
| 84 | vector = vector / (np.linalg.norm(vector) or 1) | ||
| 85 | with self.lock: | ||
| 86 | rows = np.flatnonzero(self.eps_ids[:self._size] == eps_id) | ||
| 87 | scores = self.vectors[rows] @ vector | ||
| 88 | order = np.lexsort((self.ids[rows], -scores))[:max(0, k)] | ||
| 89 | return [(int(self.ids[rows[i]]), float(scores[i]), | ||
| 90 | int(self.versions[rows[i]])) for i in order] | ||
| 91 | |||
| 92 | def stats(self): | ||
| 93 | with self.lock: | ||
| 94 | tenants, counts = np.unique(self.eps_ids[:self._size], return_counts=True) | ||
| 95 | return {'total_vectors': self._size, | ||
| 96 | 'by_eps_id': {str(t): int(n) for t, n in zip(tenants, counts)}} |
This diff is collapsed.
Click to expand it.
This diff is collapsed.
Click to expand it.
| ... | @@ -3,22 +3,22 @@ version: '3.0' | ... | @@ -3,22 +3,22 @@ version: '3.0' |
| 3 | services: | 3 | services: |
| 4 | design-image-search: | 4 | design-image-search: |
| 5 | build: . | 5 | build: . |
| 6 | container_name: design-image-search | 6 | container_name: ${CONTAINER_NAME:-design-image-search} |
| 7 | ports: | 7 | ports: |
| 8 | - "5088:5088" | 8 | - "${SERVICE_PORT:-5088}:5088" |
| 9 | environment: | 9 | environment: |
| 10 | - MYSQL_HOST=${MYSQL_HOST:-host.docker.internal} | 10 | - MYSQL_HOST=${MYSQL_HOST:-host.docker.internal} |
| 11 | - MYSQL_PORT=${MYSQL_PORT:-3306} | 11 | - MYSQL_PORT=${MYSQL_PORT:-3306} |
| 12 | - MYSQL_USER=${MYSQL_USER:-root} | 12 | - MYSQL_USER=${MYSQL_USER:-root} |
| 13 | - MYSQL_PASSWORD=${MYSQL_PASSWORD} | 13 | - MYSQL_PASSWORD=${MYSQL_PASSWORD} |
| 14 | - MYSQL_DATABASE=${MYSQL_DATABASE:-saas_design} | 14 | - MYSQL_DB=${MYSQL_DATABASE:-saas_design} |
| 15 | - JWT_SECRET=${JWT_SECRET} | 15 | - JWT_SECRET=${JWT_SECRET} |
| 16 | - SERVER_PORT=5088 | 16 | - SERVER_PORT=5088 |
| 17 | - SYNC_INTERVAL_SECONDS=${SYNC_INTERVAL_SECONDS:-60} | 17 | - SYNC_INTERVAL_SECONDS=${SYNC_INTERVAL_SECONDS:-60} |
| 18 | - LOG_LEVEL=${LOG_LEVEL:-INFO} | 18 | - LOG_LEVEL=${LOG_LEVEL:-INFO} |
| 19 | - KMP_DUPLICATE_LIB_OK=TRUE | 19 | - KMP_DUPLICATE_LIB_OK=TRUE |
| 20 | volumes: | 20 | volumes: |
| 21 | - ./data:/app/data | 21 | - ${DATA_DIR:-./data}:/app/data |
| 22 | - ./logs:/app/logs | 22 | - ./logs:/app/logs |
| 23 | - ./config.yml:/app/config.yml:ro | 23 | - ./config.yml:/app/config.yml:ro |
| 24 | restart: unless-stopped | 24 | restart: unless-stopped | ... | ... |
pytest.ini
0 → 100644
| ... | @@ -8,7 +8,6 @@ python-multipart>=0.0.6 | ... | @@ -8,7 +8,6 @@ python-multipart>=0.0.6 |
| 8 | --find-links https://download.pytorch.org/whl/torch_stable.html | 8 | --find-links https://download.pytorch.org/whl/torch_stable.html |
| 9 | torch==2.0.1+cpu | 9 | torch==2.0.1+cpu |
| 10 | torchvision==0.15.2+cpu | 10 | torchvision==0.15.2+cpu |
| 11 | faiss-cpu>=1.7.4 | ||
| 12 | opencv-python>=4.8.0 | 11 | opencv-python>=4.8.0 |
| 13 | Pillow>=10.0.0 | 12 | Pillow>=10.0.0 |
| 14 | 13 | ... | ... |
| ... | @@ -7,7 +7,6 @@ python-multipart>=0.0.6 | ... | @@ -7,7 +7,6 @@ python-multipart>=0.0.6 |
| 7 | # Use version ranges to avoid CUDA dependencies (CPU version from mirror) | 7 | # Use version ranges to avoid CUDA dependencies (CPU version from mirror) |
| 8 | torch>=2.0.0,<2.1.0 | 8 | torch>=2.0.0,<2.1.0 |
| 9 | torchvision>=0.15.0,<0.16.0 | 9 | torchvision>=0.15.0,<0.16.0 |
| 10 | faiss-cpu>=1.7.4 | ||
| 11 | opencv-python>=4.8.0 | 10 | opencv-python>=4.8.0 |
| 12 | Pillow>=10.0.0 | 11 | Pillow>=10.0.0 |
| 13 | 12 | ... | ... |
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
tests/.tmp/test_old_schema_rejected0/old.db
0 → 100644
No preview for this file type
64.3 KB
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
tests/conftest.py
0 → 100644
| 1 | """Fail immediately if a test accidentally uses a production source or downloader.""" | ||
| 2 | import pytest | ||
| 3 | |||
| 4 | |||
| 5 | @pytest.fixture(autouse=True) | ||
| 6 | def offline_only(monkeypatch): | ||
| 7 | import requests | ||
| 8 | import pymysql | ||
| 9 | |||
| 10 | def forbidden(*args, **kwargs): | ||
| 11 | raise AssertionError('Tests must inject an offline source and downloader') | ||
| 12 | |||
| 13 | monkeypatch.setattr(requests.sessions.Session, 'request', forbidden) | ||
| 14 | monkeypatch.setattr(pymysql, 'connect', forbidden) |
tests/reference_feature_extractor.py
0 → 100644
This diff is collapsed.
Click to expand it.
tests/reference_search_engine.py
0 → 100644
This diff is collapsed.
Click to expand it.
tests/test_equivalence.py
0 → 100644
| 1 | """Production HEAD reference modules are frozen verbatim alongside these tests.""" | ||
| 2 | import ast | ||
| 3 | from pathlib import Path | ||
| 4 | from types import SimpleNamespace | ||
| 5 | |||
| 6 | import cv2 | ||
| 7 | import numpy as np | ||
| 8 | import pytest | ||
| 9 | |||
| 10 | from core.feature_extractor import FeatureExtractor | ||
| 11 | from core.search_engine import ImageSearchEngine | ||
| 12 | from core.vector_index import VectorIndex | ||
| 13 | from database import DatabaseManager | ||
| 14 | |||
| 15 | |||
| 16 | def reference_class(module, name): | ||
| 17 | # Compile only the original class, avoiding its obsolete dependency imports. | ||
| 18 | tree = ast.parse(Path(__file__).with_name('reference_' + module + '.py').read_text(encoding='utf-8')) | ||
| 19 | cls = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == name) | ||
| 20 | scope = {'np': np, 'cv2': cv2, 'logger': __import__('logging').getLogger('reference')} | ||
| 21 | exec(compile(ast.Module(body=[cls], type_ignores=[]), module, 'exec'), scope) | ||
| 22 | return scope[name] | ||
| 23 | |||
| 24 | |||
| 25 | @pytest.mark.parametrize('weights', [{}, {'cnn': 0.37, 'ransac': 0.63}]) | ||
| 26 | def test_scores_and_confidence_match_production(tmp_path, weights): | ||
| 27 | old_cls = reference_class('search_engine', 'ImageSearchEngine') | ||
| 28 | old = old_cls.__new__(old_cls) | ||
| 29 | old.weights = {'cnn': weights.get('cnn', .2) * 100, 'ransac': weights.get('ransac', .8) * 100} | ||
| 30 | old.max_candidates = old.cnn_top_k = 20 | ||
| 31 | old.top_results = 20 | ||
| 32 | sims = [.9, .81, .8, .75, .71, .7, .5] | ||
| 33 | inliers = [18, 15, 16, 8, 7, 20, 0] | ||
| 34 | query = {'cnn_vector': np.eye(1, 576, dtype=np.float32)[0], | ||
| 35 | 'orb_kp': np.zeros((20, 2), np.float32), 'orb_desc': np.zeros((20, 32), np.uint8)} | ||
| 36 | index = VectorIndex() | ||
| 37 | db = DatabaseManager(tmp_path / 'features.db') | ||
| 38 | for i, sim in enumerate(sims, 1): | ||
| 39 | vector = np.zeros(576, np.float32) | ||
| 40 | vector[:2] = [sim, np.sqrt(1 - sim * sim)] | ||
| 41 | features = dict(query, cnn_vector=vector, | ||
| 42 | orb_desc=np.full((20, 32), i, np.uint8)) | ||
| 43 | db.upsert(i, 2, str(i), 'https://image/' + str(i), features, i, None) | ||
| 44 | index.upsert(i, 2, vector, i) | ||
| 45 | recalled = index.search(query['cnn_vector'], 2, 20) | ||
| 46 | old.faiss_manager = SimpleNamespace(search=lambda *a, **kw: [(i, sim) for i, sim, _ in recalled]) | ||
| 47 | old.memory_index = SimpleNamespace(img_metadata={str(i): {'path': str(i)} for i in range(1, 8)}) | ||
| 48 | old.extractor = SimpleNamespace(extract_all_features=lambda path: query) | ||
| 49 | old._ransac_verify_single = lambda i, *args: inliers[i - 1] | ||
| 50 | options = {'min_inliers': 11, 'reproj_threshold': 3.5, 'confidence': .98} | ||
| 51 | calls = [] | ||
| 52 | def ransac(q, candidate, **kwargs): | ||
| 53 | calls.append(kwargs) | ||
| 54 | return inliers[int(candidate[1][0, 0]) - 1] | ||
| 55 | extractor = SimpleNamespace(extract_all_features=lambda path: query, compute_orb_ransac_score=ransac) | ||
| 56 | new = ImageSearchEngine(config={'search': {'fusion_weights': weights, 'ransac': options}}, | ||
| 57 | index=index, db_manager=db, extractor=extractor) | ||
| 58 | actual, expected = new.search('query', 2), old.search('query') | ||
| 59 | assert [(r['img_id'], r['score'], r['confidence'], r['details']) for r in actual] == [ | ||
| 60 | (r['img_id'], r['score'], r['confidence'], r['details']) for r in expected] | ||
| 61 | assert calls == [{'min_inliers': 11, 'ransac_thresh': 3.5, 'confidence': .98}] * 7 | ||
| 62 | |||
| 63 | |||
| 64 | @pytest.mark.parametrize('scale,min_inliers', [(1., 15), (1., 33), (.2, 15), (4., 15)]) | ||
| 65 | def test_array_ransac_matches_original_keypoints(scale, min_inliers): | ||
| 66 | old_cls = reference_class('feature_extractor', 'FeatureExtractor') | ||
| 67 | old = old_cls.__new__(old_cls) | ||
| 68 | new = FeatureExtractor(cnn_enabled=False) | ||
| 69 | rng = np.random.RandomState(42) | ||
| 70 | points = rng.uniform(0, 200, (32, 2)).astype(np.float32) | ||
| 71 | target = points * scale + 7 | ||
| 72 | desc = rng.randint(0, 256, (32, 32), dtype=np.uint8) | ||
| 73 | kp1 = [cv2.KeyPoint(float(x), float(y), 1) for x, y in points] | ||
| 74 | kp2 = [cv2.KeyPoint(float(x), float(y), 1) for x, y in target] | ||
| 75 | cv2.setRNGSeed(42) | ||
| 76 | expected = old.compute_orb_ransac_score((kp1, desc), (kp2, desc), min_inliers=min_inliers) | ||
| 77 | cv2.setRNGSeed(42) | ||
| 78 | actual = new.compute_orb_ransac_score((points, desc), (target, desc), min_inliers=min_inliers) | ||
| 79 | assert actual == expected | ||
| 80 | assert actual == (32 if scale == 1 and min_inliers <= 32 else 0) | ||
| 81 | |||
| 82 | |||
| 83 | def test_orb_detector_is_thread_local_and_points_float32(tmp_path): | ||
| 84 | import threading | ||
| 85 | from PIL import Image | ||
| 86 | rng = np.random.RandomState(42) | ||
| 87 | path = tmp_path / 'noise.png' | ||
| 88 | Image.fromarray(rng.randint(0, 256, (256, 256), dtype=np.uint8)).save(path) | ||
| 89 | extractor = FeatureExtractor(cnn_enabled=False) | ||
| 90 | first = extractor.orb | ||
| 91 | others = [] | ||
| 92 | worker = threading.Thread(target=lambda: others.append(extractor.orb)) | ||
| 93 | worker.start() | ||
| 94 | worker.join() | ||
| 95 | assert first is extractor.orb and first is not others[0] | ||
| 96 | points, desc = extractor.compute_orb_with_keypoints(str(path)) | ||
| 97 | assert points.dtype == np.float32 and points.shape == (len(desc), 2) | ||
| 98 | features = extractor.extract_all_features(str(path)) | ||
| 99 | np.testing.assert_array_equal(features['orb_kp'], points) |
tests/test_integrity.py
0 → 100644
This diff is collapsed.
Click to expand it.
-
Please register or sign in to post a comment