Files
guwangtu b91954df4a
CI / check (push) Failing after 15m48s
chore: initial open-source baseline v1.0.0
Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
2026-12-05 15:44:53 +00:00

1842 lines
64 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""医院审计管理系统 - FastAPI 后端服务"""
import os
import json
import uuid
from pathlib import Path
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
import uvicorn
from config import HOST, PORT, UPLOAD_DIR, BACKUP_DIR
from services import local_service as feishu
from services.local_service import TokenExpiredError
from services import llm_service as llm
from services import local_wiki_service as wiki
from services import web_search_service as web_search
from services import attachment_parser
app = FastAPI(title="医院审计管理系统")
# 允许通过 /static 访问的文件类型(防止数据库、源码等被直接下载)
_SAFE_STATIC_SUFFIXES = {
".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp",
".css", ".js", ".woff", ".woff2", ".ttf",
}
@app.middleware("http")
async def _block_unsafe_static(request, call_next):
"""/static 只放行图片/样式/脚本,避免 audit_data.db、*.py 等被下载"""
if request.url.path.startswith("/static/"):
suffix = os.path.splitext(request.url.path)[1].lower()
if suffix not in _SAFE_STATIC_SUFFIXES:
return JSONResponse(status_code=404, content={"detail": "Not Found"})
return await call_next(request)
# ====== 登录会话(Cookie + HMAC 签名,四套系统共享) ======
import auth_guard as auth
@app.middleware("http")
async def _auth_middleware(request, call_next):
resp = auth.guard(request)
if resp is not None:
return resp
return await call_next(request)
# ====== 辅助函数:构建分析内容(正文 + 附件)======
def _build_analysis_content(doc: dict) -> str:
"""从审计资料记录中构建分析所需的内容文本
优先级:
1. 优先使用正文内容
2. 正文为空时,尝试从附件提取内容
3. 附件也无法提取时,使用基本信息兜底
Args:
doc: 审计资料记录字典
Returns:
用于大模型分析的内容文本
"""
content = doc.get("正文内容") or ""
base_info = f"资料标题:{doc.get('资料标题') or ''}\n资料类型:{doc.get('资料类型') or ''}"
# 尝试从附件提取内容
attachment_content = ""
try:
attachment_content = attachment_parser.extract_from_doc_attachments(
doc, feishu.download_attachment
)
except Exception as e:
print(f"附件内容提取失败: {e}")
# 构建最终内容
if content.strip() and attachment_content.strip():
# 正文和附件都有内容,合并两者
return f"{base_info}\n\n## 正文内容\n{content}\n\n## 附件内容\n{attachment_content}"
elif content.strip():
# 只有正文
return f"{base_info}\n\n{content}"
elif attachment_content.strip():
# 正文为空,但附件有内容
return f"{base_info}\n\n{attachment_content}"
else:
# 都没有内容,使用基本信息兜底
return base_info
# 确保上传目录存在
os.makedirs(UPLOAD_DIR, exist_ok=True)
# ====== 全局异常处理 ======
@app.exception_handler(TokenExpiredError)
async def token_expired_handler(request, exc):
"""飞书 Token 过期:返回 401,前端据此展示友好提示"""
return JSONResponse(
status_code=401,
content={"detail": "token_expired", "message": str(exc)}
)
# ====== API 路由 ======
@app.get("/api/health")
async def health():
"""健康检查"""
return {"status": "ok"}
# -- 人员表 --
@app.get("/api/persons")
async def get_persons():
"""获取人员列表"""
try:
persons = feishu.list_persons()
return {"persons": persons}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/persons/{person_id}")
async def get_person(person_id: str):
"""获取单个人员"""
try:
person = feishu.get_person(person_id)
if not person:
raise HTTPException(status_code=404, detail="人员不存在")
return {"person": person}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/persons")
async def create_person(
name: str = Form(...),
dept: str = Form(...),
role: str = Form(...),
contact: str = Form("")
):
"""创建人员记录"""
try:
result = feishu.create_person(name, dept, role, contact)
return {"id": result.get("record_id"), "message": "人员创建成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/persons/{person_id}")
async def update_person(
person_id: str,
name: str = Form(""),
dept: str = Form(""),
role: str = Form(""),
contact: str = Form("")
):
"""更新人员记录"""
try:
kwargs = {}
if name: kwargs["name"] = name
if dept: kwargs["dept"] = dept
if role: kwargs["role"] = role
if contact: kwargs["contact"] = contact
result = feishu.update_person(person_id, **kwargs)
return {"id": result.get("record_id"), "message": "人员更新成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# -- 项目大类表 --
@app.get("/api/categories")
async def get_categories():
"""获取项目大类列表"""
try:
categories = feishu.list_categories()
return {"categories": categories}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/categories/{category_id}")
async def get_category(category_id: str):
"""获取单个项目大类"""
try:
category = feishu.get_category(category_id)
if not category:
raise HTTPException(status_code=404, detail="项目大类不存在")
return {"category": category}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/categories")
async def create_category(
name: str = Form(...),
description: str = Form(""),
status: str = Form("未开始"),
leader_id: str = Form("")
):
"""创建项目大类记录"""
try:
result = feishu.create_category(name, description, status, leader_id)
return {"id": result.get("record_id"), "message": "项目大类创建成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/categories/{category_id}")
async def update_category(
category_id: str,
name: str = Form(""),
description: str = Form(""),
status: str = Form(""),
leader_id: str = Form("")
):
"""更新项目大类记录"""
try:
kwargs = {}
if name: kwargs["name"] = name
if description: kwargs["description"] = description
if status: kwargs["status"] = status
if leader_id: kwargs["leader_id"] = leader_id
result = feishu.update_category(category_id, **kwargs)
return {"id": result.get("record_id"), "message": "项目大类更新成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# -- 年度表 --
@app.get("/api/years")
async def get_years():
"""获取年度列表"""
try:
years = feishu.list_years()
return {"years": years}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/years/{year_id}")
async def get_year(year_id: str):
"""获取单个年度"""
try:
year = feishu.get_year(year_id)
if not year:
raise HTTPException(status_code=404, detail="年度不存在")
return {"year": year}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/years")
async def create_year(
year: str = Form(...),
name: str = Form(...),
goal: str = Form(""),
budget: float = Form(0),
status: str = Form("未开始"),
category_id: str = Form(""),
leader_id: str = Form("")
):
"""创建年度记录"""
try:
result = feishu.create_year(year, name, goal, budget, status, category_id, leader_id)
return {"id": result.get("record_id"), "message": "年度创建成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/years/{year_id}")
async def update_year(
year_id: str,
year: str = Form(""),
name: str = Form(""),
goal: str = Form(""),
budget: float = Form(None),
status: str = Form(""),
category_id: str = Form(""),
leader_id: str = Form("")
):
"""更新年度记录"""
try:
kwargs = {}
if year: kwargs["year"] = year
if name: kwargs["name"] = name
if goal: kwargs["goal"] = goal
if budget is not None: kwargs["budget"] = budget
if status: kwargs["status"] = status
if category_id: kwargs["category_id"] = category_id
if leader_id: kwargs["leader_id"] = leader_id
result = feishu.update_year(year_id, **kwargs)
return {"id": result.get("record_id"), "message": "年度更新成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# -- 项目表 --
@app.get("/api/projects")
async def get_projects():
"""获取项目列表"""
try:
projects = feishu.list_projects()
return {"projects": projects}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/projects/{project_id}")
async def get_project(project_id: str):
"""获取单个项目详情"""
try:
project = feishu.get_project(project_id)
if not project:
raise HTTPException(status_code=404, detail="项目不存在")
return {"project": project}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/projects")
async def create_project(
name: str = Form(...),
description: str = Form(""),
status: str = Form("未开始"),
priority: str = Form("P2"),
start_date: str = Form(""),
end_date: str = Form(""),
budget: float = Form(0),
risks: str = Form(""),
leader_id: str = Form(""),
year_id: str = Form(""),
category_id: str = Form("")
):
"""创建项目记录"""
try:
result = feishu.create_project(
name, description, status, priority,
start_date, end_date, budget, risks,
leader_id, None, year_id, category_id
)
return {"id": result.get("record_id"), "message": "项目创建成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/projects/{project_id}")
async def update_project(
project_id: str,
name: str = Form(""),
description: str = Form(""),
status: str = Form(""),
priority: str = Form(""),
start_date: str = Form(""),
end_date: str = Form(""),
budget: float = Form(None),
risks: str = Form(""),
leader_id: str = Form(""),
year_id: str = Form(""),
category_id: str = Form("")
):
"""更新项目记录"""
try:
kwargs = {}
if name: kwargs["name"] = name
if description: kwargs["description"] = description
if status: kwargs["status"] = status
if priority: kwargs["priority"] = priority
if start_date: kwargs["start_date"] = start_date
if end_date: kwargs["end_date"] = end_date
if budget is not None: kwargs["budget"] = budget
if risks: kwargs["risks"] = risks
if leader_id: kwargs["leader_id"] = leader_id
if year_id: kwargs["year_id"] = year_id
if category_id: kwargs["category_id"] = category_id
result = feishu.update_project(project_id, **kwargs)
return {"id": result.get("record_id"), "message": "项目更新成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# -- 项目步骤表 --
@app.get("/api/steps")
async def get_steps():
"""获取项目步骤列表"""
try:
steps = feishu.list_steps()
return {"steps": steps}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/steps/{step_id}")
async def get_step(step_id: str):
"""获取单个项目步骤"""
try:
step = feishu.get_step(step_id)
if not step:
raise HTTPException(status_code=404, detail="项目步骤不存在")
return {"step": step}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/steps")
async def create_step(
name: str = Form(...),
status: str = Form("待开始"),
priority: str = Form("P2"),
start_date: str = Form(""),
end_date: str = Form(""),
progress: float = Form(0),
deliverable: str = Form(""),
remark: str = Form(""),
leader_id: str = Form(""),
project_id: str = Form(""),
prev_step_id: str = Form("")
):
"""创建项目步骤记录"""
try:
result = feishu.create_step(
name, status, priority, start_date, end_date,
progress, deliverable, remark, leader_id, project_id, prev_step_id
)
return {"id": result.get("record_id"), "message": "项目步骤创建成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/steps/{step_id}")
async def update_step(
step_id: str,
name: str = Form(""),
status: str = Form(""),
priority: str = Form(""),
start_date: str = Form(""),
end_date: str = Form(""),
progress: float = Form(None),
deliverable: str = Form(""),
remark: str = Form(""),
leader_id: str = Form(""),
project_id: str = Form(""),
prev_step_id: str = Form("")
):
"""更新项目步骤记录"""
try:
kwargs = {}
if name: kwargs["name"] = name
if status: kwargs["status"] = status
if priority: kwargs["priority"] = priority
if start_date: kwargs["start_date"] = start_date
if end_date: kwargs["end_date"] = end_date
if progress is not None: kwargs["progress"] = progress
if deliverable: kwargs["deliverable"] = deliverable
if remark: kwargs["remark"] = remark
if leader_id: kwargs["leader_id"] = leader_id
if project_id: kwargs["project_id"] = project_id
if prev_step_id: kwargs["prev_step_id"] = prev_step_id
result = feishu.update_step(step_id, **kwargs)
return {"id": result.get("record_id"), "message": "项目步骤更新成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# -- 审计资料相关 --
@app.get("/api/docs")
async def get_docs():
"""获取审计资料列表"""
try:
docs = feishu.attach_workflow_meta(feishu.list_audit_docs())
return {"docs": docs}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/docs/{doc_id}")
async def get_doc(doc_id: str):
"""获取单个审计资料"""
try:
doc = feishu.get_audit_doc(doc_id)
if not doc:
raise HTTPException(status_code=404, detail="资料不存在")
doc = feishu.attach_workflow_meta([doc])[0]
return {"doc": doc}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/docs")
async def create_doc(
title: str = Form(...),
doc_type: str = Form(...),
project_id: str = Form(...),
content: str = Form(""),
step_id: str = Form(""),
file: UploadFile = None
):
"""创建审计资料(可同时上传附件)"""
try:
# 1. 创建记录
result = feishu.create_audit_doc(title, doc_type, project_id, content, step_id)
doc_id = result.get("record_id") or result.get("id", "")
# 2. 上传附件(如果有)
file_info = None
if file and file.filename:
file_path = os.path.join(UPLOAD_DIR, file.filename)
with open(file_path, "wb") as f:
f.write(await file.read())
try:
upload_result = feishu.upload_attachment(doc_id, file_path)
file_info = {"filename": file.filename, "result": upload_result}
finally:
if os.path.exists(file_path):
os.remove(file_path)
return {"id": doc_id, "file": file_info, "message": "资料创建成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/docs/{doc_id}")
async def update_doc(
doc_id: str,
title: str = Form(""),
doc_type: str = Form(""),
content: str = Form(""),
project_id: str = Form(""),
step_id: str = Form("")
):
"""更新审计资料"""
try:
kwargs = {}
if title:
kwargs["title"] = title
if doc_type:
kwargs["doc_type"] = doc_type
if content:
kwargs["content"] = content
if project_id:
kwargs["project_id"] = project_id
# step_id 始终传递:空字符串表示清除步骤关联
kwargs["step_id"] = step_id
result = feishu.update_audit_doc(doc_id, **kwargs)
return {"id": result.get("record_id"), "message": "资料更新成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/docs/{doc_id}/upload")
async def upload_doc_attachment(doc_id: str, file: UploadFile = File(...)):
"""为已有审计资料上传附件"""
try:
file_path = os.path.join(UPLOAD_DIR, file.filename)
with open(file_path, "wb") as f:
f.write(await file.read())
try:
upload_result = feishu.upload_attachment(doc_id, file_path)
return {"message": "附件上传成功", "file": file.filename, "result": upload_result}
finally:
if os.path.exists(file_path):
os.remove(file_path)
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/docs/{doc_id}/download")
async def download_doc_attachment(doc_id: str, file_token: str):
"""下载审计资料附件"""
try:
# 下载到临时目录
download_dir = os.path.join(UPLOAD_DIR, "downloads")
os.makedirs(download_dir, exist_ok=True)
saved_path = feishu.download_attachment(doc_id, file_token, download_dir)
# 如果返回的是相对路径,转为绝对路径
if saved_path and not os.path.isabs(saved_path):
saved_path = os.path.join(download_dir, saved_path)
# 如果没返回路径,在下载目录中查找最新文件
if not saved_path or not os.path.exists(saved_path):
files = sorted(os.listdir(download_dir), key=lambda f: os.path.getmtime(os.path.join(download_dir, f)), reverse=True)
if files:
saved_path = os.path.join(download_dir, files[0])
else:
raise HTTPException(status_code=404, detail="附件下载失败")
return FileResponse(saved_path, filename=os.path.basename(saved_path))
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/docs/{doc_id}")
async def delete_doc(doc_id: str):
"""删除审计资料,并级联删除关联的分析结果"""
try:
result = feishu.delete_audit_doc_with_cascade(doc_id)
deleted_count = len(result.get("deleted_results", []))
msg = f"删除成功"
if deleted_count > 0:
msg += f",已同步删除 {deleted_count} 条关联分析结果"
return {"message": msg, "deleted_results": result.get("deleted_results", [])}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# -- 大模型分析相关 --
@app.post("/api/analyze/{doc_id}")
async def analyze_doc(doc_id: str, wiki_space_ids: str = Form(""), user_guidance: str = Form("")):
"""对审计资料进行大模型分析,并将结果写入分析结果表(一对一,重新分析时覆盖旧结果)
Args:
doc_id: 审计资料ID
wiki_space_ids: 知识空间ID列表,逗号分隔(可选),用于引用知识库制度作为分析依据
user_guidance: 用户自定义指导文本(可选),如只分析某张表、指定输出风格等
"""
try:
# 1. 获取资料内容
doc = feishu.get_audit_doc(doc_id)
if not doc:
raise HTTPException(status_code=404, detail="资料不存在")
# 构建分析内容(正文 + 附件)
content = _build_analysis_content(doc)
# 2. 更新状态为"分析中"
feishu.update_doc_status(doc_id, "分析中")
# 3. 删除该资料关联的旧分析结果(确保一对一)
for r in feishu.list_analysis_results():
refs = r.get("关联资料") or []
if doc_id in refs:
try:
feishu._delete_record(feishu.TABLE_ANALYSIS_RESULT, r["id"])
except Exception:
pass # 旧结果删除失败不影响新分析
# 4. 构建知识库上下文(如果用户选择了知识空间)
knowledge_context = ""
if wiki_space_ids:
space_id_list = [s.strip() for s in wiki_space_ids.split(",") if s.strip()]
if space_id_list:
try:
knowledge_context = wiki.build_knowledge_context(space_id_list)
except Exception as e:
# 知识库获取失败不影响主流程,继续无知识库分析
print(f"知识库上下文获取失败: {e}")
# 5. 调用大模型分析(传入知识库上下文和用户指导)
result = llm.analyze_audit_content(content, knowledge_context, user_guidance)
# 6. 将结果写入分析结果表
feishu.create_analysis_result(
doc_id=doc_id,
analysis_type=result["analysis_type"],
summary=result["summary"],
risk_level=result["risk_level"],
findings=result["findings"],
suggestions=result["suggestions"],
raw_output=result.get("raw_output", result["summary"])
)
# 7. 更新资料状态为"已完成"
feishu.update_doc_status(doc_id, "已完成")
return {
"message": "分析完成",
"analysis_type": result["analysis_type"],
"summary": result["summary"],
"risk_level": result["risk_level"],
"findings": result["findings"],
"suggestions": result["suggestions"],
"references": result.get("references", ""),
"knowledge_used": bool(knowledge_context)
}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
# 分析失败,恢复状态
try:
feishu.update_doc_status(doc_id, "待分析")
except Exception:
pass
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analyze-combined/{doc_id}")
async def analyze_doc_combined(doc_id: str, wiki_space_ids: str = Form(""), user_guidance: str = Form("")):
"""综合分析:先分别执行直接分析和引用知识库分析,再用大模型整合两者结果
Args:
doc_id: 审计资料ID
wiki_space_ids: 知识空间ID列表,逗号分隔
user_guidance: 用户自定义指导文本(可选)
"""
try:
# 1. 获取资料内容
doc = feishu.get_audit_doc(doc_id)
if not doc:
raise HTTPException(status_code=404, detail="资料不存在")
# 构建分析内容(正文 + 附件)
content = _build_analysis_content(doc)
# 2. 更新状态
feishu.update_doc_status(doc_id, "分析中")
# 3. 删除旧分析结果
for r in feishu.list_analysis_results():
refs = r.get("关联资料") or []
if doc_id in refs:
try:
feishu._delete_record(feishu.TABLE_ANALYSIS_RESULT, r["id"])
except Exception:
pass
# 4. 构建知识库上下文
knowledge_context = ""
if wiki_space_ids:
space_id_list = [s.strip() for s in wiki_space_ids.split(",") if s.strip()]
if space_id_list:
try:
knowledge_context = wiki.build_knowledge_context(space_id_list)
except Exception as e:
print(f"知识库上下文获取失败: {e}")
if not knowledge_context:
raise HTTPException(status_code=400, detail="综合分析需要选择至少一个知识空间")
# 5. 第一步:直接分析(不引用知识库,但含用户指导)
plain_result = llm.analyze_audit_content(content, "", user_guidance)
# 6. 第二步:引用知识库分析(含用户指导)
wiki_result = llm.analyze_audit_content(content, knowledge_context, user_guidance)
# 7. 第三步:整合两次分析结果
merged = llm.merge_analyses(content, plain_result, wiki_result)
# 8. 将综合结果写入分析结果表
feishu.create_analysis_result(
doc_id=doc_id,
analysis_type=merged["analysis_type"],
summary=merged["summary"],
risk_level=merged["risk_level"],
findings=merged["findings"],
suggestions=merged["suggestions"],
raw_output=merged.get("raw_output", merged["summary"])
)
# 9. 更新资料状态
feishu.update_doc_status(doc_id, "已完成")
return {
"message": "综合分析完成",
"analysis_type": merged["analysis_type"],
"summary": merged["summary"],
"risk_level": merged["risk_level"],
"findings": merged["findings"],
"suggestions": merged["suggestions"],
"references": merged.get("references", ""),
"knowledge_used": True,
"combined": True
}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
try:
feishu.update_doc_status(doc_id, "待分析")
except Exception:
pass
raise HTTPException(status_code=500, detail=str(e))
# -- 分析结果相关 --
@app.get("/api/results")
async def get_results():
"""获取所有分析结果"""
try:
results = feishu.list_analysis_results()
return {"results": results}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/results/{result_id}")
async def get_result(result_id: str):
"""获取单个分析结果"""
try:
result = feishu.get_analysis_result(result_id)
if not result:
raise HTTPException(status_code=404, detail="分析结果不存在")
return {"result": result}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/results/{result_id}")
async def update_result(
result_id: str,
analysis_type: str = Form(""),
summary: str = Form(""),
risk_level: str = Form(""),
findings: str = Form(""),
suggestions: str = Form(""),
raw_output: str = Form("")
):
"""更新分析结果"""
try:
kwargs = {}
if analysis_type: kwargs["analysis_type"] = analysis_type
if summary: kwargs["summary"] = summary
if risk_level: kwargs["risk_level"] = risk_level
if findings: kwargs["findings"] = findings
if suggestions: kwargs["suggestions"] = suggestions
if raw_output: kwargs["raw_output"] = raw_output
result = feishu.update_analysis_result(result_id, **kwargs)
return {"id": result.get("record_id"), "message": "分析结果更新成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/results/{result_id}")
async def delete_result(result_id: str):
"""删除单条分析结果(不动审计资料;资料状态回退为待分析)"""
try:
ok = feishu.delete_analysis_result(result_id)
if not ok:
raise HTTPException(status_code=404, detail="分析结果不存在")
return {"message": "分析结果已删除"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# -- 通用删除与关联检查 --
TABLE_MAP = {
"persons": (feishu.TABLE_PERSON, "person"),
"categories": (feishu.TABLE_CATEGORY, "category"),
"years": (feishu.TABLE_YEAR, "year"),
"projects": (feishu.TABLE_PROJECT, "project"),
"steps": (feishu.TABLE_STEP, "step"),
"docs": (feishu.TABLE_AUDIT_DOC, "audit_doc"),
}
@app.get("/api/{table}/{record_id}/related")
async def get_related_records(table: str, record_id: str):
"""获取指定记录的关联信息"""
if table not in TABLE_MAP:
raise HTTPException(status_code=404, detail="表不存在")
_, table_key = TABLE_MAP[table]
try:
related = feishu.check_related_records(record_id, table_key)
return {"related": related}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/{table}/{record_id}")
async def delete_record(table: str, record_id: str):
"""删除记录(会先检查关联)"""
if table not in TABLE_MAP:
raise HTTPException(status_code=404, detail="表不存在")
table_id, table_key = TABLE_MAP[table]
try:
related = feishu.check_related_records(record_id, table_key)
if related:
raise HTTPException(
status_code=400,
detail={"message": "存在关联记录,无法删除", "related": related}
)
feishu._delete_record(table_id, record_id)
return {"message": "删除成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/docs/{doc_id}/attachments/{file_token}")
async def delete_doc_attachment(doc_id: str, file_token: str):
"""删除审计资料中的指定附件"""
try:
feishu.remove_attachment(doc_id, file_token)
return {"message": "附件删除成功"}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 人员表操作 ======
@app.post("/api/backup")
async def backup_project():
"""备份项目代码到指定目录"""
import shutil
from datetime import datetime
try:
project_dir = Path(__file__).parent
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"hospital-audit-system-backup-{timestamp}"
backup_path = os.path.join(BACKUP_DIR, backup_name)
def ignore_pycache(dir, contents):
# 排除缓存、虚拟环境、上传文件,并防止把备份目录自身递归复制进去
skip = set()
for name in ('__pycache__', 'uploads', '.venv', 'venv', '.git'):
if name in contents:
skip.add(name)
if os.path.abspath(dir) == os.path.abspath(BACKUP_DIR):
skip.update(contents)
elif os.path.basename(os.path.abspath(BACKUP_DIR)) in contents:
skip.add(os.path.basename(os.path.abspath(BACKUP_DIR)))
return skip
os.makedirs(BACKUP_DIR, exist_ok=True)
shutil.copytree(project_dir, backup_path, ignore=ignore_pycache, dirs_exist_ok=True)
# 统计备份文件数
file_count = sum(len(files) for _, _, files in os.walk(backup_path))
return {
"message": "备份成功",
"backup_path": backup_path,
"file_count": file_count,
"timestamp": timestamp
}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/backups")
async def list_backups():
"""列出已有备份"""
try:
if not os.path.exists(BACKUP_DIR):
return {"backups": []}
backups = []
for name in sorted(os.listdir(BACKUP_DIR), reverse=True):
full_path = os.path.join(BACKUP_DIR, name)
if os.path.isdir(full_path) and name.startswith("hospital-audit-system-backup"):
import time
mtime = os.path.getmtime(full_path)
mtime_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(mtime))
file_count = sum(len(files) for _, _, files in os.walk(full_path))
backups.append({
"name": name,
"path": full_path,
"time": mtime_str,
"file_count": file_count
})
return {"backups": backups}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 知识库接口 ======
@app.get("/api/wiki/spaces")
async def get_wiki_spaces():
"""获取飞书知识空间列表"""
try:
spaces = wiki.list_spaces()
return {"spaces": spaces}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/wiki/spaces/{space_id}/nodes")
async def get_wiki_nodes(space_id: str):
"""获取知识空间下的文档节点列表"""
try:
nodes = wiki.list_nodes(space_id)
# 只返回基本信息,不包含完整内容
result = [{
"node_token": n["node_token"],
"title": n["title"],
"obj_type": n["obj_type"],
"has_child": n["has_child"],
"parent_node_token": n["parent_node_token"]
} for n in nodes]
return {"nodes": result, "count": len(result)}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 审计实施方案生成 ======
# 保存最近生成的方案(供下载使用)
_last_plan = {}
@app.post("/api/audit-plan/generate")
async def generate_audit_plan(
project_desc: str = Form(...),
wiki_space_ids: str = Form("")
):
"""生成审计实施方案
流程:
1. 从选中的知识库空间获取内部制度参考材料
2. 根据项目描述搜索网络获取外部法规/最佳实践补充材料
3. 调用大模型整合生成详尽的审计实施方案
Args:
project_desc: 审计项目描述
wiki_space_ids: 知识空间ID列表,逗号分隔(可选)
"""
try:
# 1. 构建知识库上下文
knowledge_content = ""
if wiki_space_ids:
space_id_list = [s.strip() for s in wiki_space_ids.split(",") if s.strip()]
if space_id_list:
try:
knowledge_content = wiki.build_knowledge_context(space_id_list)
except Exception as e:
print(f"知识库上下文获取失败: {e}")
# 2. 构建网络搜索补充材料
# 从项目描述中提取关键词进行搜索
search_query = f"医院审计 {project_desc[:50]} 法规 制度"
web_content = ""
try:
web_content = web_search.build_web_context(search_query)
except Exception as e:
print(f"网络搜索失败: {e}")
# 3. 调用大模型生成方案
plan = llm.generate_audit_plan(project_desc, knowledge_content, web_content)
# 4. 保存方案供下载
plan_id = str(uuid.uuid4())[:8]
_last_plan[plan_id] = {
"title": plan["title"],
"content": plan["content"],
"references": plan.get("references", ""),
"project_desc": project_desc
}
return {
"plan_id": plan_id,
"title": plan["title"],
"content": plan["content"],
"references": plan.get("references", ""),
"knowledge_used": bool(knowledge_content),
"web_used": bool(web_content),
"message": "审计实施方案生成完成"
}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/audit-plan/{plan_id}/download")
async def download_audit_plan(plan_id: str):
"""下载审计实施方案为 Markdown 文件"""
if plan_id not in _last_plan:
raise HTTPException(status_code=404, detail="方案不存在或已过期,请重新生成")
plan = _last_plan[plan_id]
# 构建 Markdown 文件内容
md_content = f"# {plan['title']}\n\n"
md_content += f"> 生成时间:{__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M')}\n\n"
md_content += f"**项目描述:** {plan['project_desc']}\n\n"
md_content += "---\n\n"
md_content += plan["content"]
if plan.get("references"):
md_content += "\n\n---\n\n"
md_content += "## 参考资料\n\n"
md_content += plan["references"]
# 保存到临时文件
output_dir = os.path.join(UPLOAD_DIR, "plans")
os.makedirs(output_dir, exist_ok=True)
safe_title = "".join(c for c in plan["title"] if c.isalnum() or c in "-_" or '\u4e00' <= c <= '\u9fff')
filename = f"{safe_title}_{plan_id}.md"
file_path = os.path.join(output_dir, filename)
with open(file_path, "w", encoding="utf-8") as f:
f.write(md_content)
return FileResponse(file_path, filename=filename, media_type="text/markdown")
@app.post("/api/audit-plan/{plan_id}/download-docx")
async def download_audit_plan_docx(plan_id: str):
"""下载审计实施方案为 Word 文档"""
if plan_id not in _last_plan:
raise HTTPException(status_code=404, detail="方案不存在或已过期,请重新生成")
plan = _last_plan[plan_id]
output_dir = os.path.join(UPLOAD_DIR, "plans")
os.makedirs(output_dir, exist_ok=True)
safe_title = "".join(c for c in plan["title"] if c.isalnum() or c in "-_" or '\u4e00' <= c <= '\u9fff')
filename = f"{safe_title}_{plan_id}.docx"
file_path = os.path.join(output_dir, filename)
try:
from docx import Document
from docx.shared import Pt, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document()
# 设置默认字体
style = doc.styles['Normal']
font = style.font
font.name = '宋体'
font.size = Pt(12)
# 标题
title_para = doc.add_heading(plan["title"], level=0)
title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 项目描述
doc.add_paragraph(f"项目描述:{plan['project_desc']}")
# 正文内容(按 Markdown 章节解析)
content = plan["content"]
lines = content.split("\n")
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith("## "):
doc.add_heading(line[3:].strip(), level=1)
elif line.startswith("### "):
doc.add_heading(line[4:].strip(), level=2)
elif line.startswith("# "):
doc.add_heading(line[2:].strip(), level=0)
elif line.startswith("- ") or line.startswith("* "):
doc.add_paragraph(line[2:].strip(), style='List Bullet')
elif line[0].isdigit() and "." in line[:4]:
# 数字编号列表
idx = line.find(".")
if idx > 0:
doc.add_paragraph(line[idx+1:].strip(), style='List Number')
else:
doc.add_paragraph(line)
# 参考资料
if plan.get("references"):
doc.add_heading("参考资料", level=1)
for ref in plan["references"].split("\n"):
ref = ref.strip()
if ref:
doc.add_paragraph(ref, style='List Bullet')
doc.save(file_path)
return FileResponse(file_path, filename=filename,
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
except ImportError:
# python-docx 未安装,回退到 Markdown 下载
raise HTTPException(status_code=400, detail="Word 文档生成需要安装 python-docx 库,请使用 Markdown 下载")
except Exception as e:
raise HTTPException(status_code=500, detail=f"文档生成失败: {str(e)}")
# ====== 审计报告生成 ======
# 保存最近生成的报告(供下载使用)
_last_report = {}
@app.get("/api/audit-report/project-docs/{project_id}")
async def get_project_docs_and_results(project_id: str):
"""获取项目下所有审计资料和分析结果,供用户勾选"""
try:
project = feishu.get_project(project_id)
if not project:
raise HTTPException(status_code=404, detail="项目不存在")
project_name = project.get("项目名称", "")
# 获取该项目下所有步骤
all_steps = feishu.list_steps()
proj_steps = [s for s in all_steps if project_id in (s.get("所属项目") or [])]
proj_step_ids = {s["id"] for s in proj_steps}
step_map = {s["id"]: s.get("步骤名称", "未命名步骤") for s in proj_steps}
# 获取该项目下所有审计资料
all_docs = feishu.list_audit_docs()
proj_docs = [d for d in all_docs if any(sid in proj_step_ids for sid in (d.get("所属步骤") or []))]
# 获取这些资料的分析结果
all_results = feishu.list_analysis_results()
proj_doc_ids = {d["id"] for d in proj_docs}
proj_results = []
for r in all_results:
doc_refs = r.get("关联资料") or []
if any(rid in proj_doc_ids for rid in doc_refs):
proj_results.append(r)
return {
"project_name": project_name,
"docs": [
{
"id": d["id"],
"title": d.get("资料标题", "未命名"),
"type": d.get("资料类型", ""),
"status": d.get("资料状态", ""),
"step_names": [step_map.get(sid, "") for sid in (d.get("所属步骤") or []) if sid in step_map]
}
for d in proj_docs
],
"results": [
{
"id": r["id"],
"analysis_type": r.get("分析类型", ""),
"risk_level": r.get("风险等级", ""),
"summary": r.get("分析摘要", ""),
"doc_ids": r.get("关联资料") or []
}
for r in proj_results
]
}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
def _build_docx_from_markdown(title: str, subtitle: str, content: str, references: str, file_path: str):
"""通用的 Markdown 转 Word 文档生成函数"""
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document()
style = doc.styles['Normal']
style.font.name = '宋体'
style.font.size = Pt(12)
# 标题
title_para = doc.add_heading(title, level=0)
title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 副标题/描述
if subtitle:
doc.add_paragraph(subtitle)
# 正文内容(按 Markdown 章节解析)
lines = content.split("\n")
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith("## "):
doc.add_heading(line[3:].strip(), level=1)
elif line.startswith("### "):
doc.add_heading(line[4:].strip(), level=2)
elif line.startswith("# "):
doc.add_heading(line[2:].strip(), level=0)
elif line.startswith("- ") or line.startswith("* "):
doc.add_paragraph(line[2:].strip(), style='List Bullet')
elif len(line) > 0 and line[0].isdigit() and "." in line[:4]:
idx = line.find(".")
if idx > 0:
doc.add_paragraph(line[idx+1:].strip(), style='List Number')
else:
doc.add_paragraph(line)
# 参考资料
if references:
doc.add_heading("参考资料", level=1)
for ref in references.split("\n"):
ref = ref.strip()
if ref:
doc.add_paragraph(ref, style='List Bullet')
doc.save(file_path)
@app.post("/api/audit-report/generate")
async def generate_audit_report_api(
project_id: str = Form(...),
doc_ids: str = Form(""),
result_ids: str = Form(""),
report_desc: str = Form(""),
wiki_space_ids: str = Form("")
):
"""生成审计报告
流程:
1. 获取用户选中的审计资料和分析结果
2. 从选中的知识库空间获取内部制度参考材料
3. 根据项目信息搜索网络获取外部法规/最佳实践补充材料
4. 调用大模型整合生成详尽的审计报告
Args:
project_id: 项目ID
doc_ids: 用户选中的审计资料ID列表,逗号分隔
result_ids: 用户选中的分析结果ID列表,逗号分隔
report_desc: 报告要求和格式描述
wiki_space_ids: 知识空间ID列表,逗号分隔(可选)
"""
try:
# 1. 获取项目信息
project = feishu.get_project(project_id)
if not project:
raise HTTPException(status_code=404, detail="项目不存在")
project_name = project.get("项目名称", "")
year_name = ""
category_name = ""
yr_ids = project.get("所属年度") or []
if yr_ids:
year = feishu.get_year(yr_ids[0])
if year:
year_name = year.get("年度名称") or year.get("年度", "")
cat_ids = year.get("所属大类") or []
if cat_ids:
cat = feishu.get_category(cat_ids[0])
if cat:
category_name = cat.get("大类名称", "")
# 2. 获取项目下所有步骤名称映射
all_steps = feishu.list_steps()
proj_steps = [s for s in all_steps if project_id in (s.get("所属项目") or [])]
step_map = {s["id"]: s.get("步骤名称", "未命名步骤") for s in proj_steps}
# 3. 获取用户选中的审计资料
selected_doc_ids = set(s.strip() for s in doc_ids.split(",") if s.strip())
all_docs = feishu.list_audit_docs()
proj_step_ids = set(step_map.keys())
proj_docs = [d for d in all_docs if any(sid in proj_step_ids for sid in (d.get("所属步骤") or []))]
selected_docs = [d for d in proj_docs if d["id"] in selected_doc_ids] if selected_doc_ids else proj_docs
# 4. 获取用户选中的分析结果
selected_result_ids = set(s.strip() for s in result_ids.split(",") if s.strip())
all_results = feishu.list_analysis_results()
proj_doc_ids = {d["id"] for d in proj_docs}
proj_results = []
for r in all_results:
doc_refs = r.get("关联资料") or []
if any(rid in proj_doc_ids for rid in doc_refs):
proj_results.append(r)
selected_results = [r for r in proj_results if r["id"] in selected_result_ids] if selected_result_ids else proj_results
# 5. 构建审计资料和分析结果汇总文本
docs_text_parts = []
for i, d in enumerate(selected_docs, 1):
title = d.get("资料标题", "未命名")
doc_type = d.get("资料类型", "")
doc_content = _build_analysis_content(d)
status = d.get("资料状态", "")
step_names = [step_map.get(sid, "") for sid in (d.get("所属步骤") or []) if sid in step_map]
step_label = f"(步骤:{'、'.join(step_names)})" if step_names else ""
docs_text_parts.append(f"### 资料{i}:{title}{step_label}\n类型:{doc_type} | 状态:{status}\n内容:\n{doc_content}")
# 找到该资料的分析结果(仅选中的)
for r in selected_results:
r_refs = r.get("关联资料") or []
if d["id"] in r_refs:
docs_text_parts.append(
f"分析结果:\n"
f"- 分析类型:{r.get('分析类型', '')}\n"
f"- 风险等级:{r.get('风险等级', '')}\n"
f"- 分析摘要:{r.get('分析摘要', '')}\n"
f"- 关键发现:{r.get('关键发现', '')}\n"
f"- 改进建议:{r.get('改进建议', '')}"
)
docs_and_results = "\n\n---\n\n".join(docs_text_parts) if docs_text_parts else ""
if not selected_docs:
raise HTTPException(status_code=400, detail="该项目下暂无审计资料,无法生成报告")
# 6. 构建知识库上下文
knowledge_content = ""
if wiki_space_ids:
space_id_list = [s.strip() for s in wiki_space_ids.split(",") if s.strip()]
if space_id_list:
try:
knowledge_content = wiki.build_knowledge_context(space_id_list)
except Exception as e:
print(f"知识库上下文获取失败: {e}")
# 7. 构建网络搜索补充材料
search_query = f"医院审计 {project_name} 报告 法规"
web_content = ""
try:
web_content = web_search.build_web_context(search_query)
except Exception as e:
print(f"网络搜索失败: {e}")
# 8. 调用大模型生成报告
report = llm.generate_audit_report(
step_name="",
project_name=project_name,
year_name=year_name,
category_name=category_name,
docs_and_results=docs_and_results,
report_desc=report_desc,
knowledge_content=knowledge_content,
web_content=web_content
)
# 9. 保存报告供下载
report_id = str(uuid.uuid4())[:8]
_last_report[report_id] = {
"title": report["title"],
"content": report["content"],
"references": report.get("references", ""),
"project_name": project_name,
"doc_count": len(selected_docs),
"result_count": len(selected_results)
}
return {
"report_id": report_id,
"title": report["title"],
"content": report["content"],
"references": report.get("references", ""),
"knowledge_used": bool(knowledge_content),
"web_used": bool(web_content),
"doc_count": len(selected_docs),
"result_count": len(selected_results),
"message": "审计报告生成完成"
}
except HTTPException:
raise
except TokenExpiredError:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/audit-report/{report_id}/download")
async def download_audit_report(report_id: str):
"""下载审计报告为 Markdown 文件"""
if report_id not in _last_report:
raise HTTPException(status_code=404, detail="报告不存在或已过期,请重新生成")
report = _last_report[report_id]
md_content = f"# {report['title']}\n\n"
md_content += f"> 生成时间:{__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M')}\n\n"
md_content += f"**所属项目:** {report.get('project_name', '')}"
md_content += f"\n**引用审计资料:** {report['doc_count']} 份 | **分析结果:** {report['result_count']} 条\n\n"
md_content += "---\n\n"
md_content += report["content"]
if report.get("references"):
md_content += "\n\n---\n\n"
md_content += "## 参考资料\n\n"
md_content += report["references"]
output_dir = os.path.join(UPLOAD_DIR, "reports")
os.makedirs(output_dir, exist_ok=True)
safe_title = "".join(c for c in report["title"] if c.isalnum() or c in "-_" or '\u4e00' <= c <= '\u9fff')
filename = f"{safe_title}_{report_id}.md"
file_path = os.path.join(output_dir, filename)
with open(file_path, "w", encoding="utf-8") as f:
f.write(md_content)
return FileResponse(file_path, filename=filename, media_type="text/markdown")
@app.post("/api/audit-report/{report_id}/download-docx")
async def download_audit_report_docx(report_id: str):
"""下载审计报告为 Word 文档"""
if report_id not in _last_report:
raise HTTPException(status_code=404, detail="报告不存在或已过期,请重新生成")
report = _last_report[report_id]
output_dir = os.path.join(UPLOAD_DIR, "reports")
os.makedirs(output_dir, exist_ok=True)
safe_title = "".join(c for c in report["title"] if c.isalnum() or c in "-_" or '\u4e00' <= c <= '\u9fff')
filename = f"{safe_title}_{report_id}.docx"
file_path = os.path.join(output_dir, filename)
try:
subtitle = f"所属项目:{report.get('project_name', '')}"
subtitle += f"\n引用审计资料:{report['doc_count']} 份 | 分析结果:{report['result_count']} 条"
_build_docx_from_markdown(
title=report["title"],
subtitle=subtitle,
content=report["content"],
references=report.get("references", ""),
file_path=file_path
)
return FileResponse(file_path, filename=filename,
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
except ImportError:
raise HTTPException(status_code=400, detail="Word 文档生成需要安装 python-docx 库,请使用 Markdown 下载")
except Exception as e:
raise HTTPException(status_code=500, detail=f"文档生成失败: {str(e)}")
# ====== 前端页面 ======
app.mount("/static", StaticFiles(directory=str(Path(__file__).parent)), name="static")
@app.get("/", response_class=HTMLResponse)
async def index():
"""返回主页面"""
html_path = Path(__file__).parent / "templates" / "index.html"
return HTMLResponse(html_path.read_text(encoding="utf-8"))
@app.post("/api/restart")
async def restart_server():
"""重启后端服务(用于飞书重新授权后刷新 token)"""
import threading
import sys
import time
def _restart():
time.sleep(1) # 等待响应发送完成
import subprocess
# CREATE_NEW_PROCESS_GROUP 仅 Windows 支持,Linux 下传 0
creationflags = subprocess.CREATE_NEW_PROCESS_GROUP if os.name == "nt" else 0
subprocess.Popen(
[sys.executable] + sys.argv,
cwd=os.path.dirname(os.path.abspath(sys.argv[0] if sys.argv else __file__)),
creationflags=creationflags
)
os._exit(0)
threading.Thread(target=_restart, daemon=True).start()
return {"message": "服务正在重启,请稍候几秒后刷新页面"}
# ====== 文件预览接口 ======
@app.get("/api/preview/{file_token}")
async def preview_file(file_token: str):
"""预览附件文件:PDF直接返回,Word/Excel转HTML"""
from fastapi.responses import Response, FileResponse
import html as html_module
import base64
# 通过attachment id查找文件
try:
att_id = int(file_token)
except ValueError:
raise HTTPException(status_code=400, detail="无效的文件标识")
from services.local_service import _get_conn
conn = _get_conn()
row = conn.execute("SELECT * FROM attachments WHERE id = ?", (att_id,)).fetchone()
conn.close()
if not row:
raise HTTPException(status_code=404, detail="附件不存在")
file_path = row["file_path"]
if not file_path or not os.path.exists(file_path):
file_path = os.path.join(UPLOAD_DIR, row["file_name"])
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="文件不存在: " + row["file_name"])
filename = row["file_name"]
ext = os.path.splitext(filename)[1].lower()
if ext == ".pdf":
return FileResponse(file_path, media_type="application/pdf")
elif ext == ".docx":
from docx import Document
from docx.opc.constants import RELATIONSHIP_TYPE as RT
doc = Document(file_path)
html_parts = ['<!DOCTYPE html><html><head><meta charset="UTF-8">']
html_parts.append('<style>')
html_parts.append('body{font-family:"Microsoft YaHei",sans-serif;padding:20px;color:#333;max-width:900px;margin:0 auto;line-height:1.8;}')
html_parts.append('h1{font-size:22px;color:#1a5276;border-bottom:2px solid #2980b9;padding-bottom:8px;}')
html_parts.append('h2{font-size:18px;color:#2874a6;margin-top:20px;}')
html_parts.append('h3{font-size:16px;color:#2e86c1;}')
html_parts.append('p{margin:8px 0;text-align:justify;}')
html_parts.append('table{border-collapse:collapse;width:100%;margin:12px 0;}')
html_parts.append('td,th{border:1px solid #bbb;padding:6px 10px;font-size:14px;}')
html_parts.append('th{background:#d6eaf8;font-weight:bold;}')
html_parts.append('tr:nth-child(even){background:#f8f9fa;}')
html_parts.append('img{max-width:100%;height:auto;margin:10px 0;}')
html_parts.append('</style></head><body>')
# Extract images
image_map = {}
for rel in doc.part.rels.values():
if "image" in rel.reltype:
image_data = rel.target_part.blob
b64 = base64.b64encode(image_data).decode()
image_map[rel.rId] = f"data:image/png;base64,{b64}"
for para in doc.paragraphs:
text = para.text.strip()
if not text:
continue
style = para.style.name.lower()
if "heading 1" in style:
html_parts.append(f'<h1>{html_module.escape(text)}</h1>')
elif "heading 2" in style:
html_parts.append(f'<h2>{html_module.escape(text)}</h2>')
elif "heading 3" in style:
html_parts.append(f'<h3>{html_module.escape(text)}</h3>')
elif "title" in style:
html_parts.append(f'<h1>{html_module.escape(text)}</h1>')
else:
html_parts.append(f'<p>{html_module.escape(text)}</p>')
for table in doc.tables:
html_parts.append('<table>')
for row in table.rows:
html_parts.append('<tr>')
for cell in row.cells:
cell_text = cell.text.strip()
html_parts.append(f'<td>{html_module.escape(cell_text)}</td>')
html_parts.append('</tr>')
html_parts.append('</table>')
html_parts.append('</body></html>')
return HTMLResponse(content="".join(html_parts))
elif ext == ".xlsx":
from openpyxl import load_workbook
wb = load_workbook(file_path, data_only=True)
html_parts = ['<!DOCTYPE html><html><head><meta charset="UTF-8">']
html_parts.append('<style>')
html_parts.append('body{font-family:"Microsoft YaHei",sans-serif;padding:20px;color:#333;}')
html_parts.append('.sheet-tabs{display:flex;gap:4px;margin-bottom:12px;flex-wrap:wrap;}')
html_parts.append('.sheet-tab{padding:4px 14px;background:#e8e8e8;border-radius:4px 4px 0 0;cursor:pointer;font-size:13px;border:1px solid #ccc;}')
html_parts.append('.sheet-tab.active{background:#2980b9;color:white;border-color:#2980b9;}')
html_parts.append('.sheet-content{display:none;}')
html_parts.append('.sheet-content.active{display:block;}')
html_parts.append('table{border-collapse:collapse;width:100%;margin-bottom:20px;}')
html_parts.append('td,th{border:1px solid #ccc;padding:4px 8px;font-size:13px;}')
html_parts.append('th{background:#d6eaf8;font-weight:bold;}')
html_parts.append('tr:nth-child(even){background:#f8f9fa;}')
html_parts.append('.empty{color:#aaa;font-style:italic;}')
html_parts.append('</style></head><body>')
# Sheet tabs
html_parts.append('<div class="sheet-tabs">')
for i, name in enumerate(wb.sheetnames):
active = ' active' if i == 0 else ''
html_parts.append(f'<div class="sheet-tab{active}" onclick="switchSheet({i})">{html_module.escape(name)}</div>')
html_parts.append('</div>')
for i, name in enumerate(wb.sheetnames):
ws = wb[name]
active = ' active' if i == 0 else ''
html_parts.append(f'<div class="sheet-content{active}" id="sheet-{i}">')
html_parts.append('<table>')
for row in ws.iter_rows(values_only=True):
html_parts.append('<tr>')
for cell in row:
val = str(cell) if cell is not None else ''
if val:
html_parts.append(f'<td>{html_module.escape(val)}</td>')
else:
html_parts.append('<td class="empty"></td>')
html_parts.append('</tr>')
html_parts.append('</table>')
html_parts.append('</div>')
html_parts.append('<script>')
html_parts.append('function switchSheet(idx){')
html_parts.append('document.querySelectorAll(".sheet-tab").forEach((t,i)=>{t.classList.toggle("active",i===idx);});')
html_parts.append('document.querySelectorAll(".sheet-content").forEach((c,i)=>{c.classList.toggle("active",i===idx);});')
html_parts.append('}')
html_parts.append('</script>')
html_parts.append('</body></html>')
return HTMLResponse(content="".join(html_parts))
else:
raise HTTPException(status_code=400, detail=f"不支持预览 {ext} 格式的文件,请下载后查看")
if __name__ == "__main__":
print(f"🚀 医院审计管理系统启动中...")
print(f"📋 打开浏览器访问: http://localhost:{PORT}")
print(f"⚠️ 如需使用大模型分析,请先在 config.py 中配置 LLM_API_KEY")
uvicorn.run(app, host=HOST, port=PORT, log_level="info")