f3dcd391 by 柴进

:bug: fix: 单图解码内存上界(超 4000 万像素先缩小 + 大文件分块暂存哈希)

NAS 首轮扫描 VmHWM 8.92GB(稳态 3.87GB),瞬时峰值来自超大 TIFF:
原字节整份 read() 与全分辨率多份数组同存。
- staged_image:分块 SHA-1,>32MiB 落临时文件,哈希与解码同一份字节
- _read_rgb:>MAX_DECODE_PIXELS(40M) 先 Image.reduce,阈值内特征逐字节不变
- 本地单图峰值:170M 像素 TIFF 2681→1118 MiB,150M 像素 JPEG 2392→1287 MiB

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent af626929
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
4 - ORB特征: 保留关键点,支持RANSAC 4 - ORB特征: 保留关键点,支持RANSAC
5 """ 5 """
6 6
7 from contextlib import nullcontext
8 from math import ceil, sqrt
7 import threading 9 import threading
8 import logging 10 import logging
9 import cv2 11 import cv2
...@@ -13,6 +15,7 @@ import pillow_avif # Registers AVIF with Pillow. ...@@ -13,6 +15,7 @@ import pillow_avif # Registers AVIF with Pillow.
13 15
14 CNN_VECTOR_DIM = 1152 16 CNN_VECTOR_DIM = 1152
15 ORB_MAX_SIDE = 1024 17 ORB_MAX_SIDE = 1024
18 MAX_DECODE_PIXELS = 40_000_000
16 19
17 # 延迟导入torch(避免启动时加载) 20 # 延迟导入torch(避免启动时加载)
18 _torch_model = None 21 _torch_model = None
...@@ -97,9 +100,19 @@ class FeatureExtractor: ...@@ -97,9 +100,19 @@ class FeatureExtractor:
97 100
98 @staticmethod 101 @staticmethod
99 def _read_rgb(image): 102 def _read_rgb(image):
100 if isinstance(image, Image.Image): 103 source = nullcontext(image) if isinstance(image, Image.Image) else Image.open(image)
101 return np.array(image.convert('RGB')) 104 with source as decoded:
102 with Image.open(image) as decoded: 105 width, height = decoded.size
106 pixels = width * height
107 if pixels > MAX_DECODE_PIXELS:
108 factor = ceil(sqrt(pixels / MAX_DECODE_PIXELS))
109 # Pillow rounds both output dimensions up.
110 while ceil(width / factor) * ceil(height / factor) > MAX_DECODE_PIXELS:
111 factor += 1
112 # Pillow cannot reduce bilevel, palette or 16-bit integer images directly.
113 if decoded.mode in ('1', 'P') or decoded.mode.startswith('I;16'):
114 decoded = decoded.convert('RGB')
115 decoded = decoded.reduce(factor)
103 return np.array(decoded.convert('RGB')) 116 return np.array(decoded.convert('RGB'))
104 117
105 def _enhance_gray(self, rgb): 118 def _enhance_gray(self, rgb):
......
...@@ -17,6 +17,7 @@ VIDEO_FORMATS = {'.mp4', '.mov'} ...@@ -17,6 +17,7 @@ VIDEO_FORMATS = {'.mp4', '.mov'}
17 IGNORE_DIRS = {'__macosx', '.ds_store', 'thumbs.db', '.thumbnails', '.picasaoriginals', 17 IGNORE_DIRS = {'__macosx', '.ds_store', 'thumbs.db', '.thumbnails', '.picasaoriginals',
18 '@eadir', '#recycle', '$recycle.bin', 'system volume information'} 18 '@eadir', '#recycle', '$recycle.bin', 'system volume information'}
19 IGNORE_FILES = {'thumbs.db', '.ds_store', 'desktop.ini', '.picasa.ini'} 19 IGNORE_FILES = {'thumbs.db', '.ds_store', 'desktop.ini', '.picasa.ini'}
20 IMAGE_SPOOL_BYTES = 32 * 1024 * 1024
20 21
21 22
22 def below(path, root): 23 def below(path, root):
...@@ -204,10 +205,17 @@ def extract_video(path, frame_cap, extractor): ...@@ -204,10 +205,17 @@ def extract_video(path, frame_cap, extractor):
204 for when in frame_times(duration, frame_cap)] 205 for when in frame_times(duration, frame_cap)]
205 206
206 207
207 def read_image_bytes(path, root, expected): 208 @contextmanager
208 with open_checked(path, root, expected) as src: 209 def staged_image(path, root, expected):
209 content = src.read() 210 """Hash and decode the same checked bytes without retaining large files in memory."""
210 return content, sha1(content).hexdigest() 211 digest = sha1()
212 with tempfile.SpooledTemporaryFile(max_size=IMAGE_SPOOL_BYTES) as staged:
213 with open_checked(path, root, expected) as src:
214 while chunk := src.read(1024 * 1024):
215 digest.update(chunk)
216 staged.write(chunk)
217 staged.seek(0)
218 yield staged, digest.hexdigest()
211 219
212 220
213 def jpeg_thumbnail(path, root, expected, frame_ms): 221 def jpeg_thumbnail(path, root, expected, frame_ms):
......
1 """Two-phase enumeration and bounded, per-path publication to SQLite and recall.""" 1 """Two-phase enumeration and bounded, per-path publication to SQLite and recall."""
2 from datetime import datetime 2 from datetime import datetime
3 from hashlib import sha1 3 from hashlib import sha1
4 from io import BytesIO
5 import logging 4 import logging
6 import os 5 import os
7 import stat 6 import stat
...@@ -12,7 +11,7 @@ import cv2 ...@@ -12,7 +11,7 @@ import cv2
12 11
13 from filesystem_files import (IGNORE_DIRS, IGNORE_FILES, IMAGE_FORMATS, VIDEO_FORMATS, 12 from filesystem_files import (IGNORE_DIRS, IGNORE_FILES, IMAGE_FORMATS, VIDEO_FORMATS,
14 FilePaths, extract_video, file_metadata, linked, marker_identity, 13 FilePaths, extract_video, file_metadata, linked, marker_identity,
15 open_checked, read_image_bytes, staged_video) 14 open_checked, staged_image, staged_video)
16 15
17 logger = logging.getLogger(__name__) 16 logger = logging.getLogger(__name__)
18 17
...@@ -156,10 +155,10 @@ class FileSystemSync: ...@@ -156,10 +155,10 @@ class FileSystemSync:
156 except (ValueError, cv2.error): 155 except (ValueError, cv2.error):
157 frames = [] 156 frames = []
158 else: 157 else:
159 content, digest = read_image_bytes(path, root, metadata) 158 with staged_image(path, root, metadata) as (staged, digest):
160 counts['read_bytes'] += len(content) 159 counts['read_bytes'] += metadata[1]
161 frames = (None if old and old['sha1'] == digest else 160 frames = (None if old and old['sha1'] == digest else
162 [(-1, self.extractor.extract_all_features(BytesIO(content)))]) 161 [(-1, self.extractor.extract_all_features(staged))])
163 if frames is None: 162 if frames is None:
164 with self.db.get_connection() as conn: 163 with self.db.get_connection() as conn:
165 conn.execute('UPDATE images SET mtime=?, size=? WHERE path=?', (*metadata, path)) 164 conn.execute('UPDATE images SET mtime=?, size=? WHERE path=?', (*metadata, path))
......
...@@ -78,6 +78,41 @@ def test_dual_vector_order_and_norm(monkeypatch, extractor): ...@@ -78,6 +78,41 @@ def test_dual_vector_order_and_norm(monkeypatch, extractor):
78 np.testing.assert_array_equal(extractor.extract_cnn_feature(RING), actual) 78 np.testing.assert_array_equal(extractor.extract_cnn_feature(RING), actual)
79 79
80 80
81 def test_decode_at_cap_preserves_feature_bytes(monkeypatch, extractor):
82 with Image.open(RING) as image:
83 pixels = image.width * image.height
84 original_rgb = np.array(image.convert('RGB'))
85 with monkeypatch.context() as reference:
86 reference.setattr(extractor, '_read_rgb', lambda path: original_rgb)
87 expected = extractor.extract_all_features(RING)
88
89 monkeypatch.setattr(feature_module, 'MAX_DECODE_PIXELS', pixels)
90 actual = extractor.extract_all_features(RING)
91 for key in ('cnn_vector', 'orb_kp', 'orb_desc'):
92 assert actual[key].shape == expected[key].shape
93 assert actual[key].dtype == expected[key].dtype
94 assert actual[key].tobytes() == expected[key].tobytes()
95
96
97 def test_oversize_image_is_reduced_before_feature_extraction(monkeypatch, extractor):
98 # Halving 1313 x 717 rounds up to 657 x 359, which still exceeds this cap.
99 monkeypatch.setattr(feature_module, 'MAX_DECODE_PIXELS', 235_356)
100 preprocess = extractor._preprocess
101
102 def check_reduced(rgb):
103 assert rgb.shape == (239, 438, 3)
104 return preprocess(rgb)
105
106 monkeypatch.setattr(extractor, '_preprocess', check_reduced)
107 features = extractor.extract_all_features(RING)
108 vector = features['cnn_vector']
109 assert vector.shape == (1152,) and np.isfinite(vector).all()
110 assert np.linalg.norm(vector) == pytest.approx(1.0, abs=1e-7)
111 points, descriptors = features['orb_kp'], features['orb_desc']
112 assert len(points) > 0 and points.shape == (len(points), 2) and points.dtype == np.float32
113 assert descriptors.shape == (len(points), 32) and descriptors.dtype == np.uint8
114
115
81 @pytest.mark.parametrize('name', ['zero_cnn', 'blank']) 116 @pytest.mark.parametrize('name', ['zero_cnn', 'blank'])
82 def test_zero_cnn_or_blank_is_not_written(monkeypatch, extractor, tmp_path, name): 117 def test_zero_cnn_or_blank_is_not_written(monkeypatch, extractor, tmp_path, name):
83 path = tmp_path / 'main.jpg' 118 path = tmp_path / 'main.jpg'
......
...@@ -50,8 +50,9 @@ class Extractor: ...@@ -50,8 +50,9 @@ class Extractor:
50 self.verifications = 0 50 self.verifications = 0
51 51
52 def extract_all_features(self, source): 52 def extract_all_features(self, source):
53 if isinstance(source, BytesIO): 53 if hasattr(source, 'read'):
54 self.contents.append(source.getvalue()) 54 self.contents.append(source.read())
55 source.seek(0)
55 try: 56 try:
56 with Image.open(source) as opened: 57 with Image.open(source) as opened:
57 opened.load() 58 opened.load()
...@@ -64,6 +65,24 @@ class Extractor: ...@@ -64,6 +65,24 @@ class Extractor:
64 return 15 65 return 15
65 66
66 67
68 def test_large_tiff_spools_the_same_bytes_used_for_sha1_and_decode(tmp_path, monkeypatch):
69 monkeypatch.setattr(filesystem_files, 'IMAGE_SPOOL_BYTES', 4096)
70 content = image_bytes('TIFF')
71 assert len(content) > filesystem_files.IMAGE_SPOOL_BYTES
72 path = tmp_path / 'large.tiff'
73 path.write_bytes(content)
74 metadata = filesystem_files.file_metadata(path.stat())
75
76 with filesystem_files.staged_image(str(path), str(tmp_path), metadata) as (staged, digest):
77 assert staged._rolled
78 assert digest == sha1(content).hexdigest()
79 assert staged.read() == content
80 staged.seek(0)
81 with Image.open(staged) as decoded:
82 decoded.load()
83 assert decoded.getpixel((0, 0)) == (255, 0, 0)
84
85
67 def build(tmp_path, capacity=32, video=False): 86 def build(tmp_path, capacity=32, video=False):
68 left, right = tmp_path / 'a', tmp_path / 'ab' 87 left, right = tmp_path / 'a', tmp_path / 'ab'
69 for root in (left, right): 88 for root in (left, right):
......
1 """Validate and import a V3 database. Run from the worktree with python -m tools.migrate_v3.""" 1 """Validate and import a V3 database. Run from the worktree with python -m tools.migrate_v3."""
2 import argparse 2 import argparse
3 from collections import Counter, defaultdict, deque 3 from collections import Counter, defaultdict, deque
4 from contextlib import closing 4 from contextlib import ExitStack, closing
5 from io import BytesIO
6 import json 5 import json
7 import math 6 import math
8 import os 7 import os
...@@ -15,7 +14,7 @@ import numpy as np ...@@ -15,7 +14,7 @@ import numpy as np
15 14
16 from core.feature_extractor import CNN_VECTOR_DIM, FeatureExtractor 15 from core.feature_extractor import CNN_VECTOR_DIM, FeatureExtractor
17 from database import DatabaseManager 16 from database import DatabaseManager
18 from filesystem_files import FilePaths, read_image_bytes 17 from filesystem_files import FilePaths, staged_image
19 from filesystem_sync import ScanInventory 18 from filesystem_sync import ScanInventory
20 19
21 LEGACY_PREFIXES = { 20 LEGACY_PREFIXES = {
...@@ -168,19 +167,21 @@ def validate_samples(conn, strata, paths, inventory, extractor, minimum, report) ...@@ -168,19 +167,21 @@ def validate_samples(conn, strata, paths, inventory, extractor, minimum, report)
168 if samples: 167 if samples:
169 work.append((batch, samples)) 168 work.append((batch, samples))
170 row = conn.execute('SELECT * FROM images WHERE id=?', (image_id,)).fetchone() 169 row = conn.execute('SELECT * FROM images WHERE id=?', (image_id,)).fetchone()
171 try: 170 with ExitStack() as sample:
172 data, digest = read_image_bytes(path, paths.root_for(path), inventory.files[path]) 171 try:
173 except OSError: 172 staged, digest = sample.enter_context(staged_image(path, paths.root_for(path),
174 stale += 1 173 inventory.files[path]))
175 continue 174 except OSError:
176 if digest != row['sha1']: 175 stale += 1
177 stale += 1 176 continue
178 changed[path] = (row['mtime'], row['size']) 177 if digest != row['sha1']:
179 continue 178 stale += 1
180 checked += 1 179 changed[path] = (row['mtime'], row['size'])
181 by_batch[batch] += 1 180 continue
182 untested.discard(batch) 181 checked += 1
183 failures = compare_features(row, extractor.extract_all_features(BytesIO(data))) 182 by_batch[batch] += 1
183 untested.discard(batch)
184 failures = compare_features(row, extractor.extract_all_features(staged))
184 if failures: 185 if failures:
185 mismatches.append({'path': path, 'batch': batch, 'failures': failures}) 186 mismatches.append({'path': path, 'batch': batch, 'failures': failures})
186 report['sample'] = {'checked': checked, 'stale_replaced': stale, 'by_batch': dict(by_batch), 187 report['sample'] = {'checked': checked, 'stale_replaced': stale, 'by_batch': dict(by_batch),
......