visualize_match_graph.py 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899
  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. overflow: auto;
  76. }}
  77. #sidebar {{
  78. width: 300px;
  79. background: #16213e;
  80. padding: 15px;
  81. overflow-y: auto;
  82. border-left: 1px solid #0f3460;
  83. display: flex;
  84. flex-direction: column;
  85. }}
  86. #persona-tree-panel {{
  87. flex: 1;
  88. overflow-y: auto;
  89. margin-top: 15px;
  90. border-top: 1px solid #0f3460;
  91. padding-top: 10px;
  92. }}
  93. .tree-dimension {{
  94. margin-bottom: 15px;
  95. }}
  96. .tree-dimension-title {{
  97. font-size: 12px;
  98. font-weight: bold;
  99. padding: 5px 8px;
  100. border-radius: 4px;
  101. margin-bottom: 5px;
  102. cursor: pointer;
  103. display: flex;
  104. align-items: center;
  105. gap: 5px;
  106. }}
  107. .tree-dimension-title:hover {{
  108. opacity: 0.8;
  109. }}
  110. .tree-dimension-title .toggle {{
  111. font-size: 10px;
  112. transition: transform 0.2s;
  113. }}
  114. .tree-dimension-title.collapsed .toggle {{
  115. transform: rotate(-90deg);
  116. }}
  117. .tree-dimension.inspiration .tree-dimension-title {{
  118. background: rgba(243, 156, 18, 0.2);
  119. color: #f39c12;
  120. }}
  121. .tree-dimension.purpose .tree-dimension-title {{
  122. background: rgba(52, 152, 219, 0.2);
  123. color: #3498db;
  124. }}
  125. .tree-dimension.key .tree-dimension-title {{
  126. background: rgba(155, 89, 182, 0.2);
  127. color: #9b59b6;
  128. }}
  129. .tree-list {{
  130. list-style: none;
  131. padding-left: 0;
  132. margin: 0;
  133. font-size: 11px;
  134. }}
  135. .tree-list.collapsed {{
  136. display: none;
  137. }}
  138. .tree-item {{
  139. padding: 3px 0;
  140. color: #aaa;
  141. cursor: pointer;
  142. border-radius: 3px;
  143. padding: 3px 6px;
  144. margin: 1px 0;
  145. }}
  146. .tree-item:hover {{
  147. background: rgba(255,255,255,0.08);
  148. color: #fff;
  149. }}
  150. .tree-item.matched {{
  151. color: #2ecc71;
  152. font-weight: 500;
  153. }}
  154. .tree-item .indent {{
  155. display: inline-block;
  156. width: 12px;
  157. color: #555;
  158. }}
  159. h1 {{
  160. font-size: 15px;
  161. margin-bottom: 10px;
  162. color: #e94560;
  163. }}
  164. h2 {{
  165. font-size: 12px;
  166. margin: 10px 0 6px;
  167. color: #0f9b8e;
  168. }}
  169. .legend {{
  170. margin-top: 10px;
  171. }}
  172. .legend-grid {{
  173. display: grid;
  174. grid-template-columns: 1fr 1fr;
  175. gap: 4px 8px;
  176. }}
  177. .legend-item {{
  178. display: flex;
  179. align-items: center;
  180. font-size: 11px;
  181. }}
  182. .legend-color {{
  183. width: 12px;
  184. height: 12px;
  185. border-radius: 50%;
  186. margin-right: 6px;
  187. flex-shrink: 0;
  188. }}
  189. .legend-line {{
  190. width: 20px;
  191. height: 3px;
  192. margin-right: 6px;
  193. flex-shrink: 0;
  194. }}
  195. .detail-panel {{
  196. margin-top: 20px;
  197. padding: 15px;
  198. background: #0f3460;
  199. border-radius: 8px;
  200. display: none;
  201. }}
  202. .detail-panel.active {{
  203. display: block;
  204. }}
  205. .detail-panel h3 {{
  206. font-size: 14px;
  207. margin-bottom: 10px;
  208. color: #e94560;
  209. }}
  210. .detail-panel p {{
  211. font-size: 12px;
  212. line-height: 1.6;
  213. color: #ccc;
  214. margin: 5px 0;
  215. }}
  216. .detail-panel .label {{
  217. color: #888;
  218. }}
  219. .detail-panel .close-btn {{
  220. position: absolute;
  221. top: 10px;
  222. right: 10px;
  223. background: none;
  224. border: none;
  225. color: #888;
  226. cursor: pointer;
  227. font-size: 16px;
  228. }}
  229. .detail-panel .close-btn:hover {{
  230. color: #e94560;
  231. }}
  232. .detail-panel-wrapper {{
  233. position: relative;
  234. }}
  235. .similarity-score {{
  236. background: #e94560;
  237. color: #fff;
  238. padding: 2px 6px;
  239. border-radius: 4px;
  240. font-weight: bold;
  241. }}
  242. .edge-description {{
  243. background: #1a1a2e;
  244. padding: 10px;
  245. border-radius: 4px;
  246. margin-top: 8px;
  247. font-size: 11px;
  248. line-height: 1.5;
  249. }}
  250. .edge-list {{
  251. background: #1a1a2e;
  252. padding: 8px;
  253. border-radius: 4px;
  254. margin-top: 4px;
  255. font-size: 11px;
  256. }}
  257. .edge-type-item {{
  258. display: flex;
  259. justify-content: space-between;
  260. padding: 2px 0;
  261. border-bottom: 1px solid rgba(255,255,255,0.05);
  262. }}
  263. .edge-type {{
  264. color: #aaa;
  265. }}
  266. .edge-count {{
  267. color: #e94560;
  268. font-weight: bold;
  269. }}
  270. .edge-detail {{
  271. padding: 3px 0;
  272. color: #888;
  273. font-size: 10px;
  274. border-left: 2px solid #333;
  275. padding-left: 8px;
  276. margin: 2px 0;
  277. }}
  278. .edge-type-tag {{
  279. background: rgba(255,255,255,0.1);
  280. padding: 1px 4px;
  281. border-radius: 2px;
  282. font-size: 9px;
  283. margin-left: 4px;
  284. }}
  285. .edge-more {{
  286. color: #666;
  287. font-size: 10px;
  288. text-align: center;
  289. padding: 4px 0;
  290. }}
  291. .edge-empty {{
  292. color: #555;
  293. font-size: 10px;
  294. padding: 4px 0;
  295. }}
  296. svg {{
  297. width: 100%;
  298. display: block; /* 避免底部多余空间 */
  299. }}
  300. .node {{
  301. cursor: pointer;
  302. }}
  303. .node circle, .node rect, .node polygon {{
  304. stroke-width: 3px;
  305. }}
  306. .node .post-point-node {{
  307. stroke: #fff;
  308. stroke-width: 4px;
  309. }}
  310. .node .post-node {{
  311. stroke: #fff;
  312. stroke-dasharray: 4,2;
  313. }}
  314. .node .post-node.unmatched {{
  315. stroke: #555;
  316. stroke-dasharray: 2,2;
  317. }}
  318. .node .persona-node {{
  319. stroke: #fff;
  320. }}
  321. .node text {{
  322. font-size: 11px;
  323. fill: #fff;
  324. pointer-events: none;
  325. }}
  326. .link {{
  327. stroke-opacity: 0.7;
  328. }}
  329. .link-hitarea {{
  330. stroke: transparent;
  331. stroke-width: 15px;
  332. cursor: pointer;
  333. fill: none;
  334. }}
  335. .link-hitarea:hover + .link {{
  336. stroke-opacity: 1;
  337. stroke-width: 3px;
  338. }}
  339. .edge-label {{
  340. font-size: 10px;
  341. fill: #fff;
  342. pointer-events: none;
  343. text-anchor: middle;
  344. }}
  345. .edge-label-bg {{
  346. fill: rgba(0,0,0,0.7);
  347. }}
  348. .link.match {{
  349. stroke: #e94560;
  350. stroke-dasharray: 5,5;
  351. }}
  352. .link.category-cross {{
  353. stroke: #2ecc71;
  354. }}
  355. .link.category-intra {{
  356. stroke: #27ae60;
  357. stroke-dasharray: 3,3;
  358. }}
  359. .link.tag-cooccur {{
  360. stroke: #f39c12;
  361. }}
  362. .link.belong {{
  363. stroke: #9b59b6;
  364. }}
  365. .link.contain {{
  366. stroke: #8e44ad;
  367. stroke-dasharray: 2,2;
  368. }}
  369. /* 镜像边样式(实线,颜色与原边相同) */
  370. .link.mirror-category-cross {{
  371. stroke: #2ecc71;
  372. }}
  373. .link.mirror-category-intra {{
  374. stroke: #27ae60;
  375. }}
  376. .link.mirror-tag-cooccur {{
  377. stroke: #f39c12;
  378. }}
  379. .link.mirror-belong {{
  380. stroke: #9b59b6;
  381. }}
  382. .link.mirror-contain {{
  383. stroke: #8e44ad;
  384. }}
  385. /* 二阶边现在使用与镜像边相同的样式(基于原始边类型) */
  386. /* 高亮/灰化样式 */
  387. .node.dimmed circle, .node.dimmed rect, .node.dimmed polygon {{
  388. opacity: 0.15 !important;
  389. }}
  390. .node.dimmed text {{
  391. opacity: 0.15 !important;
  392. }}
  393. .link-group.dimmed .link {{
  394. stroke-opacity: 0.08 !important;
  395. }}
  396. .link-group.dimmed .edge-label-group {{
  397. opacity: 0.15 !important;
  398. }}
  399. .node.highlighted circle, .node.highlighted rect, .node.highlighted polygon {{
  400. stroke: #fff !important;
  401. stroke-width: 4px !important;
  402. filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
  403. }}
  404. .link-group.highlighted .link {{
  405. stroke-opacity: 1 !important;
  406. stroke-width: 3px !important;
  407. filter: drop-shadow(0 0 4px rgba(255,255,255,0.3));
  408. }}
  409. .tooltip {{
  410. position: absolute;
  411. background: rgba(0,0,0,0.9);
  412. color: #fff;
  413. padding: 10px 15px;
  414. border-radius: 6px;
  415. font-size: 12px;
  416. pointer-events: none;
  417. max-width: 300px;
  418. z-index: 1000;
  419. display: none;
  420. }}
  421. .controls {{
  422. position: absolute;
  423. top: 20px;
  424. left: 20px;
  425. background: rgba(22, 33, 62, 0.9);
  426. padding: 15px;
  427. border-radius: 8px;
  428. z-index: 100;
  429. }}
  430. .controls button {{
  431. background: #0f3460;
  432. color: #fff;
  433. border: none;
  434. padding: 8px 15px;
  435. margin: 5px;
  436. border-radius: 4px;
  437. cursor: pointer;
  438. font-size: 12px;
  439. }}
  440. .controls button:hover {{
  441. background: #e94560;
  442. }}
  443. .controls button.active {{
  444. background: #e94560;
  445. }}
  446. .controls .control-group {{
  447. margin-top: 10px;
  448. padding-top: 10px;
  449. border-top: 1px solid rgba(255,255,255,0.1);
  450. }}
  451. .controls .control-label {{
  452. font-size: 11px;
  453. color: #888;
  454. margin-bottom: 5px;
  455. }}
  456. .controls select {{
  457. background: #0f3460;
  458. color: #fff;
  459. border: none;
  460. padding: 6px 10px;
  461. border-radius: 4px;
  462. font-size: 12px;
  463. cursor: pointer;
  464. }}
  465. /* 关系子图节点样式 */
  466. .ego-node {{
  467. cursor: pointer;
  468. }}
  469. .ego-node circle {{
  470. stroke-width: 2px;
  471. }}
  472. .ego-node.center circle {{
  473. stroke: #fff;
  474. stroke-width: 3px;
  475. filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
  476. }}
  477. .ego-node text {{
  478. font-size: 10px;
  479. fill: #fff;
  480. pointer-events: none;
  481. }}
  482. .ego-edge {{
  483. stroke-opacity: 0.6;
  484. stroke-width: 1.5;
  485. }}
  486. </style>
  487. </head>
  488. <body>
  489. <div id="container">
  490. <div class="tabs" id="tabs">
  491. {tabs_html}
  492. </div>
  493. <div class="main-content">
  494. <div id="graph">
  495. <div class="controls">
  496. <button onclick="resetZoom()">重置视图</button>
  497. <button onclick="toggleLabels()">切换标签</button>
  498. <button onclick="toggleCrossLayerEdges()" id="crossLayerBtn">显示跨层边</button>
  499. <div class="control-group">
  500. <div class="control-label">人设树配置</div>
  501. <button onclick="toggleTreeTags()" id="treeTagBtn" class="active">显示标签</button>
  502. <select id="treeDepthSelect" onchange="setTreeDepth(this.value)">
  503. <option value="0">全部层级</option>
  504. <option value="2">2层</option>
  505. <option value="3">3层</option>
  506. <option value="4">4层</option>
  507. <option value="5">5层</option>
  508. </select>
  509. </div>
  510. </div>
  511. <div class="tooltip" id="tooltip"></div>
  512. </div>
  513. <div id="sidebar">
  514. <h1>匹配图谱</h1>
  515. <div class="detail-panel active" id="detailPanel">
  516. <h3 id="detailTitle">点击节点或边查看详情</h3>
  517. <div id="detailContent">
  518. <p style="color: #888; font-size: 11px;">点击图中的节点或边,这里会显示详细信息</p>
  519. </div>
  520. </div>
  521. <div class="legend">
  522. <h2>节点</h2>
  523. <div class="legend-grid">
  524. <div class="legend-item">
  525. <div class="legend-color" style="background: #666; border: 2px dashed #fff;"></div>
  526. <span>帖子(虚线)</span>
  527. </div>
  528. <div class="legend-item">
  529. <div class="legend-color" style="background: #666; border: 2px solid #fff;"></div>
  530. <span>人设(实线)</span>
  531. </div>
  532. <div class="legend-item">
  533. <div class="legend-color" style="background: #666; border-radius: 50%;"></div>
  534. <span>标签(圆)</span>
  535. </div>
  536. <div class="legend-item">
  537. <div class="legend-color" style="background: #666; border-radius: 2px;"></div>
  538. <span>分类(方)</span>
  539. </div>
  540. <div class="legend-item">
  541. <div class="legend-color" style="background: #666; opacity: 1;"></div>
  542. <span>直接匹配</span>
  543. </div>
  544. <div class="legend-item">
  545. <div class="legend-color" style="background: #666; opacity: 0.5;"></div>
  546. <span>扩展节点</span>
  547. </div>
  548. <div class="legend-item">
  549. <div class="legend-color" style="background: #f39c12;"></div>
  550. <span>灵感点</span>
  551. </div>
  552. <div class="legend-item">
  553. <div class="legend-color" style="background: #3498db;"></div>
  554. <span>目的点</span>
  555. </div>
  556. <div class="legend-item">
  557. <div class="legend-color" style="background: #9b59b6;"></div>
  558. <span>关键点</span>
  559. </div>
  560. </div>
  561. <h2>边(人设/实线)</h2>
  562. <div class="legend-grid">
  563. <div class="legend-item">
  564. <div class="legend-line" style="background: #e94560;"></div>
  565. <span>匹配</span>
  566. </div>
  567. <div class="legend-item">
  568. <div class="legend-line" style="background: #2ecc71;"></div>
  569. <span>分类共现(跨)</span>
  570. </div>
  571. <div class="legend-item">
  572. <div class="legend-line" style="background: #27ae60;"></div>
  573. <span>分类共现(内)</span>
  574. </div>
  575. <div class="legend-item">
  576. <div class="legend-line" style="background: #f39c12;"></div>
  577. <span>标签共现</span>
  578. </div>
  579. <div class="legend-item">
  580. <div class="legend-line" style="background: #9b59b6;"></div>
  581. <span>属于</span>
  582. </div>
  583. <div class="legend-item">
  584. <div class="legend-line" style="background: #8e44ad;"></div>
  585. <span>包含</span>
  586. </div>
  587. </div>
  588. <h2>帖子镜像边(直接)</h2>
  589. <div class="legend-grid">
  590. <div class="legend-item">
  591. <div class="legend-line" style="background: #2ecc71;"></div>
  592. <span>分类共现</span>
  593. </div>
  594. <div class="legend-item">
  595. <div class="legend-line" style="background: #f39c12;"></div>
  596. <span>标签共现</span>
  597. </div>
  598. <div class="legend-item">
  599. <div class="legend-line" style="background: #9b59b6;"></div>
  600. <span>属于</span>
  601. </div>
  602. <div class="legend-item">
  603. <div class="legend-line" style="background: #8e44ad;"></div>
  604. <span>包含</span>
  605. </div>
  606. </div>
  607. <h2>帖子镜像边(二阶)</h2>
  608. <div class="legend-grid">
  609. <div class="legend-item">
  610. <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>
  611. <span>通过扩展节点</span>
  612. </div>
  613. </div>
  614. </div>
  615. </div>
  616. </div>
  617. </div>
  618. <script>
  619. // 所有帖子的图谱数据
  620. const allGraphData = {all_graph_data};
  621. // 完整的人设树数据(所有人设节点和属于边)
  622. const personaTreeData = {persona_tree_data};
  623. // 当前选中的帖子索引
  624. let currentIndex = 0;
  625. let simulation = null;
  626. let svg = null;
  627. let g = null;
  628. let zoom = null;
  629. let showLabels = true;
  630. let showCrossLayerEdges = false; // 跨层边默认隐藏
  631. let isCrossLayerEdge = null; // 跨层边判断函数(在renderGraph中设置)
  632. // 人设树配置
  633. let showTreeTags = true; // 是否显示标签节点
  634. let treeMaxDepth = 0; // 显示的最大层数(0=全部)
  635. // 切换标签显示
  636. function toggleTreeTags() {{
  637. showTreeTags = !showTreeTags;
  638. const btn = document.getElementById("treeTagBtn");
  639. btn.textContent = showTreeTags ? "显示标签" : "隐藏标签";
  640. btn.classList.toggle("active", showTreeTags);
  641. // 重新渲染当前图谱
  642. renderGraph(allGraphData[currentIndex]);
  643. }}
  644. // 设置树的显示层数
  645. function setTreeDepth(depth) {{
  646. treeMaxDepth = parseInt(depth);
  647. // 重新渲染当前图谱
  648. renderGraph(allGraphData[currentIndex]);
  649. }}
  650. // 初始化
  651. function init() {{
  652. const container = document.getElementById("graph");
  653. const width = container.clientWidth;
  654. const height = container.clientHeight;
  655. svg = d3.select("#graph")
  656. .append("svg")
  657. .attr("width", width)
  658. .attr("height", height);
  659. g = svg.append("g");
  660. zoom = d3.zoom()
  661. .scaleExtent([0.1, 4])
  662. .on("zoom", (event) => {{
  663. g.attr("transform", event.transform);
  664. }});
  665. svg.call(zoom);
  666. // 绑定Tab点击事件
  667. document.querySelectorAll(".tab").forEach((tab, index) => {{
  668. tab.addEventListener("click", () => switchTab(index));
  669. }});
  670. // 显示第一个帖子
  671. switchTab(0);
  672. }}
  673. // 构建人设树数据(合并为一棵树,根节点为"人设")
  674. // showTreeTags: 控制是否显示标签节点
  675. // treeMaxDepth: 控制树的显示深度(0=全部,2=维度,3=+一层,4=+两层...)
  676. function buildPersonaTreeData() {{
  677. const dimensions = ["灵感点", "目的点", "关键点"];
  678. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  679. const dimensionChildren = [];
  680. let totalNodeCount = 0;
  681. dimensions.forEach(dim => {{
  682. // 根据 showTreeTags 过滤节点(独立于深度控制)
  683. let dimNodes = personaTreeData.nodes.filter(n => n.节点层级 === dim);
  684. if (!showTreeTags) {{
  685. dimNodes = dimNodes.filter(n => n.节点类型 !== "标签");
  686. }}
  687. if (dimNodes.length === 0) {{
  688. const dimNode = {{
  689. name: dim,
  690. 节点名称: dim,
  691. isDimension: true,
  692. dimColor: dimColors[dim],
  693. children: []
  694. }};
  695. dimensionChildren.push(dimNode);
  696. return;
  697. }}
  698. const nodeMap = {{}};
  699. dimNodes.forEach(n => nodeMap[n.节点ID] = {{ ...n, name: n.节点名称, children: [], dimColor: dimColors[dim] }});
  700. // 只用属于边构建父子关系
  701. const hierarchyEdgeTypes = ["属于"];
  702. const hasParent = new Set();
  703. personaTreeData.edges.forEach(e => {{
  704. if (!hierarchyEdgeTypes.includes(e.边类型)) return; // 跳过非层级边
  705. const srcNode = nodeMap[e.源节点ID];
  706. const tgtNode = nodeMap[e.目标节点ID];
  707. if (srcNode && tgtNode) {{
  708. tgtNode.children.push(srcNode);
  709. hasParent.add(e.源节点ID);
  710. }}
  711. }});
  712. const roots = dimNodes.filter(n => !hasParent.has(n.节点ID)).map(n => nodeMap[n.节点ID]);
  713. const dimNode = {{
  714. name: dim,
  715. 节点名称: dim,
  716. isDimension: true,
  717. dimColor: dimColors[dim],
  718. children: roots
  719. }};
  720. dimensionChildren.push(dimNode);
  721. totalNodeCount += dimNodes.length;
  722. }});
  723. // 根节点"人设"
  724. const rootNode = {{
  725. name: "人设",
  726. 节点名称: "人设",
  727. isRoot: true,
  728. children: dimensionChildren
  729. }};
  730. // 根据 treeMaxDepth 截断树深度(0=全部)
  731. // 深度1=根,深度2=维度,深度3+=子节点
  732. if (treeMaxDepth > 0) {{
  733. truncateTree(rootNode, 1, treeMaxDepth);
  734. }}
  735. return {{ root: rootNode, nodeCount: totalNodeCount }};
  736. }}
  737. // 递归截断树的深度
  738. function truncateTree(node, currentDepth, maxDepth) {{
  739. if (currentDepth >= maxDepth) {{
  740. node.children = [];
  741. return;
  742. }}
  743. if (node.children) {{
  744. node.children.forEach(child => truncateTree(child, currentDepth + 1, maxDepth));
  745. }}
  746. }}
  747. // 切换Tab
  748. function switchTab(index) {{
  749. currentIndex = index;
  750. // 更新Tab样式
  751. document.querySelectorAll(".tab").forEach((tab, i) => {{
  752. tab.classList.toggle("active", i === index);
  753. }});
  754. // 更新图谱
  755. renderGraph(allGraphData[index]);
  756. }}
  757. // 渲染图谱
  758. function renderGraph(data) {{
  759. // 清空现有图谱
  760. g.selectAll("*").remove();
  761. if (simulation) {{
  762. simulation.stop();
  763. }}
  764. const container = document.getElementById("graph");
  765. const width = container.clientWidth;
  766. // 布局配置:左侧人设树,右侧三层圆形
  767. // 树宽度自适应:占总宽度的35%,最小400,最大550
  768. const treeAreaWidth = Math.max(400, Math.min(550, width * 0.35));
  769. const circleAreaLeft = treeAreaWidth + 40; // 圆形区域起始X
  770. const circleAreaWidth = width - circleAreaLeft - 50;
  771. const circleAreaCenterX = circleAreaLeft + circleAreaWidth / 2;
  772. // 准备数据
  773. const nodes = data.nodes.map(n => ({{
  774. ...n,
  775. id: n.节点ID,
  776. source: n.节点ID.startsWith("帖子_") ? "帖子" : "人设",
  777. level: n.节点层级
  778. }}));
  779. const links = data.edges.map(e => ({{
  780. ...e,
  781. source: e.源节点ID,
  782. target: e.目标节点ID,
  783. type: e.边类型
  784. }}));
  785. // 分离节点类型
  786. const postNodes = nodes.filter(n => n.source === "帖子");
  787. const personaNodes = nodes.filter(n => n.source === "人设" && !n.是否扩展);
  788. const expandedNodes = nodes.filter(n => n.source === "人设" && n.是否扩展);
  789. const matchLinks = links.filter(l => l.type === "匹配");
  790. // 构建帖子节点到人设节点的映射
  791. const postToPersona = {{}};
  792. const personaToPost = {{}};
  793. matchLinks.forEach(l => {{
  794. const sid = typeof l.source === "object" ? l.source.id : l.source;
  795. const tid = typeof l.target === "object" ? l.target.id : l.target;
  796. if (!postToPersona[sid]) postToPersona[sid] = [];
  797. postToPersona[sid].push(tid);
  798. if (!personaToPost[tid]) personaToPost[tid] = [];
  799. personaToPost[tid].push(sid);
  800. }});
  801. // 找出所有连通分量
  802. function findConnectedComponents(nodes, links) {{
  803. const nodeIds = new Set(nodes.map(n => n.id));
  804. const adj = {{}};
  805. nodeIds.forEach(id => adj[id] = []);
  806. links.forEach(l => {{
  807. const sid = typeof l.source === "object" ? l.source.id : l.source;
  808. const tid = typeof l.target === "object" ? l.target.id : l.target;
  809. if (nodeIds.has(sid) && nodeIds.has(tid)) {{
  810. adj[sid].push(tid);
  811. adj[tid].push(sid);
  812. }}
  813. }});
  814. const visited = new Set();
  815. const components = [];
  816. nodeIds.forEach(startId => {{
  817. if (visited.has(startId)) return;
  818. const component = [];
  819. const queue = [startId];
  820. while (queue.length > 0) {{
  821. const id = queue.shift();
  822. if (visited.has(id)) continue;
  823. visited.add(id);
  824. component.push(id);
  825. adj[id].forEach(neighbor => {{
  826. if (!visited.has(neighbor)) queue.push(neighbor);
  827. }});
  828. }}
  829. components.push(component);
  830. }});
  831. return components;
  832. }}
  833. // 按大小排序连通分量(大的在前)
  834. const components = findConnectedComponents(nodes, links)
  835. .sort((a, b) => b.length - a.length);
  836. console.log(`找到 ${{components.length}} 个连通分量`);
  837. // 为每个节点分配连通分量ID和分量内的X范围
  838. const nodeToComponent = {{}};
  839. const componentCenters = {{}};
  840. const componentBounds = {{}};
  841. const padding = 50; // 分量之间的间距
  842. const totalPadding = padding * (components.length - 1);
  843. const availableWidth = width - totalPadding - 100; // 留边距
  844. // 根据分量大小分配宽度
  845. const totalNodes = nodes.length;
  846. let currentX = 50; // 起始边距
  847. components.forEach((comp, i) => {{
  848. const compWidth = Math.max(150, (comp.length / totalNodes) * availableWidth);
  849. const centerX = currentX + compWidth / 2;
  850. componentCenters[i] = centerX;
  851. componentBounds[i] = {{ start: currentX, end: currentX + compWidth, width: compWidth }};
  852. comp.forEach(nodeId => {{
  853. nodeToComponent[nodeId] = i;
  854. }});
  855. currentX += compWidth + padding;
  856. }});
  857. // 使用重心法(Barycenter)减少边交叉
  858. // 迭代优化:交替调整两层节点的顺序
  859. const nodeTargetX = {{}};
  860. const personaXMap = {{}};
  861. // 对每个连通分量单独处理
  862. components.forEach((comp, compIdx) => {{
  863. const bounds = componentBounds[compIdx];
  864. const compPostNodes = postNodes.filter(n => nodeToComponent[n.id] === compIdx);
  865. const compPersonaNodes = personaNodes.filter(n => nodeToComponent[n.id] === compIdx);
  866. if (compPostNodes.length === 0 || compPersonaNodes.length === 0) {{
  867. // 没有匹配关系的分量,均匀分布
  868. const spacing = bounds.width / (comp.length + 1);
  869. comp.forEach((nodeId, i) => {{
  870. const node = nodes.find(n => n.id === nodeId);
  871. if (node) {{
  872. node.x = bounds.start + spacing * (i + 1);
  873. nodeTargetX[nodeId] = node.x;
  874. if (node.source === "人设") personaXMap[nodeId] = node.x;
  875. }}
  876. }});
  877. return;
  878. }}
  879. // 初始化:给人设节点一个初始顺序
  880. let personaOrder = compPersonaNodes.map((n, i) => ({{ node: n, order: i }}));
  881. // 迭代优化(3轮)
  882. for (let iter = 0; iter < 3; iter++) {{
  883. // 1. 根据人设节点位置,计算帖子节点的重心
  884. const postBarycenter = {{}};
  885. compPostNodes.forEach(pn => {{
  886. const matched = postToPersona[pn.id] || [];
  887. if (matched.length > 0) {{
  888. const avgOrder = matched.reduce((sum, pid) => {{
  889. const po = personaOrder.find(p => p.node.id === pid);
  890. return sum + (po ? po.order : 0);
  891. }}, 0) / matched.length;
  892. postBarycenter[pn.id] = avgOrder;
  893. }} else {{
  894. postBarycenter[pn.id] = 0;
  895. }}
  896. }});
  897. // 按重心排序帖子节点
  898. const sortedPosts = [...compPostNodes].sort((a, b) =>
  899. postBarycenter[a.id] - postBarycenter[b.id]
  900. );
  901. // 2. 根据帖子节点位置,重新计算人设节点的重心
  902. const personaBarycenter = {{}};
  903. compPersonaNodes.forEach(pn => {{
  904. const matched = personaToPost[pn.id] || [];
  905. if (matched.length > 0) {{
  906. const avgOrder = matched.reduce((sum, pid) => {{
  907. const idx = sortedPosts.findIndex(p => p.id === pid);
  908. return sum + (idx >= 0 ? idx : 0);
  909. }}, 0) / matched.length;
  910. personaBarycenter[pn.id] = avgOrder;
  911. }} else {{
  912. personaBarycenter[pn.id] = personaOrder.find(p => p.node.id === pn.id)?.order || 0;
  913. }}
  914. }});
  915. // 更新人设节点顺序
  916. personaOrder = compPersonaNodes
  917. .map(n => ({{ node: n, order: personaBarycenter[n.id] }}))
  918. .sort((a, b) => a.order - b.order)
  919. .map((item, i) => ({{ node: item.node, order: i }}));
  920. }}
  921. // 最终排序
  922. const finalPersonaOrder = personaOrder.map(p => p.node);
  923. const postBarycenter = {{}};
  924. compPostNodes.forEach(pn => {{
  925. const matched = postToPersona[pn.id] || [];
  926. if (matched.length > 0) {{
  927. const avgOrder = matched.reduce((sum, pid) => {{
  928. const idx = finalPersonaOrder.findIndex(n => n.id === pid);
  929. return sum + (idx >= 0 ? idx : 0);
  930. }}, 0) / matched.length;
  931. postBarycenter[pn.id] = avgOrder;
  932. }} else {{
  933. postBarycenter[pn.id] = 0;
  934. }}
  935. }});
  936. const finalPostOrder = [...compPostNodes].sort((a, b) =>
  937. postBarycenter[a.id] - postBarycenter[b.id]
  938. );
  939. // 设置位置
  940. const personaSpacing = bounds.width / (finalPersonaOrder.length + 1);
  941. finalPersonaOrder.forEach((n, i) => {{
  942. n.x = bounds.start + personaSpacing * (i + 1);
  943. nodeTargetX[n.id] = n.x;
  944. personaXMap[n.id] = n.x;
  945. }});
  946. const postSpacing = bounds.width / (finalPostOrder.length + 1);
  947. finalPostOrder.forEach((n, i) => {{
  948. // 帖子节点用重心位置(匹配人设的平均X)
  949. const matched = postToPersona[n.id] || [];
  950. if (matched.length > 0) {{
  951. const avgX = matched.reduce((sum, pid) => sum + (personaXMap[pid] || bounds.start + bounds.width/2), 0) / matched.length;
  952. n.x = avgX;
  953. }} else {{
  954. n.x = bounds.start + postSpacing * (i + 1);
  955. }}
  956. nodeTargetX[n.id] = n.x;
  957. }});
  958. }});
  959. // 节点颜色
  960. const levelColors = {{
  961. "灵感点": "#f39c12",
  962. "目的点": "#3498db",
  963. "关键点": "#9b59b6"
  964. }};
  965. // 获取节点的层级编号(三层结构)
  966. function getNodeLayer(d) {{
  967. if (d.source === "帖子") {{
  968. return d.节点类型 === "点" ? 0 : 1; // 点=0, 标签=1
  969. }}
  970. return 2; // 人设(标签+分类)都在层2
  971. }}
  972. // 统计每层节点数量(三层结构)
  973. const layerCounts = {{0: 0, 1: 0, 2: 0}};
  974. nodes.forEach(n => {{
  975. const layer = getNodeLayer(n);
  976. layerCounts[layer]++;
  977. }});
  978. console.log("每层节点数:", layerCounts);
  979. // 根据节点数量计算每层圆的半径
  980. const minRadius = 80;
  981. const maxRadius = Math.min(circleAreaWidth / 2 - 30, 350);
  982. const nodeSpacing = 70;
  983. function calcRadius(nodeCount) {{
  984. if (nodeCount <= 1) return minRadius;
  985. const circumference = nodeCount * nodeSpacing;
  986. const r = circumference / (2 * Math.PI);
  987. return Math.max(minRadius, Math.min(maxRadius, r));
  988. }}
  989. const layerRadius = {{
  990. 0: calcRadius(layerCounts[0]),
  991. 1: calcRadius(layerCounts[1]),
  992. 2: calcRadius(layerCounts[2]),
  993. 3: 250 // 关系图层默认半径(更大,容纳更多节点)
  994. }};
  995. console.log("每层半径:", layerRadius);
  996. // 计算四层的高度和圆心Y坐标
  997. const layerPadding = 50;
  998. const layerHeights = {{
  999. 0: layerRadius[0] * 2 + layerPadding,
  1000. 1: layerRadius[1] * 2 + layerPadding,
  1001. 2: layerRadius[2] * 2 + layerPadding,
  1002. 3: layerRadius[3] * 2 + layerPadding
  1003. }};
  1004. // 获取人设树数据(单棵树)
  1005. const personaTree = buildPersonaTreeData();
  1006. // 树高度自适应:根据节点数量,每个节点约12px,最小800
  1007. const treeHeight = Math.max(800, personaTree.nodeCount * 12 + 150);
  1008. // 计算总高度(取圆形和树的最大值)
  1009. const circleHeight = layerHeights[0] + layerHeights[1] + layerHeights[2] + layerHeights[3];
  1010. const height = Math.max(circleHeight + 100, treeHeight + 80, container.clientHeight);
  1011. // 计算每层圆心坐标(在右侧区域)
  1012. const layerCenterX = {{}};
  1013. const layerCenterY = {{}};
  1014. let currentY = layerRadius[0] + layerPadding / 2 + 30;
  1015. layerCenterY[0] = currentY;
  1016. layerCenterX[0] = circleAreaCenterX;
  1017. currentY += layerRadius[0] + layerPadding + layerRadius[1];
  1018. layerCenterY[1] = currentY;
  1019. layerCenterX[1] = circleAreaCenterX;
  1020. currentY += layerRadius[1] + layerPadding + layerRadius[2];
  1021. layerCenterY[2] = currentY;
  1022. layerCenterX[2] = circleAreaCenterX;
  1023. currentY += layerRadius[2] + layerPadding + layerRadius[3];
  1024. layerCenterY[3] = currentY;
  1025. layerCenterX[3] = circleAreaCenterX;
  1026. console.log("每层圆心X:", layerCenterX);
  1027. console.log("每层圆心Y:", layerCenterY);
  1028. // 更新SVG高度
  1029. svg.attr("height", height);
  1030. // 获取节点的基准Y(层圆心)
  1031. function getNodeBaseY(d) {{
  1032. const layer = getNodeLayer(d);
  1033. return layerCenterY[layer];
  1034. }}
  1035. // 获取节点的基准X(层圆心)
  1036. function getNodeBaseX(d) {{
  1037. const layer = getNodeLayer(d);
  1038. return layerCenterX[layer];
  1039. }}
  1040. // 层边界配置(不再使用)
  1041. const layerBounds = {{}};
  1042. // 自定义层内排斥力(只对同层节点生效,尽量分散)
  1043. function forceIntraLayerRepulsion(strength) {{
  1044. let nodes;
  1045. function force(alpha) {{
  1046. for (let i = 0; i < nodes.length; i++) {{
  1047. const nodeA = nodes[i];
  1048. const layerA = getNodeLayer(nodeA);
  1049. for (let j = i + 1; j < nodes.length; j++) {{
  1050. const nodeB = nodes[j];
  1051. const layerB = getNodeLayer(nodeB);
  1052. // 只对同层节点施加排斥力
  1053. if (layerA !== layerB) continue;
  1054. const dx = nodeB.x - nodeA.x;
  1055. const dy = nodeB.y - nodeA.y;
  1056. const dist = Math.sqrt(dx * dx + dy * dy) || 1;
  1057. const minDist = 150; // 增大最小距离,让节点更分散
  1058. if (dist < minDist) {{
  1059. // 排斥力随距离衰减,但基础强度更大
  1060. const pushStrength = strength * alpha * (minDist - dist) / dist * 2;
  1061. const px = dx * pushStrength;
  1062. const py = dy * pushStrength;
  1063. nodeA.vx -= px;
  1064. nodeA.vy -= py;
  1065. nodeB.vx += px;
  1066. nodeB.vy += py;
  1067. }}
  1068. }}
  1069. }}
  1070. }}
  1071. force.initialize = function(_) {{
  1072. nodes = _;
  1073. }};
  1074. return force;
  1075. }}
  1076. // 层圆的半径(使用动态计算的 layerRadius)
  1077. // layerRadius 和 layerCenterY 已在前面定义
  1078. // 层边界约束力(把节点限制在层内)
  1079. function forceLayerBoundary() {{
  1080. let nodes;
  1081. function force(alpha) {{
  1082. nodes.forEach(node => {{
  1083. const layer = getNodeLayer(node);
  1084. const centerX = layerCenterX[layer];
  1085. const centerY = layerCenterY[layer];
  1086. // 使用圆形边界
  1087. const maxRadius = layerRadius[layer] - 15;
  1088. // 计算到圆心的距离
  1089. const dx = node.x - centerX;
  1090. const dy = node.y - centerY;
  1091. const dist = Math.sqrt(dx * dx + dy * dy);
  1092. // 如果超出圆形边界,拉回来
  1093. if (dist > maxRadius) {{
  1094. const scale = maxRadius / dist;
  1095. node.x = centerX + dx * scale;
  1096. node.y = centerY + dy * scale;
  1097. // 阻止继续向外运动
  1098. const angle = Math.atan2(dy, dx);
  1099. const vOutward = node.vx * Math.cos(angle) + node.vy * Math.sin(angle);
  1100. if (vOutward > 0) {{
  1101. node.vx -= vOutward * Math.cos(angle);
  1102. node.vy -= vOutward * Math.sin(angle);
  1103. }}
  1104. }}
  1105. }});
  1106. }}
  1107. force.initialize = function(_) {{
  1108. nodes = _;
  1109. }};
  1110. return force;
  1111. }}
  1112. // 层内圆形布局力(让同层节点围绕圆心分布)
  1113. function forceCircularLayout(strength) {{
  1114. let nodes;
  1115. function force(alpha) {{
  1116. // 按层分组(三层)
  1117. const layerNodes = {{0: [], 1: [], 2: []}};
  1118. nodes.forEach(node => {{
  1119. const layer = getNodeLayer(node);
  1120. layerNodes[layer].push(node);
  1121. }});
  1122. // 对每层计算布局
  1123. Object.entries(layerNodes).forEach(([layerIdx, layerGroup]) => {{
  1124. if (layerGroup.length === 0) return;
  1125. const layer = parseInt(layerIdx);
  1126. const centerX = layerCenterX[layer];
  1127. const centerY = layerCenterY[layer];
  1128. // 使用圆形布局
  1129. const nodeRadius = layerRadius[layer] - 20;
  1130. if (layerGroup.length === 1) {{
  1131. // 单个节点放在圆心
  1132. const node = layerGroup[0];
  1133. node.vx += (centerX - node.x) * strength * alpha;
  1134. node.vy += (centerY - node.y) * strength * alpha;
  1135. return;
  1136. }}
  1137. // 按角度排序节点(保持相对位置稳定)
  1138. layerGroup.forEach(node => {{
  1139. node._angle = Math.atan2(node.y - centerY, node.x - centerX);
  1140. }});
  1141. layerGroup.sort((a, b) => a._angle - b._angle);
  1142. // 均匀分布在圆周上
  1143. const angleStep = (2 * Math.PI) / layerGroup.length;
  1144. layerGroup.forEach((node, i) => {{
  1145. const angle = -Math.PI / 2 + i * angleStep; // 从顶部开始
  1146. const idealX = centerX + nodeRadius * Math.cos(angle);
  1147. const idealY = centerY + nodeRadius * Math.sin(angle);
  1148. node.vx += (idealX - node.x) * strength * alpha;
  1149. node.vy += (idealY - node.y) * strength * alpha;
  1150. }});
  1151. }});
  1152. }}
  1153. force.initialize = function(_) {{
  1154. nodes = _;
  1155. }};
  1156. return force;
  1157. }}
  1158. // 力导向模拟
  1159. simulation = d3.forceSimulation(nodes)
  1160. // 连线力(跨层连接)
  1161. .force("link", d3.forceLink(links).id(d => d.id)
  1162. .distance(d => {{
  1163. // 跨层连线距离
  1164. if (d.type === "匹配" || d.type === "属于") {{
  1165. return 150; // 跨层边
  1166. }}
  1167. return 60; // 同层边
  1168. }})
  1169. .strength(d => {{
  1170. // 跨层边力度弱一些,不要拉扯节点出层
  1171. if (d.type === "匹配" || d.type === "属于") {{
  1172. return 0.03;
  1173. }}
  1174. return 0.1;
  1175. }}))
  1176. // X方向:轻微拉向各层中心
  1177. .force("x", d3.forceX(d => getNodeBaseX(d)).strength(0.02))
  1178. // Y方向:轻微拉向层中心
  1179. .force("y", d3.forceY(d => getNodeBaseY(d)).strength(0.02))
  1180. // 层内碰撞检测
  1181. .force("collision", d3.forceCollide().radius(30))
  1182. // 层内排斥力(同层节点相互排斥)
  1183. .force("intraLayer", forceIntraLayerRepulsion(0.8))
  1184. // 层内布局(圆形或树状)
  1185. .force("circularLayout", forceCircularLayout(0.15))
  1186. // 层边界约束(节点不能跑出层,硬约束)
  1187. .force("boundary", forceLayerBoundary());
  1188. // 边类型到CSS类的映射
  1189. const edgeTypeClass = {{
  1190. "匹配": "match",
  1191. "分类共现(跨点)": "category-cross",
  1192. "分类共现(点内)": "category-intra",
  1193. "标签共现": "tag-cooccur",
  1194. "属于": "belong",
  1195. "包含": "contain",
  1196. // 镜像边(帖子节点之间,虚线)
  1197. "镜像_分类共现(跨点)": "mirror-category-cross",
  1198. "镜像_分类共现(点内)": "mirror-category-intra",
  1199. "镜像_标签共现": "mirror-tag-cooccur",
  1200. "镜像_属于": "mirror-belong",
  1201. "镜像_包含": "mirror-contain"
  1202. }};
  1203. // 获取边的CSS类(处理二阶边,映射到对应的镜像边样式)
  1204. function getEdgeClass(edgeType) {{
  1205. if (edgeTypeClass[edgeType]) return edgeTypeClass[edgeType];
  1206. // 二阶边映射到对应的镜像边样式(颜色相同,都用虚线)
  1207. if (edgeType.startsWith("二阶_")) {{
  1208. const originalType = edgeType.replace("二阶_", "");
  1209. const mirrorType = "镜像_" + originalType;
  1210. if (edgeTypeClass[mirrorType]) return edgeTypeClass[mirrorType];
  1211. }}
  1212. return "match";
  1213. }}
  1214. // 绘制层背景(圆形,使用动态大小)
  1215. const layerBg = g.append("g").attr("class", "layer-backgrounds");
  1216. // 层配置:名称、颜色(四层圆)
  1217. const layerConfig = [
  1218. {{ name: "帖子点", layer: 0, color: "rgba(243, 156, 18, 0.08)", stroke: "rgba(243, 156, 18, 0.3)" }},
  1219. {{ name: "帖子标签", layer: 1, color: "rgba(52, 152, 219, 0.08)", stroke: "rgba(52, 152, 219, 0.3)" }},
  1220. {{ name: "人设", layer: 2, color: "rgba(155, 89, 182, 0.08)", stroke: "rgba(155, 89, 182, 0.3)" }},
  1221. {{ name: "关系图", layer: 3, color: "rgba(233, 69, 96, 0.08)", stroke: "rgba(233, 69, 96, 0.3)" }}
  1222. ];
  1223. // 绘制四层圆形背景
  1224. layerConfig.forEach(cfg => {{
  1225. const cx = layerCenterX[cfg.layer];
  1226. const cy = layerCenterY[cfg.layer];
  1227. const r = layerRadius[cfg.layer];
  1228. layerBg.append("circle")
  1229. .attr("cx", cx)
  1230. .attr("cy", cy)
  1231. .attr("r", r)
  1232. .attr("fill", cfg.color)
  1233. .attr("stroke", cfg.stroke)
  1234. .attr("stroke-width", 2);
  1235. // 层标签(圆的左侧)
  1236. layerBg.append("text")
  1237. .attr("x", cx - r - 15)
  1238. .attr("y", cy)
  1239. .attr("dy", "0.35em")
  1240. .attr("fill", "rgba(255,255,255,0.5)")
  1241. .attr("font-size", "13px")
  1242. .attr("font-weight", "bold")
  1243. .attr("text-anchor", "end")
  1244. .text(cfg.name);
  1245. // 关系图层添加占位提示
  1246. if (cfg.layer === 3) {{
  1247. layerBg.append("text")
  1248. .attr("class", "ego-placeholder")
  1249. .attr("x", cx)
  1250. .attr("y", cy)
  1251. .attr("dy", "0.35em")
  1252. .attr("fill", "rgba(255,255,255,0.3)")
  1253. .attr("font-size", "12px")
  1254. .attr("text-anchor", "middle")
  1255. .text("点击左侧人设树节点查看关系");
  1256. }}
  1257. }});
  1258. // 创建关系图层内容组(动态填充)
  1259. const egoGraphGroup = g.append("g")
  1260. .attr("class", "ego-graph-content")
  1261. .attr("transform", `translate(${{layerCenterX[3]}}, ${{layerCenterY[3]}})`);
  1262. // 绘制左侧人设树(单棵树,根节点为"人设")
  1263. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  1264. const treeGroup = g.append("g")
  1265. .attr("class", "persona-tree")
  1266. .attr("transform", `translate(15, 25)`);
  1267. // 绘制背景矩形
  1268. treeGroup.append("rect")
  1269. .attr("x", -5)
  1270. .attr("y", -10)
  1271. .attr("width", treeAreaWidth - 20)
  1272. .attr("height", treeHeight - 20)
  1273. .attr("rx", 8)
  1274. .attr("fill", "rgba(100, 100, 100, 0.08)")
  1275. .attr("stroke", "rgba(150, 150, 150, 0.2)")
  1276. .attr("stroke-width", 1);
  1277. // D3树布局 - 宽度留出边距给标签
  1278. const treeLayout = d3.tree()
  1279. .size([treeHeight - 50, treeAreaWidth - 70]);
  1280. const root = d3.hierarchy(personaTree.root);
  1281. treeLayout(root);
  1282. // 获取节点颜色(根据维度)
  1283. function getNodeColor(d) {{
  1284. if (d.data.isRoot) return "#e94560"; // 根节点红色
  1285. if (d.data.isDimension) return d.data.dimColor; // 维度节点用维度颜色
  1286. return d.data.dimColor || "#888"; // 分类节点继承维度颜色
  1287. }}
  1288. // 构建节点ID到D3节点的映射(用于绘制原始边和高亮)
  1289. const treeNodeById = {{}};
  1290. root.descendants().forEach(d => {{
  1291. if (d.data.节点ID) {{
  1292. treeNodeById[d.data.节点ID] = d;
  1293. }}
  1294. }});
  1295. // 边类型颜色和样式
  1296. const treeEdgeColors = {{
  1297. "分类层级": "#2ecc71", // 绿色 - 分类的层级关系
  1298. "属于": "#9b59b6", // 紫色 - 标签属于分类
  1299. "包含": "#8e44ad", // 深紫 - 分类包含标签
  1300. "分类共现(跨点)": "#e74c3c", // 红色 - 跨维度分类共现
  1301. "分类共现(点内)": "#c0392b", // 深红 - 同维度分类共现
  1302. "标签共现": "#f39c12" // 橙色 - 标签共现
  1303. }};
  1304. const treeEdgeDash = {{
  1305. "分类层级": "none",
  1306. "属于": "3,2",
  1307. "包含": "3,2",
  1308. "分类共现(跨点)": "5,3",
  1309. "分类共现(点内)": "5,3",
  1310. "标签共现": "2,2"
  1311. }};
  1312. // 只保留"属于"边用于树的展示(其他边用专门子图展示)
  1313. const visibleTreeEdges = personaTreeData.edges.filter(e => {{
  1314. return e.边类型 === "属于" && treeNodeById[e.源节点ID] && treeNodeById[e.目标节点ID];
  1315. }});
  1316. // 添加树结构边(根节点->维度,维度->子节点)
  1317. root.links().forEach(link => {{
  1318. visibleTreeEdges.push({{
  1319. 源节点ID: link.source.data.节点ID || link.source.data.name,
  1320. 目标节点ID: link.target.data.节点ID || link.target.data.name,
  1321. 边类型: "属于",
  1322. isTreeLink: true,
  1323. sourceNode: link.source,
  1324. targetNode: link.target
  1325. }});
  1326. }});
  1327. // 绘制原始边(分类层级、标签属于)
  1328. const treeEdgeGroup = treeGroup.append("g").attr("class", "tree-edges");
  1329. // 先绘制可见边
  1330. const treeEdges = treeEdgeGroup.selectAll(".tree-edge")
  1331. .data(visibleTreeEdges)
  1332. .join("path")
  1333. .attr("class", "tree-edge")
  1334. .attr("fill", "none")
  1335. .attr("stroke", "#9b59b6") // 属于边用紫色
  1336. .attr("stroke-opacity", 0.3)
  1337. .attr("stroke-width", 1)
  1338. .attr("d", d => {{
  1339. const source = d.isTreeLink ? d.sourceNode : treeNodeById[d.源节点ID];
  1340. const target = d.isTreeLink ? d.targetNode : treeNodeById[d.目标节点ID];
  1341. if (!source || !target) return "";
  1342. const midX = (source.y + target.y) / 2;
  1343. return `M${{source.y}},${{source.x}} C${{midX}},${{source.x}} ${{midX}},${{target.x}} ${{target.y}},${{target.x}}`;
  1344. }});
  1345. // 绘制透明的热区边(便于点击)
  1346. const treeEdgeHitareas = treeEdgeGroup.selectAll(".tree-edge-hitarea")
  1347. .data(visibleTreeEdges)
  1348. .join("path")
  1349. .attr("class", "tree-edge-hitarea")
  1350. .attr("fill", "none")
  1351. .attr("stroke", "transparent")
  1352. .attr("stroke-width", 12)
  1353. .style("cursor", "pointer")
  1354. .attr("d", d => {{
  1355. const source = d.isTreeLink ? d.sourceNode : treeNodeById[d.源节点ID];
  1356. const target = d.isTreeLink ? d.targetNode : treeNodeById[d.目标节点ID];
  1357. if (!source || !target) return "";
  1358. const midX = (source.y + target.y) / 2;
  1359. return `M${{source.y}},${{source.x}} C${{midX}},${{source.x}} ${{midX}},${{target.x}} ${{target.y}},${{target.x}}`;
  1360. }})
  1361. .on("click", (event, d) => {{
  1362. event.stopPropagation();
  1363. // 调用共享的边点击处理函数
  1364. handleEdgeClick(d.源节点ID, d.目标节点ID, d.边类型);
  1365. }});
  1366. // 绘制节点
  1367. const treeNodes = treeGroup.selectAll(".tree-node")
  1368. .data(root.descendants())
  1369. .join("g")
  1370. .attr("class", "tree-node")
  1371. .attr("transform", d => `translate(${{d.y}},${{d.x}})`)
  1372. .style("cursor", "pointer")
  1373. .on("click", (event, d) => {{
  1374. event.stopPropagation();
  1375. // 调用共享的节点点击处理函数
  1376. handleNodeClick(d.data.节点ID, d.data.节点名称 || d.data.name);
  1377. }});
  1378. // 节点形状:根节点/维度=圆形,分类=正方形,标签=圆形
  1379. // 统一实心填充维度颜色
  1380. treeNodes.each(function(d) {{
  1381. const el = d3.select(this);
  1382. const nodeType = d.data.节点类型;
  1383. const isRoot = d.data.isRoot;
  1384. const isDimension = d.data.isDimension;
  1385. const nodeColor = getNodeColor(d);
  1386. if (nodeType === "分类") {{
  1387. // 分类节点:正方形,实心填充
  1388. el.append("rect")
  1389. .attr("class", "tree-shape")
  1390. .attr("x", -4)
  1391. .attr("y", -4)
  1392. .attr("width", 8)
  1393. .attr("height", 8)
  1394. .attr("rx", 1)
  1395. .attr("fill", nodeColor)
  1396. .attr("stroke", "rgba(255,255,255,0.5)")
  1397. .attr("stroke-width", 1);
  1398. }} else {{
  1399. // 根节点、维度节点、标签节点:圆形,实心填充
  1400. const radius = isRoot ? 6 : (isDimension ? 5 : 3);
  1401. el.append("circle")
  1402. .attr("class", "tree-shape")
  1403. .attr("r", radius)
  1404. .attr("fill", nodeColor)
  1405. .attr("stroke", "rgba(255,255,255,0.5)")
  1406. .attr("stroke-width", 1);
  1407. }}
  1408. }});
  1409. // 节点标签
  1410. treeNodes.append("text")
  1411. .attr("dy", "0.31em")
  1412. .attr("x", d => d.children ? -8 : 8)
  1413. .attr("text-anchor", d => d.children ? "end" : "start")
  1414. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
  1415. .attr("font-size", d => d.data.isRoot ? "11px" : (d.data.isDimension ? "10px" : "8px"))
  1416. .attr("font-weight", d => (d.data.isRoot || d.data.isDimension) ? "bold" : "normal")
  1417. .text(d => d.data.name);
  1418. // 重置树高亮状态的函数
  1419. function resetTreeHighlight() {{
  1420. treeGroup.selectAll(".tree-node")
  1421. .classed("tree-dimmed", false)
  1422. .classed("tree-highlighted", false);
  1423. // 重置所有形状(圆形和方形)- 统一实心填充
  1424. treeGroup.selectAll(".tree-node .tree-shape")
  1425. .attr("fill", d => getNodeColor(d))
  1426. .attr("stroke", "rgba(255,255,255,0.5)")
  1427. .attr("stroke-opacity", 1)
  1428. .attr("opacity", 1);
  1429. treeGroup.selectAll(".tree-node text")
  1430. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
  1431. .attr("opacity", 1);
  1432. // 重置边样式
  1433. treeGroup.selectAll(".tree-edge")
  1434. .attr("stroke-opacity", 0.3)
  1435. .attr("stroke-width", 1);
  1436. }}
  1437. // 重置右侧图高亮状态的函数
  1438. function resetGraphHighlight() {{
  1439. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  1440. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  1441. }}
  1442. // 点击树背景也取消高亮
  1443. treeGroup.select("rect").on("click", function(event) {{
  1444. event.stopPropagation();
  1445. resetTreeHighlight();
  1446. resetGraphHighlight();
  1447. clearEgoGraph();
  1448. closeDetailPanel();
  1449. }});
  1450. // 创建边的容器
  1451. const linkGroup = g.append("g").attr("class", "links");
  1452. // 为每条边创建组
  1453. const linkG = linkGroup.selectAll("g")
  1454. .data(links)
  1455. .join("g")
  1456. .attr("class", "link-group");
  1457. // 绘制点击热区(透明宽线)
  1458. const linkHitarea = linkG.append("line")
  1459. .attr("class", "link-hitarea");
  1460. // 绘制可见的边
  1461. const link = linkG.append("line")
  1462. .attr("class", d => "link " + getEdgeClass(d.type))
  1463. .attr("stroke-width", d => d.type === "匹配" ? 2.5 : 1.5);
  1464. // 判断是否为跨层边(根据源和目标节点的层级)- 赋值给全局变量
  1465. isCrossLayerEdge = function(d) {{
  1466. const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
  1467. const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
  1468. if (!sourceNode || !targetNode) return false;
  1469. return getNodeLayer(sourceNode) !== getNodeLayer(targetNode);
  1470. }};
  1471. // 设置跨层边的初始可见性(默认隐藏)
  1472. linkG.each(function(d) {{
  1473. if (isCrossLayerEdge(d) && !showCrossLayerEdges) {{
  1474. d3.select(this).style("display", "none");
  1475. }}
  1476. }});
  1477. // 为匹配边添加分数标签
  1478. const edgeLabels = linkG.filter(d => d.type === "匹配" && d.边详情 && d.边详情.相似度)
  1479. .append("g")
  1480. .attr("class", "edge-label-group");
  1481. edgeLabels.append("rect")
  1482. .attr("class", "edge-label-bg")
  1483. .attr("rx", 3)
  1484. .attr("ry", 3);
  1485. edgeLabels.append("text")
  1486. .attr("class", "edge-label")
  1487. .text(d => {{
  1488. const score = d.边详情.相似度;
  1489. return typeof score === "number" ? score.toFixed(2) : score;
  1490. }});
  1491. // 边的点击事件
  1492. linkHitarea.on("click", (event, d, i) => {{
  1493. event.stopPropagation();
  1494. const linkIndex = links.indexOf(d);
  1495. highlightEdge(d, linkIndex);
  1496. showEdgeInfo(d);
  1497. }})
  1498. .on("mouseover", function(event, d) {{
  1499. d3.select(this.parentNode).select(".link")
  1500. .attr("stroke-opacity", 1)
  1501. .attr("stroke-width", 4);
  1502. }})
  1503. .on("mouseout", function(event, d) {{
  1504. d3.select(this.parentNode).select(".link")
  1505. .attr("stroke-opacity", 0.7)
  1506. .attr("stroke-width", d.type === "匹配" ? 2.5 : 1.5);
  1507. }});
  1508. // 绘制节点
  1509. const node = g.append("g")
  1510. .selectAll("g")
  1511. .data(nodes)
  1512. .join("g")
  1513. .attr("class", "node")
  1514. .call(d3.drag()
  1515. .on("start", dragstarted)
  1516. .on("drag", dragged)
  1517. .on("end", dragended));
  1518. // 根据节点类型绘制不同形状
  1519. // - 点节点(帖子点):六边形(更大)
  1520. // - 标签节点:圆形
  1521. // - 分类节点:方形
  1522. node.each(function(d) {{
  1523. const el = d3.select(this);
  1524. const isExpanded = d.是否扩展 === true;
  1525. const isUnmatched = d.source === "帖子" && d.节点类型 === "标签" && d.已匹配 === false;
  1526. const isPointNode = d.节点类型 === "点";
  1527. // 点节点更大,标签节点根据来源区分大小
  1528. let size;
  1529. if (isPointNode) {{
  1530. size = 16; // 点节点最大
  1531. }} else if (d.source === "帖子") {{
  1532. size = 12; // 帖子标签
  1533. }} else if (isExpanded) {{
  1534. size = 8; // 扩展的分类节点
  1535. }} else {{
  1536. size = 10; // 人设标签
  1537. }}
  1538. const fill = levelColors[d.level] || "#666";
  1539. const nodeClass = d.source === "帖子"
  1540. ? (isPointNode ? "post-point-node" : (isUnmatched ? "post-node unmatched" : "post-node"))
  1541. : "persona-node";
  1542. const opacity = isExpanded ? 0.5 : (isUnmatched ? 0.4 : 1);
  1543. if (isPointNode) {{
  1544. // 六边形(点节点)
  1545. const hexPoints = [];
  1546. for (let i = 0; i < 6; i++) {{
  1547. const angle = (i * 60 - 30) * Math.PI / 180;
  1548. hexPoints.push([size * Math.cos(angle), size * Math.sin(angle)]);
  1549. }}
  1550. el.append("polygon")
  1551. .attr("points", hexPoints.map(p => p.join(",")).join(" "))
  1552. .attr("fill", fill)
  1553. .attr("class", nodeClass)
  1554. .attr("opacity", opacity);
  1555. }} else if (d.节点类型 === "分类") {{
  1556. // 方形(分类节点)
  1557. el.append("rect")
  1558. .attr("width", size * 2)
  1559. .attr("height", size * 2)
  1560. .attr("x", -size)
  1561. .attr("y", -size)
  1562. .attr("fill", fill)
  1563. .attr("class", nodeClass)
  1564. .attr("rx", 3)
  1565. .attr("opacity", opacity);
  1566. }} else {{
  1567. // 圆形(标签节点)
  1568. el.append("circle")
  1569. .attr("r", size)
  1570. .attr("fill", isUnmatched ? "#666" : fill)
  1571. .attr("class", nodeClass)
  1572. .attr("opacity", opacity);
  1573. }}
  1574. }});
  1575. const labels = node.append("text")
  1576. .attr("dx", 15)
  1577. .attr("dy", 4)
  1578. .text(d => d.节点名称)
  1579. .style("display", showLabels ? "block" : "none");
  1580. // 工具提示
  1581. const tooltip = d3.select("#tooltip");
  1582. node.on("mouseover", (event, d) => {{
  1583. let html = `<strong>${{d.节点名称}}</strong><br/>类型: ${{d.节点类型}}<br/>层级: ${{d.节点层级}}`;
  1584. // 点节点显示描述
  1585. if (d.描述) {{
  1586. html += `<br/><br/><em style="font-size:10px;color:#aaa">${{d.描述.slice(0, 100)}}${{d.描述.length > 100 ? '...' : ''}}</em>`;
  1587. }}
  1588. tooltip.style("display", "block").html(html);
  1589. }})
  1590. .on("mousemove", (event) => {{
  1591. tooltip.style("left", (event.pageX + 15) + "px")
  1592. .style("top", (event.pageY - 10) + "px");
  1593. }})
  1594. .on("mouseout", () => {{
  1595. tooltip.style("display", "none");
  1596. }})
  1597. .on("click", (event, d) => {{
  1598. event.stopPropagation();
  1599. highlightNode(d);
  1600. showNodeInfo(d);
  1601. }});
  1602. // 更新位置
  1603. simulation.on("tick", () => {{
  1604. // 更新热区线
  1605. linkHitarea
  1606. .attr("x1", d => d.source.x)
  1607. .attr("y1", d => d.source.y)
  1608. .attr("x2", d => d.target.x)
  1609. .attr("y2", d => d.target.y);
  1610. // 更新可见边
  1611. link
  1612. .attr("x1", d => d.source.x)
  1613. .attr("y1", d => d.source.y)
  1614. .attr("x2", d => d.target.x)
  1615. .attr("y2", d => d.target.y);
  1616. // 更新边标签位置(放在边的中点)
  1617. edgeLabels.attr("transform", d => {{
  1618. const midX = (d.source.x + d.target.x) / 2;
  1619. const midY = (d.source.y + d.target.y) / 2;
  1620. return `translate(${{midX}},${{midY}})`;
  1621. }});
  1622. // 更新标签背景大小
  1623. edgeLabels.each(function(d) {{
  1624. const textEl = d3.select(this).select("text").node();
  1625. if (textEl) {{
  1626. const bbox = textEl.getBBox();
  1627. d3.select(this).select("rect")
  1628. .attr("x", bbox.x - 3)
  1629. .attr("y", bbox.y - 1)
  1630. .attr("width", bbox.width + 6)
  1631. .attr("height", bbox.height + 2);
  1632. }}
  1633. }});
  1634. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  1635. }});
  1636. // 拖拽函数
  1637. function dragstarted(event, d) {{
  1638. if (!event.active) simulation.alphaTarget(0.3).restart();
  1639. d.fx = d.x;
  1640. d.fy = d.y;
  1641. }}
  1642. function dragged(event, d) {{
  1643. d.fx = event.x;
  1644. d.fy = event.y;
  1645. }}
  1646. function dragended(event, d) {{
  1647. if (!event.active) simulation.alphaTarget(0);
  1648. d.fx = null;
  1649. d.fy = null;
  1650. }}
  1651. // 清除所有高亮
  1652. function clearHighlight() {{
  1653. node.classed("dimmed", false).classed("highlighted", false);
  1654. linkG.classed("dimmed", false).classed("highlighted", false);
  1655. // 恢复跨层边的可见性状态(根据全局开关)
  1656. linkG.each(function(d) {{
  1657. if (isCrossLayerEdge(d)) {{
  1658. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  1659. }}
  1660. }});
  1661. }}
  1662. // 高亮指定的节点和边
  1663. function highlightElements(highlightNodeIds, highlightLinkIndices) {{
  1664. // 先灰化所有
  1665. node.classed("dimmed", true).classed("highlighted", false);
  1666. linkG.classed("dimmed", true).classed("highlighted", false);
  1667. // 高亮指定节点
  1668. node.filter(d => highlightNodeIds.has(d.id))
  1669. .classed("dimmed", false)
  1670. .classed("highlighted", true);
  1671. // 高亮指定边
  1672. linkG.filter((d, i) => highlightLinkIndices.has(i))
  1673. .classed("dimmed", false)
  1674. .classed("highlighted", true);
  1675. }}
  1676. // 点击节点时的高亮逻辑
  1677. function highlightNode(clickedNode) {{
  1678. const highlightNodeIds = new Set([clickedNode.id]);
  1679. const highlightLinkIndices = new Set();
  1680. links.forEach((link, i) => {{
  1681. const sourceId = typeof link.source === "object" ? link.source.id : link.source;
  1682. const targetId = typeof link.target === "object" ? link.target.id : link.target;
  1683. // 与点击节点直接相连的边
  1684. if (sourceId === clickedNode.id || targetId === clickedNode.id) {{
  1685. highlightLinkIndices.add(i);
  1686. highlightNodeIds.add(sourceId);
  1687. highlightNodeIds.add(targetId);
  1688. // 如果是帖子节点,还要高亮对应的镜像边
  1689. if (clickedNode.source === "帖子") {{
  1690. // 找到通过该帖子连接的其他帖子(镜像边)
  1691. links.forEach((otherLink, j) => {{
  1692. const otherType = otherLink.type;
  1693. if (otherType.startsWith("镜像_") || otherType.startsWith("二阶_")) {{
  1694. const oSrc = typeof otherLink.source === "object" ? otherLink.source.id : otherLink.source;
  1695. const oTgt = typeof otherLink.target === "object" ? otherLink.target.id : otherLink.target;
  1696. if (oSrc === clickedNode.id || oTgt === clickedNode.id) {{
  1697. highlightLinkIndices.add(j);
  1698. highlightNodeIds.add(oSrc);
  1699. highlightNodeIds.add(oTgt);
  1700. }}
  1701. }}
  1702. }});
  1703. }}
  1704. }}
  1705. }});
  1706. // 高亮相关的节点和边
  1707. highlightElements(highlightNodeIds, highlightLinkIndices);
  1708. // 临时显示关联的跨层边(即使全局开关是关闭的)
  1709. linkG.each(function(d, i) {{
  1710. if (highlightLinkIndices.has(i)) {{
  1711. d3.select(this).style("display", "block");
  1712. }}
  1713. }});
  1714. }}
  1715. // 点击边时的高亮逻辑
  1716. function highlightEdge(clickedLink, clickedIndex) {{
  1717. const highlightNodeIds = new Set();
  1718. const highlightLinkIndices = new Set([clickedIndex]);
  1719. const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
  1720. const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
  1721. highlightNodeIds.add(sourceId);
  1722. highlightNodeIds.add(targetId);
  1723. // 如果是二阶边,显示完整路径
  1724. if (clickedLink.type.startsWith("二阶_") && clickedLink.边详情) {{
  1725. const detail = clickedLink.边详情;
  1726. // 分类节点
  1727. if (detail.分类节点1) highlightNodeIds.add(detail.分类节点1);
  1728. if (detail.分类节点2) highlightNodeIds.add(detail.分类节点2);
  1729. // 标签节点
  1730. if (detail.标签节点1) highlightNodeIds.add(detail.标签节点1);
  1731. if (detail.标签节点2) highlightNodeIds.add(detail.标签节点2);
  1732. // 找出路径上的边
  1733. links.forEach((link, i) => {{
  1734. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  1735. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  1736. // 帖子->标签 的匹配边
  1737. if (link.type === "匹配") {{
  1738. if ((lSrc === sourceId && lTgt === detail.标签节点1) ||
  1739. (lSrc === targetId && lTgt === detail.标签节点2)) {{
  1740. highlightLinkIndices.add(i);
  1741. }}
  1742. }}
  1743. // 标签->分类 的属于边
  1744. if (link.type === "属于") {{
  1745. if ((lSrc === detail.标签节点1 && lTgt === detail.分类节点1) ||
  1746. (lSrc === detail.标签节点2 && lTgt === detail.分类节点2)) {{
  1747. highlightLinkIndices.add(i);
  1748. }}
  1749. }}
  1750. // 分类之间的边
  1751. if ((lSrc === detail.分类节点1 && lTgt === detail.分类节点2) ||
  1752. (lSrc === detail.分类节点2 && lTgt === detail.分类节点1)) {{
  1753. highlightLinkIndices.add(i);
  1754. }}
  1755. }});
  1756. }}
  1757. // 如果是镜像边,显示对应的人设边
  1758. else if (clickedLink.type.startsWith("镜像_") && clickedLink.边详情) {{
  1759. const detail = clickedLink.边详情;
  1760. if (detail.源人设节点) highlightNodeIds.add(detail.源人设节点);
  1761. if (detail.目标人设节点) highlightNodeIds.add(detail.目标人设节点);
  1762. // 找出对应的人设边和匹配边
  1763. links.forEach((link, i) => {{
  1764. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  1765. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  1766. // 匹配边
  1767. if (link.type === "匹配") {{
  1768. if ((lSrc === sourceId && lTgt === detail.源人设节点) ||
  1769. (lSrc === targetId && lTgt === detail.目标人设节点)) {{
  1770. highlightLinkIndices.add(i);
  1771. }}
  1772. }}
  1773. // 人设边
  1774. if ((lSrc === detail.源人设节点 && lTgt === detail.目标人设节点) ||
  1775. (lSrc === detail.目标人设节点 && lTgt === detail.源人设节点)) {{
  1776. highlightLinkIndices.add(i);
  1777. }}
  1778. }});
  1779. }}
  1780. // 高亮相关的节点和边
  1781. highlightElements(highlightNodeIds, highlightLinkIndices);
  1782. // 临时显示关联的跨层边(即使全局开关是关闭的)
  1783. linkG.each(function(d, i) {{
  1784. if (highlightLinkIndices.has(i)) {{
  1785. d3.select(this).style("display", "block");
  1786. }}
  1787. }});
  1788. }}
  1789. // 点击空白处清除高亮(合并所有空白点击逻辑)
  1790. svg.on("click", (event) => {{
  1791. // 检查是否点击的是空白区域(svg本身或layer-backgrounds)
  1792. const isBlank = event.target === svg.node() ||
  1793. event.target.tagName === "svg" ||
  1794. event.target.classList.contains("layer-backgrounds");
  1795. if (isBlank) {{
  1796. // 清除右侧图高亮
  1797. clearHighlight();
  1798. // 清除人设树高亮
  1799. resetTreeHighlight();
  1800. resetGraphHighlight();
  1801. // 关闭详情面板
  1802. closeDetailPanel();
  1803. // 清除关系图
  1804. clearEgoGraph();
  1805. }}
  1806. }});
  1807. }}
  1808. // 控制函数
  1809. function resetZoom() {{
  1810. const container = document.getElementById("svg-container");
  1811. const width = container.clientWidth;
  1812. const height = container.clientHeight;
  1813. svg.transition().duration(750).call(
  1814. zoom.transform,
  1815. d3.zoomIdentity.translate(width/2, height/2).scale(1).translate(-width/2, -height/2)
  1816. );
  1817. }}
  1818. function toggleLabels() {{
  1819. showLabels = !showLabels;
  1820. g.selectAll(".node text").style("display", showLabels ? "block" : "none");
  1821. }}
  1822. // 切换跨层边显示
  1823. function toggleCrossLayerEdges() {{
  1824. showCrossLayerEdges = !showCrossLayerEdges;
  1825. const btn = document.getElementById("crossLayerBtn");
  1826. btn.textContent = showCrossLayerEdges ? "隐藏跨层边" : "显示跨层边";
  1827. btn.style.background = showCrossLayerEdges ? "#e94560" : "";
  1828. // 更新边的可见性(使用 isCrossLayerEdge 函数判断)
  1829. g.selectAll(".link-group").each(function(d) {{
  1830. if (isCrossLayerEdge(d)) {{
  1831. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  1832. }}
  1833. }});
  1834. }}
  1835. function showNodeInfo(d) {{
  1836. const panel = document.getElementById("detailPanel");
  1837. panel.classList.add("active");
  1838. document.getElementById("detailTitle").textContent = d.source === "帖子" ? "📌 帖子节点" : "👤 人设节点";
  1839. let html = `
  1840. <p><span class="label">节点ID:</span> ${{d.节点ID}}</p>
  1841. <p><span class="label">名称:</span> <strong>${{d.节点名称}}</strong></p>
  1842. <p><span class="label">类型:</span> ${{d.节点类型}}</p>
  1843. <p><span class="label">层级:</span> ${{d.节点层级}}</p>
  1844. `;
  1845. if (d.权重) {{
  1846. html += `<p><span class="label">权重:</span> ${{d.权重}}</p>`;
  1847. }}
  1848. if (d.所属分类 && d.所属分类.length > 0) {{
  1849. html += `<p><span class="label">所属分类:</span> ${{d.所属分类.join(" > ")}}</p>`;
  1850. }}
  1851. if (d.帖子数) {{
  1852. html += `<p><span class="label">帖子数:</span> ${{d.帖子数}}</p>`;
  1853. }}
  1854. document.getElementById("detailContent").innerHTML = html;
  1855. }}
  1856. // 显示人设树节点详情(包含入边、出边、相关节点)
  1857. function showTreeNodeDetail(nodeData, inEdges, outEdges) {{
  1858. const panel = document.getElementById("detailPanel");
  1859. panel.classList.add("active");
  1860. document.getElementById("detailTitle").textContent = "🌳 人设树节点";
  1861. // 节点基本信息
  1862. let html = `
  1863. <p><span class="label">名称:</span> <strong>${{nodeData.节点名称 || nodeData.name}}</strong></p>
  1864. <p><span class="label">类型:</span> ${{nodeData.节点类型 || (nodeData.isRoot ? "根节点" : "维度")}}</p>
  1865. <p><span class="label">层级:</span> ${{nodeData.节点层级 || "-"}}</p>
  1866. `;
  1867. if (nodeData.所属分类 && nodeData.所属分类.length > 0) {{
  1868. html += `<p><span class="label">所属分类:</span> ${{nodeData.所属分类.join(" > ")}}</p>`;
  1869. }}
  1870. if (nodeData.帖子数) {{
  1871. html += `<p><span class="label">帖子数:</span> ${{nodeData.帖子数}}</p>`;
  1872. }}
  1873. // 统计边类型
  1874. const inEdgeTypes = {{}};
  1875. const outEdgeTypes = {{}};
  1876. inEdges.forEach(e => {{ inEdgeTypes[e.边类型] = (inEdgeTypes[e.边类型] || 0) + 1; }});
  1877. outEdges.forEach(e => {{ outEdgeTypes[e.边类型] = (outEdgeTypes[e.边类型] || 0) + 1; }});
  1878. // 入边统计
  1879. html += `<h4 style="margin-top:12px;color:#3498db;font-size:12px;">📥 入边 (${{inEdges.length}})</h4>`;
  1880. if (inEdges.length > 0) {{
  1881. html += `<div class="edge-list">`;
  1882. for (const [type, count] of Object.entries(inEdgeTypes)) {{
  1883. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  1884. }}
  1885. // 显示前5条入边详情
  1886. const showInEdges = inEdges.slice(0, 5);
  1887. showInEdges.forEach(e => {{
  1888. const srcName = personaTreeData.nodes.find(n => n.节点ID === e.源节点ID)?.节点名称 || e.源节点ID;
  1889. html += `<div class="edge-detail">← ${{srcName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  1890. }});
  1891. if (inEdges.length > 5) {{
  1892. html += `<div class="edge-more">... 还有 ${{inEdges.length - 5}} 条</div>`;
  1893. }}
  1894. html += `</div>`;
  1895. }} else {{
  1896. html += `<div class="edge-empty">无</div>`;
  1897. }}
  1898. // 出边统计
  1899. html += `<h4 style="margin-top:12px;color:#e74c3c;font-size:12px;">📤 出边 (${{outEdges.length}})</h4>`;
  1900. if (outEdges.length > 0) {{
  1901. html += `<div class="edge-list">`;
  1902. for (const [type, count] of Object.entries(outEdgeTypes)) {{
  1903. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  1904. }}
  1905. // 显示前5条出边详情
  1906. const showOutEdges = outEdges.slice(0, 5);
  1907. showOutEdges.forEach(e => {{
  1908. const tgtName = personaTreeData.nodes.find(n => n.节点ID === e.目标节点ID)?.节点名称 || e.目标节点ID;
  1909. html += `<div class="edge-detail">→ ${{tgtName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  1910. }});
  1911. if (outEdges.length > 5) {{
  1912. html += `<div class="edge-more">... 还有 ${{outEdges.length - 5}} 条</div>`;
  1913. }}
  1914. html += `</div>`;
  1915. }} else {{
  1916. html += `<div class="edge-empty">无</div>`;
  1917. }}
  1918. document.getElementById("detailContent").innerHTML = html;
  1919. }}
  1920. function showEdgeInfo(d) {{
  1921. const panel = document.getElementById("detailPanel");
  1922. panel.classList.add("active");
  1923. const sourceNode = typeof d.source === "object" ? d.source : {{ id: d.source }};
  1924. const targetNode = typeof d.target === "object" ? d.target : {{ id: d.target }};
  1925. // 判断是否为镜像边
  1926. const isMirror = d.type.startsWith("镜像_");
  1927. document.getElementById("detailTitle").textContent = isMirror ? "🪞 镜像边详情" : "🔗 边详情";
  1928. let html = `
  1929. <p><span class="label">边类型:</span> <strong>${{d.type}}</strong></p>
  1930. <p><span class="label">源节点:</span> ${{sourceNode.节点名称 || sourceNode.id}}</p>
  1931. <p><span class="label">目标节点:</span> ${{targetNode.节点名称 || targetNode.id}}</p>
  1932. `;
  1933. if (d.边详情) {{
  1934. if (d.边详情.相似度 !== undefined) {{
  1935. const score = typeof d.边详情.相似度 === "number" ? d.边详情.相似度.toFixed(2) : d.边详情.相似度;
  1936. html += `<p><span class="label">相似度:</span> <span class="similarity-score">${{score}}</span></p>`;
  1937. }}
  1938. if (d.边详情.说明) {{
  1939. html += `<p><span class="label">说明:</span></p><div class="edge-description">${{d.边详情.说明}}</div>`;
  1940. }}
  1941. if (d.边详情.共现次数 !== undefined) {{
  1942. html += `<p><span class="label">共现次数:</span> ${{d.边详情.共现次数}}</p>`;
  1943. }}
  1944. // 镜像边特有信息
  1945. if (d.边详情.原始边类型) {{
  1946. html += `<p><span class="label">原始边类型:</span> ${{d.边详情.原始边类型}}</p>`;
  1947. }}
  1948. if (d.边详情.源人设节点) {{
  1949. html += `<p><span class="label">源人设节点:</span> ${{d.边详情.源人设节点}}</p>`;
  1950. }}
  1951. if (d.边详情.目标人设节点) {{
  1952. html += `<p><span class="label">目标人设节点:</span> ${{d.边详情.目标人设节点}}</p>`;
  1953. }}
  1954. }}
  1955. document.getElementById("detailContent").innerHTML = html;
  1956. }}
  1957. function closeDetailPanel() {{
  1958. document.getElementById("detailPanel").classList.remove("active");
  1959. }}
  1960. // 获取节点颜色(全局版本,根据节点数据判断维度)
  1961. function getTreeNodeColor(d) {{
  1962. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  1963. if (d.data.isRoot) return "#e94560";
  1964. if (d.data.isDimension) return d.data.dimColor;
  1965. return d.data.dimColor || "#888";
  1966. }}
  1967. // 共享的节点点击处理函数(人设树和关系图复用)
  1968. function handleNodeClick(clickedNodeId, clickedNodeName) {{
  1969. if (!clickedNodeId) return;
  1970. // 动态获取树相关元素
  1971. const treeGroup = d3.select(".persona-tree");
  1972. if (treeGroup.empty()) return;
  1973. const treeEdges = treeGroup.selectAll(".tree-edge");
  1974. // 先重置所有高亮状态
  1975. treeGroup.selectAll(".tree-node")
  1976. .classed("tree-dimmed", false)
  1977. .classed("tree-highlighted", false);
  1978. treeGroup.selectAll(".tree-node .tree-shape")
  1979. .attr("fill", d => getTreeNodeColor(d))
  1980. .attr("stroke", "rgba(255,255,255,0.5)")
  1981. .attr("stroke-width", 1)
  1982. .attr("stroke-opacity", 1)
  1983. .attr("opacity", 1);
  1984. treeGroup.selectAll(".tree-node text")
  1985. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  1986. .attr("opacity", 1);
  1987. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  1988. if (g) {{
  1989. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  1990. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  1991. }}
  1992. // 构建节点ID到D3节点的映射
  1993. const treeNodeById = {{}};
  1994. treeGroup.selectAll(".tree-node").each(function(n) {{
  1995. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  1996. }});
  1997. // 查找所有与该节点相关的边
  1998. const allConnectedEdges = personaTreeData.edges.filter(e =>
  1999. e.源节点ID === clickedNodeId || e.目标节点ID === clickedNodeId
  2000. );
  2001. // 收集所有相关节点ID
  2002. const connectedNodeIds = new Set();
  2003. connectedNodeIds.add(clickedNodeId);
  2004. allConnectedEdges.forEach(e => {{
  2005. connectedNodeIds.add(e.源节点ID);
  2006. connectedNodeIds.add(e.目标节点ID);
  2007. }});
  2008. // 获取D3树节点
  2009. const clickedD3Node = treeNodeById[clickedNodeId];
  2010. // 也添加树结构中的父子节点
  2011. if (clickedD3Node) {{
  2012. if (clickedD3Node.parent && clickedD3Node.parent.data.节点ID) {{
  2013. connectedNodeIds.add(clickedD3Node.parent.data.节点ID);
  2014. }}
  2015. if (clickedD3Node.children) {{
  2016. clickedD3Node.children.forEach(c => {{
  2017. if (c.data.节点ID) connectedNodeIds.add(c.data.节点ID);
  2018. }});
  2019. }}
  2020. }}
  2021. // 转换为D3节点集合
  2022. const connectedD3Nodes = new Set();
  2023. if (clickedD3Node) connectedD3Nodes.add(clickedD3Node);
  2024. connectedNodeIds.forEach(id => {{
  2025. if (treeNodeById[id]) connectedD3Nodes.add(treeNodeById[id]);
  2026. }});
  2027. if (clickedD3Node) {{
  2028. if (clickedD3Node.parent) connectedD3Nodes.add(clickedD3Node.parent);
  2029. if (clickedD3Node.children) clickedD3Node.children.forEach(c => connectedD3Nodes.add(c));
  2030. }}
  2031. // 高亮树中的节点
  2032. treeGroup.selectAll(".tree-node")
  2033. .classed("tree-dimmed", n => !connectedD3Nodes.has(n))
  2034. .classed("tree-highlighted", n => connectedD3Nodes.has(n));
  2035. // 高亮所有形状(不变粗)
  2036. treeGroup.selectAll(".tree-node .tree-shape")
  2037. .attr("fill", function(n) {{
  2038. if (!connectedD3Nodes.has(n)) return "#555";
  2039. return getTreeNodeColor(n);
  2040. }})
  2041. .attr("stroke", function(n) {{
  2042. if (n.data.节点ID === clickedNodeId) return "#fff";
  2043. return connectedD3Nodes.has(n) ? "rgba(255,255,255,0.8)" : "#333";
  2044. }})
  2045. .attr("stroke-opacity", 1);
  2046. treeGroup.selectAll(".tree-node text")
  2047. .attr("fill", function(n) {{
  2048. if (!connectedD3Nodes.has(n)) return "#555";
  2049. return (n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb";
  2050. }});
  2051. // 边高亮
  2052. treeEdges.attr("stroke-opacity", function(e) {{
  2053. const isConnected = (e.源节点ID === clickedNodeId || e.目标节点ID === clickedNodeId) ||
  2054. (e.isTreeLink && (e.源节点ID === clickedNodeName || e.目标节点ID === clickedNodeName));
  2055. return isConnected ? 0.9 : 0.15;
  2056. }});
  2057. // 计算入边和出边
  2058. const inEdges = allConnectedEdges.filter(e => e.目标节点ID === clickedNodeId);
  2059. const outEdges = allConnectedEdges.filter(e => e.源节点ID === clickedNodeId);
  2060. // 显示详情面板
  2061. const nodeData = personaTreeData.nodes.find(n => n.节点ID === clickedNodeId);
  2062. if (nodeData) {{
  2063. showTreeNodeDetail(nodeData, inEdges, outEdges);
  2064. }}
  2065. // 显示关系子图
  2066. renderEgoGraph(clickedNodeId, clickedNodeName);
  2067. // 高亮右侧图中对应节点
  2068. if (g) {{
  2069. const graphNode = g.selectAll(".node").filter(n => n.节点ID === clickedNodeId);
  2070. if (!graphNode.empty()) {{
  2071. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2072. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2073. graphNode.classed("dimmed", false).classed("highlighted", true);
  2074. }}
  2075. }}
  2076. }}
  2077. // 共享的边点击处理函数(人设树和关系图复用)
  2078. function handleEdgeClick(srcNodeId, tgtNodeId, edgeType) {{
  2079. // 动态获取树相关元素
  2080. const treeGroup = d3.select(".persona-tree");
  2081. if (treeGroup.empty()) return;
  2082. const treeEdges = treeGroup.selectAll(".tree-edge");
  2083. // 先重置所有高亮状态
  2084. treeGroup.selectAll(".tree-node")
  2085. .classed("tree-dimmed", false)
  2086. .classed("tree-highlighted", false);
  2087. treeGroup.selectAll(".tree-node .tree-shape")
  2088. .attr("fill", d => getTreeNodeColor(d))
  2089. .attr("stroke", "rgba(255,255,255,0.5)")
  2090. .attr("stroke-width", 1)
  2091. .attr("stroke-opacity", 1)
  2092. .attr("opacity", 1);
  2093. treeGroup.selectAll(".tree-node text")
  2094. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  2095. .attr("opacity", 1);
  2096. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  2097. if (g) {{
  2098. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  2099. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  2100. }}
  2101. // 构建节点ID到D3节点的映射
  2102. const treeNodeById = {{}};
  2103. treeGroup.selectAll(".tree-node").each(function(n) {{
  2104. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  2105. }});
  2106. const sourceTreeNode = treeNodeById[srcNodeId];
  2107. const targetTreeNode = treeNodeById[tgtNodeId];
  2108. // 高亮树边(不变粗)
  2109. treeEdges.attr("stroke-opacity", function(e) {{
  2110. const isThisEdge = (e.源节点ID === srcNodeId && e.目标节点ID === tgtNodeId) ||
  2111. (e.源节点ID === tgtNodeId && e.目标节点ID === srcNodeId);
  2112. return isThisEdge ? 1 : 0.1;
  2113. }});
  2114. // 高亮相关节点
  2115. const connectedNodes = new Set();
  2116. if (sourceTreeNode) connectedNodes.add(sourceTreeNode);
  2117. if (targetTreeNode) connectedNodes.add(targetTreeNode);
  2118. treeGroup.selectAll(".tree-node .tree-shape")
  2119. .attr("fill", n => connectedNodes.has(n) ? getTreeNodeColor(n) : "#555")
  2120. .attr("opacity", 1);
  2121. treeGroup.selectAll(".tree-node text")
  2122. .attr("fill", n => connectedNodes.has(n) ?
  2123. ((n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb") : "#555")
  2124. .attr("opacity", 1);
  2125. // 显示边详情
  2126. const panel = document.getElementById("detailPanel");
  2127. panel.classList.add("active");
  2128. document.getElementById("detailTitle").textContent = "🔗 边详情";
  2129. const srcNode = personaTreeData.nodes.find(n => n.节点ID === srcNodeId);
  2130. const tgtNode = personaTreeData.nodes.find(n => n.节点ID === tgtNodeId);
  2131. const srcName = sourceTreeNode ? (sourceTreeNode.data.节点名称 || sourceTreeNode.data.name) : (srcNode?.节点名称 || srcNodeId);
  2132. const tgtName = targetTreeNode ? (targetTreeNode.data.节点名称 || targetTreeNode.data.name) : (tgtNode?.节点名称 || tgtNodeId);
  2133. let html = `
  2134. <p><span class="label">边类型:</span> <strong>${{edgeType}}</strong></p>
  2135. <p><span class="label">源节点:</span> ${{srcName}}</p>
  2136. <p><span class="label">目标节点:</span> ${{tgtName}}</p>
  2137. `;
  2138. document.getElementById("detailContent").innerHTML = html;
  2139. // 在关系图中展示这条边和两个节点
  2140. const edgeData = {{
  2141. 边类型: edgeType,
  2142. 源节点ID: srcNodeId,
  2143. 目标节点ID: tgtNodeId
  2144. }};
  2145. renderEgoGraphEdge(edgeData, sourceTreeNode, targetTreeNode);
  2146. }}
  2147. // 关系子图(Ego Graph)- 在画布第四层显示
  2148. let currentEgoSimulation = null; // 保存当前的力模拟,用于停止
  2149. function renderEgoGraph(centerNodeId, centerNodeName) {{
  2150. // 获取关系图层组
  2151. const egoGroup = d3.select(".ego-graph-content");
  2152. if (egoGroup.empty()) return;
  2153. // 停止之前的模拟
  2154. if (currentEgoSimulation) {{
  2155. currentEgoSimulation.stop();
  2156. currentEgoSimulation = null;
  2157. }}
  2158. // 清除旧内容
  2159. egoGroup.selectAll("*").remove();
  2160. // 隐藏占位提示
  2161. d3.select(".ego-placeholder").style("display", "none");
  2162. // 获取层半径(需要从全局获取或重新计算)
  2163. const radius = 120; // 固定半径
  2164. // 找到所有相关的边
  2165. const relatedEdges = personaTreeData.edges.filter(e =>
  2166. e.源节点ID === centerNodeId || e.目标节点ID === centerNodeId
  2167. );
  2168. // 收集所有相关节点ID
  2169. const nodeIds = new Set([centerNodeId]);
  2170. relatedEdges.forEach(e => {{
  2171. nodeIds.add(e.源节点ID);
  2172. nodeIds.add(e.目标节点ID);
  2173. }});
  2174. // 构建节点数据
  2175. const nodeMap = {{}};
  2176. personaTreeData.nodes.forEach(n => {{
  2177. if (nodeIds.has(n.节点ID)) {{
  2178. nodeMap[n.节点ID] = {{
  2179. id: n.节点ID,
  2180. name: n.节点名称,
  2181. type: n.节点类型,
  2182. level: n.节点层级,
  2183. isCenter: n.节点ID === centerNodeId
  2184. }};
  2185. }}
  2186. }});
  2187. const nodes = Object.values(nodeMap);
  2188. const links = relatedEdges.map(e => ({{
  2189. source: e.源节点ID,
  2190. target: e.目标节点ID,
  2191. type: e.边类型
  2192. }}));
  2193. // 根据节点数量动态计算实际使用的半径
  2194. const nodeCount = nodes.length;
  2195. const nodeSpacingEgo = 65; // 节点间距(增大)
  2196. const minEgoRadius = 120;
  2197. const maxEgoRadius = Math.max(radius, 250); // 允许更大的半径
  2198. let actualRadius;
  2199. if (nodeCount <= 1) {{
  2200. actualRadius = minEgoRadius;
  2201. }} else {{
  2202. const circumference = nodeCount * nodeSpacingEgo;
  2203. const calcR = circumference / (2 * Math.PI);
  2204. actualRadius = Math.max(minEgoRadius, Math.min(maxEgoRadius, calcR));
  2205. }}
  2206. // 显示节点名称作为标题
  2207. egoGroup.append("text")
  2208. .attr("class", "ego-title")
  2209. .attr("y", -actualRadius - 15)
  2210. .attr("text-anchor", "middle")
  2211. .attr("fill", "#e94560")
  2212. .attr("font-size", "12px")
  2213. .attr("font-weight", "bold")
  2214. .text(centerNodeName + ` (${{nodeCount}}个节点)`);
  2215. // 如果没有相关节点,显示提示
  2216. if (nodes.length <= 1) {{
  2217. egoGroup.append("text")
  2218. .attr("text-anchor", "middle")
  2219. .attr("fill", "rgba(255,255,255,0.4)")
  2220. .attr("font-size", "11px")
  2221. .text("该节点没有相关边");
  2222. return;
  2223. }}
  2224. // 边类型颜色(统一用实线)
  2225. const edgeColors = {{
  2226. "属于": "#9b59b6", // 紫色 - 层级关系
  2227. "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
  2228. "分类共现(点内)": "#27ae60", // 深绿 - 同帖子分类共现
  2229. "标签共现": "#f39c12" // 橙色 - 标签共现
  2230. }};
  2231. // 维度颜色(与人设树完全一致)
  2232. const dimColors = {{
  2233. "灵感点": "#f39c12",
  2234. "目的点": "#3498db",
  2235. "关键点": "#9b59b6"
  2236. }};
  2237. // 获取节点的维度颜色(与人设树一致)
  2238. function getNodeDimColor(d) {{
  2239. // 根据节点层级判断维度
  2240. const level = d.level || "";
  2241. if (level.includes("灵感点")) return dimColors["灵感点"];
  2242. if (level.includes("目的点")) return dimColors["目的点"];
  2243. if (level.includes("关键点")) return dimColors["关键点"];
  2244. return "#888";
  2245. }}
  2246. // 获取节点填充色(实心,用维度颜色,不因选中而改变)
  2247. function getNodeFill(d) {{
  2248. return getNodeDimColor(d); // 始终用维度颜色填充
  2249. }}
  2250. // 获取节点边框色(选中节点用白色边框区分)
  2251. function getNodeStroke(d) {{
  2252. if (d.isCenter) return "#fff"; // 选中节点白色边框
  2253. return "rgba(255,255,255,0.5)"; // 普通节点半透明白边框
  2254. }}
  2255. // 获取节点边框粗细(选中节点更粗)
  2256. function getNodeStrokeWidth(d) {{
  2257. return d.isCenter ? 3 : 1.5;
  2258. }}
  2259. // 根据节点数量调整力模拟参数
  2260. const linkDistance = Math.max(50, Math.min(80, actualRadius / 2.5));
  2261. const chargeStrength = Math.max(-300, Math.min(-100, -nodeCount * 10));
  2262. const collisionRadius = 35; // 碰撞半径,防止重叠
  2263. // 创建力导向模拟(中心在0,0因为已经平移了)
  2264. const simulation = d3.forceSimulation(nodes)
  2265. .force("link", d3.forceLink(links).id(d => d.id).distance(linkDistance))
  2266. .force("charge", d3.forceManyBody().strength(chargeStrength))
  2267. .force("center", d3.forceCenter(0, 0))
  2268. .force("collision", d3.forceCollide().radius(collisionRadius))
  2269. .force("boundary", function() {{
  2270. // 限制节点在圆形区域内
  2271. const maxR = actualRadius - 30;
  2272. return function(alpha) {{
  2273. nodes.forEach(d => {{
  2274. const dist = Math.sqrt(d.x * d.x + d.y * d.y);
  2275. if (dist > maxR) {{
  2276. const scale = maxR / dist;
  2277. d.x *= scale;
  2278. d.y *= scale;
  2279. }}
  2280. }});
  2281. }};
  2282. }}());
  2283. currentEgoSimulation = simulation;
  2284. // 绘制边(统一用实线)
  2285. const link = egoGroup.selectAll(".ego-edge")
  2286. .data(links)
  2287. .join("line")
  2288. .attr("class", "ego-edge")
  2289. .attr("stroke", d => edgeColors[d.type] || "#666")
  2290. .attr("stroke-width", 1.5)
  2291. .attr("stroke-opacity", 0.7);
  2292. // 绘制节点(分类用方形,标签用圆形)
  2293. const node = egoGroup.selectAll(".ego-node")
  2294. .data(nodes)
  2295. .join("g")
  2296. .attr("class", d => "ego-node" + (d.isCenter ? " center" : ""));
  2297. // 根据节点类型绘制不同形状(与人设树样式一致)
  2298. const nodeSize = 8;
  2299. node.each(function(d) {{
  2300. const el = d3.select(this);
  2301. const fill = getNodeFill(d);
  2302. const stroke = getNodeStroke(d);
  2303. const size = d.isCenter ? nodeSize + 2 : nodeSize;
  2304. const strokeWidth = getNodeStrokeWidth(d);
  2305. if (d.type === "分类") {{
  2306. // 方形(分类节点)- 与人设树一致
  2307. el.append("rect")
  2308. .attr("class", "ego-shape")
  2309. .attr("width", size * 2)
  2310. .attr("height", size * 2)
  2311. .attr("x", -size)
  2312. .attr("y", -size)
  2313. .attr("fill", fill)
  2314. .attr("stroke", stroke)
  2315. .attr("stroke-width", strokeWidth)
  2316. .attr("rx", 1);
  2317. }} else {{
  2318. // 圆形(标签节点)- 与人设树一致
  2319. el.append("circle")
  2320. .attr("class", "ego-shape")
  2321. .attr("r", size)
  2322. .attr("fill", fill)
  2323. .attr("stroke", stroke)
  2324. .attr("stroke-width", strokeWidth);
  2325. }}
  2326. }});
  2327. node.append("text")
  2328. .attr("dy", -12)
  2329. .attr("text-anchor", "middle")
  2330. .attr("font-size", "9px")
  2331. .attr("fill", "#fff")
  2332. .text(d => d.name.length > 6 ? d.name.substring(0, 6) + ".." : d.name);
  2333. // 添加点击事件(直接调用共享函数)
  2334. node.on("click", function(event, d) {{
  2335. event.stopPropagation();
  2336. handleNodeClick(d.id, d.name);
  2337. }});
  2338. // 边点击事件(直接调用共享函数)
  2339. link.on("click", function(event, d) {{
  2340. event.stopPropagation();
  2341. handleEdgeClick(d.source.id, d.target.id, d.type);
  2342. }});
  2343. // 更新位置
  2344. simulation.on("tick", () => {{
  2345. link
  2346. .attr("x1", d => d.source.x)
  2347. .attr("y1", d => d.source.y)
  2348. .attr("x2", d => d.target.x)
  2349. .attr("y2", d => d.target.y);
  2350. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  2351. }});
  2352. }}
  2353. function clearEgoGraph() {{
  2354. const egoGroup = d3.select(".ego-graph-content");
  2355. if (!egoGroup.empty()) {{
  2356. egoGroup.selectAll("*").remove();
  2357. }}
  2358. // 显示占位提示
  2359. d3.select(".ego-placeholder").style("display", null);
  2360. // 停止模拟
  2361. if (currentEgoSimulation) {{
  2362. currentEgoSimulation.stop();
  2363. currentEgoSimulation = null;
  2364. }}
  2365. }}
  2366. // 渲染单条边和两个节点(点击树边时调用)
  2367. function renderEgoGraphEdge(edgeData, sourceNode, targetNode) {{
  2368. const egoGroup = d3.select(".ego-graph-content");
  2369. if (egoGroup.empty()) return;
  2370. // 停止之前的模拟
  2371. if (currentEgoSimulation) {{
  2372. currentEgoSimulation.stop();
  2373. currentEgoSimulation = null;
  2374. }}
  2375. // 清除旧内容
  2376. egoGroup.selectAll("*").remove();
  2377. d3.select(".ego-placeholder").style("display", "none");
  2378. const radius = 250;
  2379. // 边类型颜色
  2380. const edgeColors = {{
  2381. "属于": "#9b59b6",
  2382. "分类共现(跨点)": "#2ecc71",
  2383. "分类共现(点内)": "#27ae60",
  2384. "标签共现": "#f39c12"
  2385. }};
  2386. // 维度颜色
  2387. const dimColors = {{
  2388. "灵感点": "#f39c12",
  2389. "目的点": "#3498db",
  2390. "关键点": "#9b59b6"
  2391. }};
  2392. // 获取节点颜色
  2393. function getNodeColor(nodeData) {{
  2394. const level = nodeData.节点层级 || "";
  2395. if (level.includes("灵感点")) return dimColors["灵感点"];
  2396. if (level.includes("目的点")) return dimColors["目的点"];
  2397. if (level.includes("关键点")) return dimColors["关键点"];
  2398. return "#888";
  2399. }}
  2400. // 标题
  2401. egoGroup.append("text")
  2402. .attr("class", "ego-title")
  2403. .attr("y", -80)
  2404. .attr("text-anchor", "middle")
  2405. .attr("fill", edgeColors[edgeData.边类型] || "#666")
  2406. .attr("font-size", "12px")
  2407. .attr("font-weight", "bold")
  2408. .text(`${{edgeData.边类型}}`);
  2409. // 两个节点的位置
  2410. const srcX = -60, srcY = 0;
  2411. const tgtX = 60, tgtY = 0;
  2412. // 绘制边
  2413. egoGroup.append("line")
  2414. .attr("class", "ego-edge")
  2415. .attr("x1", srcX)
  2416. .attr("y1", srcY)
  2417. .attr("x2", tgtX)
  2418. .attr("y2", tgtY)
  2419. .attr("stroke", edgeColors[edgeData.边类型] || "#666")
  2420. .attr("stroke-width", 3)
  2421. .attr("stroke-opacity", 0.8);
  2422. // 获取节点数据
  2423. const srcData = sourceNode ? sourceNode.data : {{}};
  2424. const tgtData = targetNode ? targetNode.data : {{}};
  2425. // 绘制源节点
  2426. const srcGroup = egoGroup.append("g")
  2427. .attr("class", "ego-node")
  2428. .attr("transform", `translate(${{srcX}}, ${{srcY}})`);
  2429. const srcSize = 15;
  2430. const srcColor = getNodeColor(srcData);
  2431. if (srcData.节点类型 === "分类") {{
  2432. srcGroup.append("rect")
  2433. .attr("width", srcSize * 2)
  2434. .attr("height", srcSize * 2)
  2435. .attr("x", -srcSize)
  2436. .attr("y", -srcSize)
  2437. .attr("fill", srcColor)
  2438. .attr("stroke", "rgba(255,255,255,0.5)")
  2439. .attr("stroke-width", 2)
  2440. .attr("rx", 2);
  2441. }} else {{
  2442. srcGroup.append("circle")
  2443. .attr("r", srcSize)
  2444. .attr("fill", srcColor)
  2445. .attr("stroke", "rgba(255,255,255,0.5)")
  2446. .attr("stroke-width", 2);
  2447. }}
  2448. srcGroup.append("text")
  2449. .attr("dy", -srcSize - 8)
  2450. .attr("text-anchor", "middle")
  2451. .attr("fill", "#fff")
  2452. .attr("font-size", "11px")
  2453. .text(srcData.节点名称 || srcData.name || "源节点");
  2454. // 绘制目标节点
  2455. const tgtGroup = egoGroup.append("g")
  2456. .attr("class", "ego-node")
  2457. .attr("transform", `translate(${{tgtX}}, ${{tgtY}})`);
  2458. const tgtSize = 15;
  2459. const tgtColor = getNodeColor(tgtData);
  2460. if (tgtData.节点类型 === "分类") {{
  2461. tgtGroup.append("rect")
  2462. .attr("width", tgtSize * 2)
  2463. .attr("height", tgtSize * 2)
  2464. .attr("x", -tgtSize)
  2465. .attr("y", -tgtSize)
  2466. .attr("fill", tgtColor)
  2467. .attr("stroke", "rgba(255,255,255,0.5)")
  2468. .attr("stroke-width", 2)
  2469. .attr("rx", 2);
  2470. }} else {{
  2471. tgtGroup.append("circle")
  2472. .attr("r", tgtSize)
  2473. .attr("fill", tgtColor)
  2474. .attr("stroke", "rgba(255,255,255,0.5)")
  2475. .attr("stroke-width", 2);
  2476. }}
  2477. tgtGroup.append("text")
  2478. .attr("dy", -tgtSize - 8)
  2479. .attr("text-anchor", "middle")
  2480. .attr("fill", "#fff")
  2481. .attr("font-size", "11px")
  2482. .text(tgtData.节点名称 || tgtData.name || "目标节点");
  2483. // 边标签
  2484. egoGroup.append("text")
  2485. .attr("y", 25)
  2486. .attr("text-anchor", "middle")
  2487. .attr("fill", "rgba(255,255,255,0.6)")
  2488. .attr("font-size", "10px")
  2489. .text(edgeData.边类型);
  2490. }}
  2491. // 页面加载完成后初始化
  2492. window.addEventListener("load", init);
  2493. window.addEventListener("resize", () => {{
  2494. if (currentIndex >= 0) {{
  2495. renderGraph(allGraphData[currentIndex]);
  2496. }}
  2497. }});
  2498. </script>
  2499. </body>
  2500. </html>
  2501. '''
  2502. def generate_combined_html(all_graph_data: List[Dict], persona_tree_data: Dict, output_file: Path):
  2503. """
  2504. 生成包含所有帖子图谱的HTML文件
  2505. Args:
  2506. all_graph_data: 所有帖子的图谱数据列表
  2507. persona_tree_data: 完整的人设树数据(节点和边)
  2508. output_file: 输出文件路径
  2509. """
  2510. # 生成Tab HTML
  2511. tabs_html = ""
  2512. for i, data in enumerate(all_graph_data):
  2513. post_title = data.get("postTitle", "")
  2514. # 使用帖子标题,如果太长则截断
  2515. if post_title:
  2516. tab_name = post_title[:15] + "..." if len(post_title) > 15 else post_title
  2517. else:
  2518. tab_name = f"帖子 {i+1}"
  2519. active_class = "active" if i == 0 else ""
  2520. tabs_html += f'<div class="tab {active_class}" data-index="{i}">{tab_name}</div>\n'
  2521. # 生成HTML
  2522. html_content = HTML_TEMPLATE.format(
  2523. tabs_html=tabs_html,
  2524. all_graph_data=json.dumps(all_graph_data, ensure_ascii=False),
  2525. persona_tree_data=json.dumps(persona_tree_data, ensure_ascii=False)
  2526. )
  2527. with open(output_file, "w", encoding="utf-8") as f:
  2528. f.write(html_content)
  2529. def main():
  2530. # 使用路径配置
  2531. config = PathConfig()
  2532. print(f"账号: {config.account_name}")
  2533. print(f"输出版本: {config.output_version}")
  2534. print()
  2535. # 输入目录
  2536. match_graph_dir = config.intermediate_dir / "match_graph"
  2537. # 输出文件
  2538. output_file = config.intermediate_dir / "match_graph.html"
  2539. print(f"输入目录: {match_graph_dir}")
  2540. print(f"输出文件: {output_file}")
  2541. print()
  2542. # 读取人设树中间数据
  2543. persona_tree_file = config.intermediate_dir / "persona_tree.json"
  2544. persona_tree_data = {"nodes": [], "edges": []}
  2545. if persona_tree_file.exists():
  2546. print(f"读取人设树数据: {persona_tree_file.name}")
  2547. with open(persona_tree_file, "r", encoding="utf-8") as f:
  2548. tree_data = json.load(f)
  2549. persona_tree_data["nodes"] = tree_data.get("nodes", [])
  2550. persona_tree_data["edges"] = tree_data.get("edges", [])
  2551. category_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "分类"])
  2552. tag_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "标签"])
  2553. print(f" 分类节点: {category_count}, 标签节点: {tag_count}")
  2554. print(f" 边数: {len(persona_tree_data['edges'])}")
  2555. print()
  2556. # 读取所有匹配图谱文件
  2557. graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
  2558. print(f"找到 {len(graph_files)} 个匹配图谱文件")
  2559. all_graph_data = []
  2560. for i, graph_file in enumerate(graph_files, 1):
  2561. print(f" [{i}/{len(graph_files)}] 读取: {graph_file.name}")
  2562. with open(graph_file, "r", encoding="utf-8") as f:
  2563. match_graph_data = json.load(f)
  2564. # 提取需要的数据
  2565. graph_data = {
  2566. "postId": match_graph_data["说明"]["帖子ID"],
  2567. "postTitle": match_graph_data["说明"].get("帖子标题", ""),
  2568. "stats": match_graph_data["说明"]["统计"],
  2569. "nodes": match_graph_data["节点列表"],
  2570. "edges": match_graph_data["边列表"]
  2571. }
  2572. all_graph_data.append(graph_data)
  2573. # 生成HTML
  2574. print("\n生成HTML文件...")
  2575. generate_combined_html(all_graph_data, persona_tree_data, output_file)
  2576. print("\n" + "="*60)
  2577. print("处理完成!")
  2578. print(f"输出文件: {output_file}")
  2579. if __name__ == "__main__":
  2580. main()