Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,52 +1,36 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
import logging
|
| 3 |
from fastapi import FastAPI, File, UploadFile
|
| 4 |
from fastapi.responses import JSONResponse
|
| 5 |
-
from predictor import Predictor
|
| 6 |
import uvicorn
|
|
|
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
logging.basicConfig(level=logging.INFO)
|
| 10 |
-
logger = logging.getLogger(__name__)
|
| 11 |
-
|
| 12 |
-
# 创建 FastAPI app
|
| 13 |
app = FastAPI()
|
| 14 |
|
| 15 |
-
# 模型
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
@app.post("/evaluate")
|
| 19 |
async def evaluate_file(file: UploadFile = File(...)):
|
| 20 |
-
# 第一次请求时加载模型
|
| 21 |
-
if model_holder["predictor"] is None:
|
| 22 |
-
logger.info("模型实例为空,开始加载模型...")
|
| 23 |
-
try:
|
| 24 |
-
model_holder["predictor"] = Predictor()
|
| 25 |
-
logger.info("模型加载成功。")
|
| 26 |
-
except Exception as e:
|
| 27 |
-
logger.critical(f"模型加载失败: {e}", exc_info=True)
|
| 28 |
-
return JSONResponse(status_code=500, content={"error": f"Model loading failed: {str(e)}"})
|
| 29 |
-
|
| 30 |
-
predictor = model_holder["predictor"]
|
| 31 |
-
|
| 32 |
try:
|
| 33 |
-
# 读取文件内容
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
if not text.strip():
|
| 37 |
-
return JSONResponse(status_code=400, content={"error": "File content is empty."})
|
| 38 |
|
| 39 |
-
|
| 40 |
result = predictor.predict(text)
|
| 41 |
-
|
| 42 |
-
return result
|
| 43 |
|
| 44 |
except Exception as e:
|
| 45 |
-
|
| 46 |
-
|
| 47 |
|
| 48 |
if __name__ == "__main__":
|
| 49 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 50 |
|
| 51 |
|
| 52 |
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, File, UploadFile
|
| 2 |
from fastapi.responses import JSONResponse
|
|
|
|
| 3 |
import uvicorn
|
| 4 |
+
from predictor import Predictor
|
| 5 |
|
| 6 |
+
# 创建 FastAPI 应用
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
+
# 加载模型(启动时只加载一次)
|
| 10 |
+
predictor = Predictor()
|
| 11 |
+
|
| 12 |
+
@app.get("/")
|
| 13 |
+
async def root():
|
| 14 |
+
return {"message": "API is running. Use POST /evaluate to upload files."}
|
| 15 |
|
| 16 |
@app.post("/evaluate")
|
| 17 |
async def evaluate_file(file: UploadFile = File(...)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
try:
|
| 19 |
+
# 读取上传文件内容
|
| 20 |
+
content = await file.read()
|
| 21 |
+
text = content.decode("utf-8", errors="ignore")
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
# 调用 predictor 进行推理
|
| 24 |
result = predictor.predict(text)
|
| 25 |
+
|
| 26 |
+
return JSONResponse(content=result)
|
| 27 |
|
| 28 |
except Exception as e:
|
| 29 |
+
return JSONResponse(content={"error": str(e)}, status_code=500)
|
| 30 |
+
|
| 31 |
|
| 32 |
if __name__ == "__main__":
|
| 33 |
+
uvicorn.run("app:app", host="0.0.0.0", port=7860)
|
| 34 |
|
| 35 |
|
| 36 |
|