| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- """知识点路由"""
- from fastapi import APIRouter, Request, Query, Depends
- from app.database import get_connection, get_knowledge_tree, search_knowledge
- from app.routers.auth import verify_token
- router = APIRouter()
- @router.get("/knowledge/tree")
- def knowledge_tree(request: Request, _=Depends(verify_token)):
- """获取完整知识树"""
- config = request.app.state.config
- conn = get_connection(config.db_path)
- try:
- points = get_knowledge_tree(conn)
- # 构建树结构
- tree = _build_tree(points)
- return {"tree": tree, "total_leaves": len(points)}
- finally:
- conn.close()
- @router.get("/knowledge/search")
- def search_knowledge_api(
- request: Request,
- q: str = Query(..., min_length=1),
- limit: int = Query(30, le=100),
- _=Depends(verify_token),
- ):
- """搜索知识点"""
- config = request.app.state.config
- conn = get_connection(config.db_path)
- try:
- results = search_knowledge(conn, q, limit)
- return {"results": results}
- finally:
- conn.close()
- def _build_tree(points: list[dict]) -> list[dict]:
- """将扁平知识点列表构建为树结构"""
- tree = {}
- for p in points:
- code = p["code"]
- path = p.get("path", "")
- # path 格式: "章 > 节 > 小节 > 项 > 叶子"
- path_parts = path.split(" > ")
- parts = code.split(".")
- chapter_key = parts[0]
- section_key = f"{parts[0]}.{parts[1]}"
- sub_key = f"{parts[0]}.{parts[1]}.{parts[2]}"
- item_key = f"{parts[0]}.{parts[1]}.{parts[2]}.{parts[3]}"
- chapter_name = path_parts[0] if len(path_parts) > 0 else chapter_key
- section_name = path_parts[1] if len(path_parts) > 1 else section_key
- sub_name = path_parts[2] if len(path_parts) > 2 else sub_key
- item_name = path_parts[3] if len(path_parts) > 3 else item_key
- # 章
- if chapter_key not in tree:
- tree[chapter_key] = {"code": chapter_key, "name": chapter_name, "children": {}}
- # 节
- chapter = tree[chapter_key]["children"]
- if section_key not in chapter:
- chapter[section_key] = {"code": section_key, "name": section_name, "children": {}}
- # 小节
- section = chapter[section_key]["children"]
- if sub_key not in section:
- section[sub_key] = {"code": sub_key, "name": sub_name, "children": {}}
- # 项
- sub = section[sub_key]["children"]
- if item_key not in sub:
- sub[item_key] = {"code": item_key, "name": item_name, "children": []}
- # 叶子
- sub[item_key]["children"].append({
- "code": p["code"],
- "name": p["leaf_name"],
- "full_path": path,
- })
- # 转为有序列表
- def convert(d: dict) -> list:
- result = []
- for k in sorted(d.keys()):
- v = d[k]
- node = {"code": v["code"], "name": v["name"]}
- if "children" in v:
- if isinstance(v["children"], dict):
- node["children"] = convert(v["children"])
- else:
- node["children"] = v["children"]
- result.append(node)
- return result
- return convert(tree)
|