a
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
尿检识别系统后端 - FastAPI
|
||||
"""
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from database import engine, Base, SessionLocal
|
||||
from routers import auth, urinecheck
|
||||
from routers.auth import init_admin
|
||||
|
||||
# 创建数据库表
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# 初始化默认管理员
|
||||
db = SessionLocal()
|
||||
init_admin(db)
|
||||
db.close()
|
||||
|
||||
app = FastAPI(
|
||||
title="尿检识别系统 API",
|
||||
description="尿检试纸颜色识别后端API",
|
||||
version="1.0.0",
|
||||
redirect_slashes=False
|
||||
)
|
||||
|
||||
# CORS配置
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[
|
||||
"http://localhost:8905",
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:8905",
|
||||
"http://0.0.0.0:8905",
|
||||
"http://129.211.173.87:8905", # 尿检前端
|
||||
"http://129.211.173.87:9000", # SSO 中心
|
||||
],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 注册路由
|
||||
app.include_router(auth.router)
|
||||
app.include_router(urinecheck.router)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def root():
|
||||
return {
|
||||
"message": "尿检识别系统 API",
|
||||
"version": "1.0.0",
|
||||
"docs": "/docs"
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def health_check():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=8904)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
数据库配置 - SQLite
|
||||
"""
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
import os
|
||||
|
||||
# 数据库路径
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
DATABASE_URL = f"sqlite:///{os.path.join(BASE_DIR, 'urinecheck.db')}"
|
||||
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
connect_args={"check_same_thread": False}
|
||||
)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
# 依赖注入
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,431 @@
|
||||
"""
|
||||
JSON数据尿检识别器 — 直接翻译 C++ ProcessJsonDataRequest + Get14Results
|
||||
|
||||
完整复制:
|
||||
- UrineCheck_Class::ProcessJsonDataRequest (urinecheck_class.cpp:2052)
|
||||
- UrineCheck14::Get14Results(mapData, X) (UrineCheck14.cpp:1041)
|
||||
- 所有 Red*ResultIndex 修正函数 (UrineCheck14.cpp:1413-1746)
|
||||
- PRO/MAU + SG/PH 关联修正逻辑
|
||||
|
||||
Author: 小月
|
||||
Date: 2026-05-13
|
||||
"""
|
||||
|
||||
import math
|
||||
import logging
|
||||
from collections import Counter
|
||||
from typing import Dict, List, Optional, Tuple, Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
logger = logging.getLogger("json_recognizer")
|
||||
|
||||
# 延迟导入(避免循环依赖)
|
||||
_ml_config = None
|
||||
|
||||
|
||||
def _get_config():
|
||||
global _ml_config
|
||||
if _ml_config is None:
|
||||
from ml_config import MLConfigLoader
|
||||
_ml_config = MLConfigLoader()
|
||||
_ml_config.load()
|
||||
return _ml_config
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 项目类型映射 (C++ getProjectType)
|
||||
# =============================================================================
|
||||
|
||||
def get_project_type(paper_type: int) -> int:
|
||||
"""paperType → projectType 映射"""
|
||||
mapping = {
|
||||
1: 10,
|
||||
2: 2, 5: 2,
|
||||
3: 1, 4: 1,
|
||||
6: 9, 7: 9, 8: 9, 9: 9,
|
||||
10: 7, 11: 7, 12: 7, 13: 7,
|
||||
14: 8, 15: 8, 16: 8, 17: 8, 18: 8, 19: 8,
|
||||
20: 20,
|
||||
}
|
||||
return mapping.get(paper_type, 0)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 多帧投票 (C++ CountResultsModal)
|
||||
# =============================================================================
|
||||
|
||||
def count_results_modal(results: Dict[int, List[int]]) -> Dict[int, int]:
|
||||
"""对每个 position,取多帧结果中出现次数最多的 index(众数)"""
|
||||
modal = {}
|
||||
for position, indices in results.items():
|
||||
if not indices:
|
||||
continue
|
||||
counter = Counter(indices)
|
||||
most_common = counter.most_common(1)[0][0]
|
||||
modal[position] = most_common
|
||||
return modal
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 结果索引修正函数 (红色试纸, algorithm=0)
|
||||
# 直接翻译 C++ UrineCheck14::GetRed*ResultIndex
|
||||
# =============================================================================
|
||||
|
||||
def _safe_round(val) -> int:
|
||||
"""safe round like C++ round()"""
|
||||
if isinstance(val, np.ndarray):
|
||||
val = float(val.item()) if val.size == 1 else float(val[0])
|
||||
return int(round(float(val)))
|
||||
|
||||
|
||||
def red_glu_index(hsv_lab, p) -> int:
|
||||
return _safe_round(p)
|
||||
|
||||
def red_ket_index(hsv_lab, p) -> int:
|
||||
ret = _safe_round(p)
|
||||
h = float(hsv_lab[0])
|
||||
if ret > 1 and 45 < h < 145:
|
||||
return 0
|
||||
return ret
|
||||
|
||||
def red_bil_index(hsv_lab, p) -> int:
|
||||
return _safe_round(p)
|
||||
|
||||
def red_pro_index(hsv_lab, p) -> int:
|
||||
ret = _safe_round(p)
|
||||
h = float(hsv_lab[0])
|
||||
if ret > 0 and (h < 25 or h > 110):
|
||||
return 0
|
||||
return ret
|
||||
|
||||
def red_nit_index(hsv_lab, p) -> int:
|
||||
ret = _safe_round(p)
|
||||
h = float(hsv_lab[0])
|
||||
# C++ 20230731 version: h>40 && h<140
|
||||
if ret > 0 and 40 < h < 140:
|
||||
return 0
|
||||
return ret
|
||||
|
||||
def red_ph_index(hsv_lab, p) -> int:
|
||||
return _safe_round(p)
|
||||
|
||||
def red_bld_index(hsv_lab, p) -> int:
|
||||
return _safe_round(p)
|
||||
|
||||
def red_sg_index(hsv_lab, p) -> int:
|
||||
return _safe_round(p)
|
||||
|
||||
def red_wbc_index(hsv_lab, p) -> int:
|
||||
return _safe_round(p)
|
||||
|
||||
def red_vc_index(hsv_lab, p) -> int:
|
||||
return _safe_round(p)
|
||||
|
||||
def red_cre_index(hsv_lab, p) -> int:
|
||||
return _safe_round(p)
|
||||
|
||||
def red_uca_index(hsv_lab, p) -> int:
|
||||
return _safe_round(p)
|
||||
|
||||
def red_mau_index(hsv_lab, p) -> int:
|
||||
ret = _safe_round(p)
|
||||
h = float(hsv_lab[0])
|
||||
if ret > 0 and (h < 30 or h > 115):
|
||||
return 0
|
||||
return ret
|
||||
|
||||
def red_uro_index(hsv_lab, p) -> int:
|
||||
ret = _safe_round(p)
|
||||
h = float(hsv_lab[0])
|
||||
if ret > 0 and 25 < h < 150:
|
||||
return 0
|
||||
return ret
|
||||
|
||||
# ---- 绿色/蓝色试纸 (algorithm=1) ----
|
||||
def glu_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def ket_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def bil_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def pro_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def nit_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def ph_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def bld_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def sg_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def wbc_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def vc_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def cre_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def uca_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def mau_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def uro_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
|
||||
# ---- PET试纸 (algorithm=2) ----
|
||||
def pet_glu_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
def pet_sg_index(hsv_lab, p) -> int: return _safe_round(p)
|
||||
|
||||
|
||||
# 函数名 → 函数对象映射
|
||||
RESULT_FUNC_REGISTRY = {
|
||||
# Red (algorithm=0)
|
||||
"red_glu": red_glu_index, "red_ket": red_ket_index,
|
||||
"red_bil": red_bil_index, "red_pro": red_pro_index,
|
||||
"red_nit": red_nit_index, "red_ph": red_ph_index,
|
||||
"red_bld": red_bld_index, "red_sg": red_sg_index,
|
||||
"red_wbc": red_wbc_index, "red_vc": red_vc_index,
|
||||
"red_cre": red_cre_index, "red_uca": red_uca_index,
|
||||
"red_mau": red_mau_index, "red_uro": red_uro_index,
|
||||
# Green/Blue (algorithm=1)
|
||||
"glu": glu_index, "ket": ket_index, "bil": bil_index,
|
||||
"pro": pro_index, "nit": nit_index, "ph": ph_index,
|
||||
"bld": bld_index, "sg": sg_index, "wbc": wbc_index,
|
||||
"vc": vc_index, "cre": cre_index, "uca": uca_index,
|
||||
"mau": mau_index, "uro": uro_index,
|
||||
# PET (algorithm=2)
|
||||
"pet_glu": pet_glu_index, "pet_sg": pet_sg_index,
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 核心识别器
|
||||
# =============================================================================
|
||||
|
||||
class UrineJsonRecognizer:
|
||||
"""JSON数据尿检识别器"""
|
||||
|
||||
def __init__(self):
|
||||
self.config = _get_config()
|
||||
|
||||
def recognize(self, json_body: dict) -> dict:
|
||||
"""
|
||||
完整识别流程 — 翻译 ProcessJsonDataRequest
|
||||
|
||||
输入: 与 txt 文件格式一致的 JSON dict
|
||||
输出: {"score": "100", "status": "0", "data": [{id, index}, ...]}
|
||||
"""
|
||||
config = self.config
|
||||
|
||||
# ---- 1. 提取字段 ----
|
||||
data_array = json_body.get("data", [])
|
||||
extend = json_body.get("extend", {})
|
||||
|
||||
if not data_array or len(data_array) == 0:
|
||||
return {
|
||||
"score": "0", "status": "-8",
|
||||
"message": "数据为空!", "project_id": 0, "imgid": 0,
|
||||
}
|
||||
|
||||
# ---- 2. 确定试纸类型 ----
|
||||
paper_type = self._extract_paper_type(extend)
|
||||
project_id = get_project_type(paper_type)
|
||||
|
||||
if paper_type < 1 or paper_type >= 21:
|
||||
return {
|
||||
"score": "0", "status": "-10",
|
||||
"message": "设置试纸类型参数错误!",
|
||||
"project_id": paper_type, "imgid": 0,
|
||||
}
|
||||
|
||||
X = paper_type - 1 # C++ 中的 papertypeIndex
|
||||
|
||||
# ---- 3. 逐帧处理 ----
|
||||
results: Dict[int, List[int]] = {}
|
||||
|
||||
for frame in data_array:
|
||||
if not isinstance(frame, list):
|
||||
continue
|
||||
|
||||
# 3a. 解析颜色数据 → mapData
|
||||
map_data = {}
|
||||
for item in frame:
|
||||
item_id = int(item.get("id", 0))
|
||||
value_str = str(item.get("value", ""))
|
||||
try:
|
||||
values = [float(x) for x in value_str.split(",")]
|
||||
except (ValueError, AttributeError):
|
||||
continue
|
||||
if len(values) >= 6:
|
||||
map_data[item_id] = values[:6]
|
||||
|
||||
if not map_data:
|
||||
continue
|
||||
|
||||
# 3b. 调用 ML 推理
|
||||
frame_result = self._get14_results(map_data, X)
|
||||
|
||||
# 3c. 收集结果
|
||||
for position, raw_index in frame_result.items():
|
||||
if position not in results:
|
||||
results[position] = []
|
||||
results[position].append(raw_index)
|
||||
|
||||
if not results:
|
||||
return {
|
||||
"score": "0", "status": "-8",
|
||||
"message": "未能识别任何色块!", "project_id": project_id, "imgid": 0,
|
||||
}
|
||||
|
||||
# ---- 4. 多帧投票 ----
|
||||
last_result = count_results_modal(results)
|
||||
|
||||
# ---- 5. PRO/MAU 关联修正 ----
|
||||
pro_pos = config.positionsPro[X]
|
||||
mau_pos = config.positionsMau[X]
|
||||
pro_val = -1
|
||||
mau_val = -1
|
||||
max_mau = config.get_max_mau(X)
|
||||
|
||||
if pro_pos >= 0 and mau_pos >= 0:
|
||||
if pro_pos in last_result:
|
||||
pro_val = last_result[pro_pos]
|
||||
if mau_pos in last_result:
|
||||
mau_val = last_result[mau_pos]
|
||||
|
||||
if mau_val == 0:
|
||||
pro_val = 0
|
||||
else:
|
||||
if pro_val == 0 and mau_val == max_mau:
|
||||
mau_val = max_mau - 1
|
||||
if pro_val >= 1:
|
||||
mau_val = max_mau
|
||||
|
||||
# ---- 6. SG/PH 关联修正 ----
|
||||
sg_pos = config.positionsSg[X]
|
||||
ph_pos = config.positionsPh[X]
|
||||
sg_val = -1
|
||||
ph_val = -1
|
||||
max_sg = config.get_max_sg(X)
|
||||
|
||||
if sg_pos >= 0 and ph_pos >= 0:
|
||||
if sg_pos in last_result:
|
||||
sg_val = last_result[sg_pos]
|
||||
if ph_pos in last_result:
|
||||
ph_val = last_result[ph_pos]
|
||||
|
||||
if project_id < 20 and ph_val >= 2 and sg_val < max_sg:
|
||||
sg_val += 1
|
||||
|
||||
# ---- 7. 构建输出 data 数组 ----
|
||||
output_data = []
|
||||
for position in sorted(last_result.keys()):
|
||||
raw_index = last_result[position]
|
||||
output_id = config.get_stat_id(X, position)
|
||||
|
||||
# 获取最终 index
|
||||
if pro_pos >= 0 and mau_pos >= 0:
|
||||
if position == pro_pos:
|
||||
raw_index = pro_val
|
||||
elif position == mau_pos:
|
||||
raw_index = mau_val
|
||||
|
||||
if sg_pos >= 0 and ph_pos >= 0:
|
||||
if position == sg_pos:
|
||||
raw_index = sg_val
|
||||
|
||||
# 通过 indexmap 映射
|
||||
output_index = config.get_output_index(X, position, raw_index)
|
||||
|
||||
output_data.append({
|
||||
"id": output_id,
|
||||
"index": output_index,
|
||||
})
|
||||
|
||||
return {
|
||||
"score": "100",
|
||||
"status": "0",
|
||||
"message": "OK",
|
||||
"project_id": project_id,
|
||||
"paper_id": paper_type,
|
||||
"imgid": 0,
|
||||
"data": output_data,
|
||||
}
|
||||
|
||||
# ========== ML 推理 ==========
|
||||
|
||||
def _get14_results(self, map_data: Dict[int, List[float]],
|
||||
paper_type: int) -> Dict[int, int]:
|
||||
"""
|
||||
完整翻译 UrineCheck14::Get14Results(mapData, X)
|
||||
|
||||
对每个模型执行: 取6维特征 → RTrees预测 → 结果索引函数修正
|
||||
"""
|
||||
config = self.config
|
||||
results = {}
|
||||
|
||||
for position, model in config.models[paper_type].items():
|
||||
# 查找该 position 的颜色数据
|
||||
if position not in map_data:
|
||||
continue
|
||||
|
||||
vdata = map_data[position]
|
||||
if len(vdata) < 6:
|
||||
continue
|
||||
|
||||
# 构造 1×6 样本矩阵
|
||||
sample = np.array([vdata[:6]], dtype=np.float32)
|
||||
|
||||
# RTrees 预测
|
||||
try:
|
||||
resp = model.predict(sample)
|
||||
# resp 可能是 (retval, results) 元组或直接值
|
||||
if isinstance(resp, tuple):
|
||||
p = float(resp[1].item()) if resp[1].size == 1 else float(resp[1][0])
|
||||
else:
|
||||
p = float(resp)
|
||||
except Exception as e:
|
||||
logger.warning(f"预测失败 paperType={paper_type} pos={position}: {e}")
|
||||
continue
|
||||
|
||||
# 获取结果索引函数
|
||||
func_type = config.get_func_type(paper_type, position)
|
||||
if func_type is None:
|
||||
continue
|
||||
|
||||
func = RESULT_FUNC_REGISTRY.get(func_type)
|
||||
if func is None:
|
||||
continue
|
||||
|
||||
# 调用结果索引函数
|
||||
try:
|
||||
pi = func(vdata[:6], p)
|
||||
results[position] = pi
|
||||
except Exception as e:
|
||||
logger.warning(f"索引函数调用失败 {func_type}: {e}")
|
||||
continue
|
||||
|
||||
return results
|
||||
|
||||
# ========== 试纸类型提取 ==========
|
||||
|
||||
def _extract_paper_type(self, extend: dict) -> int:
|
||||
"""从 extend 字段提取 paperType"""
|
||||
if not isinstance(extend, dict) or not extend:
|
||||
return 0
|
||||
|
||||
# type 优先
|
||||
if "type" in extend:
|
||||
try:
|
||||
return int(extend["type"])
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# color_14i 其次
|
||||
if "color_14i" in extend:
|
||||
try:
|
||||
return int(extend["color_14i"])
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 全局单例
|
||||
# =============================================================================
|
||||
|
||||
_recognizer: Optional[UrineJsonRecognizer] = None
|
||||
|
||||
|
||||
def get_recognizer() -> UrineJsonRecognizer:
|
||||
global _recognizer
|
||||
if _recognizer is None:
|
||||
_recognizer = UrineJsonRecognizer()
|
||||
return _recognizer
|
||||
@@ -0,0 +1,215 @@
|
||||
"""
|
||||
ML配置加载器 — 解析 /usr/local/Models/ml.json
|
||||
直接翻译 C++ UrineCheck14::initconfig() + UrineCheck_Class::initconfig()
|
||||
|
||||
Author: 小月
|
||||
Date: 2026-05-13
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from typing import Dict, List, Optional, Callable, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
logger = logging.getLogger("ml_config")
|
||||
|
||||
# 常量(与C++一致)
|
||||
MAX_PAPER_TYPE = 21
|
||||
MAX_PAPER_BLOCK = 15
|
||||
MAX_ALG_TAG = 8
|
||||
|
||||
# 各检测项在 ml.json 中的 name → 结果索引函数类型映射
|
||||
# algorithm=0 → Red, algorithm=1 → Green/Blue (原始)
|
||||
ITEM_FUNC_MAP = {
|
||||
"uro": "uro",
|
||||
"glu": "glu",
|
||||
"ket": "ket",
|
||||
"bil": "bil",
|
||||
"pro": "pro",
|
||||
"nit": "nit",
|
||||
"ph": "ph",
|
||||
"bld": "bld",
|
||||
"sg": "sg",
|
||||
"wbc": "wbc",
|
||||
"vc": "vc",
|
||||
"cre": "cre",
|
||||
"uca": "uca",
|
||||
"mau": "mau",
|
||||
}
|
||||
|
||||
|
||||
class MLConfigLoader:
|
||||
"""ML模型配置加载器 — 全局单例"""
|
||||
|
||||
def __init__(self, config_path: str = "/usr/local/Models/ml.json"):
|
||||
self.config_path = config_path
|
||||
|
||||
# 三维查表: [paperType][position][rawIndex] → outputIndex
|
||||
self.itemsResultIdxMapTbl: List[List[List[int]]] = [
|
||||
[[-1] * MAX_ALG_TAG for _ in range(MAX_PAPER_BLOCK)]
|
||||
for _ in range(MAX_PAPER_TYPE)
|
||||
]
|
||||
|
||||
# 二维: [paperType][position] → 输出id
|
||||
self.itemsStatIds: List[List[int]] = [
|
||||
[-1] * MAX_PAPER_BLOCK for _ in range(MAX_PAPER_TYPE)
|
||||
]
|
||||
|
||||
# [paperType][position] → 已加载的 OpenCV RTrees 模型
|
||||
self.models: List[Dict[int, cv2.ml.RTrees]] = [
|
||||
{} for _ in range(MAX_PAPER_TYPE)
|
||||
]
|
||||
|
||||
# [paperType][position] → 结果索引函数类型名
|
||||
# "uro"|"glu"|...|"red_uro"|"red_glu"|...|"pet_glu"|"pet_sg"
|
||||
self.result_funcs: List[Dict[int, str]] = [
|
||||
{} for _ in range(MAX_PAPER_TYPE)
|
||||
]
|
||||
|
||||
# PRO/MAU/SG/pH 在各 paperType 上的 position
|
||||
self.positionsPro: List[int] = [-1] * MAX_PAPER_TYPE
|
||||
self.positionsMau: List[int] = [-1] * MAX_PAPER_TYPE
|
||||
self.positionsSg: List[int] = [-1] * MAX_PAPER_TYPE
|
||||
self.positionsPh: List[int] = [-1] * MAX_PAPER_TYPE
|
||||
|
||||
# 文件名缓存(避免重复加载同一个 .data 文件)
|
||||
self._file_cache: Dict[str, cv2.ml.RTrees] = {}
|
||||
|
||||
self._loaded = False
|
||||
|
||||
def load(self) -> bool:
|
||||
"""加载 ml.json 并初始化所有配置"""
|
||||
if self._loaded:
|
||||
return True
|
||||
|
||||
try:
|
||||
with open(self.config_path, 'r') as f:
|
||||
config = json.load(f)
|
||||
except Exception as e:
|
||||
logger.error(f"无法加载 {self.config_path}: {e}")
|
||||
return False
|
||||
|
||||
ml = config.get("ml", [])
|
||||
if not ml:
|
||||
logger.error("ml.json 中未找到 'ml' 数组")
|
||||
return False
|
||||
|
||||
for item in ml:
|
||||
name = item.get("name", "")
|
||||
models_list = item.get("model", [])
|
||||
|
||||
if name not in ITEM_FUNC_MAP:
|
||||
logger.warning(f"未知检测项目: {name}")
|
||||
continue
|
||||
|
||||
for paper_type, block in enumerate(models_list):
|
||||
if paper_type >= MAX_PAPER_TYPE:
|
||||
break
|
||||
|
||||
position = block.get("positon", -1)
|
||||
if position < 0:
|
||||
continue
|
||||
|
||||
item_id = block.get("id", 0)
|
||||
filepath = block.get("filepath", "")
|
||||
algorithm = block.get("algorithm", 1)
|
||||
indexmap_str = block.get("indexmap", "0")
|
||||
|
||||
# 记录 PRO/MAU/SG/pH 的 position
|
||||
if name == "pro":
|
||||
self.positionsPro[paper_type] = position
|
||||
elif name == "mau":
|
||||
self.positionsMau[paper_type] = position
|
||||
elif name == "sg":
|
||||
self.positionsSg[paper_type] = position
|
||||
elif name == "ph":
|
||||
self.positionsPh[paper_type] = position
|
||||
|
||||
# 记录 output id
|
||||
self.itemsStatIds[paper_type][position] = item_id
|
||||
|
||||
# 解析 indexmap
|
||||
index_map = [int(x.strip()) for x in indexmap_str.split(",")]
|
||||
for k, val in enumerate(index_map):
|
||||
if k < MAX_ALG_TAG:
|
||||
self.itemsResultIdxMapTbl[paper_type][position][k] = val
|
||||
|
||||
# 加载模型文件(带缓存)
|
||||
if filepath not in self._file_cache:
|
||||
try:
|
||||
model = cv2.ml.RTrees_load(filepath)
|
||||
if model is None or model.empty():
|
||||
logger.error(f"模型加载失败: {filepath}")
|
||||
continue
|
||||
self._file_cache[filepath] = model
|
||||
except Exception as e:
|
||||
logger.error(f"模型加载异常 {filepath}: {e}")
|
||||
continue
|
||||
|
||||
self.models[paper_type][position] = self._file_cache[filepath]
|
||||
|
||||
# 确定结果索引函数
|
||||
func_type = self._resolve_func_type(name, algorithm)
|
||||
self.result_funcs[paper_type][position] = func_type
|
||||
|
||||
self._loaded = True
|
||||
count = sum(len(m) for m in self.models)
|
||||
logger.info(f"ML配置加载完成: {count} 个模型, {len(self._file_cache)} 个唯一文件")
|
||||
return True
|
||||
|
||||
def _resolve_func_type(self, name: str, algorithm: int) -> str:
|
||||
"""根据试纸类型确定结果索引函数名"""
|
||||
base = ITEM_FUNC_MAP[name]
|
||||
if algorithm == 0:
|
||||
# 红色试纸
|
||||
return f"red_{base}"
|
||||
elif algorithm == 2:
|
||||
# PET 试纸 (仅 glu/sg 有)
|
||||
return f"pet_{base}"
|
||||
else:
|
||||
# 绿色/蓝色试纸(原始)
|
||||
return base
|
||||
|
||||
# ---- 便捷查询方法 ----
|
||||
|
||||
def get_model(self, paper_type: int, position: int) -> Optional[cv2.ml.RTrees]:
|
||||
if paper_type < 0 or paper_type >= MAX_PAPER_TYPE:
|
||||
return None
|
||||
return self.models[paper_type].get(position)
|
||||
|
||||
def get_func_type(self, paper_type: int, position: int) -> Optional[str]:
|
||||
if paper_type < 0 or paper_type >= MAX_PAPER_TYPE:
|
||||
return None
|
||||
return self.result_funcs[paper_type].get(position)
|
||||
|
||||
def get_stat_id(self, paper_type: int, position: int) -> int:
|
||||
if paper_type < 0 or paper_type >= MAX_PAPER_TYPE:
|
||||
return -1
|
||||
return self.itemsStatIds[paper_type][position]
|
||||
|
||||
def get_output_index(self, paper_type: int, position: int, raw_index: int) -> int:
|
||||
"""通过 indexmap 将算法输出index映射为最终输出index"""
|
||||
if paper_type < 0 or paper_type >= MAX_PAPER_TYPE:
|
||||
return 0
|
||||
if position < 0 or position >= MAX_PAPER_BLOCK:
|
||||
return 0
|
||||
if raw_index < 0 or raw_index >= MAX_ALG_TAG:
|
||||
return 0
|
||||
mapped = self.itemsResultIdxMapTbl[paper_type][position][raw_index]
|
||||
return mapped if mapped >= 0 else 0
|
||||
|
||||
def get_max_mau(self, paper_type: int) -> int:
|
||||
"""MAU最大等级: red=3, others=2"""
|
||||
return 2 if paper_type == 0 else 3
|
||||
|
||||
def get_max_sg(self, paper_type: int) -> int:
|
||||
"""SG最大等级: red=6, others=5"""
|
||||
return 5 if paper_type == 0 else 6
|
||||
|
||||
def has_model_at(self, paper_type: int, position: int) -> bool:
|
||||
if paper_type < 0 or paper_type >= MAX_PAPER_TYPE:
|
||||
return False
|
||||
return position in self.models[paper_type]
|
||||
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
数据库模型 - 仅管理员
|
||||
"""
|
||||
from sqlalchemy import Column, Integer, String, DateTime
|
||||
from datetime import datetime
|
||||
from database import Base
|
||||
|
||||
|
||||
class Admin(Base):
|
||||
"""管理员账号"""
|
||||
__tablename__ = "admins"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
username = Column(String, unique=True, index=True, default="admin")
|
||||
password_hash = Column(String)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
@@ -0,0 +1,8 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
sqlalchemy==2.0.36
|
||||
python-jose[cryptography]==3.3.0
|
||||
passlib[bcrypt]==1.7.4
|
||||
python-multipart==0.0.18
|
||||
opencv-python-headless==4.10.0.84
|
||||
numpy==1.26.4
|
||||
@@ -0,0 +1 @@
|
||||
from . import auth, urinecheck
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
认证路由
|
||||
"""
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Request, Response
|
||||
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime, timedelta
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from database import get_db
|
||||
from models import Admin
|
||||
from schemas import LoginRequest, LoginResponse, PasswordChange
|
||||
from sso_client import get_current_user_from_cookie
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["认证"])
|
||||
|
||||
# 安全配置
|
||||
SECRET_KEY = "urinecheck-secret-key-change-in-production"
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_DAYS = 30
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
||||
|
||||
# 与 SSO 中心共享的 Cookie 属性(删除 Cookie 时需一致)
|
||||
SSO_COOKIE_DOMAIN = "129.211.173.87"
|
||||
|
||||
|
||||
def verify_password(plain_password, hashed_password):
|
||||
"""验证密码"""
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
def get_password_hash(password):
|
||||
"""生成密码哈希"""
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def create_access_token(data: dict, expires_delta: timedelta = None):
|
||||
"""创建JWT令牌"""
|
||||
to_encode = data.copy()
|
||||
if expires_delta:
|
||||
expire = datetime.utcnow() + expires_delta
|
||||
else:
|
||||
expire = datetime.utcnow() + timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
async def get_current_admin(
|
||||
request: Request,
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""获取当前登录管理员 —— 双模式认证
|
||||
1. 优先读取 Authorization Header(原有本地登录)
|
||||
2. 无 Header 则读取 Cookie 中的 SSO token,本地验签后查本地 Admin 表
|
||||
"""
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="无法验证凭据",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
username = None
|
||||
|
||||
# 模式一:原有 Bearer Token
|
||||
if token:
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
username = payload.get("sub")
|
||||
except JWTError:
|
||||
pass
|
||||
|
||||
# 模式二:SSO Cookie
|
||||
if not username:
|
||||
sso_user = get_current_user_from_cookie(request)
|
||||
if sso_user:
|
||||
username = sso_user.get("username")
|
||||
|
||||
if not username:
|
||||
raise credentials_exception
|
||||
|
||||
admin = db.query(Admin).filter(Admin.username == username).first()
|
||||
if admin is None:
|
||||
raise credentials_exception
|
||||
return admin
|
||||
|
||||
|
||||
@router.post("/login", response_model=LoginResponse)
|
||||
def login(login_data: LoginRequest, db: Session = Depends(get_db)):
|
||||
"""管理员登录"""
|
||||
admin = db.query(Admin).filter(Admin.username == login_data.username).first()
|
||||
|
||||
if not admin or not verify_password(login_data.password, admin.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="用户名或密码错误"
|
||||
)
|
||||
|
||||
access_token = create_access_token(data={"sub": admin.username})
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
|
||||
|
||||
@router.post("/change-password")
|
||||
def change_password(
|
||||
password_data: PasswordChange,
|
||||
current_admin: Admin = Depends(get_current_admin),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""修改密码"""
|
||||
# 验证原密码
|
||||
if not verify_password(password_data.old_password, current_admin.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="原密码错误"
|
||||
)
|
||||
|
||||
# 更新密码
|
||||
current_admin.password_hash = get_password_hash(password_data.new_password)
|
||||
db.commit()
|
||||
|
||||
return {"message": "密码修改成功"}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def get_me(current_admin: Admin = Depends(get_current_admin)):
|
||||
"""获取当前管理员信息"""
|
||||
return {"username": current_admin.username}
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(response: Response):
|
||||
"""退出登录:清除本地 token 状态并删除 SSO Cookie"""
|
||||
response.delete_cookie("access_token", domain=SSO_COOKIE_DOMAIN, path="/")
|
||||
return {"message": "退出成功"}
|
||||
|
||||
|
||||
def init_admin(db: Session):
|
||||
"""初始化默认管理员账号"""
|
||||
admin = db.query(Admin).filter(Admin.username == "admin").first()
|
||||
if not admin:
|
||||
admin = Admin(
|
||||
username="admin",
|
||||
password_hash=get_password_hash("admin123")
|
||||
)
|
||||
db.add(admin)
|
||||
db.commit()
|
||||
print("✅ 默认管理员账号已创建: admin / admin123")
|
||||
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
尿检试纸识别 API 路由
|
||||
POST /api/urinecheck/analyze - 上传试纸图片并识别
|
||||
POST /api/urinecheck/analyze-json - JSON数据格式识别
|
||||
"""
|
||||
from fastapi import APIRouter, UploadFile, File, HTTPException
|
||||
import tempfile
|
||||
import os
|
||||
import sys
|
||||
import json as json_lib
|
||||
|
||||
# 导入核心算法
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from urine_recognizer import analyze_urine_strip
|
||||
from json_recognizer import get_recognizer
|
||||
from schemas import JsonDataRequest
|
||||
|
||||
router = APIRouter(prefix="/api/urinecheck", tags=["尿检识别"])
|
||||
|
||||
# 允许的图片格式
|
||||
ALLOWED_CONTENT_TYPES = {"image/jpeg", "image/png"}
|
||||
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
|
||||
|
||||
|
||||
@router.post("/analyze")
|
||||
async def analyze_image(
|
||||
file: UploadFile = File(...),
|
||||
):
|
||||
"""
|
||||
上传尿检试纸图片并分析颜色
|
||||
|
||||
- 支持格式: JPG, PNG
|
||||
- 最大文件大小: 10MB
|
||||
- 支持规格: 8联/11联/14联 (S型/L型)
|
||||
"""
|
||||
# 验证文件类型
|
||||
if file.content_type not in ALLOWED_CONTENT_TYPES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"不支持的文件格式: {file.content_type},仅支持 JPG 和 PNG"
|
||||
)
|
||||
|
||||
# 读取文件内容
|
||||
image_data = await file.read()
|
||||
|
||||
# 检查文件大小
|
||||
if len(image_data) > MAX_FILE_SIZE:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"文件大小超过10MB限制 (当前: {len(image_data) / (1024*1024):.1f}MB)"
|
||||
)
|
||||
|
||||
if len(image_data) == 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="上传的文件为空"
|
||||
)
|
||||
|
||||
# 保存到临时文件
|
||||
with tempfile.NamedTemporaryFile(
|
||||
suffix=os.path.splitext(file.filename or "image.jpg")[1],
|
||||
delete=False,
|
||||
) as tmp:
|
||||
tmp.write(image_data)
|
||||
tmp_path = tmp.name
|
||||
|
||||
# 执行识别
|
||||
result = analyze_urine_strip(image_data)
|
||||
|
||||
# 清理临时文件
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/analyze-json")
|
||||
async def analyze_json(
|
||||
request: JsonDataRequest,
|
||||
):
|
||||
"""
|
||||
JSON数据格式尿检识别
|
||||
|
||||
输入格式与客户端上传的txt文件一致:
|
||||
```json
|
||||
{
|
||||
"extend": {"color_14i": "2"},
|
||||
"data": [
|
||||
[{"id": 0, "value": "7.62,146.43,..."}, ...],
|
||||
[{"id": 0, "value": "6.75,139.44,..."}, ...]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- value: "H,S,V,L,A,B" 6个颜色通道值
|
||||
- data: 多帧颜色数据(通常2-5帧)
|
||||
- extend.color_14i: 试纸类型 (1=绿, 2=红, 3=蓝4联, 5=蓝14联)
|
||||
"""
|
||||
recognizer = get_recognizer()
|
||||
|
||||
# 转换为dict传给识别器
|
||||
body = json_lib.loads(request.model_dump_json())
|
||||
|
||||
result = recognizer.recognize(body)
|
||||
return result
|
||||
@@ -0,0 +1,33 @@
|
||||
"""
|
||||
Pydantic 数据验证模型
|
||||
"""
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List, Optional, Dict, Any
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class LoginResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
|
||||
|
||||
class PasswordChange(BaseModel):
|
||||
old_password: str
|
||||
new_password: str = Field(..., min_length=8, max_length=20)
|
||||
|
||||
|
||||
class JsonColorItem(BaseModel):
|
||||
"""单个色块的颜色数据"""
|
||||
id: int
|
||||
value: str
|
||||
|
||||
|
||||
class JsonDataRequest(BaseModel):
|
||||
"""JSON数据尿检请求 - 与txt文件格式一致"""
|
||||
extend: Optional[Dict[str, Any]] = Field(default_factory=dict)
|
||||
data: List[List[JsonColorItem]] = Field(default_factory=list)
|
||||
project_id: Optional[int] = None
|
||||
@@ -0,0 +1,22 @@
|
||||
"""SSO Cookie 本地验签 —— 与 SSO 中心共享 SECRET_KEY"""
|
||||
from fastapi import Request, HTTPException
|
||||
from jose import jwt, JWTError
|
||||
|
||||
# 必须与 SSO 中心 sso_config.py 完全一致
|
||||
SECRET_KEY = "your-secret-key-change-in-production"
|
||||
ALGORITHM = "HS256"
|
||||
|
||||
|
||||
def get_current_user_from_cookie(request: Request) -> dict:
|
||||
"""从请求 Cookie 中读取 access_token,本地验签后返回用户信息"""
|
||||
token = request.cookies.get("access_token")
|
||||
if not token:
|
||||
return None
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
username: str = payload.get("sub")
|
||||
if not username:
|
||||
return None
|
||||
return {"username": username}
|
||||
except JWTError:
|
||||
return None
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user