relationData.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. /**
  2. * 通用关系图 —— 独立数据模型
  3. *
  4. * 数据来自 `execute_python` 工具结果里的 `relationGraph`:
  5. * { title?, nodes: [{id,label,type,value,degree}], edges: [{source,target,relation,weight,count,directed}],
  6. * truncated?, note?, totalNodes?, totalEdges? }
  7. *
  8. * 节点/边的业务口径由模型在 Python 里决定(任意表、任意字段、任意关系名),
  9. * 本文件只做渲染前的归一化,不推断任何社交关系。
  10. */
  11. import type { EdgeData, GraphData, NodeData } from '@antv/g6';
  12. export type RelationNodeType = 'person' | 'phone' | 'card' | 'org' | 'place' | 'vehicle' | 'account' | 'other';
  13. export interface RelationTypeMeta {
  14. type: RelationNodeType;
  15. label: string;
  16. color: string;
  17. }
  18. /** 节点类型配色:与案件图谱的实体色保持一致(节点本身复用 ai-graph-node 的图标样式) */
  19. export const RELATION_TYPE_META: Record<RelationNodeType, RelationTypeMeta> = {
  20. person: { type: 'person', label: '人物', color: '#b92a31' },
  21. phone: { type: 'phone', label: '手机号', color: '#0aa0b4' },
  22. card: { type: 'card', label: '银行卡', color: '#8441ae' },
  23. org: { type: 'org', label: '机构', color: '#0f9f68' },
  24. place: { type: 'place', label: '地点', color: '#0f4c8a' },
  25. vehicle: { type: 'vehicle', label: '车辆', color: '#f29a1f' },
  26. account: { type: 'account', label: '账号', color: '#8441ae' },
  27. other: { type: 'other', label: '其他', color: '#d4ac2b' },
  28. };
  29. export const RELATION_TYPE_META_LIST: RelationTypeMeta[] = [
  30. RELATION_TYPE_META.person,
  31. RELATION_TYPE_META.phone,
  32. RELATION_TYPE_META.card,
  33. RELATION_TYPE_META.org,
  34. RELATION_TYPE_META.place,
  35. RELATION_TYPE_META.vehicle,
  36. RELATION_TYPE_META.account,
  37. RELATION_TYPE_META.other,
  38. ];
  39. export function relationTypeMeta(type?: string | null): RelationTypeMeta {
  40. const key = (type || 'other') as RelationNodeType;
  41. return Object.prototype.hasOwnProperty.call(RELATION_TYPE_META, key)
  42. ? RELATION_TYPE_META[key] || RELATION_TYPE_META.other
  43. : RELATION_TYPE_META.other;
  44. }
  45. export interface RelationModelNode {
  46. id: string;
  47. label: string;
  48. type: RelationNodeType;
  49. value: string;
  50. degree: number;
  51. }
  52. export interface RelationModelEdge {
  53. id: string;
  54. source: string;
  55. target: string;
  56. relation: string;
  57. label: string;
  58. weight: number;
  59. count: number;
  60. directed: boolean;
  61. }
  62. export interface ParsedRelationGraph {
  63. title: string;
  64. nodes: RelationModelNode[];
  65. edges: RelationModelEdge[];
  66. truncated: boolean;
  67. note: string;
  68. totalNodes: number;
  69. totalEdges: number;
  70. }
  71. /* ------------------------------------------------------------------ *
  72. * 归一化
  73. * ------------------------------------------------------------------ */
  74. function text(value: unknown): string {
  75. return String(value ?? '').trim();
  76. }
  77. function toNumber(value: unknown, fallback = 0): number {
  78. if (value === null || value === undefined || value === '') return fallback;
  79. const numeric = Number(String(value).replace(/,/g, ''));
  80. return Number.isFinite(numeric) ? numeric : fallback;
  81. }
  82. function toBoolean(value: unknown): boolean {
  83. if (typeof value === 'boolean') return value;
  84. const raw = text(value).toLowerCase();
  85. return raw === 'true' || raw === '1' || raw === 'yes';
  86. }
  87. function normalizeType(value: unknown): RelationNodeType {
  88. const raw = text(value).toLowerCase();
  89. return Object.prototype.hasOwnProperty.call(RELATION_TYPE_META, raw) ? (raw as RelationNodeType) : 'other';
  90. }
  91. /**
  92. * 把后端规范化后的 relationGraph 解析成渲染模型。
  93. *
  94. * 后端已经做过结构校验/裁剪;前端仍做一层容错(缺 id、悬空边、重复边),
  95. * 保证历史消息里的旧载荷或手工改动也不会把画布画崩。
  96. */
  97. export function parseRelationGraphPayload(raw: unknown): ParsedRelationGraph | null {
  98. if (raw === null || raw === undefined) return null;
  99. let source: any = raw;
  100. if (typeof raw === 'string') {
  101. try {
  102. source = JSON.parse(raw);
  103. } catch {
  104. return null;
  105. }
  106. }
  107. if (!source || typeof source !== 'object') return null;
  108. // 兼容「只给边数组」的写法
  109. const rawNodes = Array.isArray(source) ? [] : Array.isArray(source.nodes) ? source.nodes : [];
  110. const rawEdges = Array.isArray(source) ? source : Array.isArray(source.edges) ? source.edges : [];
  111. const title = Array.isArray(source) ? '' : text(source.title || source.meta?.title);
  112. const note = Array.isArray(source) ? '' : text(source.note);
  113. const truncated = Array.isArray(source) ? false : Boolean(source.truncated);
  114. const nodeMap = new Map<string, RelationModelNode>();
  115. const ensureNode = (id: string, label?: unknown, type?: unknown, value?: unknown) => {
  116. if (!id) return;
  117. if (nodeMap.has(id)) return;
  118. nodeMap.set(id, {
  119. id,
  120. label: text(label) || id,
  121. type: normalizeType(type),
  122. value: text(value) || id,
  123. degree: 0,
  124. });
  125. };
  126. rawNodes.forEach((item: any) => {
  127. if (!item || typeof item !== 'object' || Array.isArray(item)) return;
  128. const value = text(item.value);
  129. const label = text(item.label);
  130. const id = text(item.id) || value || label;
  131. if (!id) return;
  132. ensureNode(id, label || value, item.type, value || id);
  133. });
  134. const edgeMap = new Map<string, RelationModelEdge>();
  135. rawEdges.forEach((item: any) => {
  136. if (!item || typeof item !== 'object' || Array.isArray(item)) return;
  137. const sourceId = text(item.source);
  138. const targetId = text(item.target);
  139. if (!sourceId || !targetId || sourceId === targetId) return;
  140. ensureNode(sourceId, item.sourceLabel, item.sourceType, sourceId);
  141. ensureNode(targetId, item.targetLabel, item.targetType, targetId);
  142. const relation = text(item.relation) || text(item.label) || '关联';
  143. const weight = Math.max(0, toNumber(item.weight, toNumber(item.count, 1)));
  144. const count = Math.max(0, toNumber(item.count, 0));
  145. const directed = toBoolean(item.directed);
  146. // 无向边统一端点顺序,A→B 与 B→A 只保留一条
  147. const [from, to] = directed ? [sourceId, targetId] : [sourceId, targetId].sort();
  148. const key = `${from}\u0001${to}\u0001${relation}\u0001${directed}`;
  149. const existing = edgeMap.get(key);
  150. if (existing) {
  151. existing.weight += weight;
  152. existing.count += count;
  153. return;
  154. }
  155. edgeMap.set(key, {
  156. id: '',
  157. source: from,
  158. target: to,
  159. relation,
  160. label: relation,
  161. weight,
  162. count,
  163. directed,
  164. });
  165. });
  166. const nodes = Array.from(nodeMap.values());
  167. const degree = new Map<string, number>();
  168. const edges = Array.from(edgeMap.values()).map((edge, index) => {
  169. degree.set(edge.source, (degree.get(edge.source) || 0) + 1);
  170. degree.set(edge.target, (degree.get(edge.target) || 0) + 1);
  171. return {
  172. ...edge,
  173. id: `relation-edge-${index}`,
  174. };
  175. });
  176. nodes.forEach((node) => {
  177. node.degree = degree.get(node.id) || 0;
  178. });
  179. return {
  180. title,
  181. nodes,
  182. edges,
  183. truncated,
  184. note,
  185. totalNodes: toNumber(Array.isArray(source) ? nodes.length : source.totalNodes, nodes.length),
  186. totalEdges: toNumber(Array.isArray(source) ? edges.length : source.totalEdges, edges.length),
  187. };
  188. }
  189. /* ------------------------------------------------------------------ *
  190. * G6 数据
  191. * ------------------------------------------------------------------ */
  192. /**
  193. * 渲染模型 → G6 GraphData。
  194. *
  195. * 平行边(同一对端点之间多条关系)改为二次曲线,否则会完全重叠。
  196. */
  197. export function buildRelationG6Data(model: ParsedRelationGraph): GraphData {
  198. const nodes: NodeData[] = model.nodes.map((node) => ({
  199. id: node.id,
  200. data: {
  201. label: node.label,
  202. type: node.type,
  203. value: node.value,
  204. degree: node.degree,
  205. },
  206. style: {},
  207. }));
  208. const edges: EdgeData[] = model.edges.map((edge) => ({
  209. id: edge.id,
  210. source: edge.source,
  211. target: edge.target,
  212. type: 'line',
  213. data: {
  214. relation: edge.relation,
  215. label: edge.label,
  216. weight: edge.weight,
  217. count: edge.count,
  218. directed: edge.directed,
  219. },
  220. style: {},
  221. }));
  222. const groups = new Map<string, EdgeData[]>();
  223. edges.forEach((edge) => {
  224. const key = [String(edge.source), String(edge.target)].sort().join('::');
  225. const group = groups.get(key) || [];
  226. group.push(edge);
  227. groups.set(key, group);
  228. });
  229. groups.forEach((group) => {
  230. if (group.length <= 1) return;
  231. group.forEach((edge, index) => {
  232. const offset = (index % 2 === 0 ? 1 : -1) * Math.ceil(index / 2) * 26;
  233. edge.type = 'quadratic';
  234. edge.style = { ...(edge.style || {}), curveOffset: offset };
  235. });
  236. });
  237. return { nodes, edges, combos: [] };
  238. }