e5a0db68 by 柴进

:sparkles: feat: NAS 文件源大图预览接口 POST /images/preview(长边 2048)

- 只服务索引内文件:UNC 反解成容器路径,走 (path, frame_ms) 唯一索引,且存储的 image_url 须逐字相等
- 文件自索引后变化 → 409;未命中/越界/.. → 404
- 复用 jpeg_thumbnail(size/quality/orient 参数),预览按 EXIF 摆正,缩略图行为不变
- 全量 120 passed / 1 skipped;旧码跑新测 8 红;去掉 image_url 等值或 .. 拒绝各被测试咬住

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dd1fec07
......@@ -10,14 +10,16 @@ from pathlib import Path
import tempfile
import threading
import time
from typing import Optional
from dotenv import load_dotenv
import cv2
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, UploadFile
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, Response, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from jose import jwt, JWTError
import numpy as np
from PIL import Image, __version__ as pillow_version
from pydantic import BaseModel, conint
import uvicorn
import yaml
......@@ -26,6 +28,7 @@ from core.feature_extractor import CNN_VECTOR_DIM
from core.search_engine import ImageSearchEngine
from core.vector_index import VectorIndex, configured_dimension
from data_sync import DesignDataSync
from filesystem_files import jpeg_thumbnail
from filesystem_sync import FileSystemSync, positive_int
logger = logging.getLogger(__name__)
......@@ -33,6 +36,11 @@ FILESYSTEM_UPLOAD_BYTES = 45 * 1024 * 1024
FILESYSTEM_UPLOAD_EXTENSIONS = {'jpg', 'jpeg', 'png', 'webp', 'avif'}
class PreviewRequest(BaseModel):
path: str
frame_ms: Optional[conint(strict=True, ge=-1, le=2**63 - 1)] = None
def load_config():
load_dotenv()
with open('config.yml', encoding='utf-8') as f:
......@@ -231,6 +239,24 @@ def create_app(config=None, search_engine=None, data_sync=None):
Path(path).unlink(missing_ok=True)
if filesystem:
@app.post('/images/preview', response_class=Response)
def preview(request: PreviewRequest, token=Depends(search_token)):
engine = app.state.engine
frame_ms = -1 if request.frame_ms is None else request.frame_ms
if frame_ms != -1 and not config.get('video', {}).get('enabled', False):
raise HTTPException(404, 'File not indexed')
path = engine.file_paths.from_unc(request.path)
root = engine.file_paths.root_for(path) if path is not None else None
row = engine.db.file_preview_metadata(path, frame_ms, request.path) if root is not None else None
if row is None:
raise HTTPException(404, 'File not indexed')
try:
jpeg = jpeg_thumbnail(row['path'], root, (row['mtime'], row['size']), frame_ms,
size=2048, quality=85, orient=True)
except (OSError, ValueError, Image.DecompressionBombError, cv2.error):
raise HTTPException(409, 'Indexed file changed or is unavailable')
return Response(jpeg, media_type='image/jpeg')
return app
@app.get('/')
......
......@@ -115,6 +115,11 @@ class DatabaseManager:
def file_search_metadata(self, ids):
return self.search_rows(ids, 'id, eps_id, feat_version, image_url, path, mtime, size, frame_ms')
def file_preview_metadata(self, path, frame_ms, image_url):
with self.get_connection() as conn:
return conn.execute('''SELECT path, mtime, size FROM images
WHERE path = ? AND frame_ms = ? AND image_url = ?''', (path, frame_ms, image_url)).fetchone()
def file_search_orb(self, ids):
return self.search_rows(ids, 'id, eps_id, feat_version, orb_pts, orb_desc')
......
......@@ -12,7 +12,7 @@ import tempfile
from textwrap import dedent
import cv2
from PIL import Image, TiffImagePlugin
from PIL import Image, ImageOps, TiffImagePlugin
IMAGE_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff', '.webp'}
......@@ -117,6 +117,19 @@ class FilePaths:
return unc.rstrip('\\') + '\\' + suffix
raise ValueError(f'Path has no UNC mapping: {path}')
def from_unc(self, path):
if not path.startswith('\\\\'):
return None
parts = path[2:].split('\\')
if any(part in {'', '.', '..'} or '/' in part for part in parts):
return None
folded = [part.casefold() for part in parts]
for prefix, unc in self.unc_prefixes.items():
unc_parts = unc[2:].rstrip('\\').casefold().split('\\')
if len(parts) > len(unc_parts) and folded[:len(unc_parts)] == unc_parts:
return prefix.rstrip(os.sep) + os.sep + os.sep.join(parts[len(unc_parts):])
return None
def file_metadata(info):
return info.st_mtime, info.st_size
......@@ -253,16 +266,17 @@ def staged_image(path, root, expected):
yield staged, digest.hexdigest()
def jpeg_thumbnail(path, root, expected, frame_ms):
def jpeg_thumbnail(path, root, expected, frame_ms, *, size=180, quality=75, orient=False):
output = BytesIO()
with open_checked(path, root, expected) as src:
if frame_ms == -1:
with open_nas_image(src) as decoded:
decoded.thumbnail((180, 180))
image = decoded.convert('RGB')
# Pillow can draft JPEGs while resizing. The square bound also holds after EXIF rotation.
decoded.thumbnail((size, size))
image = (ImageOps.exif_transpose(decoded) if orient else decoded).convert('RGB')
else:
with staged_video(src, Path(path).suffix) as staged, video_capture(staged) as cap:
image = read_frame(cap, frame_ms)
image.thumbnail((180, 180))
image.save(output, 'JPEG')
image.thumbnail((size, size))
image.save(output, 'JPEG', quality=quality)
return output.getvalue()
......
......@@ -385,6 +385,17 @@ def test_path_mapping_rejects_conflicts(tmp_path):
assert paths.root_for(str(tmp_path / 'abc' / '中文.jpg')) is None
def test_from_unc_preserves_suffix_and_matches_prefix_case_insensitively(tmp_path):
root = str(tmp_path / 'a')
paths = FilePaths({root: 'a'}, {root: '\\\\nas\\Étsy\\'})
local = str(Path(root) / '目录' / 'Ä.jpg')
assert paths.from_unc(paths.unc(local)) == local
assert paths.from_unc(r'\\NAS\éTSY\目录\Ä.jpg') == local
assert paths.from_unc(r'\\nas\Étsy\目录\..\Ä.jpg') is None
assert paths.from_unc(r'\\nas\Étsy\目录/../Ä.jpg') is None
assert paths.from_unc(r'\\nas\ÉtsyExtra\目录\Ä.jpg') is None
def auth(key=PROD, **overrides):
claims = dict(sub='nas-image-search', eps_id=2, exp=int(time.time()) + 600)
claims.update(overrides)
......@@ -412,7 +423,8 @@ def test_routes_startup_and_health_expose_only_file_source(tmp_path, monkeypatch
image(env.left / 'searchable.jpg')
application = app.create_app(env.config)
assert {(route.path, frozenset(route.methods)) for route in application.routes} == {
('/health', frozenset({'GET'})), ('/images/search', frozenset({'POST'}))}
('/health', frozenset({'GET'})), ('/images/search', frozenset({'POST'})),
('/images/preview', frozenset({'POST'}))}
with TestClient(application) as client:
assert ran.wait(5)
with application.state.engine.db.get_connection() as conn:
......@@ -465,6 +477,56 @@ def test_upload_formats_decode_and_real_size_limit(tmp_path):
assert post(client, payload=exact + b'\0').json()['detail'] == 'File too large'
@pytest.mark.parametrize('size, orientation, expected', [
((9000, 4500), 1, (2048, 1024)), ((360, 240), 1, (360, 240)), ((3000, 1500), 6, (1024, 2048)),
])
def test_preview_resizes_and_orients_the_indexed_search_hit(tmp_path, size, orientation, expected):
env = build(tmp_path)
exif = Image.Exif()
exif[274] = orientation
Image.new('RGB', size, 'red').save(env.left / '大图.jpg', exif=exif)
env.sync.scan_once()
with TestClient(app.create_app(env.config, env.engine, env.sync)) as client:
hit = post(client).json()['results'][0]
response = client.post('/images/preview', json={'path': hit['path'], 'frame_ms': None}, headers=auth())
assert response.status_code == 200
assert response.headers['content-type'] == 'image/jpeg'
with Image.open(BytesIO(response.content)) as preview:
assert preview.format == 'JPEG' and preview.mode == 'RGB' and preview.size == expected
assert preview.getexif().get(274, 1) == 1
def test_preview_requires_search_auth_and_exact_index_entry(tmp_path):
env = build(tmp_path)
indexed = Path(image(env.left / 'indexed.jpg'))
env.sync.scan_once()
outside = image(tmp_path / 'outside.jpg')
image(env.left / 'unindexed.jpg')
with TestClient(app.create_app(env.config, env.engine, env.sync)) as client:
assert client.post('/images/preview', json={'path': r'\\nas\a\indexed.jpg'}, headers=auth(eps_id=3)).status_code == 401
for path in (r'\\nas\a\missing.jpg', r'\\nas\a\unindexed.jpg', r'\\nas\a\INDEXED.jpg',
r'\\NAS\A\indexed.jpg', r'\\nas\unmapped\indexed.jpg', r'\\nas\a\sub\..\indexed.jpg', outside):
assert client.post('/images/preview', json={'path': path}, headers=auth()).status_code == 404
indexed.write_bytes(indexed.read_bytes() + b'changed')
assert client.post('/images/preview', json={'path': r'\\nas\a\indexed.jpg'}, headers=auth()).status_code == 409
def test_preview_query_uses_path_and_frame_index(tmp_path, monkeypatch):
env = build(tmp_path)
path = image(env.left / 'indexed.jpg')
env.sync.scan_once()
with env.db.get_connection() as conn:
monkeypatch.setattr(env.db, 'get_connection', lambda: conn)
statements = []
conn.set_trace_callback(statements.append)
row = env.db.file_preview_metadata(path, -1, r'\\nas\a\indexed.jpg')
conn.set_trace_callback(None)
details = [row['detail'] for row in conn.execute('EXPLAIN QUERY PLAN ' + statements[0])]
assert row['path'] == path
assert any(detail.startswith('SEARCH') and 'images_path_frame' in detail for detail in details), details
assert not any(detail.startswith('SCAN') for detail in details), details
def test_inline_thumbnail_checks_same_fd_and_returns_stale(tmp_path, monkeypatch):
env = build(tmp_path)
first = Path(image(env.left / 'first.jpg'))
......@@ -661,6 +723,13 @@ def test_video_aggregates_before_top_n_and_returns_best_frame_thumbnail(tmp_path
assert [r['path'] for r in matches] == [r'\\nas\a\best.mp4', r'\\nas\a\photo.jpg']
assert matches[0]['frame_ms'] == 3000
assert Image.open(BytesIO(b64decode(matches[0]['thumbnail']))).getpixel((0, 0))[0] in range(20, 36)
with TestClient(app.create_app(env.config, env.engine, env.sync)) as client:
path = matches[0]['path']
preview = client.post('/images/preview', json={'path': path, 'frame_ms': 3000}, headers=auth())
assert preview.status_code == 200
with Image.open(BytesIO(preview.content)) as frame:
assert frame.size == (64, 48) and frame.getpixel((0, 0))[0] in range(20, 36)
assert client.post('/images/preview', json={'path': path, 'frame_ms': 1}, headers=auth()).status_code == 404
movie.unlink()
first = env.engine.search(None, 2, top_k=2)[0]
assert first['thumbnail'] is None and first['stale']
......