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 @@
- ORB特征: 保留关键点,支持RANSAC
"""
from contextlib import nullcontext
from math import ceil, sqrt
import threading
import logging
import cv2
......@@ -13,6 +15,7 @@ import pillow_avif # Registers AVIF with Pillow.
CNN_VECTOR_DIM = 1152
ORB_MAX_SIDE = 1024
MAX_DECODE_PIXELS = 40_000_000
# 延迟导入torch(避免启动时加载)
_torch_model = None
......@@ -97,9 +100,19 @@ class FeatureExtractor:
@staticmethod
def _read_rgb(image):
if isinstance(image, Image.Image):
return np.array(image.convert('RGB'))
with Image.open(image) as decoded:
source = nullcontext(image) if isinstance(image, Image.Image) else Image.open(image)
with source as decoded:
width, height = decoded.size
pixels = width * height
if pixels > MAX_DECODE_PIXELS:
factor = ceil(sqrt(pixels / MAX_DECODE_PIXELS))
# Pillow rounds both output dimensions up.
while ceil(width / factor) * ceil(height / factor) > MAX_DECODE_PIXELS:
factor += 1
# Pillow cannot reduce bilevel, palette or 16-bit integer images directly.
if decoded.mode in ('1', 'P') or decoded.mode.startswith('I;16'):
decoded = decoded.convert('RGB')
decoded = decoded.reduce(factor)
return np.array(decoded.convert('RGB'))
def _enhance_gray(self, rgb):
......
......@@ -17,6 +17,7 @@ VIDEO_FORMATS = {'.mp4', '.mov'}
IGNORE_DIRS = {'__macosx', '.ds_store', 'thumbs.db', '.thumbnails', '.picasaoriginals',
'@eadir', '#recycle', '$recycle.bin', 'system volume information'}
IGNORE_FILES = {'thumbs.db', '.ds_store', 'desktop.ini', '.picasa.ini'}
IMAGE_SPOOL_BYTES = 32 * 1024 * 1024
def below(path, root):
......@@ -204,10 +205,17 @@ def extract_video(path, frame_cap, extractor):
for when in frame_times(duration, frame_cap)]
def read_image_bytes(path, root, expected):
@contextmanager
def staged_image(path, root, expected):
"""Hash and decode the same checked bytes without retaining large files in memory."""
digest = sha1()
with tempfile.SpooledTemporaryFile(max_size=IMAGE_SPOOL_BYTES) as staged:
with open_checked(path, root, expected) as src:
content = src.read()
return content, sha1(content).hexdigest()
while chunk := src.read(1024 * 1024):
digest.update(chunk)
staged.write(chunk)
staged.seek(0)
yield staged, digest.hexdigest()
def jpeg_thumbnail(path, root, expected, frame_ms):
......
"""Two-phase enumeration and bounded, per-path publication to SQLite and recall."""
from datetime import datetime
from hashlib import sha1
from io import BytesIO
import logging
import os
import stat
......@@ -12,7 +11,7 @@ import cv2
from filesystem_files import (IGNORE_DIRS, IGNORE_FILES, IMAGE_FORMATS, VIDEO_FORMATS,
FilePaths, extract_video, file_metadata, linked, marker_identity,
open_checked, read_image_bytes, staged_video)
open_checked, staged_image, staged_video)
logger = logging.getLogger(__name__)
......@@ -156,10 +155,10 @@ class FileSystemSync:
except (ValueError, cv2.error):
frames = []
else:
content, digest = read_image_bytes(path, root, metadata)
counts['read_bytes'] += len(content)
with staged_image(path, root, metadata) as (staged, digest):
counts['read_bytes'] += metadata[1]
frames = (None if old and old['sha1'] == digest else
[(-1, self.extractor.extract_all_features(BytesIO(content)))])
[(-1, self.extractor.extract_all_features(staged))])
if frames is None:
with self.db.get_connection() as conn:
conn.execute('UPDATE images SET mtime=?, size=? WHERE path=?', (*metadata, path))
......
......@@ -78,6 +78,41 @@ def test_dual_vector_order_and_norm(monkeypatch, extractor):
np.testing.assert_array_equal(extractor.extract_cnn_feature(RING), actual)
def test_decode_at_cap_preserves_feature_bytes(monkeypatch, extractor):
with Image.open(RING) as image:
pixels = image.width * image.height
original_rgb = np.array(image.convert('RGB'))
with monkeypatch.context() as reference:
reference.setattr(extractor, '_read_rgb', lambda path: original_rgb)
expected = extractor.extract_all_features(RING)
monkeypatch.setattr(feature_module, 'MAX_DECODE_PIXELS', pixels)
actual = extractor.extract_all_features(RING)
for key in ('cnn_vector', 'orb_kp', 'orb_desc'):
assert actual[key].shape == expected[key].shape
assert actual[key].dtype == expected[key].dtype
assert actual[key].tobytes() == expected[key].tobytes()
def test_oversize_image_is_reduced_before_feature_extraction(monkeypatch, extractor):
# Halving 1313 x 717 rounds up to 657 x 359, which still exceeds this cap.
monkeypatch.setattr(feature_module, 'MAX_DECODE_PIXELS', 235_356)
preprocess = extractor._preprocess
def check_reduced(rgb):
assert rgb.shape == (239, 438, 3)
return preprocess(rgb)
monkeypatch.setattr(extractor, '_preprocess', check_reduced)
features = extractor.extract_all_features(RING)
vector = features['cnn_vector']
assert vector.shape == (1152,) and np.isfinite(vector).all()
assert np.linalg.norm(vector) == pytest.approx(1.0, abs=1e-7)
points, descriptors = features['orb_kp'], features['orb_desc']
assert len(points) > 0 and points.shape == (len(points), 2) and points.dtype == np.float32
assert descriptors.shape == (len(points), 32) and descriptors.dtype == np.uint8
@pytest.mark.parametrize('name', ['zero_cnn', 'blank'])
def test_zero_cnn_or_blank_is_not_written(monkeypatch, extractor, tmp_path, name):
path = tmp_path / 'main.jpg'
......
......@@ -50,8 +50,9 @@ class Extractor:
self.verifications = 0
def extract_all_features(self, source):
if isinstance(source, BytesIO):
self.contents.append(source.getvalue())
if hasattr(source, 'read'):
self.contents.append(source.read())
source.seek(0)
try:
with Image.open(source) as opened:
opened.load()
......@@ -64,6 +65,24 @@ class Extractor:
return 15
def test_large_tiff_spools_the_same_bytes_used_for_sha1_and_decode(tmp_path, monkeypatch):
monkeypatch.setattr(filesystem_files, 'IMAGE_SPOOL_BYTES', 4096)
content = image_bytes('TIFF')
assert len(content) > filesystem_files.IMAGE_SPOOL_BYTES
path = tmp_path / 'large.tiff'
path.write_bytes(content)
metadata = filesystem_files.file_metadata(path.stat())
with filesystem_files.staged_image(str(path), str(tmp_path), metadata) as (staged, digest):
assert staged._rolled
assert digest == sha1(content).hexdigest()
assert staged.read() == content
staged.seek(0)
with Image.open(staged) as decoded:
decoded.load()
assert decoded.getpixel((0, 0)) == (255, 0, 0)
def build(tmp_path, capacity=32, video=False):
left, right = tmp_path / 'a', tmp_path / 'ab'
for root in (left, right):
......
"""Validate and import a V3 database. Run from the worktree with python -m tools.migrate_v3."""
import argparse
from collections import Counter, defaultdict, deque
from contextlib import closing
from io import BytesIO
from contextlib import ExitStack, closing
import json
import math
import os
......@@ -15,7 +14,7 @@ import numpy as np
from core.feature_extractor import CNN_VECTOR_DIM, FeatureExtractor
from database import DatabaseManager
from filesystem_files import FilePaths, read_image_bytes
from filesystem_files import FilePaths, staged_image
from filesystem_sync import ScanInventory
LEGACY_PREFIXES = {
......@@ -168,8 +167,10 @@ def validate_samples(conn, strata, paths, inventory, extractor, minimum, report)
if samples:
work.append((batch, samples))
row = conn.execute('SELECT * FROM images WHERE id=?', (image_id,)).fetchone()
with ExitStack() as sample:
try:
data, digest = read_image_bytes(path, paths.root_for(path), inventory.files[path])
staged, digest = sample.enter_context(staged_image(path, paths.root_for(path),
inventory.files[path]))
except OSError:
stale += 1
continue
......@@ -180,7 +181,7 @@ def validate_samples(conn, strata, paths, inventory, extractor, minimum, report)
checked += 1
by_batch[batch] += 1
untested.discard(batch)
failures = compare_features(row, extractor.extract_all_features(BytesIO(data)))
failures = compare_features(row, extractor.extract_all_features(staged))
if failures:
mismatches.append({'path': path, 'batch': batch, 'failures': failures})
report['sample'] = {'checked': checked, 'stale_replaced': stale, 'by_batch': dict(by_batch),
......