feat: 文件系统数据源与 V3 迁移工具(NAS 迁入基座 Part A)
- source.type 选数据源;文件源只开 /health 与 POST /images/search,双密钥 JWT 强制 exp/sub/eps2 - 两段式扫描:根标记、扫描不完整不删、连续两轮缺失才删、坏图按 path+mtime+size 重试、同一描述符读取 - 索引一次预分配、提交前持锁预留整组位置、满则保留旧组;精排只取前 ransac_top_k 的 ORB 并复核版本 - 结果先按路径聚合再截 TopN,内联 180px 缩略图(源文件变化标 stale) - 视频关键帧 (path, frame_ms) 存储与抽帧(默认关闭) - tools/migrate_v3.py:backup 快照、结构校验、分层抽样比对、路径门禁、离线导入 openspec: migrate-nas-image-search-to-base(tasks 1.1–1.7、3b.1) 实现:codex(gpt-6.2-sol);门禁:Claude 亲跑 107 绿、7 处安全关键变异全被咬住
Showing
11 changed files
with
577 additions
and
43 deletions
| ... | @@ -2,7 +2,9 @@ | ... | @@ -2,7 +2,9 @@ |
| 2 | from contextlib import asynccontextmanager | 2 | from contextlib import asynccontextmanager |
| 3 | from hashlib import sha256 | 3 | from hashlib import sha256 |
| 4 | from importlib.metadata import version | 4 | from importlib.metadata import version |
| 5 | from io import BytesIO | ||
| 5 | import logging | 6 | import logging |
| 7 | import math | ||
| 6 | import os | 8 | import os |
| 7 | from pathlib import Path | 9 | from pathlib import Path |
| 8 | import tempfile | 10 | import tempfile |
| ... | @@ -24,8 +26,11 @@ from core.feature_extractor import CNN_VECTOR_DIM | ... | @@ -24,8 +26,11 @@ from core.feature_extractor import CNN_VECTOR_DIM |
| 24 | from core.search_engine import ImageSearchEngine | 26 | from core.search_engine import ImageSearchEngine |
| 25 | from core.vector_index import VectorIndex, configured_dimension | 27 | from core.vector_index import VectorIndex, configured_dimension |
| 26 | from data_sync import DesignDataSync | 28 | from data_sync import DesignDataSync |
| 29 | from filesystem_sync import FileSystemSync, positive_int | ||
| 27 | 30 | ||
| 28 | logger = logging.getLogger(__name__) | 31 | logger = logging.getLogger(__name__) |
| 32 | FILESYSTEM_UPLOAD_BYTES = 45 * 1024 * 1024 | ||
| 33 | FILESYSTEM_UPLOAD_EXTENSIONS = {'jpg', 'jpeg', 'png', 'webp', 'avif'} | ||
| 29 | 34 | ||
| 30 | 35 | ||
| 31 | def load_config(): | 36 | def load_config(): |
| ... | @@ -72,17 +77,43 @@ def check_search_features(engine, dimension): | ... | @@ -72,17 +77,43 @@ def check_search_features(engine, dimension): |
| 72 | 77 | ||
| 73 | 78 | ||
| 74 | def create_app(config=None, search_engine=None, data_sync=None): | 79 | def create_app(config=None, search_engine=None, data_sync=None): |
| 80 | config = config if config is not None else load_config() | ||
| 81 | source = config.get('source', {}).get('type', 'mysql_design') | ||
| 82 | if source not in {'mysql_design', 'filesystem'}: | ||
| 83 | raise ValueError(f'Unknown image search source: {source}') | ||
| 84 | filesystem = source == 'filesystem' | ||
| 85 | file_keys = () | ||
| 86 | |||
| 75 | @asynccontextmanager | 87 | @asynccontextmanager |
| 76 | async def lifespan(app): | 88 | async def lifespan(app): |
| 89 | nonlocal file_keys | ||
| 90 | if filesystem: | ||
| 91 | file_jwt = config['filesystem']['jwt'] | ||
| 92 | file_keys = tuple(key for key in (file_jwt.get('prod_secret'), file_jwt.get('daily_secret')) | ||
| 93 | if key is not None) | ||
| 94 | if (not file_jwt.get('prod_secret') or any(not isinstance(key, str) or not key.strip() | ||
| 95 | or len(key.encode('utf-8')) < 32 for key in file_keys)): | ||
| 96 | raise ValueError('Filesystem JWT secrets must have at least 32 UTF-8 bytes') | ||
| 97 | if not isinstance(file_jwt.get('subject'), str) or not file_jwt['subject'].strip(): | ||
| 98 | raise ValueError('Filesystem JWT subject is required') | ||
| 77 | if app.state.engine is None: | 99 | if app.state.engine is None: |
| 78 | settings = app.state.config | 100 | settings = app.state.config |
| 79 | db = DatabaseManager(settings['database']['sqlite']['path']) | 101 | db_path = (settings['filesystem']['sqlite_path'] if filesystem else |
| 102 | settings['database']['sqlite']['path']) | ||
| 103 | db = DatabaseManager(db_path) | ||
| 80 | dimension = configured_dimension(settings) | 104 | dimension = configured_dimension(settings) |
| 81 | index = VectorIndex(dimension) | 105 | index = VectorIndex(dimension) |
| 106 | if filesystem: | ||
| 107 | minimum = positive_int(settings['filesystem'].get('index_min_capacity', 1024), | ||
| 108 | 'index_min_capacity', minimum=0) | ||
| 109 | db.file_index_snapshot(index, minimum, settings.get('video', {}).get('enabled', False)) | ||
| 110 | else: | ||
| 111 | db.require_design_source() | ||
| 82 | index.bulk_load(db.iter_index_rows()) | 112 | index.bulk_load(db.iter_index_rows()) |
| 83 | engine = ImageSearchEngine(config=settings, index=index, db_manager=db) | 113 | engine = ImageSearchEngine(config=settings, index=index, db_manager=db) |
| 84 | check_search_features(engine, dimension) | 114 | check_search_features(engine, dimension) |
| 85 | app.state.sync = DesignDataSync(settings, index=index, db_manager=db, extractor=engine.extractor) | 115 | sync_class = FileSystemSync if filesystem else DesignDataSync |
| 116 | app.state.sync = sync_class(settings, index=index, db_manager=db, extractor=engine.extractor) | ||
| 86 | app.state.engine = engine | 117 | app.state.engine = engine |
| 87 | worker = None | 118 | worker = None |
| 88 | if data_sync is None: | 119 | if data_sync is None: |
| ... | @@ -96,8 +127,9 @@ def create_app(config=None, search_engine=None, data_sync=None): | ... | @@ -96,8 +127,9 @@ def create_app(config=None, search_engine=None, data_sync=None): |
| 96 | app.state.sync.stop_event.set() | 127 | app.state.sync.stop_event.set() |
| 97 | worker.join(timeout=5) | 128 | worker.join(timeout=5) |
| 98 | 129 | ||
| 99 | app = FastAPI(title='Design Image Search Service', lifespan=lifespan) | 130 | app = FastAPI(title='Design Image Search Service', lifespan=lifespan, |
| 100 | app.state.config = config if config is not None else load_config() | 131 | **({'openapi_url': None} if filesystem else {})) |
| 132 | app.state.config = config | ||
| 101 | app.state.engine = search_engine | 133 | app.state.engine = search_engine |
| 102 | app.state.sync = data_sync | 134 | app.state.sync = data_sync |
| 103 | app.state.sync_thread = None | 135 | app.state.sync_thread = None |
| ... | @@ -105,6 +137,21 @@ def create_app(config=None, search_engine=None, data_sync=None): | ... | @@ -105,6 +137,21 @@ def create_app(config=None, search_engine=None, data_sync=None): |
| 105 | def verify_token(authorization: str = Header(None)): | 137 | def verify_token(authorization: str = Header(None)): |
| 106 | if not authorization or not authorization.startswith('Bearer '): | 138 | if not authorization or not authorization.startswith('Bearer '): |
| 107 | raise HTTPException(401, 'Missing or invalid authorization') | 139 | raise HTTPException(401, 'Missing or invalid authorization') |
| 140 | if filesystem: | ||
| 141 | for key in file_keys: | ||
| 142 | try: | ||
| 143 | payload = jwt.decode(authorization[7:], key, algorithms=['HS256'], | ||
| 144 | options={'require_exp': True, 'require_sub': True}) | ||
| 145 | except (JWTError, TypeError, ValueError, OverflowError): | ||
| 146 | continue | ||
| 147 | expiration = payload['exp'] | ||
| 148 | valid_expiration = type(expiration) is int or ( | ||
| 149 | type(expiration) is float and math.isfinite(expiration)) | ||
| 150 | if (payload['sub'] == config['filesystem']['jwt']['subject'] | ||
| 151 | and valid_expiration | ||
| 152 | and time.time() < expiration): | ||
| 153 | return payload | ||
| 154 | raise HTTPException(401, 'Invalid or expired token') | ||
| 108 | settings = app.state.config['jwt'] | 155 | settings = app.state.config['jwt'] |
| 109 | try: | 156 | try: |
| 110 | payload = jwt.decode(authorization[7:], settings['secret'], | 157 | payload = jwt.decode(authorization[7:], settings['secret'], |
| ... | @@ -118,14 +165,14 @@ def create_app(config=None, search_engine=None, data_sync=None): | ... | @@ -118,14 +165,14 @@ def create_app(config=None, search_engine=None, data_sync=None): |
| 118 | def search_token(payload=Depends(verify_token)): | 165 | def search_token(payload=Depends(verify_token)): |
| 119 | if type(payload.get('eps_id')) is not int: | 166 | if type(payload.get('eps_id')) is not int: |
| 120 | raise HTTPException(401, 'Integer eps_id claim required') | 167 | raise HTTPException(401, 'Integer eps_id claim required') |
| 168 | if filesystem and payload['eps_id'] != 2: | ||
| 169 | raise HTTPException(401, 'Invalid enterprise') | ||
| 121 | return payload | 170 | return payload |
| 122 | 171 | ||
| 123 | @app.get('/') | ||
| 124 | def root(): | ||
| 125 | return {'service': 'Design Image Search', 'status': 'running'} | ||
| 126 | |||
| 127 | @app.get('/health') | 172 | @app.get('/health') |
| 128 | async def health(): | 173 | async def health(): |
| 174 | if filesystem: | ||
| 175 | return {'status': 'healthy', 'scan': app.state.sync.status} | ||
| 129 | # 协程里直接跑:只有一次轻量计数查询,不进工作线程池,搜索排队占满线程池时也能响应 | 176 | # 协程里直接跑:只有一次轻量计数查询,不进工作线程池,搜索排队占满线程池时也能响应 |
| 130 | stats = app.state.engine.db.health_stats() | 177 | stats = app.state.engine.db.health_stats() |
| 131 | worker = app.state.sync_thread | 178 | worker = app.state.sync_thread |
| ... | @@ -137,13 +184,31 @@ def create_app(config=None, search_engine=None, data_sync=None): | ... | @@ -137,13 +184,31 @@ def create_app(config=None, search_engine=None, data_sync=None): |
| 137 | 184 | ||
| 138 | @app.post('/images/search') | 185 | @app.post('/images/search') |
| 139 | def search(file: UploadFile = File(...), top_n: int = Form(20), token=Depends(search_token)): | 186 | def search(file: UploadFile = File(...), top_n: int = Form(20), token=Depends(search_token)): |
| 140 | settings = app.state.config['upload'] | 187 | settings = app.state.config.get('upload', {}) |
| 141 | extension = Path(file.filename or '').suffix.lower().lstrip('.') | 188 | extension = Path(file.filename or '').suffix.lower().lstrip('.') |
| 142 | if extension not in settings['allowed_formats']: | 189 | allowed_formats = FILESYSTEM_UPLOAD_EXTENSIONS if filesystem else settings['allowed_formats'] |
| 190 | limit = FILESYSTEM_UPLOAD_BYTES if filesystem else settings['max_file_size'] | ||
| 191 | if extension not in allowed_formats: | ||
| 143 | raise HTTPException(400, 'Unsupported file format') | 192 | raise HTTPException(400, 'Unsupported file format') |
| 144 | content = file.file.read(settings['max_file_size'] + 1) | 193 | content = file.file.read(limit + 1) |
| 145 | if len(content) > settings['max_file_size']: | 194 | if len(content) > limit: |
| 146 | raise HTTPException(400, 'File too large') | 195 | raise HTTPException(400, 'File too large') |
| 196 | if filesystem: | ||
| 197 | if not content: | ||
| 198 | raise HTTPException(400, 'Empty image file') | ||
| 199 | start = time.perf_counter() | ||
| 200 | try: | ||
| 201 | with Image.open(BytesIO(content), formats=['JPEG', 'PNG', 'WEBP', 'AVIF']) as decoded: | ||
| 202 | image = decoded.convert('RGB') | ||
| 203 | except (OSError, ValueError, Image.DecompressionBombError): | ||
| 204 | raise HTTPException(400, 'Image decode failed') | ||
| 205 | try: | ||
| 206 | results = app.state.engine.search(image, eps_id=token['eps_id'], top_k=min(max(1, top_n), 100)) | ||
| 207 | except Exception: | ||
| 208 | logger.exception('Filesystem image search failed') | ||
| 209 | raise HTTPException(500, 'Image search failed') | ||
| 210 | return {'results': results, 'query_time_ms': round((time.perf_counter() - start) * 1000, 2), | ||
| 211 | 'total_found': len(results)} | ||
| 147 | directory = Path(settings['temp_dir']) | 212 | directory = Path(settings['temp_dir']) |
| 148 | directory.mkdir(parents=True, exist_ok=True) | 213 | directory.mkdir(parents=True, exist_ok=True) |
| 149 | with tempfile.NamedTemporaryFile(dir=directory, suffix='.' + extension, delete=False) as f: | 214 | with tempfile.NamedTemporaryFile(dir=directory, suffix='.' + extension, delete=False) as f: |
| ... | @@ -166,6 +231,13 @@ def create_app(config=None, search_engine=None, data_sync=None): | ... | @@ -166,6 +231,13 @@ def create_app(config=None, search_engine=None, data_sync=None): |
| 166 | finally: | 231 | finally: |
| 167 | Path(path).unlink(missing_ok=True) | 232 | Path(path).unlink(missing_ok=True) |
| 168 | 233 | ||
| 234 | if filesystem: | ||
| 235 | return app | ||
| 236 | |||
| 237 | @app.get('/') | ||
| 238 | def root(): | ||
| 239 | return {'service': 'Design Image Search', 'status': 'running'} | ||
| 240 | |||
| 169 | @app.post('/sync/trigger') | 241 | @app.post('/sync/trigger') |
| 170 | def sync(token=Depends(verify_token)): | 242 | def sync(token=Depends(verify_token)): |
| 171 | return app.state.sync.sync_once() | 243 | return app.state.sync.sync_once() | ... | ... |
| ... | @@ -7,6 +7,39 @@ server: | ... | @@ -7,6 +7,39 @@ server: |
| 7 | port: 5088 | 7 | port: 5088 |
| 8 | workers: 1 | 8 | workers: 1 |
| 9 | 9 | ||
| 10 | source: | ||
| 11 | type: "${IMAGE_SEARCH_SOURCE:mysql_design}" | ||
| 12 | |||
| 13 | filesystem: | ||
| 14 | sqlite_path: "./data/filesystem_images.db" | ||
| 15 | roots: | ||
| 16 | /data/etsy: Etsy | ||
| 17 | /data/video: 摄影新人测试目录 | ||
| 18 | # Set the actual UNC server and share prefixes before enabling the file source. | ||
| 19 | unc_prefixes: | ||
| 20 | /data/etsy: '${NAS_ETSY_UNC}' | ||
| 21 | /data/video: '${NAS_VIDEO_UNC}' | ||
| 22 | interval_seconds: 14400 | ||
| 23 | # night_window: [22, 6] # Optional overnight scheduling in container local time. | ||
| 24 | batch_size: 32 | ||
| 25 | index_min_capacity: 1024 | ||
| 26 | thumbnail_top_n: 20 | ||
| 27 | jwt: | ||
| 28 | prod_secret: '${NAS_IMAGE_SEARCH_PROD_SECRET}' | ||
| 29 | daily_secret: '${NAS_IMAGE_SEARCH_DAILY_SECRET}' | ||
| 30 | subject: nas-image-search | ||
| 31 | search: | ||
| 32 | max_candidates: 2000 | ||
| 33 | ransac_top_k: 500 | ||
| 34 | ransac: | ||
| 35 | min_inliers: 8 | ||
| 36 | reproj_threshold: 6.0 | ||
| 37 | confidence: 0.95 | ||
| 38 | |||
| 39 | video: | ||
| 40 | enabled: false | ||
| 41 | frame_cap: 8 | ||
| 42 | |||
| 10 | # Database Settings | 43 | # Database Settings |
| 11 | database: | 44 | database: |
| 12 | sqlite: | 45 | sqlite: | ... | ... |
| 1 | """Exact tenant recall followed by unchanged CNN/RANSAC fusion.""" | 1 | """Exact tenant recall followed by unchanged CNN/RANSAC fusion.""" |
| 2 | from concurrent.futures import ThreadPoolExecutor | 2 | from concurrent.futures import ThreadPoolExecutor |
| 3 | from base64 import b64encode | ||
| 3 | import logging | 4 | import logging |
| 4 | import threading | 5 | import threading |
| 5 | 6 | ||
| 7 | import cv2 | ||
| 8 | from PIL import Image | ||
| 9 | |||
| 10 | from filesystem_files import FilePaths, jpeg_thumbnail | ||
| 6 | from .feature_extractor import FeatureExtractor | 11 | from .feature_extractor import FeatureExtractor |
| 7 | 12 | ||
| 8 | logger = logging.getLogger(__name__) | 13 | logger = logging.getLogger(__name__) |
| ... | @@ -13,21 +18,30 @@ class ImageSearchEngine: | ... | @@ -13,21 +18,30 @@ class ImageSearchEngine: |
| 13 | from database import DatabaseManager | 18 | from database import DatabaseManager |
| 14 | from .vector_index import VectorIndex, configured_dimension | 19 | from .vector_index import VectorIndex, configured_dimension |
| 15 | self.config = config or {} | 20 | self.config = config or {} |
| 21 | self.filesystem = self.config.get('source', {}).get('type') == 'filesystem' | ||
| 22 | self.file_paths = None | ||
| 23 | if self.filesystem: | ||
| 24 | settings = self.config['filesystem'] | ||
| 25 | self.file_paths = FilePaths(settings['roots'], settings['unc_prefixes']) | ||
| 26 | self.thumbnail_top_n = settings.get('thumbnail_top_n', 20) | ||
| 16 | self.db = db_manager if db_manager is not None else DatabaseManager(db_path) | 27 | self.db = db_manager if db_manager is not None else DatabaseManager(db_path) |
| 17 | self.index = index if index is not None else VectorIndex(configured_dimension(self.config)) | 28 | self.index = index if index is not None else VectorIndex(configured_dimension(self.config)) |
| 18 | if index is None: | 29 | if index is None and self.filesystem: |
| 30 | self.db.file_index_snapshot(self.index, settings.get('index_min_capacity', 1024), | ||
| 31 | self.config.get('video', {}).get('enabled', False)) | ||
| 32 | elif index is None: | ||
| 19 | self.index.bulk_load(self.db.iter_index_rows()) | 33 | self.index.bulk_load(self.db.iter_index_rows()) |
| 20 | self.extractor = extractor if extractor is not None else FeatureExtractor( | 34 | self.extractor = extractor if extractor is not None else FeatureExtractor( |
| 21 | orb_max_features=self.config.get('orb_max_features', 1200), | 35 | orb_max_features=self.config.get('orb_max_features', 1200), |
| 22 | cnn_enabled=self.config.get('cnn_enabled', True)) | 36 | cnn_enabled=self.config.get('cnn_enabled', True)) |
| 23 | search_config = self.config.get('search', {}) | 37 | search_config = settings.get('search', {}) if self.filesystem else self.config.get('search', {}) |
| 24 | self.max_candidates = search_config.get('max_candidates', 200) | 38 | self.max_candidates = search_config.get('max_candidates', 2000 if self.filesystem else 200) |
| 25 | self.ransac_top_k = search_config.get('ransac_top_k', 100) | 39 | self.ransac_top_k = search_config.get('ransac_top_k', 500 if self.filesystem else 100) |
| 26 | self.top_results = search_config.get('top_results', 20) | 40 | self.top_results = search_config.get('top_results', 20) |
| 27 | ransac_config = search_config.get('ransac', {}) | 41 | ransac_config = search_config.get('ransac', {}) |
| 28 | self.min_orb_inliers = ransac_config.get('min_inliers', 15) | 42 | self.min_orb_inliers = ransac_config.get('min_inliers', 8 if self.filesystem else 15) |
| 29 | self.ransac_reproj_thresh = ransac_config.get('reproj_threshold', 4.0) | 43 | self.ransac_reproj_thresh = ransac_config.get('reproj_threshold', 6.0 if self.filesystem else 4.0) |
| 30 | self.ransac_confidence = ransac_config.get('confidence', 0.995) | 44 | self.ransac_confidence = ransac_config.get('confidence', 0.95 if self.filesystem else 0.995) |
| 31 | weights_config = search_config.get('fusion_weights', {}) | 45 | weights_config = search_config.get('fusion_weights', {}) |
| 32 | self.weights = { | 46 | self.weights = { |
| 33 | "cnn": weights_config.get("cnn", 0.2) * 100, | 47 | "cnn": weights_config.get("cnn", 0.2) * 100, |
| ... | @@ -43,22 +57,38 @@ class ImageSearchEngine: | ... | @@ -43,22 +57,38 @@ class ImageSearchEngine: |
| 43 | def _search(self, path, eps_id, top_k): | 57 | def _search(self, path, eps_id, top_k): |
| 44 | query = self.extractor.extract_all_features(path) | 58 | query = self.extractor.extract_all_features(path) |
| 45 | if query is None or query.get('cnn_vector') is None: | 59 | if query is None or query.get('cnn_vector') is None: |
| 60 | if self.filesystem: | ||
| 61 | raise RuntimeError('Query feature extraction failed') | ||
| 46 | return [] | 62 | return [] |
| 47 | recalled = self.index.search(query['cnn_vector'], eps_id, self.max_candidates) | 63 | recalled = self.index.search(query['cnn_vector'], eps_id, self.max_candidates) |
| 48 | rows = self.db.get_features([item[0] for item in recalled]) | 64 | ids = [item[0] for item in recalled] |
| 65 | if self.filesystem: | ||
| 66 | rows = self.db.file_search_metadata(ids) | ||
| 67 | orbs = self.db.file_search_orb(ids[:self.ransac_top_k]) | ||
| 68 | else: | ||
| 69 | rows = self.db.get_features(ids) | ||
| 49 | candidates = [] | 70 | candidates = [] |
| 50 | for rank, (design_id, cnn_sim, version) in enumerate(recalled): | 71 | for rank, (design_id, cnn_sim, version) in enumerate(recalled): |
| 51 | row = rows.get(design_id) | 72 | row = rows.get(design_id) |
| 52 | if row is None or row['feat_version'] != version or row['eps_id'] != eps_id: | 73 | if not self._matches_recall(row, design_id, eps_id, version): |
| 74 | continue | ||
| 75 | orb = row | ||
| 76 | if self.filesystem: | ||
| 77 | orb = None | ||
| 78 | if rank < self.ransac_top_k: | ||
| 79 | raw = orbs.get(design_id) | ||
| 80 | if not self._matches_recall(raw, design_id, eps_id, version): | ||
| 53 | continue | 81 | continue |
| 54 | candidates.append({'img_id': design_id, 'design_no': row['design_no'], | 82 | orb = self.db.decode_orb(raw) |
| 83 | candidates.append({'img_id': design_id, 'design_no': row.get('design_no'), | ||
| 55 | 'image_url': row['image_url'], 'initial_score': cnn_sim * 100 * self.weights['cnn'], | 84 | 'image_url': row['image_url'], 'initial_score': cnn_sim * 100 * self.weights['cnn'], |
| 56 | 'details': {'cnn_sim': cnn_sim, 'ransac_inliers': 0}, | 85 | 'details': {'cnn_sim': cnn_sim, 'ransac_inliers': 0}, |
| 57 | 'row': row, 'use_ransac': rank < self.ransac_top_k}) | 86 | 'metadata': row if self.filesystem else None, |
| 87 | 'orb': orb if rank < self.ransac_top_k else None}) | ||
| 58 | 88 | ||
| 59 | def verify(candidate): | 89 | def verify(candidate): |
| 60 | row = candidate['row'] | 90 | row = candidate['orb'] |
| 61 | if not candidate['use_ransac'] or row['orb_pts'] is None or row['orb_desc'] is None: | 91 | if row is None or row['orb_pts'] is None or row['orb_desc'] is None: |
| 62 | return 0 | 92 | return 0 |
| 63 | try: | 93 | try: |
| 64 | return self.extractor.compute_orb_ransac_score( | 94 | return self.extractor.compute_orb_ransac_score( |
| ... | @@ -74,11 +104,42 @@ class ImageSearchEngine: | ... | @@ -74,11 +104,42 @@ class ImageSearchEngine: |
| 74 | candidate['details']['ransac_inliers'] = inliers | 104 | candidate['details']['ransac_inliers'] = inliers |
| 75 | candidate['score'] = candidate['initial_score'] + inliers * self.weights['ransac'] | 105 | candidate['score'] = candidate['initial_score'] + inliers * self.weights['ransac'] |
| 76 | candidate['confidence'] = self._assess_confidence(candidate) | 106 | candidate['confidence'] = self._assess_confidence(candidate) |
| 77 | del candidate['row'] | 107 | del candidate['orb'] |
| 78 | del candidate['use_ransac'] | ||
| 79 | candidates.sort(key=lambda c: (-c['score'], c['img_id'])) | 108 | candidates.sort(key=lambda c: (-c['score'], c['img_id'])) |
| 109 | if self.filesystem: | ||
| 110 | return self._file_results(candidates, top_k) | ||
| 111 | for candidate in candidates: | ||
| 112 | del candidate['metadata'] | ||
| 80 | return candidates[:top_k] | 113 | return candidates[:top_k] |
| 81 | 114 | ||
| 115 | @staticmethod | ||
| 116 | def _matches_recall(row, image_id, eps_id, version): | ||
| 117 | return (row is not None and row['id'] == image_id and row['eps_id'] == eps_id | ||
| 118 | and row['feat_version'] == version) | ||
| 119 | |||
| 120 | def _file_results(self, candidates, top_k): | ||
| 121 | distinct = {} | ||
| 122 | for candidate in candidates: | ||
| 123 | path = candidate['metadata']['path'] | ||
| 124 | if path and self.file_paths.root_for(path) is not None: | ||
| 125 | distinct.setdefault(path, candidate) | ||
| 126 | results = [] | ||
| 127 | for candidate in list(distinct.values())[:top_k]: | ||
| 128 | row = candidate['metadata'] | ||
| 129 | result = {key: candidate[key] for key in ('score', 'confidence', 'details')} | ||
| 130 | result.update(path=row['image_url'], thumbnail=None) | ||
| 131 | if row['frame_ms'] != -1: | ||
| 132 | result['frame_ms'] = row['frame_ms'] | ||
| 133 | if len(results) < self.thumbnail_top_n: | ||
| 134 | try: | ||
| 135 | thumbnail = jpeg_thumbnail(row['path'], self.file_paths.root_for(row['path']), | ||
| 136 | (row['mtime'], row['size']), row['frame_ms']) | ||
| 137 | result['thumbnail'] = b64encode(thumbnail).decode('ascii') | ||
| 138 | except (OSError, ValueError, Image.DecompressionBombError, cv2.error): | ||
| 139 | result['stale'] = True | ||
| 140 | results.append(result) | ||
| 141 | return results | ||
| 142 | |||
| 82 | def _assess_confidence(self, candidate): | 143 | def _assess_confidence(self, candidate): |
| 83 | """ | 144 | """ |
| 84 | 评估搜索结果的置信度(珠宝图片优化版) | 145 | 评估搜索结果的置信度(珠宝图片优化版) | ... | ... |
| ... | @@ -20,6 +20,7 @@ class VectorIndex: | ... | @@ -20,6 +20,7 @@ class VectorIndex: |
| 20 | self.versions = np.empty(0, dtype=np.int64) | 20 | self.versions = np.empty(0, dtype=np.int64) |
| 21 | self.rows = {} | 21 | self.rows = {} |
| 22 | self._size = 0 | 22 | self._size = 0 |
| 23 | self._fixed = False | ||
| 23 | 24 | ||
| 24 | def bulk_load(self, rows): | 25 | def bulk_load(self, rows): |
| 25 | """Replace the index from a single pass over SQLite's vector-only rows.""" | 26 | """Replace the index from a single pass over SQLite's vector-only rows.""" |
| ... | @@ -45,6 +46,61 @@ class VectorIndex: | ... | @@ -45,6 +46,61 @@ class VectorIndex: |
| 45 | self.eps_ids, self.versions = eps_ids, versions | 46 | self.eps_ids, self.versions = eps_ids, versions |
| 46 | self.rows = positions | 47 | self.rows = positions |
| 47 | self._size = len(rows) | 48 | self._size = len(rows) |
| 49 | self._fixed = False | ||
| 50 | |||
| 51 | def bulk_load_fixed(self, rows, row_count, minimum_capacity): | ||
| 52 | """Allocate once and consume SQLite rows one at a time.""" | ||
| 53 | capacity = max((row_count * 115 + 99) // 100, minimum_capacity) | ||
| 54 | with self.lock: | ||
| 55 | if len(self.ids) or self._fixed: | ||
| 56 | raise RuntimeError('Fixed index must be loaded into a fresh index') | ||
| 57 | self.vectors = np.empty((capacity, self.dimension), dtype=np.float32) | ||
| 58 | self.ids = np.empty(capacity, dtype=np.int64) | ||
| 59 | self.eps_ids = np.empty(capacity, dtype=np.int64) | ||
| 60 | self.versions = np.empty(capacity, dtype=np.int64) | ||
| 61 | self._fixed = True | ||
| 62 | for row in rows: | ||
| 63 | vector = np.frombuffer(row['cnn_vector'], dtype=np.float32) | ||
| 64 | image_id = row['id'] | ||
| 65 | if image_id in self.rows or self._size >= row_count or vector.shape != (self.dimension,): | ||
| 66 | raise ValueError(f'Invalid fixed index row {image_id}') | ||
| 67 | slot = self.vectors[self._size] | ||
| 68 | slot[:] = vector | ||
| 69 | self.normalize_fixed(slot) | ||
| 70 | self._put(image_id, row['eps_id'], slot, row['feat_version']) | ||
| 71 | if self._size != row_count: | ||
| 72 | raise ValueError('Fixed index row count changed during startup') | ||
| 73 | |||
| 74 | @staticmethod | ||
| 75 | def normalize_fixed(vector): | ||
| 76 | # Finite float32 vectors can overflow/underflow a float32 sum of squares. | ||
| 77 | norm = np.linalg.norm(vector.astype(np.float64)) | ||
| 78 | if not np.isfinite(norm) or norm == 0: | ||
| 79 | raise ValueError('Invalid CNN vector') | ||
| 80 | np.divide(vector, norm, out=vector, dtype=np.float64, casting='unsafe') | ||
| 81 | |||
| 82 | def normalized(self, vector): | ||
| 83 | vector = np.asarray(vector, dtype=np.float32).reshape(self.dimension) | ||
| 84 | if self._fixed: | ||
| 85 | result = vector.copy() | ||
| 86 | self.normalize_fixed(result) | ||
| 87 | return result | ||
| 88 | norm = np.linalg.norm(vector) | ||
| 89 | if not np.isfinite(norm) or norm == 0: | ||
| 90 | raise ValueError('Invalid CNN vector') | ||
| 91 | return vector / norm | ||
| 92 | |||
| 93 | def can_replace_group(self, old_ids, new_count): | ||
| 94 | """Caller holds the lock continuously from reservation through publication.""" | ||
| 95 | reclaimed = sum(image_id in self.rows for image_id in old_ids) | ||
| 96 | return self._size - reclaimed + new_count <= len(self.ids) | ||
| 97 | |||
| 98 | def replace_group(self, old_ids, entries): | ||
| 99 | """Publish normalized entries under the same lock used for reservation.""" | ||
| 100 | for image_id in old_ids: | ||
| 101 | self.remove(image_id) | ||
| 102 | for image_id, eps_id, vector, version in entries: | ||
| 103 | self._put(image_id, eps_id, vector, version) | ||
| 48 | 104 | ||
| 49 | def _grow(self): | 105 | def _grow(self): |
| 50 | """Double storage only when full, making incremental appends amortized.""" | 106 | """Double storage only when full, making incremental appends amortized.""" |
| ... | @@ -60,15 +116,16 @@ class VectorIndex: | ... | @@ -60,15 +116,16 @@ class VectorIndex: |
| 60 | self.eps_ids, self.versions = eps_ids, versions | 116 | self.eps_ids, self.versions = eps_ids, versions |
| 61 | 117 | ||
| 62 | def upsert(self, design_id, eps_id, vector, feat_version): | 118 | def upsert(self, design_id, eps_id, vector, feat_version): |
| 63 | vector = np.asarray(vector, dtype=np.float32).reshape(self.dimension) | 119 | vector = self.normalized(vector) |
| 64 | norm = np.linalg.norm(vector) | ||
| 65 | if not np.isfinite(norm) or norm == 0: | ||
| 66 | raise ValueError('Invalid CNN vector') | ||
| 67 | vector = vector / norm | ||
| 68 | with self.lock: | 120 | with self.lock: |
| 121 | self._put(design_id, eps_id, vector, feat_version) | ||
| 122 | |||
| 123 | def _put(self, design_id, eps_id, vector, feat_version): | ||
| 69 | row = self.rows.get(int(design_id)) | 124 | row = self.rows.get(int(design_id)) |
| 70 | if row is None: | 125 | if row is None: |
| 71 | if self._size == len(self.ids): | 126 | if self._size == len(self.ids): |
| 127 | if self._fixed: | ||
| 128 | raise RuntimeError('Fixed index capacity exhausted') | ||
| 72 | self._grow() | 129 | self._grow() |
| 73 | row = self._size | 130 | row = self._size |
| 74 | self.rows[int(design_id)] = row | 131 | self.rows[int(design_id)] = row |
| ... | @@ -94,8 +151,9 @@ class VectorIndex: | ... | @@ -94,8 +151,9 @@ class VectorIndex: |
| 94 | vector = np.asarray(vector, dtype=np.float32).reshape(self.dimension) | 151 | vector = np.asarray(vector, dtype=np.float32).reshape(self.dimension) |
| 95 | vector = vector / (np.linalg.norm(vector) or 1) | 152 | vector = vector / (np.linalg.norm(vector) or 1) |
| 96 | with self.lock: | 153 | with self.lock: |
| 154 | all_scores = self.vectors[:self._size] @ vector | ||
| 97 | rows = np.flatnonzero(self.eps_ids[:self._size] == eps_id) | 155 | rows = np.flatnonzero(self.eps_ids[:self._size] == eps_id) |
| 98 | scores = self.vectors[rows] @ vector | 156 | scores = all_scores[rows] |
| 99 | order = np.lexsort((self.ids[rows], -scores))[:max(0, k)] | 157 | order = np.lexsort((self.ids[rows], -scores))[:max(0, k)] |
| 100 | return [(int(self.ids[rows[i]]), float(scores[i]), | 158 | return [(int(self.ids[rows[i]]), float(scores[i]), |
| 101 | int(self.versions[rows[i]])) for i in order] | 159 | int(self.versions[rows[i]])) for i in order] | ... | ... |
| ... | @@ -259,8 +259,13 @@ class DesignDataSync: | ... | @@ -259,8 +259,13 @@ class DesignDataSync: |
| 259 | raise | 259 | raise |
| 260 | return {'status': 'started'} | 260 | return {'status': 'started'} |
| 261 | 261 | ||
| 262 | def run_forever(self): | 262 | @property |
| 263 | while not self.stop_event.is_set(): | 263 | def status(self): |
| 264 | return self.rebuild_status() | ||
| 265 | |||
| 266 | def run_forever(self, stop_event=None): | ||
| 267 | stop_event = self.stop_event if stop_event is None else stop_event | ||
| 268 | while not stop_event.is_set(): | ||
| 264 | try: | 269 | try: |
| 265 | self.sync_once() | 270 | self.sync_once() |
| 266 | now = datetime.now() | 271 | now = datetime.now() |
| ... | @@ -269,4 +274,4 @@ class DesignDataSync: | ... | @@ -269,4 +274,4 @@ class DesignDataSync: |
| 269 | self.reconcile() | 274 | self.reconcile() |
| 270 | except Exception: | 275 | except Exception: |
| 271 | logger.exception('Sync round failed') | 276 | logger.exception('Sync round failed') |
| 272 | self.stop_event.wait(self.settings.get('interval_seconds', 60)) | 277 | stop_event.wait(self.settings.get('interval_seconds', 60)) | ... | ... |
| ... | @@ -19,7 +19,7 @@ class DatabaseManager: | ... | @@ -19,7 +19,7 @@ class DatabaseManager: |
| 19 | raise RuntimeError('Old images schema: use a new SQLite file and rebuild') | 19 | raise RuntimeError('Old images schema: use a new SQLite file and rebuild') |
| 20 | conn.executescript(""" | 20 | conn.executescript(""" |
| 21 | CREATE TABLE IF NOT EXISTS images( | 21 | CREATE TABLE IF NOT EXISTS images( |
| 22 | id INTEGER PRIMARY KEY, eps_id INTEGER NOT NULL, design_no TEXT, | 22 | id INTEGER PRIMARY KEY AUTOINCREMENT, eps_id INTEGER NOT NULL, design_no TEXT, |
| 23 | image_url TEXT NOT NULL, cnn_vector BLOB NOT NULL, orb_desc BLOB, | 23 | image_url TEXT NOT NULL, cnn_vector BLOB NOT NULL, orb_desc BLOB, |
| 24 | orb_pts BLOB, feat_version INTEGER NOT NULL, | 24 | orb_pts BLOB, feat_version INTEGER NOT NULL, |
| 25 | source_modified TEXT, updated_at TEXT); | 25 | source_modified TEXT, updated_at TEXT); |
| ... | @@ -28,6 +28,18 @@ class DatabaseManager: | ... | @@ -28,6 +28,18 @@ class DatabaseManager: |
| 28 | last_sync_at TEXT, last_reconcile_at TEXT); | 28 | last_sync_at TEXT, last_reconcile_at TEXT); |
| 29 | INSERT OR IGNORE INTO sync_state(id) VALUES(1); | 29 | INSERT OR IGNORE INTO sync_state(id) VALUES(1); |
| 30 | """) | 30 | """) |
| 31 | # Existing design databases retain their IDs and features. | ||
| 32 | with conn: | ||
| 33 | conn.execute('BEGIN IMMEDIATE') | ||
| 34 | columns = {r['name'] for r in conn.execute('PRAGMA table_info(images)')} | ||
| 35 | for name, kind in [('path', 'TEXT'), ('mtime', 'REAL'), ('size', 'INTEGER'), | ||
| 36 | ('sha1', 'TEXT'), ('frame_ms', 'INTEGER NOT NULL DEFAULT -1')]: | ||
| 37 | if name not in columns: | ||
| 38 | conn.execute(f'ALTER TABLE images ADD COLUMN {name} {kind}') | ||
| 39 | conn.execute('CREATE UNIQUE INDEX IF NOT EXISTS images_path_frame ON images(path, frame_ms)') | ||
| 40 | conn.execute('''CREATE TABLE IF NOT EXISTS damaged_files( | ||
| 41 | path TEXT PRIMARY KEY, mtime REAL, size INTEGER, sha1 TEXT, | ||
| 42 | error_type TEXT, updated_at TEXT)''') | ||
| 31 | 43 | ||
| 32 | @contextmanager | 44 | @contextmanager |
| 33 | def get_connection(self): | 45 | def get_connection(self): |
| ... | @@ -59,6 +71,56 @@ class DatabaseManager: | ... | @@ -59,6 +71,56 @@ class DatabaseManager: |
| 59 | for row in conn.execute('SELECT id, eps_id, cnn_vector, feat_version FROM images'): | 71 | for row in conn.execute('SELECT id, eps_id, cnn_vector, feat_version FROM images'): |
| 60 | yield dict(row, cnn_vector=np.frombuffer(row['cnn_vector'], dtype=np.float32)) | 72 | yield dict(row, cnn_vector=np.frombuffer(row['cnn_vector'], dtype=np.float32)) |
| 61 | 73 | ||
| 74 | def file_index_snapshot(self, index, minimum_capacity, video_enabled=False): | ||
| 75 | with self.get_connection() as conn: | ||
| 76 | conn.execute('BEGIN') | ||
| 77 | count, design_count = conn.execute('SELECT COUNT(*), COUNT(*) - COUNT(path) FROM images').fetchone() | ||
| 78 | if design_count: | ||
| 79 | raise ValueError('Filesystem source requires a separate SQLite file') | ||
| 80 | where = '' if video_enabled else ' WHERE frame_ms=-1' | ||
| 81 | if where: | ||
| 82 | count = conn.execute('SELECT COUNT(*) FROM images' + where).fetchone()[0] | ||
| 83 | rows = conn.execute('SELECT id, eps_id, cnn_vector, feat_version FROM images' + where) | ||
| 84 | index.bulk_load_fixed(rows, count, minimum_capacity) | ||
| 85 | |||
| 86 | def require_design_source(self): | ||
| 87 | with self.get_connection() as conn: | ||
| 88 | if conn.execute('SELECT 1 FROM images WHERE path IS NOT NULL LIMIT 1').fetchone(): | ||
| 89 | raise ValueError('Design source requires a separate SQLite file') | ||
| 90 | |||
| 91 | def file_metadata(self): | ||
| 92 | with self.get_connection() as conn: | ||
| 93 | return {row['path']: dict(row) for row in conn.execute(''' | ||
| 94 | SELECT path, mtime, size, sha1 FROM images WHERE path IS NOT NULL GROUP BY path''')} | ||
| 95 | |||
| 96 | def damaged_metadata(self): | ||
| 97 | with self.get_connection() as conn: | ||
| 98 | return {row['path']: (row['mtime'], row['size']) for row in conn.execute( | ||
| 99 | 'SELECT path, mtime, size FROM damaged_files')} | ||
| 100 | |||
| 101 | def search_rows(self, ids, columns): | ||
| 102 | # Stay within the SQLite bind limit on all supported runtimes. | ||
| 103 | with self.get_connection() as conn: | ||
| 104 | conn.execute('BEGIN') | ||
| 105 | result = {} | ||
| 106 | for start in range(0, len(ids), 500): | ||
| 107 | batch = ids[start:start + 500] | ||
| 108 | marks = ','.join('?' for _ in batch) | ||
| 109 | rows = conn.execute(f'SELECT {columns} FROM images WHERE id IN ({marks})', batch) | ||
| 110 | result.update((row['id'], dict(row)) for row in rows) | ||
| 111 | return result | ||
| 112 | |||
| 113 | def file_search_metadata(self, ids): | ||
| 114 | return self.search_rows(ids, 'id, eps_id, feat_version, image_url, path, mtime, size, frame_ms') | ||
| 115 | |||
| 116 | def file_search_orb(self, ids): | ||
| 117 | return self.search_rows(ids, 'id, eps_id, feat_version, orb_pts, orb_desc') | ||
| 118 | |||
| 119 | @staticmethod | ||
| 120 | def decode_orb(row): | ||
| 121 | return {'orb_pts': np.frombuffer(row['orb_pts'], np.float32).reshape(-1, 2) if row['orb_pts'] else None, | ||
| 122 | 'orb_desc': np.frombuffer(row['orb_desc'], np.uint8).reshape(-1, 32) if row['orb_desc'] else None} | ||
| 123 | |||
| 62 | def max_feat_version(self): | 124 | def max_feat_version(self): |
| 63 | with self.get_connection() as conn: | 125 | with self.get_connection() as conn: |
| 64 | return conn.execute('SELECT COALESCE(MAX(feat_version), 0) FROM images').fetchone()[0] | 126 | return conn.execute('SELECT COALESCE(MAX(feat_version), 0) FROM images').fetchone()[0] |
| ... | @@ -84,21 +146,39 @@ class DatabaseManager: | ... | @@ -84,21 +146,39 @@ class DatabaseManager: |
| 84 | 'SELECT id, eps_id, design_no, image_url FROM images')} | 146 | 'SELECT id, eps_id, design_no, image_url FROM images')} |
| 85 | 147 | ||
| 86 | def upsert(self, design_id, eps_id, design_no, image_url, features, version, modified): | 148 | def upsert(self, design_id, eps_id, design_no, image_url, features, version, modified): |
| 87 | def blob(key, dtype): | ||
| 88 | value = features.get(key) | ||
| 89 | return None if value is None else np.asarray(value, dtype=dtype).tobytes() | ||
| 90 | with self.get_connection() as conn: | 149 | with self.get_connection() as conn: |
| 91 | conn.execute("""INSERT INTO images VALUES(?,?,?,?,?,?,?,?,?,?) | 150 | conn.execute("""INSERT INTO images(id, eps_id, design_no, image_url, cnn_vector, |
| 151 | orb_desc, orb_pts, feat_version, source_modified, updated_at) VALUES(?,?,?,?,?,?,?,?,?,?) | ||
| 92 | ON CONFLICT(id) DO UPDATE SET eps_id=excluded.eps_id, | 152 | ON CONFLICT(id) DO UPDATE SET eps_id=excluded.eps_id, |
| 93 | design_no=excluded.design_no, image_url=excluded.image_url, | 153 | design_no=excluded.design_no, image_url=excluded.image_url, |
| 94 | cnn_vector=excluded.cnn_vector, orb_desc=excluded.orb_desc, | 154 | cnn_vector=excluded.cnn_vector, orb_desc=excluded.orb_desc, |
| 95 | orb_pts=excluded.orb_pts, feat_version=excluded.feat_version, | 155 | orb_pts=excluded.orb_pts, feat_version=excluded.feat_version, |
| 96 | source_modified=excluded.source_modified, updated_at=excluded.updated_at""", | 156 | source_modified=excluded.source_modified, updated_at=excluded.updated_at""", |
| 97 | (int(design_id), int(eps_id), design_no, image_url, | 157 | (int(design_id), int(eps_id), design_no, image_url, |
| 98 | blob('cnn_vector', np.float32), blob('orb_desc', np.uint8), | 158 | *self.feature_blobs(features), version, |
| 99 | blob('orb_kp', np.float32), version, | ||
| 100 | str(modified) if modified is not None else None, datetime.now().isoformat())) | 159 | str(modified) if modified is not None else None, datetime.now().isoformat())) |
| 101 | 160 | ||
| 161 | @staticmethod | ||
| 162 | def feature_blobs(features): | ||
| 163 | return tuple(None if features.get(key) is None else np.asarray(features[key], dtype=dtype).tobytes() | ||
| 164 | for key, dtype in [('cnn_vector', np.float32), ('orb_desc', np.uint8), | ||
| 165 | ('orb_kp', np.float32)]) | ||
| 166 | |||
| 167 | @staticmethod | ||
| 168 | def insert_file(conn, path, image_url, mtime, size, sha1, frame_ms, blobs, version): | ||
| 169 | return conn.execute('''INSERT INTO images(eps_id, image_url, cnn_vector, orb_desc, orb_pts, | ||
| 170 | feat_version, updated_at, path, mtime, size, sha1, frame_ms) | ||
| 171 | VALUES(2, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', | ||
| 172 | (image_url, *blobs, version, datetime.now().isoformat(), path, mtime, size, | ||
| 173 | sha1, frame_ms)).lastrowid | ||
| 174 | |||
| 175 | @staticmethod | ||
| 176 | def record_damage(conn, path, mtime, size, sha1, error_type, updated_at=None): | ||
| 177 | conn.execute('''INSERT INTO damaged_files VALUES(?, ?, ?, ?, ?, ?) | ||
| 178 | ON CONFLICT(path) DO UPDATE SET mtime=excluded.mtime, size=excluded.size, | ||
| 179 | sha1=excluded.sha1, error_type=excluded.error_type, updated_at=excluded.updated_at''', | ||
| 180 | (path, mtime, size, sha1, error_type, updated_at or datetime.now().isoformat())) | ||
| 181 | |||
| 102 | def update_metadata(self, design_id, eps_id, design_no): | 182 | def update_metadata(self, design_id, eps_id, design_no): |
| 103 | with self.get_connection() as conn: | 183 | with self.get_connection() as conn: |
| 104 | conn.execute('UPDATE images SET eps_id=?, design_no=? WHERE id=?', | 184 | conn.execute('UPDATE images SET eps_id=?, design_no=? WHERE id=?', | ... | ... |
filesystem_files.py
0 → 100644
| 1 | """Path mapping, checked file descriptors and media decoding for the file source.""" | ||
| 2 | from contextlib import contextmanager | ||
| 3 | from hashlib import sha1 | ||
| 4 | from io import BytesIO | ||
| 5 | import math | ||
| 6 | import os | ||
| 7 | from pathlib import Path | ||
| 8 | import stat | ||
| 9 | import tempfile | ||
| 10 | |||
| 11 | import cv2 | ||
| 12 | from PIL import Image | ||
| 13 | |||
| 14 | |||
| 15 | IMAGE_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff', '.webp'} | ||
| 16 | VIDEO_FORMATS = {'.mp4', '.mov'} | ||
| 17 | IGNORE_DIRS = {'__macosx', '.ds_store', 'thumbs.db', '.thumbnails', '.picasaoriginals', | ||
| 18 | '@eadir', '#recycle', '$recycle.bin', 'system volume information'} | ||
| 19 | IGNORE_FILES = {'thumbs.db', '.ds_store', 'desktop.ini', '.picasa.ini'} | ||
| 20 | |||
| 21 | |||
| 22 | def below(path, root): | ||
| 23 | return path.startswith(root.rstrip(os.sep) + os.sep) | ||
| 24 | |||
| 25 | |||
| 26 | def linked(info): | ||
| 27 | return stat.S_ISLNK(info.st_mode) or bool( | ||
| 28 | getattr(info, 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT) | ||
| 29 | |||
| 30 | |||
| 31 | def reject_link(path): | ||
| 32 | info = os.lstat(path) | ||
| 33 | if linked(info): | ||
| 34 | raise OSError('Symbolic link or reparse point') | ||
| 35 | return info | ||
| 36 | |||
| 37 | |||
| 38 | class FilePaths: | ||
| 39 | def __init__(self, roots, unc_prefixes): | ||
| 40 | self.roots = self._prefixes(roots) | ||
| 41 | self.unc_prefixes = self._prefixes(unc_prefixes) | ||
| 42 | if any(not isinstance(marker, str) or not marker.strip() for marker in self.roots.values()): | ||
| 43 | raise ValueError('Each scan root requires a marker name') | ||
| 44 | destinations = [] | ||
| 45 | for prefix in self.unc_prefixes.values(): | ||
| 46 | if not isinstance(prefix, str) or not prefix.startswith('\\\\'): | ||
| 47 | raise ValueError('UNC prefix must begin with two backslashes') | ||
| 48 | parts = prefix[2:].rstrip('\\').split('\\') | ||
| 49 | if len(parts) < 2 or any(part in {'', '.', '..'} or '/' in part for part in parts): | ||
| 50 | raise ValueError('Invalid UNC prefix') | ||
| 51 | destinations.append(tuple(part.casefold() for part in parts)) | ||
| 52 | if any(a[:len(b)] == b for i, a in enumerate(destinations) | ||
| 53 | for j, b in enumerate(destinations) if i != j): | ||
| 54 | raise ValueError('Overlapping UNC destinations') | ||
| 55 | for root in self.roots: | ||
| 56 | if not any(root == prefix or below(root, prefix) for prefix in self.unc_prefixes): | ||
| 57 | raise ValueError(f'No UNC mapping for scan root {root}') | ||
| 58 | |||
| 59 | @staticmethod | ||
| 60 | def _prefixes(values): | ||
| 61 | if not isinstance(values, dict) or not values: | ||
| 62 | raise ValueError('Expected a nonempty path mapping') | ||
| 63 | paths = {} | ||
| 64 | for prefix, value in values.items(): | ||
| 65 | if not os.path.isabs(prefix) or prefix != os.path.normpath(prefix): | ||
| 66 | raise ValueError(f'Expected a canonical absolute prefix: {prefix}') | ||
| 67 | if any(os.path.normcase(prefix) == os.path.normcase(p) | ||
| 68 | or below(os.path.normcase(prefix), os.path.normcase(p)) | ||
| 69 | or below(os.path.normcase(p), os.path.normcase(prefix)) for p in paths): | ||
| 70 | raise ValueError(f'Overlapping path prefix: {prefix}') | ||
| 71 | paths[prefix] = value | ||
| 72 | return paths | ||
| 73 | |||
| 74 | def root_for(self, path): | ||
| 75 | return next((root for root in self.roots if below(path, root)), None) | ||
| 76 | |||
| 77 | def unc(self, path): | ||
| 78 | for prefix, unc in self.unc_prefixes.items(): | ||
| 79 | if below(path, prefix): | ||
| 80 | suffix = path[len(prefix.rstrip(os.sep)) + 1:].replace(os.sep, '\\') | ||
| 81 | return unc.rstrip('\\') + '\\' + suffix | ||
| 82 | raise ValueError(f'Path has no UNC mapping: {path}') | ||
| 83 | |||
| 84 | |||
| 85 | def file_metadata(info): | ||
| 86 | return info.st_mtime, info.st_size | ||
| 87 | |||
| 88 | |||
| 89 | def fingerprint(info): | ||
| 90 | return info.st_dev, info.st_ino, info.st_mode, info.st_mtime_ns, info.st_size | ||
| 91 | |||
| 92 | |||
| 93 | def check_open_file(src, path, root, initial): | ||
| 94 | current = os.fstat(src.fileno()) | ||
| 95 | real_root = os.path.realpath(root) | ||
| 96 | if (not stat.S_ISREG(current.st_mode) or fingerprint(current) != fingerprint(initial) | ||
| 97 | or os.path.normcase(real_root) != os.path.normcase(root) | ||
| 98 | or not below(os.path.normcase(os.path.realpath(path)), os.path.normcase(real_root)) | ||
| 99 | or fingerprint(reject_link(path)) != fingerprint(current)): | ||
| 100 | raise OSError('File changed or escaped scan root') | ||
| 101 | |||
| 102 | |||
| 103 | @contextmanager | ||
| 104 | def open_checked(path, root, expected=None): | ||
| 105 | """On POSIX walk from the anchor with no-follow directory and file opens.""" | ||
| 106 | if not below(path, root) or path != os.path.normpath(path): | ||
| 107 | raise OSError('Path outside scan root') | ||
| 108 | flags = os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_BINARY', 0) | ||
| 109 | if os.open in os.supports_dir_fd and getattr(os, 'O_NOFOLLOW', 0): | ||
| 110 | parts = Path(path).parts | ||
| 111 | dir_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | ||
| 112 | directory = os.open(parts[0], dir_flags) | ||
| 113 | try: | ||
| 114 | for part in parts[1:-1]: | ||
| 115 | child = os.open(part, dir_flags, dir_fd=directory) | ||
| 116 | os.close(directory) | ||
| 117 | directory = child | ||
| 118 | fd = os.open(parts[-1], flags | os.O_NONBLOCK, dir_fd=directory) | ||
| 119 | finally: | ||
| 120 | os.close(directory) | ||
| 121 | else: | ||
| 122 | for parent in Path(path).parents: | ||
| 123 | reject_link(parent) | ||
| 124 | reject_link(path) | ||
| 125 | fd = os.open(path, flags) | ||
| 126 | with os.fdopen(fd, 'rb') as src: | ||
| 127 | initial = os.fstat(src.fileno()) | ||
| 128 | check_open_file(src, path, root, initial) | ||
| 129 | if expected is not None and file_metadata(initial) != expected: | ||
| 130 | raise OSError('File changed since enumeration or indexing') | ||
| 131 | yield src | ||
| 132 | check_open_file(src, path, root, initial) | ||
| 133 | |||
| 134 | |||
| 135 | def marker_identity(root, name): | ||
| 136 | info = reject_link(root) | ||
| 137 | if not stat.S_ISDIR(info.st_mode): | ||
| 138 | raise OSError('Root is not a directory') | ||
| 139 | with open_checked(os.path.join(root, '.image-search-root'), root) as src: | ||
| 140 | marker = src.read(4097).decode('utf-8').strip() | ||
| 141 | if marker != name: | ||
| 142 | raise OSError('Root marker mismatch') | ||
| 143 | current = reject_link(root) | ||
| 144 | if not os.path.samestat(info, current): | ||
| 145 | raise OSError('Root changed during marker check') | ||
| 146 | return info.st_dev, info.st_ino | ||
| 147 | |||
| 148 | |||
| 149 | @contextmanager | ||
| 150 | def staged_video(src, suffix, digest=None): | ||
| 151 | """OpenCV 4.8 needs a seekable pathname. Stage bytes from the checked fd.""" | ||
| 152 | with tempfile.TemporaryDirectory(prefix='image-search-video-') as directory: | ||
| 153 | path = os.path.join(directory, 'video' + suffix) | ||
| 154 | with open(path, 'wb') as dst: | ||
| 155 | while chunk := src.read(1024 * 1024): | ||
| 156 | if digest is not None: | ||
| 157 | digest.update(chunk) | ||
| 158 | dst.write(chunk) | ||
| 159 | yield path | ||
| 160 | |||
| 161 | |||
| 162 | @contextmanager | ||
| 163 | def video_capture(path): | ||
| 164 | cap = cv2.VideoCapture(path) | ||
| 165 | try: | ||
| 166 | if not cap.isOpened(): | ||
| 167 | raise ValueError('Cannot decode video') | ||
| 168 | yield cap | ||
| 169 | finally: | ||
| 170 | cap.release() | ||
| 171 | |||
| 172 | |||
| 173 | def frame_times(duration, cap): | ||
| 174 | if not math.isfinite(duration) or duration <= 0 or cap <= 0: | ||
| 175 | raise ValueError('Invalid video duration or frame cap') | ||
| 176 | step = max(1.5, duration / cap) | ||
| 177 | return [round(i * step * 1000) for i in range(min(cap, math.ceil(duration / step)))] | ||
| 178 | |||
| 179 | |||
| 180 | def read_frame(capture, frame_ms): | ||
| 181 | if not capture.set(cv2.CAP_PROP_POS_MSEC, frame_ms): | ||
| 182 | raise ValueError('Cannot seek video frame') | ||
| 183 | ok, frame = capture.read() | ||
| 184 | if not ok: | ||
| 185 | # The time seek can round to EOF for a sample within the last frame's display interval. | ||
| 186 | fps = capture.get(cv2.CAP_PROP_FPS) | ||
| 187 | count = capture.get(cv2.CAP_PROP_FRAME_COUNT) | ||
| 188 | if (math.isfinite(fps) and math.isfinite(count) and fps > 0 and count >= 1 | ||
| 189 | and (count - 1) / fps <= frame_ms / 1000 < count / fps | ||
| 190 | and capture.set(cv2.CAP_PROP_POS_FRAMES, count - 1)): | ||
| 191 | ok, frame = capture.read() | ||
| 192 | if not ok: | ||
| 193 | raise ValueError('Cannot decode video frame') | ||
| 194 | return Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) | ||
| 195 | |||
| 196 | |||
| 197 | def extract_video(path, frame_cap, extractor): | ||
| 198 | with video_capture(path) as capture: | ||
| 199 | fps = capture.get(cv2.CAP_PROP_FPS) | ||
| 200 | if not math.isfinite(fps) or fps <= 0: | ||
| 201 | raise ValueError('Invalid video FPS') | ||
| 202 | duration = capture.get(cv2.CAP_PROP_FRAME_COUNT) / fps | ||
| 203 | return [(when, extractor.extract_all_features(read_frame(capture, when))) | ||
| 204 | for when in frame_times(duration, frame_cap)] | ||
| 205 | |||
| 206 | |||
| 207 | def read_image_bytes(path, root, expected): | ||
| 208 | with open_checked(path, root, expected) as src: | ||
| 209 | content = src.read() | ||
| 210 | return content, sha1(content).hexdigest() | ||
| 211 | |||
| 212 | |||
| 213 | def jpeg_thumbnail(path, root, expected, frame_ms): | ||
| 214 | output = BytesIO() | ||
| 215 | with open_checked(path, root, expected) as src: | ||
| 216 | if frame_ms == -1: | ||
| 217 | with Image.open(src) as decoded: | ||
| 218 | decoded.thumbnail((180, 180)) | ||
| 219 | image = decoded.convert('RGB') | ||
| 220 | else: | ||
| 221 | with staged_video(src, Path(path).suffix) as staged, video_capture(staged) as cap: | ||
| 222 | image = read_frame(cap, frame_ms) | ||
| 223 | image.thumbnail((180, 180)) | ||
| 224 | image.save(output, 'JPEG') | ||
| 225 | return output.getvalue() |
filesystem_sync.py
0 → 100644
This diff is collapsed.
Click to expand it.
tests/test_filesystem_source.py
0 → 100644
This diff is collapsed.
Click to expand it.
tests/test_migrate_v3.py
0 → 100644
This diff is collapsed.
Click to expand it.
tools/migrate_v3.py
0 → 100644
This diff is collapsed.
Click to expand it.
-
Please register or sign in to post a comment