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>
Showing
4 changed files
with
122 additions
and
8 deletions
| ... | @@ -10,14 +10,16 @@ from pathlib import Path | ... | @@ -10,14 +10,16 @@ from pathlib import Path |
| 10 | import tempfile | 10 | import tempfile |
| 11 | import threading | 11 | import threading |
| 12 | import time | 12 | import time |
| 13 | from typing import Optional | ||
| 13 | 14 | ||
| 14 | from dotenv import load_dotenv | 15 | from dotenv import load_dotenv |
| 15 | import cv2 | 16 | import cv2 |
| 16 | from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, UploadFile | 17 | from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, Response, UploadFile |
| 17 | from fastapi.middleware.cors import CORSMiddleware | 18 | from fastapi.middleware.cors import CORSMiddleware |
| 18 | from jose import jwt, JWTError | 19 | from jose import jwt, JWTError |
| 19 | import numpy as np | 20 | import numpy as np |
| 20 | from PIL import Image, __version__ as pillow_version | 21 | from PIL import Image, __version__ as pillow_version |
| 22 | from pydantic import BaseModel, conint | ||
| 21 | import uvicorn | 23 | import uvicorn |
| 22 | import yaml | 24 | import yaml |
| 23 | 25 | ||
| ... | @@ -26,6 +28,7 @@ from core.feature_extractor import CNN_VECTOR_DIM | ... | @@ -26,6 +28,7 @@ from core.feature_extractor import CNN_VECTOR_DIM |
| 26 | from core.search_engine import ImageSearchEngine | 28 | from core.search_engine import ImageSearchEngine |
| 27 | from core.vector_index import VectorIndex, configured_dimension | 29 | from core.vector_index import VectorIndex, configured_dimension |
| 28 | from data_sync import DesignDataSync | 30 | from data_sync import DesignDataSync |
| 31 | from filesystem_files import jpeg_thumbnail | ||
| 29 | from filesystem_sync import FileSystemSync, positive_int | 32 | from filesystem_sync import FileSystemSync, positive_int |
| 30 | 33 | ||
| 31 | logger = logging.getLogger(__name__) | 34 | logger = logging.getLogger(__name__) |
| ... | @@ -33,6 +36,11 @@ FILESYSTEM_UPLOAD_BYTES = 45 * 1024 * 1024 | ... | @@ -33,6 +36,11 @@ FILESYSTEM_UPLOAD_BYTES = 45 * 1024 * 1024 |
| 33 | FILESYSTEM_UPLOAD_EXTENSIONS = {'jpg', 'jpeg', 'png', 'webp', 'avif'} | 36 | FILESYSTEM_UPLOAD_EXTENSIONS = {'jpg', 'jpeg', 'png', 'webp', 'avif'} |
| 34 | 37 | ||
| 35 | 38 | ||
| 39 | class PreviewRequest(BaseModel): | ||
| 40 | path: str | ||
| 41 | frame_ms: Optional[conint(strict=True, ge=-1, le=2**63 - 1)] = None | ||
| 42 | |||
| 43 | |||
| 36 | def load_config(): | 44 | def load_config(): |
| 37 | load_dotenv() | 45 | load_dotenv() |
| 38 | with open('config.yml', encoding='utf-8') as f: | 46 | with open('config.yml', encoding='utf-8') as f: |
| ... | @@ -231,6 +239,24 @@ def create_app(config=None, search_engine=None, data_sync=None): | ... | @@ -231,6 +239,24 @@ def create_app(config=None, search_engine=None, data_sync=None): |
| 231 | Path(path).unlink(missing_ok=True) | 239 | Path(path).unlink(missing_ok=True) |
| 232 | 240 | ||
| 233 | if filesystem: | 241 | if filesystem: |
| 242 | @app.post('/images/preview', response_class=Response) | ||
| 243 | def preview(request: PreviewRequest, token=Depends(search_token)): | ||
| 244 | engine = app.state.engine | ||
| 245 | frame_ms = -1 if request.frame_ms is None else request.frame_ms | ||
| 246 | if frame_ms != -1 and not config.get('video', {}).get('enabled', False): | ||
| 247 | raise HTTPException(404, 'File not indexed') | ||
| 248 | path = engine.file_paths.from_unc(request.path) | ||
| 249 | root = engine.file_paths.root_for(path) if path is not None else None | ||
| 250 | row = engine.db.file_preview_metadata(path, frame_ms, request.path) if root is not None else None | ||
| 251 | if row is None: | ||
| 252 | raise HTTPException(404, 'File not indexed') | ||
| 253 | try: | ||
| 254 | jpeg = jpeg_thumbnail(row['path'], root, (row['mtime'], row['size']), frame_ms, | ||
| 255 | size=2048, quality=85, orient=True) | ||
| 256 | except (OSError, ValueError, Image.DecompressionBombError, cv2.error): | ||
| 257 | raise HTTPException(409, 'Indexed file changed or is unavailable') | ||
| 258 | return Response(jpeg, media_type='image/jpeg') | ||
| 259 | |||
| 234 | return app | 260 | return app |
| 235 | 261 | ||
| 236 | @app.get('/') | 262 | @app.get('/') | ... | ... |
| ... | @@ -115,6 +115,11 @@ class DatabaseManager: | ... | @@ -115,6 +115,11 @@ class DatabaseManager: |
| 115 | def file_search_metadata(self, ids): | 115 | def file_search_metadata(self, ids): |
| 116 | return self.search_rows(ids, 'id, eps_id, feat_version, image_url, path, mtime, size, frame_ms') | 116 | return self.search_rows(ids, 'id, eps_id, feat_version, image_url, path, mtime, size, frame_ms') |
| 117 | 117 | ||
| 118 | def file_preview_metadata(self, path, frame_ms, image_url): | ||
| 119 | with self.get_connection() as conn: | ||
| 120 | return conn.execute('''SELECT path, mtime, size FROM images | ||
| 121 | WHERE path = ? AND frame_ms = ? AND image_url = ?''', (path, frame_ms, image_url)).fetchone() | ||
| 122 | |||
| 118 | def file_search_orb(self, ids): | 123 | def file_search_orb(self, ids): |
| 119 | return self.search_rows(ids, 'id, eps_id, feat_version, orb_pts, orb_desc') | 124 | return self.search_rows(ids, 'id, eps_id, feat_version, orb_pts, orb_desc') |
| 120 | 125 | ... | ... |
| ... | @@ -12,7 +12,7 @@ import tempfile | ... | @@ -12,7 +12,7 @@ import tempfile |
| 12 | from textwrap import dedent | 12 | from textwrap import dedent |
| 13 | 13 | ||
| 14 | import cv2 | 14 | import cv2 |
| 15 | from PIL import Image, TiffImagePlugin | 15 | from PIL import Image, ImageOps, TiffImagePlugin |
| 16 | 16 | ||
| 17 | 17 | ||
| 18 | IMAGE_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff', '.webp'} | 18 | IMAGE_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff', '.webp'} |
| ... | @@ -117,6 +117,19 @@ class FilePaths: | ... | @@ -117,6 +117,19 @@ class FilePaths: |
| 117 | return unc.rstrip('\\') + '\\' + suffix | 117 | return unc.rstrip('\\') + '\\' + suffix |
| 118 | raise ValueError(f'Path has no UNC mapping: {path}') | 118 | raise ValueError(f'Path has no UNC mapping: {path}') |
| 119 | 119 | ||
| 120 | def from_unc(self, path): | ||
| 121 | if not path.startswith('\\\\'): | ||
| 122 | return None | ||
| 123 | parts = path[2:].split('\\') | ||
| 124 | if any(part in {'', '.', '..'} or '/' in part for part in parts): | ||
| 125 | return None | ||
| 126 | folded = [part.casefold() for part in parts] | ||
| 127 | for prefix, unc in self.unc_prefixes.items(): | ||
| 128 | unc_parts = unc[2:].rstrip('\\').casefold().split('\\') | ||
| 129 | if len(parts) > len(unc_parts) and folded[:len(unc_parts)] == unc_parts: | ||
| 130 | return prefix.rstrip(os.sep) + os.sep + os.sep.join(parts[len(unc_parts):]) | ||
| 131 | return None | ||
| 132 | |||
| 120 | 133 | ||
| 121 | def file_metadata(info): | 134 | def file_metadata(info): |
| 122 | return info.st_mtime, info.st_size | 135 | return info.st_mtime, info.st_size |
| ... | @@ -253,16 +266,17 @@ def staged_image(path, root, expected): | ... | @@ -253,16 +266,17 @@ def staged_image(path, root, expected): |
| 253 | yield staged, digest.hexdigest() | 266 | yield staged, digest.hexdigest() |
| 254 | 267 | ||
| 255 | 268 | ||
| 256 | def jpeg_thumbnail(path, root, expected, frame_ms): | 269 | def jpeg_thumbnail(path, root, expected, frame_ms, *, size=180, quality=75, orient=False): |
| 257 | output = BytesIO() | 270 | output = BytesIO() |
| 258 | with open_checked(path, root, expected) as src: | 271 | with open_checked(path, root, expected) as src: |
| 259 | if frame_ms == -1: | 272 | if frame_ms == -1: |
| 260 | with open_nas_image(src) as decoded: | 273 | with open_nas_image(src) as decoded: |
| 261 | decoded.thumbnail((180, 180)) | 274 | # Pillow can draft JPEGs while resizing. The square bound also holds after EXIF rotation. |
| 262 | image = decoded.convert('RGB') | 275 | decoded.thumbnail((size, size)) |
| 276 | image = (ImageOps.exif_transpose(decoded) if orient else decoded).convert('RGB') | ||
| 263 | else: | 277 | else: |
| 264 | with staged_video(src, Path(path).suffix) as staged, video_capture(staged) as cap: | 278 | with staged_video(src, Path(path).suffix) as staged, video_capture(staged) as cap: |
| 265 | image = read_frame(cap, frame_ms) | 279 | image = read_frame(cap, frame_ms) |
| 266 | image.thumbnail((180, 180)) | 280 | image.thumbnail((size, size)) |
| 267 | image.save(output, 'JPEG') | 281 | image.save(output, 'JPEG', quality=quality) |
| 268 | return output.getvalue() | 282 | return output.getvalue() | ... | ... |
| ... | @@ -385,6 +385,17 @@ def test_path_mapping_rejects_conflicts(tmp_path): | ... | @@ -385,6 +385,17 @@ def test_path_mapping_rejects_conflicts(tmp_path): |
| 385 | assert paths.root_for(str(tmp_path / 'abc' / '中文.jpg')) is None | 385 | assert paths.root_for(str(tmp_path / 'abc' / '中文.jpg')) is None |
| 386 | 386 | ||
| 387 | 387 | ||
| 388 | def test_from_unc_preserves_suffix_and_matches_prefix_case_insensitively(tmp_path): | ||
| 389 | root = str(tmp_path / 'a') | ||
| 390 | paths = FilePaths({root: 'a'}, {root: '\\\\nas\\Étsy\\'}) | ||
| 391 | local = str(Path(root) / '目录' / 'Ä.jpg') | ||
| 392 | assert paths.from_unc(paths.unc(local)) == local | ||
| 393 | assert paths.from_unc(r'\\NAS\éTSY\目录\Ä.jpg') == local | ||
| 394 | assert paths.from_unc(r'\\nas\Étsy\目录\..\Ä.jpg') is None | ||
| 395 | assert paths.from_unc(r'\\nas\Étsy\目录/../Ä.jpg') is None | ||
| 396 | assert paths.from_unc(r'\\nas\ÉtsyExtra\目录\Ä.jpg') is None | ||
| 397 | |||
| 398 | |||
| 388 | def auth(key=PROD, **overrides): | 399 | def auth(key=PROD, **overrides): |
| 389 | claims = dict(sub='nas-image-search', eps_id=2, exp=int(time.time()) + 600) | 400 | claims = dict(sub='nas-image-search', eps_id=2, exp=int(time.time()) + 600) |
| 390 | claims.update(overrides) | 401 | claims.update(overrides) |
| ... | @@ -412,7 +423,8 @@ def test_routes_startup_and_health_expose_only_file_source(tmp_path, monkeypatch | ... | @@ -412,7 +423,8 @@ def test_routes_startup_and_health_expose_only_file_source(tmp_path, monkeypatch |
| 412 | image(env.left / 'searchable.jpg') | 423 | image(env.left / 'searchable.jpg') |
| 413 | application = app.create_app(env.config) | 424 | application = app.create_app(env.config) |
| 414 | assert {(route.path, frozenset(route.methods)) for route in application.routes} == { | 425 | assert {(route.path, frozenset(route.methods)) for route in application.routes} == { |
| 415 | ('/health', frozenset({'GET'})), ('/images/search', frozenset({'POST'}))} | 426 | ('/health', frozenset({'GET'})), ('/images/search', frozenset({'POST'})), |
| 427 | ('/images/preview', frozenset({'POST'}))} | ||
| 416 | with TestClient(application) as client: | 428 | with TestClient(application) as client: |
| 417 | assert ran.wait(5) | 429 | assert ran.wait(5) |
| 418 | with application.state.engine.db.get_connection() as conn: | 430 | with application.state.engine.db.get_connection() as conn: |
| ... | @@ -465,6 +477,56 @@ def test_upload_formats_decode_and_real_size_limit(tmp_path): | ... | @@ -465,6 +477,56 @@ def test_upload_formats_decode_and_real_size_limit(tmp_path): |
| 465 | assert post(client, payload=exact + b'\0').json()['detail'] == 'File too large' | 477 | assert post(client, payload=exact + b'\0').json()['detail'] == 'File too large' |
| 466 | 478 | ||
| 467 | 479 | ||
| 480 | @pytest.mark.parametrize('size, orientation, expected', [ | ||
| 481 | ((9000, 4500), 1, (2048, 1024)), ((360, 240), 1, (360, 240)), ((3000, 1500), 6, (1024, 2048)), | ||
| 482 | ]) | ||
| 483 | def test_preview_resizes_and_orients_the_indexed_search_hit(tmp_path, size, orientation, expected): | ||
| 484 | env = build(tmp_path) | ||
| 485 | exif = Image.Exif() | ||
| 486 | exif[274] = orientation | ||
| 487 | Image.new('RGB', size, 'red').save(env.left / '大图.jpg', exif=exif) | ||
| 488 | env.sync.scan_once() | ||
| 489 | with TestClient(app.create_app(env.config, env.engine, env.sync)) as client: | ||
| 490 | hit = post(client).json()['results'][0] | ||
| 491 | response = client.post('/images/preview', json={'path': hit['path'], 'frame_ms': None}, headers=auth()) | ||
| 492 | assert response.status_code == 200 | ||
| 493 | assert response.headers['content-type'] == 'image/jpeg' | ||
| 494 | with Image.open(BytesIO(response.content)) as preview: | ||
| 495 | assert preview.format == 'JPEG' and preview.mode == 'RGB' and preview.size == expected | ||
| 496 | assert preview.getexif().get(274, 1) == 1 | ||
| 497 | |||
| 498 | |||
| 499 | def test_preview_requires_search_auth_and_exact_index_entry(tmp_path): | ||
| 500 | env = build(tmp_path) | ||
| 501 | indexed = Path(image(env.left / 'indexed.jpg')) | ||
| 502 | env.sync.scan_once() | ||
| 503 | outside = image(tmp_path / 'outside.jpg') | ||
| 504 | image(env.left / 'unindexed.jpg') | ||
| 505 | with TestClient(app.create_app(env.config, env.engine, env.sync)) as client: | ||
| 506 | assert client.post('/images/preview', json={'path': r'\\nas\a\indexed.jpg'}, headers=auth(eps_id=3)).status_code == 401 | ||
| 507 | for path in (r'\\nas\a\missing.jpg', r'\\nas\a\unindexed.jpg', r'\\nas\a\INDEXED.jpg', | ||
| 508 | r'\\NAS\A\indexed.jpg', r'\\nas\unmapped\indexed.jpg', r'\\nas\a\sub\..\indexed.jpg', outside): | ||
| 509 | assert client.post('/images/preview', json={'path': path}, headers=auth()).status_code == 404 | ||
| 510 | indexed.write_bytes(indexed.read_bytes() + b'changed') | ||
| 511 | assert client.post('/images/preview', json={'path': r'\\nas\a\indexed.jpg'}, headers=auth()).status_code == 409 | ||
| 512 | |||
| 513 | |||
| 514 | def test_preview_query_uses_path_and_frame_index(tmp_path, monkeypatch): | ||
| 515 | env = build(tmp_path) | ||
| 516 | path = image(env.left / 'indexed.jpg') | ||
| 517 | env.sync.scan_once() | ||
| 518 | with env.db.get_connection() as conn: | ||
| 519 | monkeypatch.setattr(env.db, 'get_connection', lambda: conn) | ||
| 520 | statements = [] | ||
| 521 | conn.set_trace_callback(statements.append) | ||
| 522 | row = env.db.file_preview_metadata(path, -1, r'\\nas\a\indexed.jpg') | ||
| 523 | conn.set_trace_callback(None) | ||
| 524 | details = [row['detail'] for row in conn.execute('EXPLAIN QUERY PLAN ' + statements[0])] | ||
| 525 | assert row['path'] == path | ||
| 526 | assert any(detail.startswith('SEARCH') and 'images_path_frame' in detail for detail in details), details | ||
| 527 | assert not any(detail.startswith('SCAN') for detail in details), details | ||
| 528 | |||
| 529 | |||
| 468 | def test_inline_thumbnail_checks_same_fd_and_returns_stale(tmp_path, monkeypatch): | 530 | def test_inline_thumbnail_checks_same_fd_and_returns_stale(tmp_path, monkeypatch): |
| 469 | env = build(tmp_path) | 531 | env = build(tmp_path) |
| 470 | first = Path(image(env.left / 'first.jpg')) | 532 | 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 | ... | @@ -661,6 +723,13 @@ def test_video_aggregates_before_top_n_and_returns_best_frame_thumbnail(tmp_path |
| 661 | assert [r['path'] for r in matches] == [r'\\nas\a\best.mp4', r'\\nas\a\photo.jpg'] | 723 | assert [r['path'] for r in matches] == [r'\\nas\a\best.mp4', r'\\nas\a\photo.jpg'] |
| 662 | assert matches[0]['frame_ms'] == 3000 | 724 | assert matches[0]['frame_ms'] == 3000 |
| 663 | assert Image.open(BytesIO(b64decode(matches[0]['thumbnail']))).getpixel((0, 0))[0] in range(20, 36) | 725 | assert Image.open(BytesIO(b64decode(matches[0]['thumbnail']))).getpixel((0, 0))[0] in range(20, 36) |
| 726 | with TestClient(app.create_app(env.config, env.engine, env.sync)) as client: | ||
| 727 | path = matches[0]['path'] | ||
| 728 | preview = client.post('/images/preview', json={'path': path, 'frame_ms': 3000}, headers=auth()) | ||
| 729 | assert preview.status_code == 200 | ||
| 730 | with Image.open(BytesIO(preview.content)) as frame: | ||
| 731 | assert frame.size == (64, 48) and frame.getpixel((0, 0))[0] in range(20, 36) | ||
| 732 | assert client.post('/images/preview', json={'path': path, 'frame_ms': 1}, headers=auth()).status_code == 404 | ||
| 664 | movie.unlink() | 733 | movie.unlink() |
| 665 | first = env.engine.search(None, 2, top_k=2)[0] | 734 | first = env.engine.search(None, 2, top_k=2)[0] |
| 666 | assert first['thumbnail'] is None and first['stale'] | 735 | assert first['thumbnail'] is None and first['stale'] | ... | ... |
-
Please register or sign in to post a comment