app.py 15.4 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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
"""
Design Image Search FastAPI Application
Design 图像搜索 FastAPI 服务
"""

import os
import uuid
import time
import yaml
import logging
from datetime import datetime, timedelta
from typing import Optional, Dict, Any, List
from pathlib import Path
from contextlib import asynccontextmanager

import uvicorn
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Depends, Header
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import numpy as np
from dotenv import load_dotenv
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger

# 尝试导入不同的 JWT 库
try:
    import jwt
    # 检查是否有 encode/decode 方法
    if not hasattr(jwt, 'encode') or not hasattr(jwt, 'decode'):
        # 如果没有,尝试 python-jose
        from jose import jwt
except ImportError:
    # 如果都失败了,尝试 python-jose
    from jose import jwt

from database import DatabaseManager
from core.search_engine import ImageSearchEngine
from core.faiss_manager import FAISSManager
from core.memory_index import InMemoryIndex
from data_sync import DesignDataSync

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 全局变量
config = None
db_manager = None
search_engine = None
data_sync = None
sync_thread = None
scheduler = None

os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'

def load_config():
    """加载配置文件"""
    global config
    with open('config.yml', 'r', encoding='utf-8') as f:
        config = yaml.safe_load(f)

    # 替换环境变量
    def replace_env_vars(obj):
        if isinstance(obj, dict):
            return {k: replace_env_vars(v) for k, v in obj.items()}
        elif isinstance(obj, list):
            return [replace_env_vars(item) for item in obj]
        elif isinstance(obj, str) and obj.startswith('${') and obj.endswith('}'):
            env_var = obj[2:-1]
            default = None
            if ':' in env_var:
                env_var, default = env_var.split(':', 1)
            return os.getenv(env_var, default)
        return obj

    config = replace_env_vars(config)
    return config


def scheduled_sync():
    """定时任务:每天 0:00 和 12:00 执行增量同步"""
    try:
        logger.info("🔄 定时任务:开始增量同步")
        result = data_sync.sync_once()
        logger.info(f"✅ 定时同步完成: {result}")
    except Exception as e:
        logger.error(f"❌ 定时同步失败: {e}", exc_info=True)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    global config, db_manager, search_engine, data_sync, sync_thread, scheduler

    logger.info("启动 Design Image Search 服务...")

    # 加载配置
    config = load_config()

    # 创建必要的目录
    os.makedirs(config['upload']['temp_dir'], exist_ok=True)
    os.makedirs("./logs", exist_ok=True)

    # 初始化数据库管理器
    db_manager = DatabaseManager(config['database']['sqlite']['path'])
    logger.info("数据库管理器初始化完成")

    # 初始化 FAISS 管理器
    faiss_manager = FAISSManager(
        index_path=config['faiss']['index_path'],
        mapping_path=config['faiss']['mapping_path'],
        tombstone_path=config['faiss']['tombstone_path'],
        vector_dim=config['faiss']['vector_dim']
    )

    # 尝试加载现有索引
    if not faiss_manager.load_index():
        logger.warning("未找到 FAISS 索引,首次搜索前需要运行数据同步")

    # 初始化内存索引
    memory_index = InMemoryIndex()
    if not memory_index.load_from_db(config['database']['sqlite']['path']):
        logger.warning("内存索引加载失败,搜索性能可能受影响")

    # 初始化搜索引擎
    search_engine = ImageSearchEngine(
        db_path=config['database']['sqlite']['path'],
        config=config,
        memory_index=memory_index,
        faiss_manager=faiss_manager
    )

    # 启动后台数据同步线程
    data_sync = DesignDataSync(config, memory_index=memory_index)

    import threading
    def sync_worker():
        try:
            data_sync.run_forever()
        except Exception as e:
            logger.error(f"数据同步线程出错: {e}")

    sync_thread = threading.Thread(target=sync_worker, daemon=True)
    sync_thread.start()
    logger.info("后台数据同步线程已启动")

    # 启动定时任务(每天 0:00 和 12:00)
    scheduler = BackgroundScheduler()
    scheduler.add_job(
        func=scheduled_sync,
        trigger=CronTrigger(hour='0,12', minute='0'),
        id='scheduled_sync',
        replace_existing=True
    )
    scheduler.start()
    logger.info("定时任务已启动(每天 0:00 和 12:00 执行)")

    logger.info("Design Image Search 服务启动完成")

    yield

    # 清理代码
    logger.info("正在关闭 Design Image Search 服务...")
    if scheduler and scheduler.running:
        scheduler.shutdown()
        logger.info("定时任务已关闭")


# 创建 FastAPI 应用
app = FastAPI(
    title="Design Image Search Service",
    description="Design 图像搜索服务 - 基于图像特征检索相似款式",
    version="1.0.0",
    lifespan=lifespan
)


def verify_token(authorization: str = Header(None)) -> Dict[str, Any]:
    """
    JWT 认证中间件

    Args:
        authorization: Authorization header

    Returns:
        Dict: JWT payload

    Raises:
        HTTPException: 认证失败
    """
    if not authorization:
        raise HTTPException(
            status_code=401,
            detail="Missing authorization header",
            headers={"WWW-Authenticate": "Bearer"}
        )

    if not authorization.startswith("Bearer "):
        raise HTTPException(
            status_code=401,
            detail="Invalid authorization header format",
            headers={"WWW-Authenticate": "Bearer"}
        )

    token = authorization.replace("Bearer ", "")

    try:
        payload = jwt.decode(
            token,
            config['jwt']['secret'],
            algorithms=[config['jwt']['algorithm']]
        )

        # 验证 subject
        if payload.get('sub') != config['jwt']['subject']:
            raise HTTPException(
                status_code=403,
                detail="Invalid service subject"
            )

        # 验证过期时间
        exp = payload.get('exp')
        if exp and datetime.fromtimestamp(exp) < datetime.now():
            raise HTTPException(
                status_code=401,
                detail="Token has expired"
            )

        return payload

    except Exception as e:
        # 处理不同 JWT 库的异常
        error_msg = str(e).lower()
        if 'expired' in error_msg or 'signature' in error_msg:
            raise HTTPException(
                status_code=401,
                detail="Token has expired or invalid signature"
            )
        else:
            raise HTTPException(
                status_code=401,
                detail=f"Invalid token: {str(e)}"
            )




@app.get("/")
async def root():
    """根路径"""
    return {
        "service": "Design Image Search",
        "version": "1.0.0",
        "status": "running",
        "timestamp": datetime.now().isoformat()
    }


@app.get("/health")
async def health_check():
    """健康检查接口"""
    try:
        # 获取数据库统计信息
        db_stats = db_manager.get_stats()

        # 获取 FAISS 索引统计信息
        faiss_stats = search_engine.faiss_manager.get_stats() if search_engine else {}

        # 获取同步状态
        last_sync = db_stats['last_sync_time']
        sync_status = "active" if sync_thread and sync_thread.is_alive() else "inactive"

        # 处理 last_sync_time 的格式
        if last_sync:
            if isinstance(last_sync, str):
                # 如果是字符串,直接使用
                last_sync_str = last_sync
            else:
                # 如果是 datetime 对象,转换为 ISO 格式
                last_sync_str = last_sync.isoformat()
        else:
            last_sync_str = None

        return {
            "status": "healthy",
            "timestamp": datetime.now().isoformat(),
            "database": {
                "total_images": db_stats['total_images'],
                "cnn_features": db_stats['cnn_features'],
                "orb_features": db_stats['orb_features']
            },
            "faiss": {
                "total_vectors": faiss_stats.get('total_vectors', 0),
                "effective_vectors": faiss_stats.get('effective_vectors', 0),
                "tombstone_count": faiss_stats.get('tombstone_count', 0),
                "tombstone_threshold": config.get('faiss', {}).get('tombstone_rebuild_threshold', 1000)
            },
            "sync": {
                "status": sync_status,
                "last_sync": last_sync_str,
                "last_sync_count": db_stats['last_sync_count']
            }
        }

    except Exception as e:
        logger.error(f"健康检查失败: {e}")
        return JSONResponse(
            status_code=500,
            content={
                "status": "unhealthy",
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }
        )


@app.post("/images/search")
async def search_images(
    file: UploadFile = File(...),
    top_n: int = Form(default=20),
    token: Dict = Depends(verify_token)
):
    """
    图像搜索接口

    Args:
        file: 上传的图片文件
        top_n: 返回结果数量(默认 20)
        token: JWT 认证信息(自动注入)

    Returns:
        Dict: 搜索结果
    """
    # 验证文件格式
    allowed_extensions = config['upload']['allowed_formats']
    file_ext = Path(file.filename).suffix.lower().lstrip('.')
    if file_ext not in allowed_extensions:
        raise HTTPException(
            status_code=400,
            detail=f"Unsupported file format. Allowed: {', '.join(allowed_extensions)}"
        )

    # 验证文件大小
    max_size = config['upload']['max_file_size']
    file_size = 0
    content = await file.read()
    file_size = len(content)

    if file_size > max_size:
        raise HTTPException(
            status_code=400,
            detail=f"File too large. Max size: {max_size // (1024*1024)}MB"
        )

    # 生成临时文件路径
    temp_filename = f"{uuid.uuid4()}.{file_ext}"
    temp_path = os.path.join(config['upload']['temp_dir'], temp_filename)

    try:
        # 保存上传的文件
        with open(temp_path, 'wb') as f:
            f.write(content)

        # 限制 top_n 范围
        top_n = min(max(1, top_n), 100)  # 1-100 之间

        # 执行搜索
        start_time = time.time()
        search_results = search_engine.search(temp_path, top_k=top_n)
        query_time = (time.time() - start_time) * 1000  # 转换为毫秒

        # 调试:打印搜索结果
        logger.info(f"搜索引擎返回 {len(search_results)} 个结果")
        if search_results:
            logger.info(f"第一个结果示例: {search_results[0]}")
        else:
            logger.warning("搜索引擎没有返回任何结果")

        # 格式化结果
        formatted_results = []
        for result in search_results:
            # 从搜索引擎获取 img_id
            img_id = result.get('img_id')
            if not img_id:
                logger.warning(f"Search result missing img_id: {result}")
                continue

            # 从数据库获取详细信息
            with db_manager.get_connection() as conn:
                cursor = conn.execute(
                    "SELECT design_no, image_url FROM images WHERE id = ?",
                    (img_id,)
                )
                row = cursor.fetchone()

                if row:
                    # 从结果中提取 CNN 相似度和 RANSAC 信息
                    details = result.get('details', {})
                    formatted_results.append({
                        "design_id": img_id,
                        "design_no": row['design_no'],
                        "image_url": row['image_url'],
                        "similarity": round(result.get('score', 0), 4),
                        "confidence": result.get('confidence', 'medium'),
                        "details": {
                            "cnn_sim": round(details.get('cnn_sim', 0), 4),
                            "ransac_inliers": result.get('ransac_inliers', 0)
                        }
                    })
                else:
                    logger.warning(f"No database record found for img_id: {img_id}")

        return {
            "results": formatted_results,
            "query_time_ms": round(query_time, 2),
            "total_found": len(formatted_results)
        }

    except Exception as e:
        logger.error(f"搜索失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Search failed: {str(e)}"
        )

    finally:
        # 清理临时文件
        if os.path.exists(temp_path):
            os.remove(temp_path)


@app.post("/sync/trigger")
async def trigger_sync(token: Dict = Depends(verify_token)):
    """
    手动触发同步

    Args:
        token: JWT 认证信息(自动注入)

    Returns:
        Dict: 同步结果
    """
    try:
        logger.info("手动触发数据同步...")
        result = data_sync.sync_once()
        return {
            "message": "Sync completed",
            "result": result
        }
    except Exception as e:
        logger.error(f"手动同步失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Sync failed: {str(e)}"
        )


@app.post("/admin/rebuild-all")
async def rebuild_all(token: Dict = Depends(verify_token)):
    """
    全量重建(临时将 last_sync_time 设为 1970,复用增量同步逻辑)

    Args:
        token: JWT 认证信息(自动注入)

    Returns:
        Dict: 重建结果
    """
    try:
        from datetime import datetime

        logger.info("🔄 手动触发全量重建")

        # 临时保存当前的 last_sync_time
        original_sync_time = db_manager.get_last_sync_time()

        # 临时设置为 1970-01-01(获取所有历史数据)
        db_manager.update_sync_time(datetime(1970, 1, 1), 0)

        try:
            # 调用增量同步(但会处理所有数据)
            result = data_sync.sync_once()

            return {
                "success": True,
                "message": "全量重建完成",
                "result": result
            }
        except Exception as e:
            # 失败时恢复原来的 sync_time
            if original_sync_time:
                db_manager.update_sync_time(original_sync_time, 0)
            raise e

    except Exception as e:
        logger.error(f"❌ 全量重建失败: {e}", exc_info=True)
        raise HTTPException(500, f"重建失败: {str(e)}")


# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该配置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


if __name__ == "__main__":
    # 加载环境变量
    load_dotenv()

    # 加载配置
    config = load_config()

    # 启动服务
    uvicorn.run(
        app,
        host=config['server']['host'],
        port=config['server']['port'],
        workers=1,  # 由于有共享状态,暂时使用单进程
        log_level="info"
    )