model_service.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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 download_model(model_id: str, use_modelscope: bool = False) -> dict[str, Any]:
  10. """从 HF 或 ModelScope 下载模型到本地缓存。"""
  11. try:
  12. if use_modelscope:
  13. from modelscope import snapshot_download as ms_download
  14. local_path = ms_download(model_id, cache_dir=str(settings.models_dir))
  15. else:
  16. from huggingface_hub import snapshot_download
  17. local_path = snapshot_download(
  18. repo_id=model_id,
  19. local_dir=str(settings.models_dir / model_id.replace("/", "_")),
  20. local_dir_use_symlinks=False,
  21. )
  22. # 读取 config.json 获取模型信息
  23. config_path = Path(local_path) / "config.json"
  24. model_type = "text"
  25. context_length = 2048
  26. peft_methods = "lora,qlora,ia3,adalora,prefix_tuning"
  27. if config_path.exists():
  28. with open(config_path) as f:
  29. cfg = json.load(f)
  30. model_type = cfg.get("model_type", "text")
  31. context_length = cfg.get("max_position_embeddings", cfg.get("max_sequence_length", 2048))
  32. # 写入数据库
  33. async with async_session() as session:
  34. record = ModelCache(
  35. id=model_id,
  36. name=model_id.split("/")[-1],
  37. model_type=model_type,
  38. path=local_path,
  39. is_downloaded=1,
  40. context_length=context_length,
  41. supported_peft_methods=peft_methods,
  42. )
  43. session.add(record)
  44. await session.commit()
  45. logger.info(f"Model downloaded: {model_id} -> {local_path}")
  46. return {"model_id": model_id, "status": "completed", "path": local_path}
  47. except Exception as e:
  48. logger.error(f"Model download failed: {e}")
  49. return {"model_id": model_id, "status": "failed", "error": str(e)}
  50. def list_cached_models() -> list[dict[str, Any]]:
  51. """列出本地已缓存的模型。"""
  52. models_dir = settings.models_dir
  53. if not models_dir.exists():
  54. return []
  55. result = []
  56. for d in models_dir.iterdir():
  57. if not d.is_dir():
  58. continue
  59. config_path = d / "config.json"
  60. info: dict[str, Any] = {
  61. "id": d.name,
  62. "name": d.name,
  63. "model_type": "text",
  64. "path": str(d),
  65. "is_downloaded": True,
  66. "context_length": None,
  67. "supported_peft_methods": [],
  68. }
  69. if config_path.exists():
  70. with open(config_path) as f:
  71. cfg = json.load(f)
  72. info["model_type"] = cfg.get("model_type", "text")
  73. info["context_length"] = cfg.get("max_position_embeddings", cfg.get("max_sequence_length", 2048))
  74. info["supported_peft_methods"] = ["lora", "qlora", "ia3", "adalora", "prefix_tuning"]
  75. result.append(info)
  76. return result
  77. async def get_model_info(model_id: str) -> dict[str, Any] | None:
  78. """获取已缓存模型的元数据。"""
  79. # 先查数据库
  80. async with async_session() as session:
  81. result = await session.execute(select(ModelCache).where(ModelCache.id == model_id))
  82. record = result.scalar_one_or_none()
  83. if record:
  84. return {
  85. "id": record.id,
  86. "name": record.name,
  87. "model_type": record.model_type,
  88. "path": record.path,
  89. "is_downloaded": bool(record.is_downloaded),
  90. "context_length": record.context_length,
  91. "supported_peft_methods": record.supported_peft_methods.split(",") if record.supported_peft_methods else [],
  92. }
  93. # 回退:直接从文件系统读取
  94. model_dir = settings.models_dir / model_id.replace("/", "_")
  95. config_path = model_dir / "config.json"
  96. if config_path.exists():
  97. with open(config_path) as f:
  98. cfg = json.load(f)
  99. return {
  100. "id": model_id,
  101. "name": model_id.split("/")[-1],
  102. "model_type": cfg.get("model_type", "text"),
  103. "path": str(model_dir),
  104. "is_downloaded": True,
  105. "context_length": cfg.get("max_position_embeddings", cfg.get("max_sequence_length", 2048)),
  106. "supported_peft_methods": ["lora", "qlora", "ia3", "adalora", "prefix_tuning"],
  107. }
  108. return None