search_engine.py
8.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""Exact tenant recall followed by unchanged CNN/RANSAC fusion."""
from concurrent.futures import ThreadPoolExecutor
from base64 import b64encode
import logging
import threading
import cv2
from PIL import Image
from filesystem_files import FilePaths, jpeg_thumbnail
from .feature_extractor import FeatureExtractor
logger = logging.getLogger(__name__)
class ImageSearchEngine:
def __init__(self, db_path=None, config=None, index=None, db_manager=None, extractor=None):
from database import DatabaseManager
from .vector_index import VectorIndex, configured_dimension
self.config = config or {}
self.filesystem = self.config.get('source', {}).get('type') == 'filesystem'
self.file_paths = None
if self.filesystem:
settings = self.config['filesystem']
self.file_paths = FilePaths(settings['roots'], settings['unc_prefixes'])
self.thumbnail_top_n = settings.get('thumbnail_top_n', 20)
self.db = db_manager if db_manager is not None else DatabaseManager(db_path, wal=self.filesystem)
self.index = index if index is not None else VectorIndex(configured_dimension(self.config))
if index is None and self.filesystem:
self.db.file_index_snapshot(self.index, settings.get('index_min_capacity', 1024),
self.config.get('video', {}).get('enabled', False))
elif index is None:
self.index.bulk_load(self.db.iter_index_rows())
self.extractor = extractor if extractor is not None else FeatureExtractor(
orb_max_features=self.config.get('orb_max_features', 1200),
cnn_enabled=self.config.get('cnn_enabled', True))
search_config = settings.get('search', {}) if self.filesystem else self.config.get('search', {})
self.max_candidates = search_config.get('max_candidates', 2000 if self.filesystem else 200)
self.ransac_top_k = search_config.get('ransac_top_k', 500 if self.filesystem else 100)
self.top_results = search_config.get('top_results', 20)
ransac_config = search_config.get('ransac', {})
self.min_orb_inliers = ransac_config.get('min_inliers', 8 if self.filesystem else 15)
self.ransac_reproj_thresh = ransac_config.get('reproj_threshold', 6.0 if self.filesystem else 4.0)
self.ransac_confidence = ransac_config.get('confidence', 0.95 if self.filesystem else 0.995)
weights_config = search_config.get('fusion_weights', {})
self.weights = {
"cnn": weights_config.get("cnn", 0.2) * 100,
"ransac": weights_config.get("ransac", 0.8) * 100
}
self.threads = search_config.get('threads', 4)
self.semaphore = threading.BoundedSemaphore(search_config.get('max_concurrent', 2))
def search(self, query_img_path, eps_id, top_k=None):
with self.semaphore:
return self._search(query_img_path, eps_id, self.top_results if top_k is None else top_k)
def _search(self, path, eps_id, top_k):
query = self.extractor.extract_all_features(path)
if query is None or query.get('cnn_vector') is None:
if self.filesystem:
raise RuntimeError('Query feature extraction failed')
return []
recalled = self.index.search(query['cnn_vector'], eps_id, self.max_candidates)
ids = [item[0] for item in recalled]
if self.filesystem:
rows = self.db.file_search_metadata(ids)
orbs = self.db.file_search_orb(ids[:self.ransac_top_k])
else:
rows = self.db.get_features(ids)
candidates = []
for rank, (design_id, cnn_sim, version) in enumerate(recalled):
row = rows.get(design_id)
if not self._matches_recall(row, design_id, eps_id, version):
continue
orb = row
if self.filesystem:
orb = None
if rank < self.ransac_top_k:
raw = orbs.get(design_id)
if not self._matches_recall(raw, design_id, eps_id, version):
continue
orb = self.db.decode_orb(raw)
candidates.append({'img_id': design_id, 'design_no': row.get('design_no'),
'image_url': row['image_url'], 'initial_score': cnn_sim * 100 * self.weights['cnn'],
'details': {'cnn_sim': cnn_sim, 'ransac_inliers': 0},
'metadata': row if self.filesystem else None,
'orb': orb if rank < self.ransac_top_k else None})
def verify(candidate):
row = candidate['orb']
if row is None or row['orb_pts'] is None or row['orb_desc'] is None:
return 0
try:
return self.extractor.compute_orb_ransac_score(
(query['orb_kp'], query['orb_desc']), (row['orb_pts'], row['orb_desc']),
min_inliers=self.min_orb_inliers, ransac_thresh=self.ransac_reproj_thresh,
confidence=self.ransac_confidence)
except Exception:
logger.warning('RANSAC failed for design %s', candidate['img_id'])
return 0
with ThreadPoolExecutor(max_workers=self.threads) as executor:
for candidate, inliers in zip(candidates, executor.map(verify, candidates)):
candidate['details']['ransac_inliers'] = inliers
candidate['score'] = candidate['initial_score'] + inliers * self.weights['ransac']
candidate['confidence'] = self._assess_confidence(candidate)
del candidate['orb']
candidates.sort(key=lambda c: (-c['score'], c['img_id']))
if self.filesystem:
return self._file_results(candidates, top_k)
for candidate in candidates:
del candidate['metadata']
return candidates[:top_k]
@staticmethod
def _matches_recall(row, image_id, eps_id, version):
return (row is not None and row['id'] == image_id and row['eps_id'] == eps_id
and row['feat_version'] == version)
def _file_results(self, candidates, top_k):
distinct = {}
for candidate in candidates:
path = candidate['metadata']['path']
if path and self.file_paths.root_for(path) is not None:
distinct.setdefault(path, candidate)
results = []
for candidate in list(distinct.values())[:top_k]:
row = candidate['metadata']
result = {key: candidate[key] for key in ('score', 'confidence', 'details')}
result.update(path=row['image_url'], thumbnail=None)
if row['frame_ms'] != -1:
result['frame_ms'] = row['frame_ms']
results.append(result)
rows = [candidate['metadata'] for candidate in list(distinct.values())[:self.thumbnail_top_n]]
# 缩略图逐张解码 NAS 原图(大 TIFF 可达数秒),并行生成;结果顺序不变。
with ThreadPoolExecutor(max_workers=self.threads) as executor:
for result, thumbnail in zip(results, executor.map(self._thumbnail, rows)):
if thumbnail is None:
result['stale'] = True
else:
result['thumbnail'] = thumbnail
return results
def _thumbnail(self, row):
try:
thumbnail = jpeg_thumbnail(row['path'], self.file_paths.root_for(row['path']),
(row['mtime'], row['size']), row['frame_ms'])
return b64encode(thumbnail).decode('ascii')
except (OSError, ValueError, Image.DecompressionBombError, cv2.error):
return None
def _assess_confidence(self, candidate):
"""
评估搜索结果的置信度(珠宝图片优化版)
针对变色和裁切场景优化的判断标准:
- high: RANSAC内点>=15(几何一致性强)或 CNN相似度>0.8
- medium: RANSAC内点>=8(降低要求)或 CNN相似度>0.7
- low: 其他
Args:
candidate: 候选结果字典
Returns:
str: "high", "medium", "low"
"""
details = candidate["details"]
ransac_inliers = details.get("ransac_inliers", 0)
cnn_sim = details.get("cnn_sim", 0.0)
# High confidence(几何一致性或语义确认)
if ransac_inliers >= 15 and cnn_sim > 0.8:
return "high"
# Medium confidence(降低要求以提升召回)
if ransac_inliers >= 8 and cnn_sim > 0.7:
return "medium"
# Low confidence
return "low"