app.py 8.54 KB
"""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
import logging
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

logger = logging.getLogger(__name__)


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):
    @asynccontextmanager
    async def lifespan(app):
        if app.state.engine is None:
            settings = app.state.config
            db = DatabaseManager(settings['database']['sqlite']['path'])
            dimension = configured_dimension(settings)
            index = VectorIndex(dimension)
            index.bulk_load(db.iter_index_rows())
            engine = ImageSearchEngine(config=settings, index=index, db_manager=db)
            check_search_features(engine, dimension)
            app.state.sync = DesignDataSync(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)
    app.state.config = config if config is not None else load_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')
        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')
        return payload

    @app.get('/')
    def root():
        return {'service': 'Design Image Search', 'status': 'running'}

    @app.get('/health')
    async def health():
        # 协程里直接跑:只有一次轻量计数查询,不进工作线程池,搜索排队占满线程池时也能响应
        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['upload']
        extension = Path(file.filename or '').suffix.lower().lstrip('.')
        if extension not in settings['allowed_formats']:
            raise HTTPException(400, 'Unsupported file format')
        content = file.file.read(settings['max_file_size'] + 1)
        if len(content) > settings['max_file_size']:
            raise HTTPException(400, 'File too large')
        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)

    @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)