-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
executable file
·2120 lines (1794 loc) · 74.2 KB
/
script.js
File metadata and controls
executable file
·2120 lines (1794 loc) · 74.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 全局变量
let networks = []; // 动态数量的网络图实例
let nodeDatasets = []; // 动态数量的独立节点数据集
let edgeDatasets = []; // 动态数量的独立边数据集
let nodeIdCounters = []; // 每个图的节点ID计数器
let selectedNodes = [];
let selectedEdges = [];
let currentFormsData = []; // 存储当前的forms数据
let highlightedNodes = []; // 存储当前高亮的节点
let originalExcelData = []; // 存储原始Excel数据
let isBeautified = false; // 跟踪图形美化状态
let currentEditEdgeId = null;
let currentSlideIndex = 0; // 当前显示的轮播图索引
let totalSlides = 0; // 总幻灯片数量
let evaluationMetricsData = []; // 存储所有语义地图的评价指标数据
// Merge功能相关的状态管理
let isMergedStates = []; // 每个地图的merge状态数组
let backupEvaluationMetricsArray = []; // 每个地图备份merge前的评价指标
let backupUnconnectedFormsArray = []; // 每个地图备份merge前的未连接表单
let mergedEdgeIdsArray = []; // 每个地图存储merge的边ID数组
// 配置网络图选项
const options = {
nodes: {
shape: 'circle',
font: {
size: 16,
face: 'Arial'
},
borderWidth: 2,
shadow: false
},
edges: {
shadow: false,
font: {
size: 12,
align: 'middle',
background: 'white',
strokeWidth: 1,
strokeColor: '#000000'
},
arrows: {
to: { enabled: false }
},
color: {
color: '#FFCCE5', // 浅粉色
highlight: '#FF69B4', // 深粉色(热粉色)
hover: '#FF69B4' // 鼠标悬停时显示深粉色
},
chosen: {
label: false
},
labelHighlightBold: false
},
physics: {
enabled: true,
barnesHut: {
gravitationalConstant: -2000,
centralGravity: 0.3,
springLength: 150,
springConstant: 0.04
}
},
interaction: {
hover: true,
multiselect: true,
navigationButtons: true,
dragNodes: true,
dragView: true,
zoomView: true
},
manipulation: {
enabled: false
}
};
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
// 初始化空的数据集数组
nodeDatasets = [];
edgeDatasets = [];
networks = [];
// 不再自动初始化网络图,等待用户上传文件后动态创建
// 初始化筛选功能
initializeFormFilter();
// 初始化文件信息显示
const fileInfo = document.getElementById('file-info');
fileInfo.textContent = 'No file selected';
// 绑定按钮事件
document.getElementById('upload-btn').addEventListener('click', handleFileUpload);
document.getElementById('download-guide-btn').addEventListener('click', handleDownloadGuide);
document.getElementById('example-btn').addEventListener('click', handleExampleUpload);
document.getElementById('example-btn-2').addEventListener('click', handleExampleUpload2);
document.getElementById('example-btn-3').addEventListener('click', handleExampleUpload3);
document.getElementById('help-btn').addEventListener('click', showHelpModal);
// 绑定自定义文件选择按钮事件
document.getElementById('file-select-btn').addEventListener('click', function() {
document.getElementById('excel-file').click();
});
// 绑定文件输入change事件
document.getElementById('excel-file').addEventListener('change', function() {
const fileInfo = document.getElementById('file-info');
const fileSelectBtn = document.getElementById('file-select-btn');
if (this.files && this.files.length > 0) {
const fileName = this.files[0].name;
fileInfo.textContent = `Selected file: ${fileName}`;
fileSelectBtn.textContent = fileName;
} else {
fileInfo.textContent = 'No file selected';
fileSelectBtn.textContent = 'Choose File';
}
});
document.getElementById('add-edge-btn').addEventListener('click', showAddEdgeForm);
document.getElementById('edit-edge-btn').addEventListener('click', showEditEdgeForm);
document.getElementById('delete-edge-btn').addEventListener('click', deleteSelectedEdge);
document.getElementById('merge-edge-btn').addEventListener('click', function() {
const currentIndex = currentSlideIndex;
if (isMergedStates[currentIndex]) {
restoreMerge();
} else {
mergeEdges();
}
});
document.getElementById('center-btn').addEventListener('click', centerGraph);
document.getElementById('beautiful-btn').addEventListener('click', beautifyGraph);
document.getElementById('download-btn').addEventListener('click', downloadGraph);
document.getElementById('confirm-add-edge').addEventListener('click', addEdge);
document.getElementById('cancel-add-edge').addEventListener('click', hideAddEdgeForm);
document.getElementById('confirm-edit-edge').addEventListener('click', updateEdge);
document.getElementById('cancel-edit-edge').addEventListener('click', hideEditEdgeForm);
// 绑定轮播控制事件
document.getElementById('prev-btn').addEventListener('click', showPreviousSlide);
document.getElementById('next-btn').addEventListener('click', showNextSlide);
// 绑定指示器点击事件
const indicators = document.querySelectorAll('.indicator');
indicators.forEach(indicator => {
indicator.addEventListener('click', function() {
const index = parseInt(this.getAttribute('data-index'));
showSlide(index);
});
});
});
// 初始化筛选功能
function initializeFormFilter() {
const filterBtn = document.getElementById('form-filter-btn');
const filterMenu = document.getElementById('form-filter-menu');
if (!filterBtn || !filterMenu) {
return; // 如果元素不存在,直接返回
}
// 点击按钮显示/隐藏下拉菜单
filterBtn.addEventListener('click', function(e) {
e.stopPropagation();
const isVisible = filterMenu.style.display === 'block';
filterMenu.style.display = isVisible ? 'none' : 'block';
});
// 点击其他地方隐藏下拉菜单
document.addEventListener('click', function() {
filterMenu.style.display = 'none';
});
// 阻止菜单内部点击事件冒泡
filterMenu.addEventListener('click', function(e) {
e.stopPropagation();
});
}
// 更新筛选模块
function updateFormFilter(formsData) {
const filterMenu = document.getElementById('form-filter-menu');
const filterBtn = document.getElementById('form-filter-btn');
if (!filterMenu || !filterBtn) {
return; // 如果元素不存在,直接返回
}
// 清空现有选项
filterMenu.innerHTML = '';
// 添加"All Forms"选项
const allOption = document.createElement('div');
allOption.className = 'dropdown-item selected';
allOption.textContent = 'All Forms';
allOption.dataset.form = 'all';
allOption.addEventListener('click', function() {
selectFormFilter('all', 'All Forms');
});
filterMenu.appendChild(allOption);
// 添加每个form选项
formsData.forEach((formData, index) => {
const option = document.createElement('div');
option.className = 'dropdown-item';
option.textContent = `${formData.form} (${formData.language})`;
option.dataset.form = index;
option.addEventListener('click', function() {
selectFormFilter(index, `${formData.form} (${formData.language})`);
});
filterMenu.appendChild(option);
});
// 重置按钮文本
filterBtn.textContent = 'All Forms ▼';
}
// 选择筛选项
function selectFormFilter(formIndex, displayText) {
const filterBtn = document.getElementById('form-filter-btn');
const filterMenu = document.getElementById('form-filter-menu');
if (!filterBtn || !filterMenu) {
return;
}
const dropdownItems = filterMenu.querySelectorAll('.dropdown-item');
// 更新选中状态
dropdownItems.forEach(item => item.classList.remove('selected'));
if (formIndex === 'all') {
dropdownItems[0].classList.add('selected');
} else {
dropdownItems[formIndex + 1].classList.add('selected');
}
// 更新按钮文本
filterBtn.textContent = displayText + ' ▼';
// 隐藏下拉菜单
filterMenu.style.display = 'none';
// 高亮对应节点
highlightFormNodes(formIndex);
}
// 高亮form对应的节点
function highlightFormNodes(formIndex) {
// 清除之前的高亮
clearNodeHighlight();
if (formIndex === 'all' || !window.currentFormsData || !window.currentFormsData[formIndex]) {
return;
}
const formData = window.currentFormsData[formIndex];
const nodeIds = formData.nodes;
// 高亮所有网络中的对应节点
networks.forEach(network => {
if (network) {
const nodes = network.body.data.nodes;
const updateNodes = [];
nodeIds.forEach(nodeId => {
const node = nodes.get(nodeId);
if (node) {
updateNodes.push({
id: nodeId,
color: {
background: '#ffeb3b', // 浅黄色
border: '#fbc02d'
}
});
highlightedNodes.push(nodeId);
}
});
if (updateNodes.length > 0) {
nodes.update(updateNodes);
}
}
});
}
// 清除节点高亮
function clearNodeHighlight() {
networks.forEach(network => {
if (network && highlightedNodes.length > 0) {
const nodes = network.body.data.nodes;
const updateNodes = [];
highlightedNodes.forEach(nodeId => {
const node = nodes.get(nodeId);
if (node) {
updateNodes.push({
id: nodeId,
color: {
background: '#97c2fc', // 恢复默认颜色
border: '#2b7ce9'
}
});
}
});
if (updateNodes.length > 0) {
nodes.update(updateNodes);
}
}
});
highlightedNodes = [];
}
// 初始化多个网络图(现在由updateGraph函数动态调用)
function initializeNetworks(count) {
// 根据实际数量初始化网络图
for (let i = 0; i < count; i++) {
const container = document.getElementById(`graph-container-${i+1}`);
// 确保容器存在
if (!container) {
console.error(`Container graph-container-${i+1} not found`);
continue;
}
// 为每个图创建独立的数据对象
const data = {
nodes: nodeDatasets[i],
edges: edgeDatasets[i]
};
// 为第一个图创建优化配置,减少性能负担
let networkOptions = options;
if (i === 0) {
networkOptions = {
...options,
physics: {
enabled: true,
stabilization: {
enabled: true,
iterations: 100,
updateInterval: 25
},
barnesHut: {
gravitationalConstant: -1000,
centralGravity: 0.1,
springLength: 100,
springConstant: 0.02
}
}
};
}
networks[i] = new vis.Network(container, data, networkOptions);
// 添加选择事件监听
networks[i].on('click', (function(index) {
return function(params) {
selectedNodes = params.nodes;
selectedEdges = params.edges;
// 更新当前图的索引
currentSlideIndex = index;
};
})(i));
}
// 显示第一个轮播图
if (count > 0) {
showSlide(0);
}
}
// 不再需要同步所有图的选择状态
// 轮播控制函数
function showSlide(index) {
// 获取所有轮播图和指示器
const slides = document.querySelectorAll('.carousel-slide');
const indicators = document.querySelectorAll('.indicator');
// 确保索引在有效范围内
if (index < 0 || index >= slides.length) {
return;
}
// 隐藏所有轮播图并移除指示器的活动状态
slides.forEach(slide => slide.classList.remove('active'));
indicators.forEach(indicator => indicator.classList.remove('active'));
// 显示指定索引的轮播图并激活对应的指示器
slides[index].classList.add('active');
indicators[index].classList.add('active');
// 更新当前索引
currentSlideIndex = index;
// 更新merge按钮状态
const mergeBtn = document.getElementById('merge-edge-btn');
if (mergeBtn) {
if (isMergedStates[index]) {
mergeBtn.textContent = 'Restore Merge';
} else {
mergeBtn.textContent = 'Merge Edge';
}
}
// 更新当前显示的评价指标
// 无论是否有评估数据,都调用updateEvaluationMetrics来确保正确显示
updateEvaluationMetrics(index, evaluationMetricsData[index] || null);
// 重新绘制当前显示的网络图
if (networks[index]) {
networks[index].redraw();
// 只在初始化时或数据更新后才调用fit,避免影响用户的视图状态
// networks[index].fit();
}
}
function showNextSlide() {
const slides = document.querySelectorAll('.carousel-slide');
const nextIndex = (currentSlideIndex + 1) % slides.length;
showSlide(nextIndex);
}
function showPreviousSlide() {
const slides = document.querySelectorAll('.carousel-slide');
const prevIndex = (currentSlideIndex - 1 + slides.length) % slides.length;
showSlide(prevIndex);
}
// 处理文件上传
async function handleFileUpload() {
const fileInput = document.getElementById('excel-file');
const fileInfo = document.getElementById('file-info');
if (!fileInput.files || fileInput.files.length === 0) {
alert('Please select an Excel file first');
return;
}
const file = fileInput.files[0];
fileInfo.textContent = `Selected file: ${file.name}`;
try {
// 读取Excel文件
const data = await readExcelFile(file);
// 保存原始Excel数据供merge edges功能使用
originalExcelData = data;
// 尝试发送数据到后端处理
try {
const response = await sendDataToBackend(data);
// 检查返回的数据格式
if (response.graph_data && response.forms_with_nodes) {
// 新格式:包含graph_data和forms_with_nodes
const graphDataArray = response.graph_data;
const formsWithNodes = response.forms_with_nodes;
// 存储forms数据供筛选功能使用
window.currentFormsData = formsWithNodes;
updateGraph(graphDataArray);
updateGraphTitles(file.name, graphDataArray);
// 更新筛选模块
updateFormFilter(formsWithNodes);
} else if (Array.isArray(response)) {
// 兼容旧格式:直接返回数组
updateGraph(response);
updateGraphTitles(file.name, response);
window.currentFormsData = [];
updateFormFilter([]);
} else {
// 兼容旧格式:单个语义地图
updateGraph([response]);
updateGraphTitles(file.name, [response]);
window.currentFormsData = [];
updateFormFilter([]);
}
} catch (error) {
console.error('后端处理失败:', error);
// 后端处理失败,显示错误信息
fileInfo.textContent = `后端处理失败: ${error.message}`;
return;
}
} catch (error) {
console.error('文件处理失败:', error);
fileInfo.textContent = `文件处理失败: ${error.message}`;
}
}
// 处理示例文件上传
async function handleExampleUpload() {
const fileInfo = document.getElementById('file-info');
try {
// 显示加载状态
fileInfo.textContent = 'Loading example file...';
// 获取示例文件
const response = await fetch('data/EAT verbs.xlsx');
if (!response.ok) {
throw new Error(`Failed to load example file: ${response.status}`);
}
// 将响应转换为Blob
const blob = await response.blob();
// 创建File对象
const file = new File([blob], 'EAT verbs.xlsx', {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
// 更新文件信息显示
fileInfo.textContent = `Loaded example file: ${file.name}`;
// 读取Excel文件
const data = await readExcelFile(file);
// 保存原始Excel数据供merge edges功能使用
originalExcelData = data;
// 尝试发送数据到后端处理
try {
const response = await sendDataToBackend(data);
// 检查返回的数据格式
if (response.graph_data && response.forms_with_nodes) {
// 新格式:包含graph_data和forms_with_nodes
const graphDataArray = response.graph_data;
const formsWithNodes = response.forms_with_nodes;
// 存储forms数据供筛选功能使用
window.currentFormsData = formsWithNodes;
updateGraph(graphDataArray);
updateGraphTitles(file.name, graphDataArray);
// 更新筛选模块
updateFormFilter(formsWithNodes);
} else if (Array.isArray(response)) {
// 兼容旧格式:直接返回数组
updateGraph(response);
updateGraphTitles(file.name, response);
window.currentFormsData = [];
updateFormFilter([]);
} else {
// 兼容旧格式:单个语义地图
updateGraph([response]);
updateGraphTitles(file.name, [response]);
window.currentFormsData = [];
updateFormFilter([]);
}
} catch (error) {
console.error('后端处理失败:', error);
// 后端处理失败,显示错误信息
fileInfo.textContent = `后端处理失败: ${error.message}`;
return;
}
} catch (error) {
console.error('示例文件加载失败:', error);
fileInfo.textContent = `示例文件加载失败: ${error.message}`;
}
}
// 处理示例文件2上传
async function handleExampleUpload2() {
const fileInfo = document.getElementById('file-info');
try {
// 显示加载状态
fileInfo.textContent = 'Loading example file 2...';
// 获取示例文件
const response = await fetch('data/supplementary adverbs.xlsx');
if (!response.ok) {
throw new Error(`Failed to load example file: ${response.status}`);
}
// 将响应转换为Blob
const blob = await response.blob();
// 创建File对象
const file = new File([blob], 'supplementary adverbs.xlsx', {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
// 更新文件信息显示
fileInfo.textContent = `Loaded example file: ${file.name}`;
// 读取Excel文件
const data = await readExcelFile(file);
// 保存原始Excel数据供merge edges功能使用
originalExcelData = data;
// 尝试发送数据到后端处理
try {
const response = await sendDataToBackend(data);
// 检查返回的数据格式
if (response.graph_data && response.forms_with_nodes) {
// 新格式:包含graph_data和forms_with_nodes
const graphDataArray = response.graph_data;
const formsWithNodes = response.forms_with_nodes;
// 存储forms数据供筛选功能使用
window.currentFormsData = formsWithNodes;
updateGraph(graphDataArray);
updateGraphTitles(file.name, graphDataArray);
// 更新筛选模块
updateFormFilter(formsWithNodes);
} else if (Array.isArray(response)) {
// 兼容旧格式:直接返回数组
updateGraph(response);
updateGraphTitles(file.name, response);
window.currentFormsData = [];
updateFormFilter([]);
} else {
// 兼容旧格式:单个语义地图
updateGraph([response]);
updateGraphTitles(file.name, [response]);
window.currentFormsData = [];
updateFormFilter([]);
}
} catch (error) {
console.error('后端处理失败:', error);
// 后端处理失败,显示错误信息
fileInfo.textContent = `后端处理失败: ${error.message}`;
return;
}
} catch (error) {
console.error('示例文件加载失败:', error);
fileInfo.textContent = `示例文件加载失败: ${error.message}`;
}
}
// 处理示例文件3上传
async function handleExampleUpload3() {
const fileInfo = document.getElementById('file-info');
try {
// 显示加载状态
fileInfo.textContent = 'Loading example file 3...';
// 获取示例文件
const response = await fetch('data/ditransitive constructions.xlsx');
if (!response.ok) {
throw new Error(`Failed to load example file: ${response.status}`);
}
// 将响应转换为Blob
const blob = await response.blob();
// 创建File对象
const file = new File([blob], 'ditransitive constructions.xlsx', {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
// 更新文件信息显示
fileInfo.textContent = `Loaded example file: ${file.name}`;
// 读取Excel文件
const data = await readExcelFile(file);
// 保存原始Excel数据供merge edges功能使用
originalExcelData = data;
// 尝试发送数据到后端处理
try {
const response = await sendDataToBackend(data);
// 检查返回的数据格式
if (response.graph_data && response.forms_with_nodes) {
// 新格式:包含graph_data和forms_with_nodes
const graphDataArray = response.graph_data;
const formsWithNodes = response.forms_with_nodes;
// 存储forms数据供筛选功能使用
window.currentFormsData = formsWithNodes;
updateGraph(graphDataArray);
updateGraphTitles(file.name, graphDataArray);
// 更新筛选模块
updateFormFilter(formsWithNodes);
} else if (Array.isArray(response)) {
// 兼容旧格式:直接返回数组
updateGraph(response);
updateGraphTitles(file.name, response);
window.currentFormsData = [];
updateFormFilter([]);
} else {
// 兼容旧格式:单个语义地图
updateGraph([response]);
updateGraphTitles(file.name, [response]);
window.currentFormsData = [];
updateFormFilter([]);
}
} catch (error) {
console.error('后端处理失败:', error);
// 后端处理失败,显示错误信息
fileInfo.textContent = `后端处理失败: ${error.message}`;
return;
}
} catch (error) {
console.error('示例文件加载失败:', error);
fileInfo.textContent = `示例文件加载失败: ${error.message}`;
}
}
// 处理下载指南文件
async function handleDownloadGuide() {
try {
// 获取guidance and examples.zip文件
const response = await fetch('data/guidance and examples.zip');
if (!response.ok) {
throw new Error(`Failed to load guide file: ${response.status}`);
}
// 将响应转换为Blob
const blob = await response.blob();
// 创建下载链接
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'guidance and examples.zip';
// 添加到DOM并触发下载
document.body.appendChild(a);
a.click();
// 清理
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
console.log('Guide file downloaded successfully');
} catch (error) {
console.error('下载指南文件失败:', error);
alert('下载指南文件失败,请稍后重试。');
}
}
// 动态创建轮播图幻灯片和指示器
function createCarouselSlides(count) {
const slidesContainer = document.querySelector('.carousel-slides');
const indicatorsContainer = document.querySelector('.carousel-indicators');
// 清空现有内容
slidesContainer.innerHTML = '';
indicatorsContainer.innerHTML = '';
// 创建幻灯片
for (let i = 0; i < count; i++) {
// 创建幻灯片
const slide = document.createElement('div');
slide.className = `carousel-slide ${i === 0 ? 'active' : ''}`;
const title = document.createElement('h3');
title.className = 'graph-title';
title.textContent = `Semantic Map`;
const container = document.createElement('div');
container.id = `graph-container-${i + 1}`;
container.className = 'graph-container';
slide.appendChild(title);
slide.appendChild(container);
slidesContainer.appendChild(slide);
// 创建指示器
const indicator = document.createElement('span');
indicator.className = `indicator ${i === 0 ? 'active' : ''}`;
indicator.setAttribute('data-index', i);
indicator.addEventListener('click', () => showSlide(i));
indicatorsContainer.appendChild(indicator);
}
}
// 更新评价指标显示
function updateEvaluationMetrics(slideIndex, evaluationMetric) {
console.log('Updating evaluation metrics for slide:', slideIndex, 'with data:', evaluationMetric);
// 查找固定的评价指标面板
const metricsPanel = document.querySelector('.evaluation-metrics-panel');
if (!metricsPanel) {
console.warn('Evaluation metrics panel not found');
return;
}
// 如果没有评价指标数据,显示默认值
if (!evaluationMetric) {
console.warn('No evaluation metric data provided for slide:', slideIndex + 1);
const metricValues = metricsPanel.querySelectorAll('.metric-value');
metricValues.forEach(value => {
value.textContent = 'N/A';
});
// 清空未连接表单显示
updateUnconnectedForms([]);
return;
}
// 更新各个指标值
const metricMapping = {
'acc': evaluationMetric.acc,
'prec': evaluationMetric.prec,
'recall': evaluationMetric.recall,
'F1': evaluationMetric.F1,
'productivity': evaluationMetric.productivity,
'coverage': evaluationMetric.coverage,
'weight_sum': evaluationMetric.weight_sum,
'deg_mean': evaluationMetric.deg_mean,
'deg_std': evaluationMetric.deg_std
};
Object.keys(metricMapping).forEach(key => {
const valueElement = metricsPanel.querySelector(`[data-metric="${key}"]`);
if (valueElement) {
const value = metricMapping[key];
if (value !== undefined && value !== null) {
// 格式化数值,保留三位小数
valueElement.textContent = typeof value === 'number' ? value.toFixed(3) : value;
} else {
valueElement.textContent = 'N/A';
}
}
});
console.log('Evaluation metrics updated successfully for slide:', slideIndex + 1);
// 更新 Unconnected Forms 显示
updateUnconnectedForms(evaluationMetric.unconnected_forms || []);
}
// 更新 Unconnected Forms 显示
function updateUnconnectedForms(unconnectedForms) {
console.log('Updating unconnected forms with data:', unconnectedForms);
const container = document.getElementById('unconnected-forms-container');
if (!container) {
console.warn('Unconnected forms container not found');
return;
}
// 清空容器内容
container.innerHTML = '';
// 如果没有数据,显示无数据消息
if (!unconnectedForms || unconnectedForms.length === 0) {
container.innerHTML = '<div class="no-data-message">No unconnected forms data available</div>';
return;
}
// 创建表格
const table = document.createElement('table');
table.className = 'forms-table';
// 创建表头
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
const languageHeader = document.createElement('th');
languageHeader.textContent = 'Language';
headerRow.appendChild(languageHeader);
const formHeader = document.createElement('th');
formHeader.textContent = 'Form';
headerRow.appendChild(formHeader);
thead.appendChild(headerRow);
table.appendChild(thead);
// 创建表体
const tbody = document.createElement('tbody');
unconnectedForms.forEach((formData, index) => {
const row = document.createElement('tr');
// 语言列
const languageCell = document.createElement('td');
const languageTag = document.createElement('span');
languageTag.className = 'language-tag';
languageTag.textContent = formData.language || 'Unknown';
languageCell.appendChild(languageTag);
row.appendChild(languageCell);
// Form列
const formCell = document.createElement('td');
formCell.textContent = formData.form || 'N/A';
row.appendChild(formCell);
tbody.appendChild(row);
});
table.appendChild(tbody);
container.appendChild(table);
console.log(`Unconnected forms updated successfully with ${unconnectedForms.length} items`);
}
// Merge Edges 功能
async function mergeEdges() {
console.log('开始执行 Merge Edges 功能');
// 检查是否有原始Excel数据
if (!originalExcelData || originalExcelData.length === 0) {
alert('请先上传Excel文件');
return;
}
// 获取当前显示的语义地图数据
const currentIndex = currentSlideIndex;
const currentNodes = nodeDatasets[currentIndex];
const currentEdges = edgeDatasets[currentIndex];
if (!currentNodes || !currentEdges) {
alert('当前没有可用的语义地图数据');
return;
}
// 获取当前显示的地图标题作为map_name
const currentSlide = document.querySelector('.carousel-slide.active');
const currentMapName = currentSlide ? currentSlide.querySelector('.graph-title').textContent : `Semantic Map`;
// 构建当前语义地图的数据结构
const currentGraph = {
map_name: currentMapName,
nodes: currentNodes.get().map(node => ({
id: node.id,
title: node.title || node.label,
label: node.label
})),
edges: currentEdges.get().map(edge => ({
id: edge.id,
from: edge.from,
to: edge.to,
label: edge.label || '',
value: parseFloat(edge.title) || parseFloat(edge.label) || 1.0
}))
};
console.log('当前语义地图数据:', currentGraph);
console.log('原始Excel数据:', originalExcelData);
try {
// 备份merge前的数据
const currentIndex = currentSlideIndex;
backupEvaluationMetricsArray[currentIndex] = evaluationMetricsData[currentIndex] ? JSON.parse(JSON.stringify(evaluationMetricsData[currentIndex])) : null;
// 备份当前的未连接表单数据
const unconnectedFormsElement = document.getElementById('unconnected-forms');
if (unconnectedFormsElement) {
backupUnconnectedFormsArray[currentIndex] = unconnectedFormsElement.innerHTML;
}
// 显示加载提示
const originalText = document.getElementById('merge-edge-btn').textContent;
document.getElementById('merge-edge-btn').textContent = 'Merging...';
document.getElementById('merge-edge-btn').disabled = true;
// 调用后端merge edges接口
const response = await fetch('/api/merge-edges', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
data: originalExcelData.data,
label: originalExcelData.label,
graph: currentGraph
})
});
if (!response.ok) {
// 尝试解析后端返回的错误信息
try {
const errorData = await response.json();
if (errorData.error) {
console.error(`Merge edges 错误 (${response.status}): ${errorData.error}`);
throw new Error(errorData.error);
}
} catch (parseError) {
console.error(`Merge edges 错误: HTTP ${response.status}`);
throw new Error(`HTTP error! status: ${response.status}`);
}
}
const result = await response.json();
console.log('Merge edges 返回结果:', result);
// 处理新增的边数据 - graph_data现在是一个dict包含edges和evaluation_metric
if (result.graph_data && result.graph_data.edges && Array.isArray(result.graph_data.edges)) {
const newEdgesData = result.graph_data.edges;
// 将新边添加到当前边数据集中,并设置高亮样式
const newEdges = newEdgesData.map(edge => {
const value = parseFloat(edge.value) || 1;
return {