Spaces:
Sleeping
Sleeping
| # app.py | |
| from fastapi import FastAPI, File, UploadFile, HTTPException | |
| from fastapi.responses import JSONResponse | |
| from contextlib import asynccontextmanager | |
| import logging | |
| # --- 关键修改:将 Predictor 的导入放在最前面 --- | |
| from predictor import Predictor | |
| # 设置日志 | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| # --- 关键修改:使用 lifespan 管理模型加载 --- | |
| # 创建一个全局变量来存放模型实例 | |
| model_instance = {} | |
| async def lifespan(app: FastAPI): | |
| # 在应用启动时执行的代码 | |
| logger.info("应用启动,开始加载模型...") | |
| # 将模型实例存入一个字典中,更灵活 | |
| model_instance["predictor"] = Predictor() | |
| logger.info("模型加载完成。应用准备就绪。") | |
| yield # lifespan的核心,yield之前的代码在启动时运行,之后的在关闭时运行 | |
| # 在应用关闭时执行的代码(可选) | |
| model_instance.clear() | |
| logger.info("应用关闭,模型已卸载。") | |
| # 初始化FastAPI应用,并传入lifespan管理器 | |
| app = FastAPI( | |
| lifespan=lifespan, | |
| title="课堂评价系统 API", | |
| description="接收学生发言文本,通过AI模型进行分析并返回评价等级和总结。", | |
| version="1.1.0" # 版本升级 | |
| ) | |
| # --- API 端点定义 --- | |
| async def evaluate_text_file(file: UploadFile = File(...)): | |
| """ | |
| 接收安卓App上传的文本文件,进行评价。 | |
| """ | |
| if "predictor" not in model_instance: | |
| logger.error("模型实例未在lifespan中成功加载!") | |
| raise HTTPException(status_code=503, detail="服务暂时不可用:模型正在加载或加载失败。") | |
| if file.content_type != "text/plain": | |
| raise HTTPException(status_code=400, detail="文件格式错误,请上传 .txt 文件。") | |
| try: | |
| contents = await file.read() | |
| text = contents.decode('utf-8') | |
| if not text.strip(): | |
| raise HTTPException(status_code=400, detail="上传的文件内容为空。") | |
| logger.info(f"接收到文件: {file.filename}, 开始处理...") | |
| # 使用已加载的模型实例进行预测 | |
| predictor = model_instance["predictor"] | |
| result = predictor.predict(text) | |
| logger.info(f"处理完成,返回结果: {result}") | |
| return JSONResponse(content=result) | |
| except Exception as e: | |
| logger.error(f"处理文件时发生错误: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail=f"服务器处理文件时发生未知错误: {str(e)}") | |
| def read_root(): | |
| """一个简单的端点,用于检查服务是否正在运行。""" | |
| return {"status": "ok", "message": "欢迎使用课堂评价系统 API v1.1.0"} | |