102 lines
3.3 KiB
Python
102 lines
3.3 KiB
Python
from typing import Any, Dict
|
|
|
|
|
|
class GlobalContext:
|
|
"""
|
|
模型管理器类,负责管理模型状态和任务进度。
|
|
使用依赖注入替代全局变量,提供更好的代码结构和可测试性。
|
|
"""
|
|
|
|
def __init__(self):
|
|
self.model = None
|
|
self.tokenizer = None
|
|
self.upload_progress: Dict[str, Dict[str, Any]] = {}
|
|
|
|
async def load_model(self) -> bool:
|
|
"""
|
|
异步加载机器学习模型。
|
|
在应用启动时调用,用于初始化模型和分词器。
|
|
"""
|
|
try:
|
|
# 模拟模型加载逻辑
|
|
# 实际情况下,这里可以加载真实的模型和分词器,例如使用 ModelScope 或 PyTorch
|
|
# 非模型任务也可以不用加载模型
|
|
# from modelscope import AutoModelForCausalLM, AutoTokenizer
|
|
# import torch
|
|
# model_name = "Qwen/Qwen3-30B-A3B"
|
|
# self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
|
# self.model = AutoModelForCausalLM.from_pretrained(
|
|
# model_name, torch_dtype="auto", device_map="auto"
|
|
# )
|
|
self.model = "mock_model" # 模拟模型对象
|
|
self.tokenizer = "mock_tokenizer" # 模拟分词器对象
|
|
print("模型加载成功 (模拟)")
|
|
return True
|
|
except Exception as e:
|
|
# 如果加载失败,打印错误信息并将模型和分词器设置为 None
|
|
print(f"模型加载失败: {e}")
|
|
self.model = None
|
|
self.tokenizer = None
|
|
return False
|
|
|
|
def unload_model(self):
|
|
"""
|
|
卸载模型并释放资源。
|
|
"""
|
|
self.model = None
|
|
self.tokenizer = None
|
|
print("模型已卸载 (模拟)")
|
|
|
|
def is_model_loaded(self) -> bool:
|
|
"""
|
|
检查模型是否已加载。
|
|
"""
|
|
return self.model is not None and self.tokenizer is not None
|
|
|
|
def create_task(self, task_id: str):
|
|
"""
|
|
创建新任务并初始化进度。
|
|
"""
|
|
self.upload_progress[task_id] = {
|
|
"status": "pending",
|
|
"progress": 0.0,
|
|
"message": "任务已创建",
|
|
}
|
|
|
|
def update_task_progress(
|
|
self, task_id: str, progress: float, message: str | None = None
|
|
):
|
|
"""
|
|
更新任务进度。
|
|
"""
|
|
if task_id in self.upload_progress:
|
|
self.upload_progress[task_id]["progress"] = progress
|
|
if message:
|
|
self.upload_progress[task_id]["message"] = message
|
|
|
|
def set_task_status(self, task_id: str, status: str):
|
|
"""
|
|
设置任务状态。
|
|
"""
|
|
if task_id in self.upload_progress:
|
|
self.upload_progress[task_id]["status"] = status
|
|
|
|
def set_task_result(self, task_id: str, result: Any):
|
|
"""
|
|
设置任务结果。
|
|
"""
|
|
if task_id in self.upload_progress:
|
|
self.upload_progress[task_id]["result"] = result
|
|
|
|
def get_task_progress(self, task_id: str) -> Dict[str, Any]:
|
|
"""
|
|
获取任务进度数据。
|
|
"""
|
|
return self.upload_progress.get(task_id) # type: ignore
|
|
|
|
def task_exists(self, task_id: str) -> bool:
|
|
"""
|
|
检查任务是否存在。
|
|
"""
|
|
return task_id in self.upload_progress
|