app.py
12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
"""Design image search API. Blocking work runs in FastAPI's worker pool."""
from contextlib import asynccontextmanager
from hashlib import sha256
from importlib.metadata import version
from io import BytesIO
import logging
import math
import os
from pathlib import Path
import tempfile
import threading
import time
from dotenv import load_dotenv
import cv2
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from jose import jwt, JWTError
import numpy as np
from PIL import Image, __version__ as pillow_version
import uvicorn
import yaml
from database import DatabaseManager
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_sync import FileSystemSync, positive_int
logger = logging.getLogger(__name__)
FILESYSTEM_UPLOAD_BYTES = 45 * 1024 * 1024
FILESYSTEM_UPLOAD_EXTENSIONS = {'jpg', 'jpeg', 'png', 'webp', 'avif'}
def load_config():
load_dotenv()
with open('config.yml', encoding='utf-8') as f:
raw = yaml.safe_load(f)
def resolve(value):
if isinstance(value, dict):
return {k: resolve(v) for k, v in value.items()}
if isinstance(value, list):
return [resolve(v) for v in value]
if isinstance(value, str) and value.startswith('${') and value.endswith('}'):
key, _, default = value[2:-1].partition(':')
return os.getenv(key, default or None)
return value
return resolve(raw)
def check_search_features(engine, dimension):
"""Fail lifespan startup if the production extractor and index disagree."""
import torch
import torchvision
weights = torchvision.models.MobileNet_V3_Small_Weights.DEFAULT
checkpoint = Path(torch.hub.get_dir()) / 'checkpoints' / weights.url.rsplit('/', 1)[-1]
logger.info('Feature runtime torch=%s torchvision=%s cv2=%s Pillow=%s AVIF=%s numpy=%s',
torch.__version__, torchvision.__version__, cv2.__version__,
pillow_version, version('pillow-avif-plugin'), np.__version__)
# Fixed 16x16 RGB checkerboard. Ship it with the code, independently of test fixtures.
pixels = bytes((24, 48, 64, 192, 160, 96) * 8)
reversed_row = pixels[3:] + pixels[:3]
probe = Image.frombytes('RGB', (16, 16), (pixels + reversed_row) * 8)
features = engine.extractor.extract_all_features(probe)
vector = None if features is None else features.get('cnn_vector')
if (not isinstance(vector, np.ndarray) or vector.dtype != np.float32
or vector.shape != (CNN_VECTOR_DIM,) or not np.isfinite(vector).all()
or not np.any(vector)):
raise RuntimeError('Feature self-check failed: expected a finite non-zero float32 (1152,) vector')
if not engine.index.dimension == dimension == vector.shape[0] == CNN_VECTOR_DIM:
raise RuntimeError(f'Feature dimension mismatch: index={engine.index.dimension}, '
f'config={dimension}, probe={vector.shape[0]}, expected={CNN_VECTOR_DIM}')
logger.info('MobileNetV3-Small weights sha256=%s', sha256(checkpoint.read_bytes()).hexdigest())
def create_app(config=None, search_engine=None, data_sync=None):
config = config if config is not None else load_config()
source = config.get('source', {}).get('type', 'mysql_design')
if source not in {'mysql_design', 'filesystem'}:
raise ValueError(f'Unknown image search source: {source}')
filesystem = source == 'filesystem'
file_keys = ()
@asynccontextmanager
async def lifespan(app):
nonlocal file_keys
if filesystem:
file_jwt = config['filesystem']['jwt']
file_keys = tuple(key for key in (file_jwt.get('prod_secret'), file_jwt.get('daily_secret'))
if key is not None)
if (not file_jwt.get('prod_secret') or any(not isinstance(key, str) or not key.strip()
or len(key.encode('utf-8')) < 32 for key in file_keys)):
raise ValueError('Filesystem JWT secrets must have at least 32 UTF-8 bytes')
if not isinstance(file_jwt.get('subject'), str) or not file_jwt['subject'].strip():
raise ValueError('Filesystem JWT subject is required')
if app.state.engine is None:
settings = app.state.config
db_path = (settings['filesystem']['sqlite_path'] if filesystem else
settings['database']['sqlite']['path'])
db = DatabaseManager(db_path)
dimension = configured_dimension(settings)
index = VectorIndex(dimension)
if filesystem:
minimum = positive_int(settings['filesystem'].get('index_min_capacity', 1024),
'index_min_capacity', minimum=0)
db.file_index_snapshot(index, minimum, settings.get('video', {}).get('enabled', False))
else:
db.require_design_source()
index.bulk_load(db.iter_index_rows())
engine = ImageSearchEngine(config=settings, index=index, db_manager=db)
check_search_features(engine, dimension)
sync_class = FileSystemSync if filesystem else DesignDataSync
app.state.sync = sync_class(settings, index=index, db_manager=db, extractor=engine.extractor)
app.state.engine = engine
worker = None
if data_sync is None:
worker = threading.Thread(target=app.state.sync.run_forever, daemon=True)
app.state.sync_thread = worker
worker.start()
try:
yield
finally:
if worker is not None:
app.state.sync.stop_event.set()
worker.join(timeout=5)
app = FastAPI(title='Design Image Search Service', lifespan=lifespan,
**({'openapi_url': None} if filesystem else {}))
app.state.config = config
app.state.engine = search_engine
app.state.sync = data_sync
app.state.sync_thread = None
def verify_token(authorization: str = Header(None)):
if not authorization or not authorization.startswith('Bearer '):
raise HTTPException(401, 'Missing or invalid authorization')
if filesystem:
for key in file_keys:
try:
payload = jwt.decode(authorization[7:], key, algorithms=['HS256'],
options={'require_exp': True, 'require_sub': True})
except (JWTError, TypeError, ValueError, OverflowError):
continue
expiration = payload['exp']
valid_expiration = type(expiration) is int or (
type(expiration) is float and math.isfinite(expiration))
if (payload['sub'] == config['filesystem']['jwt']['subject']
and valid_expiration
and time.time() < expiration):
return payload
raise HTTPException(401, 'Invalid or expired token')
settings = app.state.config['jwt']
try:
payload = jwt.decode(authorization[7:], settings['secret'],
algorithms=[settings['algorithm']])
if payload.get('sub') != settings['subject']:
raise HTTPException(401, 'Invalid service subject')
return payload
except JWTError:
raise HTTPException(401, 'Invalid or expired token')
def search_token(payload=Depends(verify_token)):
if type(payload.get('eps_id')) is not int:
raise HTTPException(401, 'Integer eps_id claim required')
if filesystem and payload['eps_id'] != 2:
raise HTTPException(401, 'Invalid enterprise')
return payload
@app.get('/health')
async def health():
if filesystem:
return {'status': 'healthy', 'scan': app.state.sync.status}
# 协程里直接跑:只有一次轻量计数查询,不进工作线程池,搜索排队占满线程池时也能响应
stats = app.state.engine.db.health_stats()
worker = app.state.sync_thread
return {'status': 'healthy', 'index': app.state.engine.index.stats(),
'database': {'total_images': stats['total_images']},
'sync': {'status': 'active' if worker is not None and worker.is_alive() else 'inactive',
'last_sync': stats['last_sync_at'], 'last_reconcile': stats['last_reconcile_at']},
'rebuild': app.state.sync.rebuild_status()}
@app.post('/images/search')
def search(file: UploadFile = File(...), top_n: int = Form(20), token=Depends(search_token)):
settings = app.state.config.get('upload', {})
extension = Path(file.filename or '').suffix.lower().lstrip('.')
allowed_formats = FILESYSTEM_UPLOAD_EXTENSIONS if filesystem else settings['allowed_formats']
limit = FILESYSTEM_UPLOAD_BYTES if filesystem else settings['max_file_size']
if extension not in allowed_formats:
raise HTTPException(400, 'Unsupported file format')
content = file.file.read(limit + 1)
if len(content) > limit:
raise HTTPException(400, 'File too large')
if filesystem:
if not content:
raise HTTPException(400, 'Empty image file')
start = time.perf_counter()
try:
with Image.open(BytesIO(content), formats=['JPEG', 'PNG', 'WEBP', 'AVIF']) as decoded:
image = decoded.convert('RGB')
except (OSError, ValueError, Image.DecompressionBombError):
raise HTTPException(400, 'Image decode failed')
try:
results = app.state.engine.search(image, eps_id=token['eps_id'], top_k=min(max(1, top_n), 100))
except Exception:
logger.exception('Filesystem image search failed')
raise HTTPException(500, 'Image search failed')
return {'results': results, 'query_time_ms': round((time.perf_counter() - start) * 1000, 2),
'total_found': len(results)}
directory = Path(settings['temp_dir'])
directory.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=directory, suffix='.' + extension, delete=False) as f:
f.write(content)
path = f.name
try:
start = time.perf_counter()
matches = app.state.engine.search(path, eps_id=token['eps_id'], top_k=min(max(1, top_n), 100))
results = [{'design_id': str(r['img_id']), 'design_no': r['design_no'],
'image_url': r['image_url'], 'similarity': round(r['score'], 4),
'confidence': r['confidence'],
'details': {'cnn_sim': round(r['details']['cnn_sim'], 4),
'ransac_inliers': r['details']['ransac_inliers']}}
for r in matches]
return {'results': results, 'query_time_ms': round((time.perf_counter() - start) * 1000, 2),
'total_found': len(results)}
except Exception:
logger.exception('Image search failed')
raise HTTPException(500, 'Image search failed')
finally:
Path(path).unlink(missing_ok=True)
if filesystem:
return app
@app.get('/')
def root():
return {'service': 'Design Image Search', 'status': 'running'}
@app.post('/sync/trigger')
def sync(token=Depends(verify_token)):
return app.state.sync.sync_once()
@app.post('/admin/reconcile')
def reconcile(token=Depends(verify_token)):
return app.state.sync.reconcile()
@app.post('/admin/rebuild-all')
def rebuild(token=Depends(verify_token)):
return app.state.sync.start_rebuild()
@app.get('/admin/rebuild-status')
def status(token=Depends(verify_token)):
return app.state.sync.rebuild_status()
app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_credentials=True,
allow_methods=['*'], allow_headers=['*'])
return app
app = create_app()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
settings = app.state.config['server']
uvicorn.run(app, host=os.getenv('SERVER_HOST', settings['host']),
port=int(os.getenv('SERVER_PORT', settings['port'])), workers=1)