test/app/infrastructure/model_utils.py

49 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# -*- coding: utf-8 -*-
"""
模型工具模块 - 提供模型路径解析等通用功能
"""
import logging
from pathlib import Path
from typing import Optional
from app.core.config import settings
logger = logging.getLogger(__name__)
def resolve_model_path(model_id: Optional[str]) -> str:
"""将模型 ID 解析为本地模型路径(如果存在)
本项目默认模型目录结构:
./models/{publisher}/{model_name}/
如果本地模型存在,返回本地路径;否则返回原始 model_id
"""
if not model_id:
raise ValueError("model_id 不能为空")
# 项目内扁平化模型根目录
local_path = Path(settings.MODELSCOPE_PATH) / model_id
if local_path.exists() and local_path.is_dir():
resolved = str(local_path)
logger.info(f"模型 {model_id} 使用本地缓存: {resolved}")
return resolved
# 兼容历史错误配置:MODELSCOPE_CACHE 指向了 models 目录时,
# ModelScope 会生成 /models/models/{publisher}/{model_name}。
legacy_nested_path = Path(settings.MODELSCOPE_PATH) / "models" / model_id
if legacy_nested_path.exists() and legacy_nested_path.is_dir():
resolved = str(legacy_nested_path)
logger.warning(
"模型 %s 命中历史嵌套缓存: %s。建议迁移到 %s",
model_id,
resolved,
local_path,
)
return resolved
logger.warning(f"模型 {model_id} 本地缓存不存在,将在运行时下载")
return model_id