tree_html_back.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. from __future__ import annotations
  2. import html as html_lib
  3. from dataclasses import dataclass, field
  4. from pathlib import Path
  5. from sqlalchemy import text
  6. from examples.demand.db_manager import DatabaseManager
  7. db = DatabaseManager()
  8. SOURCE_TYPES = ["实质", "形式", "意图"]
  9. THEME = {
  10. "实质": {"root": "#e8841a", "mid": "#f0c389", "leaf": "#fae6cc", "line": "#d4a574"},
  11. "形式": {"root": "#5b9bd5", "mid": "#a3c9e8", "leaf": "#daeaf8", "line": "#8cb9dc"},
  12. "意图": {"root": "#70ad47", "mid": "#a9d18e", "leaf": "#dbefd0", "line": "#8fc270"},
  13. }
  14. @dataclass
  15. class CatNode:
  16. id: int
  17. name: str
  18. source_stable_id: int | None
  19. source_type: str
  20. description: str | None
  21. level: int | None
  22. parent_id: int | None
  23. element_count: int
  24. children: list[CatNode] = field(default_factory=list)
  25. @property
  26. def subtree_element_count(self) -> int:
  27. total = self.element_count or 0
  28. for c in self.children:
  29. total += c.subtree_element_count
  30. return total
  31. def fetch_categories(eid: int) -> list[dict]:
  32. session = db.get_session()
  33. try:
  34. rows = session.execute(
  35. text(
  36. "SELECT id, source_stable_id, source_type, name, description, "
  37. "level, parent_id, element_count "
  38. "FROM topic_pattern_category WHERE execution_id = :eid "
  39. "ORDER BY source_type, level, id"
  40. ),
  41. {"eid": eid},
  42. ).mappings().fetchall()
  43. return [dict(r) for r in rows]
  44. finally:
  45. session.close()
  46. def build_trees(categories: list[dict]) -> dict[str, list[CatNode]]:
  47. nodes: dict[int, CatNode] = {}
  48. for c in categories:
  49. n = CatNode(
  50. id=c["id"],
  51. name=c["name"],
  52. source_stable_id=c.get("source_stable_id"),
  53. source_type=c["source_type"],
  54. description=c.get("description"),
  55. level=c.get("level"),
  56. parent_id=c.get("parent_id"),
  57. element_count=c.get("element_count") or 0,
  58. )
  59. nodes[n.id] = n
  60. roots: dict[str, list[CatNode]] = {}
  61. for n in nodes.values():
  62. if n.parent_id and n.parent_id in nodes:
  63. nodes[n.parent_id].children.append(n)
  64. else:
  65. roots.setdefault(n.source_type, []).append(n)
  66. for n in nodes.values():
  67. n.children.sort(key=lambda x: x.id)
  68. return roots
  69. # ---------------------------------------------------------------------------
  70. # HTML rendering
  71. # ---------------------------------------------------------------------------
  72. def _node_html(n: CatNode, th: dict, depth: int = 0, is_root: bool = False) -> str:
  73. has_ch = bool(n.children)
  74. ec = n.element_count or 0
  75. cc = len(n.children)
  76. if is_root:
  77. bg, tc = th["root"], "#fff"
  78. elif has_ch:
  79. bg, tc = th["mid"], "#4a3520"
  80. else:
  81. bg, tc = th["leaf"], "#6b5240"
  82. badge_inner: list[str] = []
  83. if has_ch:
  84. badge_inner.append('<span class="ti">\u25BC</span>')
  85. badge_inner.append(f'<span class="nn">{html_lib.escape(n.name)}</span>')
  86. if n.source_stable_id is not None:
  87. badge_inner.append(f'<span class="si">{n.source_stable_id}</span>')
  88. if ec:
  89. badge_inner.append(f'<span class="ec">{ec}</span>')
  90. if cc:
  91. badge_inner.append(f'<span class="cc">{cc}\u25B6</span>')
  92. onclick = ' onclick="tog(this)"' if has_ch else ''
  93. cls = "b e" if has_ch else "b"
  94. title = f' title="{html_lib.escape(n.description)}"' if n.description else ""
  95. h = f'<div class="t" data-depth="{depth}">'
  96. h += f'<div class="{cls}" style="background:{bg};color:{tc}"{onclick}{title}>'
  97. h += "".join(badge_inner)
  98. h += "</div>"
  99. if has_ch:
  100. h += f'<div class="ch" style="--lc:{th["line"]}">'
  101. for child in n.children:
  102. h += _node_html(child, th, depth + 1)
  103. h += "</div>"
  104. h += "</div>"
  105. return h
  106. def _section_html(source_type: str, roots: list[CatNode]) -> str:
  107. th = THEME.get(source_type, THEME["实质"])
  108. total = sum(r.subtree_element_count for r in roots)
  109. h = '<div class="sec">'
  110. h += (
  111. f'<div class="sh" style="background:{th["root"]}">'
  112. f"\u25BC {html_lib.escape(source_type)} ({total})</div>"
  113. )
  114. h += '<div class="sb">'
  115. for r in roots:
  116. h += _node_html(r, th, depth=0, is_root=True)
  117. h += "</div></div>"
  118. return h
  119. def generate_tree_html(eid: int) -> str:
  120. categories = fetch_categories(eid)
  121. trees = build_trees(categories)
  122. sections = [_section_html(st, trees[st]) for st in SOURCE_TYPES if st in trees]
  123. body = "\n".join(sections)
  124. return _PAGE_HTML.replace("{{EID}}", str(eid)).replace("{{BODY}}", body)
  125. # ---------------------------------------------------------------------------
  126. # Full-page HTML template
  127. # ---------------------------------------------------------------------------
  128. _PAGE_HTML = r"""<!DOCTYPE html>
  129. <html lang="zh-CN">
  130. <head>
  131. <meta charset="UTF-8">
  132. <meta name="viewport" content="width=device-width,initial-scale=1">
  133. <title>分类树 · execution_id={{EID}}</title>
  134. <style>
  135. *{box-sizing:border-box;margin:0;padding:0}
  136. body{
  137. font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Noto Sans SC",sans-serif;
  138. background:#faf8f5;color:#333;padding:24px;
  139. }
  140. /* header */
  141. .hdr{display:flex;align-items:center;gap:10px;margin-bottom:28px;flex-wrap:wrap}
  142. .hdr h1{font-size:20px;font-weight:700;color:#4a3520}
  143. .hdr .eid{color:#999;font-size:13px}
  144. .hdr button{
  145. padding:5px 12px;border:1px solid #d0c8c0;border-radius:6px;
  146. background:#fff;cursor:pointer;font-size:12px;color:#4a3520;
  147. }
  148. .hdr button:hover{background:#f5ebe0}
  149. /* section */
  150. .sec{margin-bottom:36px}
  151. .sh{
  152. display:inline-block;padding:8px 18px;border-radius:8px;color:#fff;
  153. font-size:15px;font-weight:700;margin-bottom:14px;
  154. }
  155. .sb{overflow-x:auto;padding:12px 0 12px 4px}
  156. /* ---- horizontal tree ---- */
  157. .t{display:inline-flex;align-items:center}
  158. /* badge */
  159. .b{
  160. display:inline-flex;align-items:center;gap:5px;
  161. padding:4px 10px;border-radius:5px;white-space:nowrap;font-size:13px;
  162. box-shadow:0 1px 2px rgba(0,0,0,.08);user-select:none;
  163. }
  164. .b.e{cursor:pointer}
  165. .b.e:hover{filter:brightness(1.06);box-shadow:0 2px 5px rgba(0,0,0,.12)}
  166. .ti{font-size:10px;transition:transform .15s ease;display:inline-block}
  167. .nn{font-weight:600}
  168. .si{font-size:11px;opacity:.55}
  169. .ec,.cc{
  170. font-size:11px;background:rgba(255,255,255,.45);
  171. padding:0 4px;border-radius:3px;line-height:1.6;
  172. }
  173. .ec{font-weight:600}
  174. /* children container */
  175. .ch{
  176. display:flex;flex-direction:column;position:relative;
  177. padding-left:28px;margin-left:10px;
  178. }
  179. /* horizontal line from parent to junction */
  180. .ch::before{
  181. content:'';position:absolute;left:0;top:50%;width:14px;
  182. border-top:1.5px solid var(--lc);
  183. }
  184. /* each child row */
  185. .ch>.t{position:relative;padding:3px 0}
  186. /* vertical line between siblings */
  187. .ch>.t::before{
  188. content:'';position:absolute;left:-14px;top:0;bottom:0;
  189. border-left:1.5px solid var(--lc);
  190. }
  191. .ch>.t:first-child::before{top:50%}
  192. .ch>.t:last-child::before{bottom:50%}
  193. .ch>.t:only-child::before{display:none}
  194. /* horizontal connector to child */
  195. .ch>.t::after{
  196. content:'';position:absolute;left:-14px;top:50%;width:14px;
  197. border-top:1.5px solid var(--lc);
  198. }
  199. .ch>.t:only-child::after{left:-28px;width:28px}
  200. /* collapsed state */
  201. .t.collapsed>.ch{display:none}
  202. .t.collapsed>.b>.ti{transform:rotate(-90deg)}
  203. </style>
  204. </head>
  205. <body>
  206. <div class="hdr">
  207. <h1>选题模式分类树</h1>
  208. <span class="eid">execution_id = {{EID}}</span>
  209. <button onclick="ea()">全部展开</button>
  210. <button onclick="ca()">全部收起</button>
  211. <button onclick="lv(1)">展开1层</button>
  212. <button onclick="lv(2)">展开2层</button>
  213. <button onclick="lv(3)">展开3层</button>
  214. <button onclick="lv(4)">展开4层</button>
  215. </div>
  216. {{BODY}}
  217. <script>
  218. function tog(el){el.closest('.t').classList.toggle('collapsed')}
  219. function ea(){document.querySelectorAll('.t.collapsed').forEach(function(e){e.classList.remove('collapsed')})}
  220. function ca(){document.querySelectorAll('.t').forEach(function(e){if(e.querySelector(':scope>.ch'))e.classList.add('collapsed')})}
  221. function lv(n){document.querySelectorAll('.t').forEach(function(e){
  222. var ch=e.querySelector(':scope>.ch');if(!ch)return;
  223. var d=+(e.dataset.depth||0);
  224. if(d<n)e.classList.remove('collapsed');else e.classList.add('collapsed');
  225. })}
  226. </script>
  227. </body>
  228. </html>
  229. """
  230. # ---------------------------------------------------------------------------
  231. # Entry
  232. # ---------------------------------------------------------------------------
  233. if __name__ == "__main__":
  234. execution_id = 58
  235. html_content = generate_tree_html(execution_id)
  236. out = Path(__file__).resolve().parent / "new_result" / f"topic_pattern_tree_{execution_id}.html"
  237. out.parent.mkdir(parents=True, exist_ok=True)
  238. out.write_text(html_content, encoding="utf-8")
  239. print(f"已生成: {out}")