visualize_match_graph.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 将匹配图谱数据可视化为交互式HTML文件
  5. 输入:match_graph目录下的JSON文件
  6. 输出:单个HTML文件,包含所有帖子的图谱,可通过Tab切换
  7. """
  8. import json
  9. from pathlib import Path
  10. from typing import Dict, List
  11. import sys
  12. # 添加项目根目录到路径
  13. project_root = Path(__file__).parent.parent.parent
  14. sys.path.insert(0, str(project_root))
  15. from script.data_processing.path_config import PathConfig
  16. HTML_TEMPLATE = '''<!DOCTYPE html>
  17. <html lang="zh-CN">
  18. <head>
  19. <meta charset="UTF-8">
  20. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  21. <title>匹配图谱可视化</title>
  22. <script src="https://d3js.org/d3.v7.min.js"></script>
  23. <style>
  24. * {{
  25. margin: 0;
  26. padding: 0;
  27. box-sizing: border-box;
  28. }}
  29. body {{
  30. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  31. background: #1a1a2e;
  32. color: #eee;
  33. overflow: hidden;
  34. }}
  35. #container {{
  36. display: flex;
  37. height: 100vh;
  38. flex-direction: column;
  39. }}
  40. /* Tab样式 */
  41. .tabs {{
  42. display: flex;
  43. background: #0f3460;
  44. padding: 0 20px;
  45. overflow-x: auto;
  46. flex-shrink: 0;
  47. }}
  48. .tab {{
  49. padding: 12px 20px;
  50. cursor: pointer;
  51. border-bottom: 3px solid transparent;
  52. white-space: nowrap;
  53. font-size: 13px;
  54. color: #888;
  55. transition: all 0.2s;
  56. }}
  57. .tab:hover {{
  58. color: #fff;
  59. background: rgba(255,255,255,0.05);
  60. }}
  61. .tab.active {{
  62. color: #e94560;
  63. border-bottom-color: #e94560;
  64. background: rgba(233, 69, 96, 0.1);
  65. }}
  66. /* 主内容区 */
  67. .main-content {{
  68. display: flex;
  69. flex: 1;
  70. overflow: hidden;
  71. }}
  72. #graph {{
  73. flex: 1;
  74. position: relative;
  75. }}
  76. #sidebar {{
  77. width: 280px;
  78. background: #16213e;
  79. padding: 15px;
  80. overflow-y: auto;
  81. border-left: 1px solid #0f3460;
  82. }}
  83. h1 {{
  84. font-size: 15px;
  85. margin-bottom: 10px;
  86. color: #e94560;
  87. }}
  88. h2 {{
  89. font-size: 12px;
  90. margin: 10px 0 6px;
  91. color: #0f9b8e;
  92. }}
  93. .legend {{
  94. margin-top: 10px;
  95. }}
  96. .legend-grid {{
  97. display: grid;
  98. grid-template-columns: 1fr 1fr;
  99. gap: 4px 8px;
  100. }}
  101. .legend-item {{
  102. display: flex;
  103. align-items: center;
  104. font-size: 11px;
  105. }}
  106. .legend-color {{
  107. width: 12px;
  108. height: 12px;
  109. border-radius: 50%;
  110. margin-right: 6px;
  111. flex-shrink: 0;
  112. }}
  113. .legend-line {{
  114. width: 20px;
  115. height: 3px;
  116. margin-right: 6px;
  117. flex-shrink: 0;
  118. }}
  119. .detail-panel {{
  120. margin-top: 20px;
  121. padding: 15px;
  122. background: #0f3460;
  123. border-radius: 8px;
  124. display: none;
  125. }}
  126. .detail-panel.active {{
  127. display: block;
  128. }}
  129. .detail-panel h3 {{
  130. font-size: 14px;
  131. margin-bottom: 10px;
  132. color: #e94560;
  133. }}
  134. .detail-panel p {{
  135. font-size: 12px;
  136. line-height: 1.6;
  137. color: #ccc;
  138. margin: 5px 0;
  139. }}
  140. .detail-panel .label {{
  141. color: #888;
  142. }}
  143. .detail-panel .close-btn {{
  144. position: absolute;
  145. top: 10px;
  146. right: 10px;
  147. background: none;
  148. border: none;
  149. color: #888;
  150. cursor: pointer;
  151. font-size: 16px;
  152. }}
  153. .detail-panel .close-btn:hover {{
  154. color: #e94560;
  155. }}
  156. .detail-panel-wrapper {{
  157. position: relative;
  158. }}
  159. .similarity-score {{
  160. background: #e94560;
  161. color: #fff;
  162. padding: 2px 6px;
  163. border-radius: 4px;
  164. font-weight: bold;
  165. }}
  166. .edge-description {{
  167. background: #1a1a2e;
  168. padding: 10px;
  169. border-radius: 4px;
  170. margin-top: 8px;
  171. font-size: 11px;
  172. line-height: 1.5;
  173. }}
  174. svg {{
  175. width: 100%;
  176. height: 100%;
  177. }}
  178. .node {{
  179. cursor: pointer;
  180. }}
  181. .node circle, .node rect, .node polygon {{
  182. stroke-width: 3px;
  183. }}
  184. .node .post-point-node {{
  185. stroke: #fff;
  186. stroke-width: 4px;
  187. }}
  188. .node .post-node {{
  189. stroke: #fff;
  190. stroke-dasharray: 4,2;
  191. }}
  192. .node .post-node.unmatched {{
  193. stroke: #555;
  194. stroke-dasharray: 2,2;
  195. }}
  196. .node .persona-node {{
  197. stroke: #fff;
  198. }}
  199. .node text {{
  200. font-size: 11px;
  201. fill: #fff;
  202. pointer-events: none;
  203. }}
  204. .link {{
  205. stroke-opacity: 0.7;
  206. }}
  207. .link-hitarea {{
  208. stroke: transparent;
  209. stroke-width: 15px;
  210. cursor: pointer;
  211. fill: none;
  212. }}
  213. .link-hitarea:hover + .link {{
  214. stroke-opacity: 1;
  215. stroke-width: 3px;
  216. }}
  217. .edge-label {{
  218. font-size: 10px;
  219. fill: #fff;
  220. pointer-events: none;
  221. text-anchor: middle;
  222. }}
  223. .edge-label-bg {{
  224. fill: rgba(0,0,0,0.7);
  225. }}
  226. .link.match {{
  227. stroke: #e94560;
  228. stroke-dasharray: 5,5;
  229. }}
  230. .link.category-cross {{
  231. stroke: #2ecc71;
  232. }}
  233. .link.category-intra {{
  234. stroke: #27ae60;
  235. stroke-dasharray: 3,3;
  236. }}
  237. .link.tag-cooccur {{
  238. stroke: #f39c12;
  239. }}
  240. .link.belong {{
  241. stroke: #9b59b6;
  242. }}
  243. .link.contain {{
  244. stroke: #8e44ad;
  245. stroke-dasharray: 2,2;
  246. }}
  247. /* 镜像边样式(虚线,颜色与原边相同) */
  248. .link.mirror-category-cross {{
  249. stroke: #2ecc71;
  250. stroke-dasharray: 6,3;
  251. }}
  252. .link.mirror-category-intra {{
  253. stroke: #27ae60;
  254. stroke-dasharray: 6,3;
  255. }}
  256. .link.mirror-tag-cooccur {{
  257. stroke: #f39c12;
  258. stroke-dasharray: 6,3;
  259. }}
  260. .link.mirror-belong {{
  261. stroke: #9b59b6;
  262. stroke-dasharray: 6,3;
  263. }}
  264. .link.mirror-contain {{
  265. stroke: #8e44ad;
  266. stroke-dasharray: 6,3;
  267. }}
  268. /* 二阶边现在使用与镜像边相同的样式(基于原始边类型) */
  269. /* 高亮/灰化样式 */
  270. .node.dimmed circle, .node.dimmed rect, .node.dimmed polygon {{
  271. opacity: 0.15 !important;
  272. }}
  273. .node.dimmed text {{
  274. opacity: 0.15 !important;
  275. }}
  276. .link-group.dimmed .link {{
  277. stroke-opacity: 0.08 !important;
  278. }}
  279. .link-group.dimmed .edge-label-group {{
  280. opacity: 0.15 !important;
  281. }}
  282. .node.highlighted circle, .node.highlighted rect, .node.highlighted polygon {{
  283. stroke: #fff !important;
  284. stroke-width: 4px !important;
  285. filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
  286. }}
  287. .link-group.highlighted .link {{
  288. stroke-opacity: 1 !important;
  289. stroke-width: 3px !important;
  290. filter: drop-shadow(0 0 4px rgba(255,255,255,0.3));
  291. }}
  292. .tooltip {{
  293. position: absolute;
  294. background: rgba(0,0,0,0.9);
  295. color: #fff;
  296. padding: 10px 15px;
  297. border-radius: 6px;
  298. font-size: 12px;
  299. pointer-events: none;
  300. max-width: 300px;
  301. z-index: 1000;
  302. display: none;
  303. }}
  304. .controls {{
  305. position: absolute;
  306. top: 20px;
  307. left: 20px;
  308. background: rgba(22, 33, 62, 0.9);
  309. padding: 15px;
  310. border-radius: 8px;
  311. z-index: 100;
  312. }}
  313. .controls button {{
  314. background: #0f3460;
  315. color: #fff;
  316. border: none;
  317. padding: 8px 15px;
  318. margin: 5px;
  319. border-radius: 4px;
  320. cursor: pointer;
  321. font-size: 12px;
  322. }}
  323. .controls button:hover {{
  324. background: #e94560;
  325. }}
  326. </style>
  327. </head>
  328. <body>
  329. <div id="container">
  330. <div class="tabs" id="tabs">
  331. {tabs_html}
  332. </div>
  333. <div class="main-content">
  334. <div id="graph">
  335. <div class="controls">
  336. <button onclick="resetZoom()">重置视图</button>
  337. <button onclick="toggleLabels()">切换标签</button>
  338. </div>
  339. <div class="tooltip" id="tooltip"></div>
  340. </div>
  341. <div id="sidebar">
  342. <h1>匹配图谱</h1>
  343. <div class="detail-panel active" id="detailPanel">
  344. <h3 id="detailTitle">点击节点或边查看详情</h3>
  345. <div id="detailContent">
  346. <p style="color: #888; font-size: 11px;">点击图中的节点或边,这里会显示详细信息</p>
  347. </div>
  348. </div>
  349. <div class="legend">
  350. <h2>节点</h2>
  351. <div class="legend-grid">
  352. <div class="legend-item">
  353. <div class="legend-color" style="background: #666; border: 2px dashed #fff;"></div>
  354. <span>帖子(虚线)</span>
  355. </div>
  356. <div class="legend-item">
  357. <div class="legend-color" style="background: #666; border: 2px solid #fff;"></div>
  358. <span>人设(实线)</span>
  359. </div>
  360. <div class="legend-item">
  361. <div class="legend-color" style="background: #666; border-radius: 50%;"></div>
  362. <span>标签(圆)</span>
  363. </div>
  364. <div class="legend-item">
  365. <div class="legend-color" style="background: #666; border-radius: 2px;"></div>
  366. <span>分类(方)</span>
  367. </div>
  368. <div class="legend-item">
  369. <div class="legend-color" style="background: #666; opacity: 1;"></div>
  370. <span>直接匹配</span>
  371. </div>
  372. <div class="legend-item">
  373. <div class="legend-color" style="background: #666; opacity: 0.5;"></div>
  374. <span>扩展节点</span>
  375. </div>
  376. <div class="legend-item">
  377. <div class="legend-color" style="background: #f39c12;"></div>
  378. <span>灵感点</span>
  379. </div>
  380. <div class="legend-item">
  381. <div class="legend-color" style="background: #3498db;"></div>
  382. <span>目的点</span>
  383. </div>
  384. <div class="legend-item">
  385. <div class="legend-color" style="background: #9b59b6;"></div>
  386. <span>关键点</span>
  387. </div>
  388. </div>
  389. <h2>边(人设/实线)</h2>
  390. <div class="legend-grid">
  391. <div class="legend-item">
  392. <div class="legend-line" style="background: #e94560;"></div>
  393. <span>匹配</span>
  394. </div>
  395. <div class="legend-item">
  396. <div class="legend-line" style="background: #2ecc71;"></div>
  397. <span>分类共现(跨)</span>
  398. </div>
  399. <div class="legend-item">
  400. <div class="legend-line" style="background: #27ae60;"></div>
  401. <span>分类共现(内)</span>
  402. </div>
  403. <div class="legend-item">
  404. <div class="legend-line" style="background: #f39c12;"></div>
  405. <span>标签共现</span>
  406. </div>
  407. <div class="legend-item">
  408. <div class="legend-line" style="background: #9b59b6;"></div>
  409. <span>属于</span>
  410. </div>
  411. <div class="legend-item">
  412. <div class="legend-line" style="background: #8e44ad;"></div>
  413. <span>包含</span>
  414. </div>
  415. </div>
  416. <h2>帖子镜像边(直接)</h2>
  417. <div class="legend-grid">
  418. <div class="legend-item">
  419. <div class="legend-line" style="background: repeating-linear-gradient(90deg, #2ecc71, #2ecc71 6px, transparent 6px, transparent 9px);"></div>
  420. <span>分类共现</span>
  421. </div>
  422. <div class="legend-item">
  423. <div class="legend-line" style="background: repeating-linear-gradient(90deg, #f39c12, #f39c12 6px, transparent 6px, transparent 9px);"></div>
  424. <span>标签共现</span>
  425. </div>
  426. <div class="legend-item">
  427. <div class="legend-line" style="background: repeating-linear-gradient(90deg, #9b59b6, #9b59b6 6px, transparent 6px, transparent 9px);"></div>
  428. <span>属于</span>
  429. </div>
  430. <div class="legend-item">
  431. <div class="legend-line" style="background: repeating-linear-gradient(90deg, #8e44ad, #8e44ad 6px, transparent 6px, transparent 9px);"></div>
  432. <span>包含</span>
  433. </div>
  434. </div>
  435. <h2>帖子镜像边(二阶)</h2>
  436. <div class="legend-grid">
  437. <div class="legend-item">
  438. <div class="legend-line" style="background: repeating-linear-gradient(90deg, #17a2b8, #17a2b8 8px, transparent 8px, transparent 11px, #17a2b8 11px, #17a2b8 13px, transparent 13px, transparent 16px);"></div>
  439. <span>通过扩展节点</span>
  440. </div>
  441. </div>
  442. </div>
  443. </div>
  444. </div>
  445. </div>
  446. <script>
  447. // 所有帖子的图谱数据
  448. const allGraphData = {all_graph_data};
  449. // 当前选中的帖子索引
  450. let currentIndex = 0;
  451. let simulation = null;
  452. let svg = null;
  453. let g = null;
  454. let zoom = null;
  455. let showLabels = true;
  456. // 初始化
  457. function init() {{
  458. const container = document.getElementById("graph");
  459. const width = container.clientWidth;
  460. const height = container.clientHeight;
  461. svg = d3.select("#graph")
  462. .append("svg")
  463. .attr("width", width)
  464. .attr("height", height);
  465. g = svg.append("g");
  466. zoom = d3.zoom()
  467. .scaleExtent([0.1, 4])
  468. .on("zoom", (event) => {{
  469. g.attr("transform", event.transform);
  470. }});
  471. svg.call(zoom);
  472. // 绑定Tab点击事件
  473. document.querySelectorAll(".tab").forEach((tab, index) => {{
  474. tab.addEventListener("click", () => switchTab(index));
  475. }});
  476. // 显示第一个帖子
  477. switchTab(0);
  478. }}
  479. // 切换Tab
  480. function switchTab(index) {{
  481. currentIndex = index;
  482. // 更新Tab样式
  483. document.querySelectorAll(".tab").forEach((tab, i) => {{
  484. tab.classList.toggle("active", i === index);
  485. }});
  486. // 更新图谱
  487. renderGraph(allGraphData[index]);
  488. }}
  489. // 渲染图谱
  490. function renderGraph(data) {{
  491. // 清空现有图谱
  492. g.selectAll("*").remove();
  493. if (simulation) {{
  494. simulation.stop();
  495. }}
  496. const container = document.getElementById("graph");
  497. const width = container.clientWidth;
  498. const height = container.clientHeight;
  499. // 准备数据
  500. const nodes = data.nodes.map(n => ({{
  501. ...n,
  502. id: n.节点ID,
  503. source: n.节点ID.startsWith("帖子_") ? "帖子" : "人设",
  504. level: n.节点层级
  505. }}));
  506. const links = data.edges.map(e => ({{
  507. ...e,
  508. source: e.源节点ID,
  509. target: e.目标节点ID,
  510. type: e.边类型
  511. }}));
  512. // 分离节点类型
  513. const postNodes = nodes.filter(n => n.source === "帖子");
  514. const personaNodes = nodes.filter(n => n.source === "人设" && !n.是否扩展);
  515. const expandedNodes = nodes.filter(n => n.source === "人设" && n.是否扩展);
  516. const matchLinks = links.filter(l => l.type === "匹配");
  517. // 构建帖子节点到人设节点的映射
  518. const postToPersona = {{}};
  519. const personaToPost = {{}};
  520. matchLinks.forEach(l => {{
  521. const sid = typeof l.source === "object" ? l.source.id : l.source;
  522. const tid = typeof l.target === "object" ? l.target.id : l.target;
  523. if (!postToPersona[sid]) postToPersona[sid] = [];
  524. postToPersona[sid].push(tid);
  525. if (!personaToPost[tid]) personaToPost[tid] = [];
  526. personaToPost[tid].push(sid);
  527. }});
  528. // 找出所有连通分量
  529. function findConnectedComponents(nodes, links) {{
  530. const nodeIds = new Set(nodes.map(n => n.id));
  531. const adj = {{}};
  532. nodeIds.forEach(id => adj[id] = []);
  533. links.forEach(l => {{
  534. const sid = typeof l.source === "object" ? l.source.id : l.source;
  535. const tid = typeof l.target === "object" ? l.target.id : l.target;
  536. if (nodeIds.has(sid) && nodeIds.has(tid)) {{
  537. adj[sid].push(tid);
  538. adj[tid].push(sid);
  539. }}
  540. }});
  541. const visited = new Set();
  542. const components = [];
  543. nodeIds.forEach(startId => {{
  544. if (visited.has(startId)) return;
  545. const component = [];
  546. const queue = [startId];
  547. while (queue.length > 0) {{
  548. const id = queue.shift();
  549. if (visited.has(id)) continue;
  550. visited.add(id);
  551. component.push(id);
  552. adj[id].forEach(neighbor => {{
  553. if (!visited.has(neighbor)) queue.push(neighbor);
  554. }});
  555. }}
  556. components.push(component);
  557. }});
  558. return components;
  559. }}
  560. // 按大小排序连通分量(大的在前)
  561. const components = findConnectedComponents(nodes, links)
  562. .sort((a, b) => b.length - a.length);
  563. console.log(`找到 ${{components.length}} 个连通分量`);
  564. // 为每个节点分配连通分量ID和分量内的X范围
  565. const nodeToComponent = {{}};
  566. const componentCenters = {{}};
  567. const componentBounds = {{}};
  568. const padding = 50; // 分量之间的间距
  569. const totalPadding = padding * (components.length - 1);
  570. const availableWidth = width - totalPadding - 100; // 留边距
  571. // 根据分量大小分配宽度
  572. const totalNodes = nodes.length;
  573. let currentX = 50; // 起始边距
  574. components.forEach((comp, i) => {{
  575. const compWidth = Math.max(150, (comp.length / totalNodes) * availableWidth);
  576. const centerX = currentX + compWidth / 2;
  577. componentCenters[i] = centerX;
  578. componentBounds[i] = {{ start: currentX, end: currentX + compWidth, width: compWidth }};
  579. comp.forEach(nodeId => {{
  580. nodeToComponent[nodeId] = i;
  581. }});
  582. currentX += compWidth + padding;
  583. }});
  584. // 使用重心法(Barycenter)减少边交叉
  585. // 迭代优化:交替调整两层节点的顺序
  586. const nodeTargetX = {{}};
  587. const personaXMap = {{}};
  588. // 对每个连通分量单独处理
  589. components.forEach((comp, compIdx) => {{
  590. const bounds = componentBounds[compIdx];
  591. const compPostNodes = postNodes.filter(n => nodeToComponent[n.id] === compIdx);
  592. const compPersonaNodes = personaNodes.filter(n => nodeToComponent[n.id] === compIdx);
  593. if (compPostNodes.length === 0 || compPersonaNodes.length === 0) {{
  594. // 没有匹配关系的分量,均匀分布
  595. const spacing = bounds.width / (comp.length + 1);
  596. comp.forEach((nodeId, i) => {{
  597. const node = nodes.find(n => n.id === nodeId);
  598. if (node) {{
  599. node.x = bounds.start + spacing * (i + 1);
  600. nodeTargetX[nodeId] = node.x;
  601. if (node.source === "人设") personaXMap[nodeId] = node.x;
  602. }}
  603. }});
  604. return;
  605. }}
  606. // 初始化:给人设节点一个初始顺序
  607. let personaOrder = compPersonaNodes.map((n, i) => ({{ node: n, order: i }}));
  608. // 迭代优化(3轮)
  609. for (let iter = 0; iter < 3; iter++) {{
  610. // 1. 根据人设节点位置,计算帖子节点的重心
  611. const postBarycenter = {{}};
  612. compPostNodes.forEach(pn => {{
  613. const matched = postToPersona[pn.id] || [];
  614. if (matched.length > 0) {{
  615. const avgOrder = matched.reduce((sum, pid) => {{
  616. const po = personaOrder.find(p => p.node.id === pid);
  617. return sum + (po ? po.order : 0);
  618. }}, 0) / matched.length;
  619. postBarycenter[pn.id] = avgOrder;
  620. }} else {{
  621. postBarycenter[pn.id] = 0;
  622. }}
  623. }});
  624. // 按重心排序帖子节点
  625. const sortedPosts = [...compPostNodes].sort((a, b) =>
  626. postBarycenter[a.id] - postBarycenter[b.id]
  627. );
  628. // 2. 根据帖子节点位置,重新计算人设节点的重心
  629. const personaBarycenter = {{}};
  630. compPersonaNodes.forEach(pn => {{
  631. const matched = personaToPost[pn.id] || [];
  632. if (matched.length > 0) {{
  633. const avgOrder = matched.reduce((sum, pid) => {{
  634. const idx = sortedPosts.findIndex(p => p.id === pid);
  635. return sum + (idx >= 0 ? idx : 0);
  636. }}, 0) / matched.length;
  637. personaBarycenter[pn.id] = avgOrder;
  638. }} else {{
  639. personaBarycenter[pn.id] = personaOrder.find(p => p.node.id === pn.id)?.order || 0;
  640. }}
  641. }});
  642. // 更新人设节点顺序
  643. personaOrder = compPersonaNodes
  644. .map(n => ({{ node: n, order: personaBarycenter[n.id] }}))
  645. .sort((a, b) => a.order - b.order)
  646. .map((item, i) => ({{ node: item.node, order: i }}));
  647. }}
  648. // 最终排序
  649. const finalPersonaOrder = personaOrder.map(p => p.node);
  650. const postBarycenter = {{}};
  651. compPostNodes.forEach(pn => {{
  652. const matched = postToPersona[pn.id] || [];
  653. if (matched.length > 0) {{
  654. const avgOrder = matched.reduce((sum, pid) => {{
  655. const idx = finalPersonaOrder.findIndex(n => n.id === pid);
  656. return sum + (idx >= 0 ? idx : 0);
  657. }}, 0) / matched.length;
  658. postBarycenter[pn.id] = avgOrder;
  659. }} else {{
  660. postBarycenter[pn.id] = 0;
  661. }}
  662. }});
  663. const finalPostOrder = [...compPostNodes].sort((a, b) =>
  664. postBarycenter[a.id] - postBarycenter[b.id]
  665. );
  666. // 设置位置
  667. const personaSpacing = bounds.width / (finalPersonaOrder.length + 1);
  668. finalPersonaOrder.forEach((n, i) => {{
  669. n.x = bounds.start + personaSpacing * (i + 1);
  670. nodeTargetX[n.id] = n.x;
  671. personaXMap[n.id] = n.x;
  672. }});
  673. const postSpacing = bounds.width / (finalPostOrder.length + 1);
  674. finalPostOrder.forEach((n, i) => {{
  675. // 帖子节点用重心位置(匹配人设的平均X)
  676. const matched = postToPersona[n.id] || [];
  677. if (matched.length > 0) {{
  678. const avgX = matched.reduce((sum, pid) => sum + (personaXMap[pid] || bounds.start + bounds.width/2), 0) / matched.length;
  679. n.x = avgX;
  680. }} else {{
  681. n.x = bounds.start + postSpacing * (i + 1);
  682. }}
  683. nodeTargetX[n.id] = n.x;
  684. }});
  685. }});
  686. // 节点颜色
  687. const levelColors = {{
  688. "灵感点": "#f39c12",
  689. "目的点": "#3498db",
  690. "关键点": "#9b59b6"
  691. }};
  692. // 四层Y坐标(带倾斜:右边高,左边低)
  693. const postPointBaseY = height * 0.10; // 帖子点节点(第1层-顶层)
  694. const postTagBaseY = height * 0.30; // 帖子标签节点(第2层)
  695. const personaBaseY = height * 0.55; // 人设标签节点(第3层)
  696. const expandedBaseY = height * 0.82; // 人设分类节点(第4层-底层)
  697. const tiltAmount = height * 0.15; // 倾斜幅度
  698. // 根据X位置计算Y(右边高,左边低)
  699. function getTiltedY(baseY, x) {{
  700. const tilt = tiltAmount * (0.5 - x / width);
  701. return baseY + tilt;
  702. }}
  703. // 获取节点的基准Y(四层布局)
  704. function getNodeBaseY(d) {{
  705. if (d.source === "帖子") {{
  706. // 帖子侧:点节点在顶层,标签节点在第2层
  707. return d.节点类型 === "点" ? postPointBaseY : postTagBaseY;
  708. }}
  709. // 人设侧:扩展节点(分类)在底层,直接匹配节点在第3层
  710. if (d.是否扩展) return expandedBaseY;
  711. return personaBaseY;
  712. }}
  713. // 力导向模拟
  714. simulation = d3.forceSimulation(nodes)
  715. .force("link", d3.forceLink(links).id(d => d.id)
  716. .distance(d => {{
  717. // 帖子之间的边(镜像边/二阶边)距离更大
  718. if (d.type && (d.type.startsWith("镜像_") || d.type.startsWith("二阶_"))) {{
  719. return 200;
  720. }}
  721. return 80;
  722. }})
  723. .strength(0.1))
  724. .force("charge", d3.forceManyBody()
  725. .strength(d => {{
  726. // 帖子节点排斥力更强
  727. if (d.source === "帖子") return -600;
  728. return -300;
  729. }}))
  730. // X方向:拉向目标位置,但允许被推开
  731. .force("x", d3.forceX(d => nodeTargetX[d.id] || width / 2).strength(0.15))
  732. // Y方向力:三层布局+倾斜
  733. .force("y", d3.forceY(d => {{
  734. const baseY = getNodeBaseY(d);
  735. return getTiltedY(baseY, d.x || width / 2);
  736. }}).strength(0.5))
  737. .force("collision", d3.forceCollide()
  738. .radius(d => {{
  739. // 帖子节点碰撞半径更大
  740. if (d.source === "帖子") return 60;
  741. return 40;
  742. }}));
  743. // 边类型到CSS类的映射
  744. const edgeTypeClass = {{
  745. "匹配": "match",
  746. "分类共现(跨点)": "category-cross",
  747. "分类共现(点内)": "category-intra",
  748. "标签共现": "tag-cooccur",
  749. "属于": "belong",
  750. "包含": "contain",
  751. // 镜像边(帖子节点之间,虚线)
  752. "镜像_分类共现(跨点)": "mirror-category-cross",
  753. "镜像_分类共现(点内)": "mirror-category-intra",
  754. "镜像_标签共现": "mirror-tag-cooccur",
  755. "镜像_属于": "mirror-belong",
  756. "镜像_包含": "mirror-contain"
  757. }};
  758. // 获取边的CSS类(处理二阶边,映射到对应的镜像边样式)
  759. function getEdgeClass(edgeType) {{
  760. if (edgeTypeClass[edgeType]) return edgeTypeClass[edgeType];
  761. // 二阶边映射到对应的镜像边样式(颜色相同,都用虚线)
  762. if (edgeType.startsWith("二阶_")) {{
  763. const originalType = edgeType.replace("二阶_", "");
  764. const mirrorType = "镜像_" + originalType;
  765. if (edgeTypeClass[mirrorType]) return edgeTypeClass[mirrorType];
  766. }}
  767. return "match";
  768. }}
  769. // 创建边的容器
  770. const linkGroup = g.append("g").attr("class", "links");
  771. // 为每条边创建组
  772. const linkG = linkGroup.selectAll("g")
  773. .data(links)
  774. .join("g")
  775. .attr("class", "link-group");
  776. // 绘制点击热区(透明宽线)
  777. const linkHitarea = linkG.append("line")
  778. .attr("class", "link-hitarea");
  779. // 绘制可见的边
  780. const link = linkG.append("line")
  781. .attr("class", d => "link " + getEdgeClass(d.type))
  782. .attr("stroke-width", d => d.type === "匹配" ? 2.5 : 1.5);
  783. // 为匹配边添加分数标签
  784. const edgeLabels = linkG.filter(d => d.type === "匹配" && d.边详情 && d.边详情.相似度)
  785. .append("g")
  786. .attr("class", "edge-label-group");
  787. edgeLabels.append("rect")
  788. .attr("class", "edge-label-bg")
  789. .attr("rx", 3)
  790. .attr("ry", 3);
  791. edgeLabels.append("text")
  792. .attr("class", "edge-label")
  793. .text(d => {{
  794. const score = d.边详情.相似度;
  795. return typeof score === "number" ? score.toFixed(2) : score;
  796. }});
  797. // 边的点击事件
  798. linkHitarea.on("click", (event, d, i) => {{
  799. event.stopPropagation();
  800. const linkIndex = links.indexOf(d);
  801. highlightEdge(d, linkIndex);
  802. showEdgeInfo(d);
  803. }})
  804. .on("mouseover", function(event, d) {{
  805. d3.select(this.parentNode).select(".link")
  806. .attr("stroke-opacity", 1)
  807. .attr("stroke-width", 4);
  808. }})
  809. .on("mouseout", function(event, d) {{
  810. d3.select(this.parentNode).select(".link")
  811. .attr("stroke-opacity", 0.7)
  812. .attr("stroke-width", d.type === "匹配" ? 2.5 : 1.5);
  813. }});
  814. // 绘制节点
  815. const node = g.append("g")
  816. .selectAll("g")
  817. .data(nodes)
  818. .join("g")
  819. .attr("class", "node")
  820. .call(d3.drag()
  821. .on("start", dragstarted)
  822. .on("drag", dragged)
  823. .on("end", dragended));
  824. // 根据节点类型绘制不同形状
  825. // - 点节点(帖子点):六边形(更大)
  826. // - 标签节点:圆形
  827. // - 分类节点:方形
  828. node.each(function(d) {{
  829. const el = d3.select(this);
  830. const isExpanded = d.是否扩展 === true;
  831. const isUnmatched = d.source === "帖子" && d.节点类型 === "标签" && d.已匹配 === false;
  832. const isPointNode = d.节点类型 === "点";
  833. // 点节点更大,标签节点根据来源区分大小
  834. let size;
  835. if (isPointNode) {{
  836. size = 16; // 点节点最大
  837. }} else if (d.source === "帖子") {{
  838. size = 12; // 帖子标签
  839. }} else if (isExpanded) {{
  840. size = 8; // 扩展的分类节点
  841. }} else {{
  842. size = 10; // 人设标签
  843. }}
  844. const fill = levelColors[d.level] || "#666";
  845. const nodeClass = d.source === "帖子"
  846. ? (isPointNode ? "post-point-node" : (isUnmatched ? "post-node unmatched" : "post-node"))
  847. : "persona-node";
  848. const opacity = isExpanded ? 0.5 : (isUnmatched ? 0.4 : 1);
  849. if (isPointNode) {{
  850. // 六边形(点节点)
  851. const hexPoints = [];
  852. for (let i = 0; i < 6; i++) {{
  853. const angle = (i * 60 - 30) * Math.PI / 180;
  854. hexPoints.push([size * Math.cos(angle), size * Math.sin(angle)]);
  855. }}
  856. el.append("polygon")
  857. .attr("points", hexPoints.map(p => p.join(",")).join(" "))
  858. .attr("fill", fill)
  859. .attr("class", nodeClass)
  860. .attr("opacity", opacity);
  861. }} else if (d.节点类型 === "分类") {{
  862. // 方形(分类节点)
  863. el.append("rect")
  864. .attr("width", size * 2)
  865. .attr("height", size * 2)
  866. .attr("x", -size)
  867. .attr("y", -size)
  868. .attr("fill", fill)
  869. .attr("class", nodeClass)
  870. .attr("rx", 3)
  871. .attr("opacity", opacity);
  872. }} else {{
  873. // 圆形(标签节点)
  874. el.append("circle")
  875. .attr("r", size)
  876. .attr("fill", isUnmatched ? "#666" : fill)
  877. .attr("class", nodeClass)
  878. .attr("opacity", opacity);
  879. }}
  880. }});
  881. const labels = node.append("text")
  882. .attr("dx", 15)
  883. .attr("dy", 4)
  884. .text(d => d.节点名称)
  885. .style("display", showLabels ? "block" : "none");
  886. // 工具提示
  887. const tooltip = d3.select("#tooltip");
  888. node.on("mouseover", (event, d) => {{
  889. let html = `<strong>${{d.节点名称}}</strong><br/>类型: ${{d.节点类型}}<br/>层级: ${{d.节点层级}}`;
  890. // 点节点显示描述
  891. if (d.描述) {{
  892. html += `<br/><br/><em style="font-size:10px;color:#aaa">${{d.描述.slice(0, 100)}}${{d.描述.length > 100 ? '...' : ''}}</em>`;
  893. }}
  894. tooltip.style("display", "block").html(html);
  895. }})
  896. .on("mousemove", (event) => {{
  897. tooltip.style("left", (event.pageX + 15) + "px")
  898. .style("top", (event.pageY - 10) + "px");
  899. }})
  900. .on("mouseout", () => {{
  901. tooltip.style("display", "none");
  902. }})
  903. .on("click", (event, d) => {{
  904. event.stopPropagation();
  905. highlightNode(d);
  906. showNodeInfo(d);
  907. }});
  908. // 更新位置
  909. simulation.on("tick", () => {{
  910. // 更新热区线
  911. linkHitarea
  912. .attr("x1", d => d.source.x)
  913. .attr("y1", d => d.source.y)
  914. .attr("x2", d => d.target.x)
  915. .attr("y2", d => d.target.y);
  916. // 更新可见边
  917. link
  918. .attr("x1", d => d.source.x)
  919. .attr("y1", d => d.source.y)
  920. .attr("x2", d => d.target.x)
  921. .attr("y2", d => d.target.y);
  922. // 更新边标签位置(放在边的中点)
  923. edgeLabels.attr("transform", d => {{
  924. const midX = (d.source.x + d.target.x) / 2;
  925. const midY = (d.source.y + d.target.y) / 2;
  926. return `translate(${{midX}},${{midY}})`;
  927. }});
  928. // 更新标签背景大小
  929. edgeLabels.each(function(d) {{
  930. const textEl = d3.select(this).select("text").node();
  931. if (textEl) {{
  932. const bbox = textEl.getBBox();
  933. d3.select(this).select("rect")
  934. .attr("x", bbox.x - 3)
  935. .attr("y", bbox.y - 1)
  936. .attr("width", bbox.width + 6)
  937. .attr("height", bbox.height + 2);
  938. }}
  939. }});
  940. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  941. }});
  942. // 拖拽函数
  943. function dragstarted(event, d) {{
  944. if (!event.active) simulation.alphaTarget(0.3).restart();
  945. d.fx = d.x;
  946. d.fy = d.y;
  947. }}
  948. function dragged(event, d) {{
  949. d.fx = event.x;
  950. d.fy = event.y;
  951. }}
  952. function dragended(event, d) {{
  953. if (!event.active) simulation.alphaTarget(0);
  954. d.fx = null;
  955. d.fy = null;
  956. }}
  957. // 清除所有高亮
  958. function clearHighlight() {{
  959. node.classed("dimmed", false).classed("highlighted", false);
  960. linkG.classed("dimmed", false).classed("highlighted", false);
  961. }}
  962. // 高亮指定的节点和边
  963. function highlightElements(highlightNodeIds, highlightLinkIndices) {{
  964. // 先灰化所有
  965. node.classed("dimmed", true).classed("highlighted", false);
  966. linkG.classed("dimmed", true).classed("highlighted", false);
  967. // 高亮指定节点
  968. node.filter(d => highlightNodeIds.has(d.id))
  969. .classed("dimmed", false)
  970. .classed("highlighted", true);
  971. // 高亮指定边
  972. linkG.filter((d, i) => highlightLinkIndices.has(i))
  973. .classed("dimmed", false)
  974. .classed("highlighted", true);
  975. }}
  976. // 点击节点时的高亮逻辑
  977. function highlightNode(clickedNode) {{
  978. const highlightNodeIds = new Set([clickedNode.id]);
  979. const highlightLinkIndices = new Set();
  980. links.forEach((link, i) => {{
  981. const sourceId = typeof link.source === "object" ? link.source.id : link.source;
  982. const targetId = typeof link.target === "object" ? link.target.id : link.target;
  983. // 与点击节点直接相连的边
  984. if (sourceId === clickedNode.id || targetId === clickedNode.id) {{
  985. highlightLinkIndices.add(i);
  986. highlightNodeIds.add(sourceId);
  987. highlightNodeIds.add(targetId);
  988. // 如果是帖子节点,还要高亮对应的镜像边
  989. if (clickedNode.source === "帖子") {{
  990. // 找到通过该帖子连接的其他帖子(镜像边)
  991. links.forEach((otherLink, j) => {{
  992. const otherType = otherLink.type;
  993. if (otherType.startsWith("镜像_") || otherType.startsWith("二阶_")) {{
  994. const oSrc = typeof otherLink.source === "object" ? otherLink.source.id : otherLink.source;
  995. const oTgt = typeof otherLink.target === "object" ? otherLink.target.id : otherLink.target;
  996. if (oSrc === clickedNode.id || oTgt === clickedNode.id) {{
  997. highlightLinkIndices.add(j);
  998. highlightNodeIds.add(oSrc);
  999. highlightNodeIds.add(oTgt);
  1000. }}
  1001. }}
  1002. }});
  1003. }}
  1004. }}
  1005. }});
  1006. highlightElements(highlightNodeIds, highlightLinkIndices);
  1007. }}
  1008. // 点击边时的高亮逻辑
  1009. function highlightEdge(clickedLink, clickedIndex) {{
  1010. const highlightNodeIds = new Set();
  1011. const highlightLinkIndices = new Set([clickedIndex]);
  1012. const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
  1013. const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
  1014. highlightNodeIds.add(sourceId);
  1015. highlightNodeIds.add(targetId);
  1016. // 如果是二阶边,显示完整路径
  1017. if (clickedLink.type.startsWith("二阶_") && clickedLink.边详情) {{
  1018. const detail = clickedLink.边详情;
  1019. // 分类节点
  1020. if (detail.分类节点1) highlightNodeIds.add(detail.分类节点1);
  1021. if (detail.分类节点2) highlightNodeIds.add(detail.分类节点2);
  1022. // 标签节点
  1023. if (detail.标签节点1) highlightNodeIds.add(detail.标签节点1);
  1024. if (detail.标签节点2) highlightNodeIds.add(detail.标签节点2);
  1025. // 找出路径上的边
  1026. links.forEach((link, i) => {{
  1027. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  1028. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  1029. // 帖子->标签 的匹配边
  1030. if (link.type === "匹配") {{
  1031. if ((lSrc === sourceId && lTgt === detail.标签节点1) ||
  1032. (lSrc === targetId && lTgt === detail.标签节点2)) {{
  1033. highlightLinkIndices.add(i);
  1034. }}
  1035. }}
  1036. // 标签->分类 的属于边
  1037. if (link.type === "属于") {{
  1038. if ((lSrc === detail.标签节点1 && lTgt === detail.分类节点1) ||
  1039. (lSrc === detail.标签节点2 && lTgt === detail.分类节点2)) {{
  1040. highlightLinkIndices.add(i);
  1041. }}
  1042. }}
  1043. // 分类之间的边
  1044. if ((lSrc === detail.分类节点1 && lTgt === detail.分类节点2) ||
  1045. (lSrc === detail.分类节点2 && lTgt === detail.分类节点1)) {{
  1046. highlightLinkIndices.add(i);
  1047. }}
  1048. }});
  1049. }}
  1050. // 如果是镜像边,显示对应的人设边
  1051. else if (clickedLink.type.startsWith("镜像_") && clickedLink.边详情) {{
  1052. const detail = clickedLink.边详情;
  1053. if (detail.源人设节点) highlightNodeIds.add(detail.源人设节点);
  1054. if (detail.目标人设节点) highlightNodeIds.add(detail.目标人设节点);
  1055. // 找出对应的人设边和匹配边
  1056. links.forEach((link, i) => {{
  1057. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  1058. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  1059. // 匹配边
  1060. if (link.type === "匹配") {{
  1061. if ((lSrc === sourceId && lTgt === detail.源人设节点) ||
  1062. (lSrc === targetId && lTgt === detail.目标人设节点)) {{
  1063. highlightLinkIndices.add(i);
  1064. }}
  1065. }}
  1066. // 人设边
  1067. if ((lSrc === detail.源人设节点 && lTgt === detail.目标人设节点) ||
  1068. (lSrc === detail.目标人设节点 && lTgt === detail.源人设节点)) {{
  1069. highlightLinkIndices.add(i);
  1070. }}
  1071. }});
  1072. }}
  1073. highlightElements(highlightNodeIds, highlightLinkIndices);
  1074. }}
  1075. // 点击空白处清除高亮
  1076. svg.on("click", (event) => {{
  1077. if (event.target === svg.node()) {{
  1078. clearHighlight();
  1079. closeDetailPanel();
  1080. }}
  1081. }});
  1082. }}
  1083. // 控制函数
  1084. function resetZoom() {{
  1085. const container = document.getElementById("graph");
  1086. const width = container.clientWidth;
  1087. const height = container.clientHeight;
  1088. svg.transition().duration(750).call(
  1089. zoom.transform,
  1090. d3.zoomIdentity.translate(width/2, height/2).scale(1).translate(-width/2, -height/2)
  1091. );
  1092. }}
  1093. function toggleLabels() {{
  1094. showLabels = !showLabels;
  1095. g.selectAll(".node text").style("display", showLabels ? "block" : "none");
  1096. }}
  1097. function showNodeInfo(d) {{
  1098. const panel = document.getElementById("detailPanel");
  1099. panel.classList.add("active");
  1100. document.getElementById("detailTitle").textContent = d.source === "帖子" ? "📌 帖子节点" : "👤 人设节点";
  1101. let html = `
  1102. <p><span class="label">节点ID:</span> ${{d.节点ID}}</p>
  1103. <p><span class="label">名称:</span> <strong>${{d.节点名称}}</strong></p>
  1104. <p><span class="label">类型:</span> ${{d.节点类型}}</p>
  1105. <p><span class="label">层级:</span> ${{d.节点层级}}</p>
  1106. `;
  1107. if (d.权重) {{
  1108. html += `<p><span class="label">权重:</span> ${{d.权重}}</p>`;
  1109. }}
  1110. if (d.所属分类 && d.所属分类.length > 0) {{
  1111. html += `<p><span class="label">所属分类:</span> ${{d.所属分类.join(" > ")}}</p>`;
  1112. }}
  1113. if (d.帖子数) {{
  1114. html += `<p><span class="label">帖子数:</span> ${{d.帖子数}}</p>`;
  1115. }}
  1116. document.getElementById("detailContent").innerHTML = html;
  1117. }}
  1118. function showEdgeInfo(d) {{
  1119. const panel = document.getElementById("detailPanel");
  1120. panel.classList.add("active");
  1121. const sourceNode = typeof d.source === "object" ? d.source : {{ id: d.source }};
  1122. const targetNode = typeof d.target === "object" ? d.target : {{ id: d.target }};
  1123. // 判断是否为镜像边
  1124. const isMirror = d.type.startsWith("镜像_");
  1125. document.getElementById("detailTitle").textContent = isMirror ? "🪞 镜像边详情" : "🔗 边详情";
  1126. let html = `
  1127. <p><span class="label">边类型:</span> <strong>${{d.type}}</strong></p>
  1128. <p><span class="label">源节点:</span> ${{sourceNode.节点名称 || sourceNode.id}}</p>
  1129. <p><span class="label">目标节点:</span> ${{targetNode.节点名称 || targetNode.id}}</p>
  1130. `;
  1131. if (d.边详情) {{
  1132. if (d.边详情.相似度 !== undefined) {{
  1133. const score = typeof d.边详情.相似度 === "number" ? d.边详情.相似度.toFixed(2) : d.边详情.相似度;
  1134. html += `<p><span class="label">相似度:</span> <span class="similarity-score">${{score}}</span></p>`;
  1135. }}
  1136. if (d.边详情.说明) {{
  1137. html += `<p><span class="label">说明:</span></p><div class="edge-description">${{d.边详情.说明}}</div>`;
  1138. }}
  1139. if (d.边详情.共现次数 !== undefined) {{
  1140. html += `<p><span class="label">共现次数:</span> ${{d.边详情.共现次数}}</p>`;
  1141. }}
  1142. // 镜像边特有信息
  1143. if (d.边详情.原始边类型) {{
  1144. html += `<p><span class="label">原始边类型:</span> ${{d.边详情.原始边类型}}</p>`;
  1145. }}
  1146. if (d.边详情.源人设节点) {{
  1147. html += `<p><span class="label">源人设节点:</span> ${{d.边详情.源人设节点}}</p>`;
  1148. }}
  1149. if (d.边详情.目标人设节点) {{
  1150. html += `<p><span class="label">目标人设节点:</span> ${{d.边详情.目标人设节点}}</p>`;
  1151. }}
  1152. }}
  1153. document.getElementById("detailContent").innerHTML = html;
  1154. }}
  1155. function closeDetailPanel() {{
  1156. document.getElementById("detailPanel").classList.remove("active");
  1157. }}
  1158. // 页面加载完成后初始化
  1159. window.addEventListener("load", init);
  1160. window.addEventListener("resize", () => {{
  1161. if (currentIndex >= 0) {{
  1162. renderGraph(allGraphData[currentIndex]);
  1163. }}
  1164. }});
  1165. </script>
  1166. </body>
  1167. </html>
  1168. '''
  1169. def generate_combined_html(all_graph_data: List[Dict], output_file: Path):
  1170. """
  1171. 生成包含所有帖子图谱的HTML文件
  1172. Args:
  1173. all_graph_data: 所有帖子的图谱数据列表
  1174. output_file: 输出文件路径
  1175. """
  1176. # 生成Tab HTML
  1177. tabs_html = ""
  1178. for i, data in enumerate(all_graph_data):
  1179. post_title = data.get("postTitle", "")
  1180. # 使用帖子标题,如果太长则截断
  1181. if post_title:
  1182. tab_name = post_title[:15] + "..." if len(post_title) > 15 else post_title
  1183. else:
  1184. tab_name = f"帖子 {i+1}"
  1185. active_class = "active" if i == 0 else ""
  1186. tabs_html += f'<div class="tab {active_class}" data-index="{i}">{tab_name}</div>\n'
  1187. # 生成HTML
  1188. html_content = HTML_TEMPLATE.format(
  1189. tabs_html=tabs_html,
  1190. all_graph_data=json.dumps(all_graph_data, ensure_ascii=False)
  1191. )
  1192. with open(output_file, "w", encoding="utf-8") as f:
  1193. f.write(html_content)
  1194. def main():
  1195. # 使用路径配置
  1196. config = PathConfig()
  1197. print(f"账号: {config.account_name}")
  1198. print(f"输出版本: {config.output_version}")
  1199. print()
  1200. # 输入目录
  1201. match_graph_dir = config.intermediate_dir / "match_graph"
  1202. # 输出文件
  1203. output_file = config.intermediate_dir / "match_graph.html"
  1204. print(f"输入目录: {match_graph_dir}")
  1205. print(f"输出文件: {output_file}")
  1206. print()
  1207. # 读取所有匹配图谱文件
  1208. graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
  1209. print(f"找到 {len(graph_files)} 个匹配图谱文件")
  1210. all_graph_data = []
  1211. for i, graph_file in enumerate(graph_files, 1):
  1212. print(f" [{i}/{len(graph_files)}] 读取: {graph_file.name}")
  1213. with open(graph_file, "r", encoding="utf-8") as f:
  1214. match_graph_data = json.load(f)
  1215. # 提取需要的数据
  1216. graph_data = {
  1217. "postId": match_graph_data["说明"]["帖子ID"],
  1218. "postTitle": match_graph_data["说明"].get("帖子标题", ""),
  1219. "stats": match_graph_data["说明"]["统计"],
  1220. "nodes": match_graph_data["节点列表"],
  1221. "edges": match_graph_data["边列表"]
  1222. }
  1223. all_graph_data.append(graph_data)
  1224. # 生成HTML
  1225. print("\n生成HTML文件...")
  1226. generate_combined_html(all_graph_data, output_file)
  1227. print("\n" + "="*60)
  1228. print("处理完成!")
  1229. print(f"输出文件: {output_file}")
  1230. if __name__ == "__main__":
  1231. main()