| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279 |
- from __future__ import annotations
- import html as html_lib
- from dataclasses import dataclass, field
- from pathlib import Path
- from sqlalchemy import text
- from examples.demand.db_manager import DatabaseManager
- db = DatabaseManager()
- SOURCE_TYPES = ["实质", "形式", "意图"]
- THEME = {
- "实质": {"root": "#e8841a", "mid": "#f0c389", "leaf": "#fae6cc", "line": "#d4a574"},
- "形式": {"root": "#5b9bd5", "mid": "#a3c9e8", "leaf": "#daeaf8", "line": "#8cb9dc"},
- "意图": {"root": "#70ad47", "mid": "#a9d18e", "leaf": "#dbefd0", "line": "#8fc270"},
- }
- @dataclass
- class CatNode:
- id: int
- name: str
- source_stable_id: int | None
- source_type: str
- description: str | None
- level: int | None
- parent_id: int | None
- element_count: int
- children: list[CatNode] = field(default_factory=list)
- @property
- def subtree_element_count(self) -> int:
- total = self.element_count or 0
- for c in self.children:
- total += c.subtree_element_count
- return total
- def fetch_categories(eid: int) -> list[dict]:
- session = db.get_session()
- try:
- rows = session.execute(
- text(
- "SELECT id, source_stable_id, source_type, name, description, "
- "level, parent_id, element_count "
- "FROM topic_pattern_category WHERE execution_id = :eid "
- "ORDER BY source_type, level, id"
- ),
- {"eid": eid},
- ).mappings().fetchall()
- return [dict(r) for r in rows]
- finally:
- session.close()
- def build_trees(categories: list[dict]) -> dict[str, list[CatNode]]:
- nodes: dict[int, CatNode] = {}
- for c in categories:
- n = CatNode(
- id=c["id"],
- name=c["name"],
- source_stable_id=c.get("source_stable_id"),
- source_type=c["source_type"],
- description=c.get("description"),
- level=c.get("level"),
- parent_id=c.get("parent_id"),
- element_count=c.get("element_count") or 0,
- )
- nodes[n.id] = n
- roots: dict[str, list[CatNode]] = {}
- for n in nodes.values():
- if n.parent_id and n.parent_id in nodes:
- nodes[n.parent_id].children.append(n)
- else:
- roots.setdefault(n.source_type, []).append(n)
- for n in nodes.values():
- n.children.sort(key=lambda x: x.id)
- return roots
- # ---------------------------------------------------------------------------
- # HTML rendering
- # ---------------------------------------------------------------------------
- def _node_html(n: CatNode, th: dict, depth: int = 0, is_root: bool = False) -> str:
- has_ch = bool(n.children)
- ec = n.element_count or 0
- cc = len(n.children)
- if is_root:
- bg, tc = th["root"], "#fff"
- elif has_ch:
- bg, tc = th["mid"], "#4a3520"
- else:
- bg, tc = th["leaf"], "#6b5240"
- badge_inner: list[str] = []
- if has_ch:
- badge_inner.append('<span class="ti">\u25BC</span>')
- badge_inner.append(f'<span class="nn">{html_lib.escape(n.name)}</span>')
- if n.source_stable_id is not None:
- badge_inner.append(f'<span class="si">{n.source_stable_id}</span>')
- if ec:
- badge_inner.append(f'<span class="ec">{ec}</span>')
- if cc:
- badge_inner.append(f'<span class="cc">{cc}\u25B6</span>')
- onclick = ' onclick="tog(this)"' if has_ch else ''
- cls = "b e" if has_ch else "b"
- title = f' title="{html_lib.escape(n.description)}"' if n.description else ""
- h = f'<div class="t" data-depth="{depth}">'
- h += f'<div class="{cls}" style="background:{bg};color:{tc}"{onclick}{title}>'
- h += "".join(badge_inner)
- h += "</div>"
- if has_ch:
- h += f'<div class="ch" style="--lc:{th["line"]}">'
- for child in n.children:
- h += _node_html(child, th, depth + 1)
- h += "</div>"
- h += "</div>"
- return h
- def _section_html(source_type: str, roots: list[CatNode]) -> str:
- th = THEME.get(source_type, THEME["实质"])
- total = sum(r.subtree_element_count for r in roots)
- h = '<div class="sec">'
- h += (
- f'<div class="sh" style="background:{th["root"]}">'
- f"\u25BC {html_lib.escape(source_type)} ({total})</div>"
- )
- h += '<div class="sb">'
- for r in roots:
- h += _node_html(r, th, depth=0, is_root=True)
- h += "</div></div>"
- return h
- def generate_tree_html(eid: int) -> str:
- categories = fetch_categories(eid)
- trees = build_trees(categories)
- sections = [_section_html(st, trees[st]) for st in SOURCE_TYPES if st in trees]
- body = "\n".join(sections)
- return _PAGE_HTML.replace("{{EID}}", str(eid)).replace("{{BODY}}", body)
- # ---------------------------------------------------------------------------
- # Full-page HTML template
- # ---------------------------------------------------------------------------
- _PAGE_HTML = r"""<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width,initial-scale=1">
- <title>分类树 · execution_id={{EID}}</title>
- <style>
- *{box-sizing:border-box;margin:0;padding:0}
- body{
- font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Noto Sans SC",sans-serif;
- background:#faf8f5;color:#333;padding:24px;
- }
- /* header */
- .hdr{display:flex;align-items:center;gap:10px;margin-bottom:28px;flex-wrap:wrap}
- .hdr h1{font-size:20px;font-weight:700;color:#4a3520}
- .hdr .eid{color:#999;font-size:13px}
- .hdr button{
- padding:5px 12px;border:1px solid #d0c8c0;border-radius:6px;
- background:#fff;cursor:pointer;font-size:12px;color:#4a3520;
- }
- .hdr button:hover{background:#f5ebe0}
- /* section */
- .sec{margin-bottom:36px}
- .sh{
- display:inline-block;padding:8px 18px;border-radius:8px;color:#fff;
- font-size:15px;font-weight:700;margin-bottom:14px;
- }
- .sb{overflow-x:auto;padding:12px 0 12px 4px}
- /* ---- horizontal tree ---- */
- .t{display:inline-flex;align-items:center}
- /* badge */
- .b{
- display:inline-flex;align-items:center;gap:5px;
- padding:4px 10px;border-radius:5px;white-space:nowrap;font-size:13px;
- box-shadow:0 1px 2px rgba(0,0,0,.08);user-select:none;
- }
- .b.e{cursor:pointer}
- .b.e:hover{filter:brightness(1.06);box-shadow:0 2px 5px rgba(0,0,0,.12)}
- .ti{font-size:10px;transition:transform .15s ease;display:inline-block}
- .nn{font-weight:600}
- .si{font-size:11px;opacity:.55}
- .ec,.cc{
- font-size:11px;background:rgba(255,255,255,.45);
- padding:0 4px;border-radius:3px;line-height:1.6;
- }
- .ec{font-weight:600}
- /* children container */
- .ch{
- display:flex;flex-direction:column;position:relative;
- padding-left:28px;margin-left:10px;
- }
- /* horizontal line from parent to junction */
- .ch::before{
- content:'';position:absolute;left:0;top:50%;width:14px;
- border-top:1.5px solid var(--lc);
- }
- /* each child row */
- .ch>.t{position:relative;padding:3px 0}
- /* vertical line between siblings */
- .ch>.t::before{
- content:'';position:absolute;left:-14px;top:0;bottom:0;
- border-left:1.5px solid var(--lc);
- }
- .ch>.t:first-child::before{top:50%}
- .ch>.t:last-child::before{bottom:50%}
- .ch>.t:only-child::before{display:none}
- /* horizontal connector to child */
- .ch>.t::after{
- content:'';position:absolute;left:-14px;top:50%;width:14px;
- border-top:1.5px solid var(--lc);
- }
- .ch>.t:only-child::after{left:-28px;width:28px}
- /* collapsed state */
- .t.collapsed>.ch{display:none}
- .t.collapsed>.b>.ti{transform:rotate(-90deg)}
- </style>
- </head>
- <body>
- <div class="hdr">
- <h1>选题模式分类树</h1>
- <span class="eid">execution_id = {{EID}}</span>
- <button onclick="ea()">全部展开</button>
- <button onclick="ca()">全部收起</button>
- <button onclick="lv(1)">展开1层</button>
- <button onclick="lv(2)">展开2层</button>
- <button onclick="lv(3)">展开3层</button>
- <button onclick="lv(4)">展开4层</button>
- </div>
- {{BODY}}
- <script>
- function tog(el){el.closest('.t').classList.toggle('collapsed')}
- function ea(){document.querySelectorAll('.t.collapsed').forEach(function(e){e.classList.remove('collapsed')})}
- function ca(){document.querySelectorAll('.t').forEach(function(e){if(e.querySelector(':scope>.ch'))e.classList.add('collapsed')})}
- function lv(n){document.querySelectorAll('.t').forEach(function(e){
- var ch=e.querySelector(':scope>.ch');if(!ch)return;
- var d=+(e.dataset.depth||0);
- if(d<n)e.classList.remove('collapsed');else e.classList.add('collapsed');
- })}
- </script>
- </body>
- </html>
- """
- # ---------------------------------------------------------------------------
- # Entry
- # ---------------------------------------------------------------------------
- if __name__ == "__main__":
- execution_id = 58
- html_content = generate_tree_html(execution_id)
- out = Path(__file__).resolve().parent / "new_result" / f"topic_pattern_tree_{execution_id}.html"
- out.parent.mkdir(parents=True, exist_ok=True)
- out.write_text(html_content, encoding="utf-8")
- print(f"已生成: {out}")
|