model_service.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import json
  2. from pathlib import Path
  3. from typing import Any
  4. from app.config import get_settings
  5. from app.core.db import async_session, ModelCache
  6. from app.core.logging import logger
  7. from sqlalchemy import select
  8. settings = get_settings()
  9. async def resolve_model_path(model_id: str) -> str | None:
  10. """解析模型的实际路径,兼容 HuggingFace 和 ModelScope 的不同目录结构。"""
  11. # 策略 1: 从数据库读取实际路径
  12. info = await get_model_info(model_id)
  13. if info and info.get("path"):
  14. p = Path(info["path"])
  15. if (p / "config.json").exists():
  16. return str(p)
  17. # 策略 2: HuggingFace 风格(namespace_name 扁平化)
  18. hf_path = settings.models_dir / model_id.replace("/", "_")
  19. if (hf_path / "config.json").exists():
  20. return str(hf_path)
  21. # 策略 3: ModelScope 风格(namespace/name 嵌套,含软链接)
  22. ms_path = settings.models_dir / model_id
  23. if (ms_path / "config.json").exists():
  24. return str(ms_path)
  25. # 策略 4: 扫描 models_dir 下所有目录,匹配名称
  26. model_name = model_id.split("/")[-1]
  27. for p in settings.models_dir.rglob("config.json"):
  28. if p.parent.name == model_name or model_name in str(p.parent):
  29. return str(p.parent)
  30. return None
  31. async def download_model(model_id: str, use_modelscope: bool = False) -> dict[str, Any]:
  32. """从 HF 或 ModelScope 下载模型到本地缓存。"""
  33. try:
  34. if use_modelscope:
  35. import subprocess
  36. # 使用 modelscope CLI 下载,避免 SDK API 兼容问题
  37. download_dir = str(settings.models_dir / model_id.replace("/", "_"))
  38. proc = subprocess.run(
  39. ["modelscope", "download", "--model", model_id, "--local_dir", download_dir],
  40. capture_output=True, text=True, timeout=3600,
  41. )
  42. if proc.returncode != 0:
  43. raise RuntimeError(f"modelscope CLI failed: {proc.stderr}")
  44. local_path = download_dir
  45. else:
  46. from huggingface_hub import snapshot_download
  47. local_path = snapshot_download(
  48. repo_id=model_id,
  49. local_dir=str(settings.models_dir / model_id.replace("/", "_")),
  50. local_dir_use_symlinks=False,
  51. )
  52. # 读取 config.json 获取模型信息
  53. config_path = Path(local_path) / "config.json"
  54. model_type = "text"
  55. context_length = 2048
  56. peft_methods = "lora,qlora,ia3,adalora,prefix_tuning"
  57. if config_path.exists():
  58. with open(config_path) as f:
  59. cfg = json.load(f)
  60. model_type = cfg.get("model_type", "text")
  61. context_length = cfg.get("max_position_embeddings", cfg.get("max_sequence_length", 2048))
  62. # 写入数据库(如果已存在则更新)
  63. async with async_session() as session:
  64. result = await session.execute(select(ModelCache).where(ModelCache.id == model_id))
  65. existing = result.scalar_one_or_none()
  66. if existing:
  67. existing.name = model_id.split("/")[-1]
  68. existing.model_type = model_type
  69. existing.path = local_path
  70. existing.is_downloaded = 1
  71. existing.context_length = context_length
  72. existing.supported_peft_methods = peft_methods
  73. else:
  74. record = ModelCache(
  75. id=model_id,
  76. name=model_id.split("/")[-1],
  77. model_type=model_type,
  78. path=local_path,
  79. is_downloaded=1,
  80. context_length=context_length,
  81. supported_peft_methods=peft_methods,
  82. )
  83. session.add(record)
  84. await session.commit()
  85. logger.info(f"Model downloaded: {model_id} -> {local_path}")
  86. return {"model_id": model_id, "status": "completed", "path": local_path}
  87. except Exception as e:
  88. error_msg = str(e)
  89. if "Connection" in error_msg or "timeout" in error_msg.lower() or "network" in error_msg.lower():
  90. error_msg += "\n提示: 可能是 HuggingFace 网络问题。尝试使用 ModelScope 下载。"
  91. logger.error(f"Model download failed: {e}")
  92. return {"model_id": model_id, "status": "failed", "error": error_msg}
  93. async def list_cached_models() -> list[dict[str, Any]]:
  94. """从数据库列出已缓存的模型(不扫描目录,避免 HF 缓存子目录干扰)。"""
  95. async with async_session() as session:
  96. result = await session.execute(select(ModelCache).order_by(ModelCache.created_at.desc()))
  97. records = result.scalars().all()
  98. models = []
  99. for r in records:
  100. # 验证目录是否真的存在,如果不存在则标记为未下载
  101. dir_exists = r.path and Path(r.path).exists()
  102. if not dir_exists:
  103. # 尝试从 models_dir 下查找
  104. alt_path = settings.models_dir / r.id.replace("/", "_")
  105. dir_exists = alt_path.exists()
  106. if dir_exists:
  107. r.path = str(alt_path)
  108. models.append({
  109. "id": r.id,
  110. "name": r.name,
  111. "model_type": r.model_type,
  112. "path": r.path,
  113. "is_downloaded": dir_exists,
  114. "context_length": r.context_length,
  115. "supported_peft_methods": r.supported_peft_methods.split(",") if r.supported_peft_methods else [],
  116. })
  117. return models
  118. async def get_model_info(model_id: str) -> dict[str, Any] | None:
  119. """获取已缓存模型的元数据。"""
  120. async with async_session() as session:
  121. result = await session.execute(select(ModelCache).where(ModelCache.id == model_id))
  122. record = result.scalar_one_or_none()
  123. if record:
  124. return {
  125. "id": record.id,
  126. "name": record.name,
  127. "model_type": record.model_type,
  128. "path": record.path,
  129. "is_downloaded": bool(record.is_downloaded) and Path(record.path).exists() if record.path else False,
  130. "context_length": record.context_length,
  131. "supported_peft_methods": record.supported_peft_methods.split(",") if record.supported_peft_methods else [],
  132. }
  133. return None
  134. async def delete_model(model_id: str) -> dict[str, Any]:
  135. """删除已缓存的模型(数据库记录 + 本地文件)。"""
  136. async with async_session() as session:
  137. result = await session.execute(select(ModelCache).where(ModelCache.id == model_id))
  138. record = result.scalar_one_or_none()
  139. if not record:
  140. return {"status": "not_found", "message": f"Model not found: {model_id}"}
  141. # 删除本地文件目录(对软链接,删除其指向的真实目录)
  142. model_dir = Path(record.path) if record.path else settings.models_dir / record.id.replace("/", "_")
  143. deleted_files = False
  144. if model_dir.is_symlink():
  145. # ModelScope 下载的模型可能是软链接,删除真实目录
  146. real_dir = model_dir.resolve()
  147. import shutil
  148. if real_dir.exists() and real_dir.is_dir():
  149. shutil.rmtree(real_dir, ignore_errors=True)
  150. # 如果还有父级软链接(如 dphn/ 下的其他链接),一并清理
  151. parent_link = model_dir.parent
  152. if parent_link.is_symlink():
  153. shutil.rmtree(parent_link, ignore_errors=True)
  154. deleted_files = True
  155. elif model_dir.exists() and model_dir.is_dir():
  156. import shutil
  157. shutil.rmtree(model_dir, ignore_errors=True)
  158. deleted_files = True
  159. # 删除数据库记录
  160. await session.delete(record)
  161. await session.commit()
  162. logger.info(f"Model deleted: {model_id} (files={deleted_files})")
  163. return {"status": "deleted", "model_id": model_id, "files_deleted": deleted_files}