feat: Phase 2 交互与纠错工作台完成

- 新增实体编辑 API (名称、类型、定义、别名)
- 新增实体删除和合并功能
- 新增关系管理 (创建、删除)
- 新增转录文本编辑功能
- 新增划词创建实体功能
- 前端新增实体编辑器模态框
- 前端新增右键菜单和工具栏
- 文本与图谱双向联动优化
This commit is contained in:
OpenClaw Bot
2026-02-18 06:03:51 +08:00
parent 2a3081c151
commit 643fe46780
5 changed files with 1142 additions and 79 deletions

View File

@@ -1,4 +1,4 @@
// InsightFlow Frontend - Production Version
// InsightFlow Frontend - Phase 2 (Interactive Workbench)
const API_BASE = '/api/v1';
let currentProject = null;
@@ -6,6 +6,9 @@ let currentData = null;
let selectedEntity = null;
let projectRelations = [];
let projectEntities = [];
let currentTranscript = null;
let editMode = false;
let contextMenuTarget = null;
// Init
document.addEventListener('DOMContentLoaded', () => {
@@ -37,6 +40,8 @@ async function initWorkbench() {
if (nameEl) nameEl.textContent = currentProject.name;
initUpload();
initContextMenu();
initTextSelection();
await loadProjectData();
} catch (err) {
@@ -65,12 +70,88 @@ async function uploadAudio(file) {
return await res.json();
}
// Phase 2: Entity Edit API
async function updateEntity(entityId, data) {
const res = await fetch(`${API_BASE}/entities/${entityId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (!res.ok) throw new Error('Failed to update entity');
return await res.json();
}
async function deleteEntityApi(entityId) {
const res = await fetch(`${API_BASE}/entities/${entityId}`, {
method: 'DELETE'
});
if (!res.ok) throw new Error('Failed to delete entity');
return await res.json();
}
async function mergeEntitiesApi(sourceId, targetId) {
const res = await fetch(`${API_BASE}/entities/${sourceId}/merge`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ source_entity_id: sourceId, target_entity_id: targetId })
});
if (!res.ok) throw new Error('Failed to merge entities');
return await res.json();
}
async function createEntityApi(data) {
const res = await fetch(`${API_BASE}/projects/${currentProject.id}/entities`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (!res.ok) throw new Error('Failed to create entity');
return await res.json();
}
// Phase 2: Relation API
async function createRelationApi(data) {
const res = await fetch(`${API_BASE}/projects/${currentProject.id}/relations`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (!res.ok) throw new Error('Failed to create relation');
return await res.json();
}
async function deleteRelationApi(relationId) {
const res = await fetch(`${API_BASE}/relations/${relationId}`, {
method: 'DELETE'
});
if (!res.ok) throw new Error('Failed to delete relation');
return await res.json();
}
// Phase 2: Transcript API
async function getTranscript(transcriptId) {
const res = await fetch(`${API_BASE}/transcripts/${transcriptId}`);
if (!res.ok) throw new Error('Failed to get transcript');
return await res.json();
}
async function updateTranscript(transcriptId, fullText) {
const res = await fetch(`${API_BASE}/transcripts/${transcriptId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ full_text: fullText })
});
if (!res.ok) throw new Error('Failed to update transcript');
return await res.json();
}
async function loadProjectData() {
try {
// 并行加载实体和关系
const [entitiesRes, relationsRes] = await Promise.all([
const [entitiesRes, relationsRes, transcriptsRes] = await Promise.all([
fetch(`${API_BASE}/projects/${currentProject.id}/entities`),
fetch(`${API_BASE}/projects/${currentProject.id}/relations`)
fetch(`${API_BASE}/projects/${currentProject.id}/relations`),
fetch(`${API_BASE}/projects/${currentProject.id}/transcripts`)
]);
if (entitiesRes.ok) {
@@ -80,14 +161,22 @@ async function loadProjectData() {
projectRelations = await relationsRes.json();
}
currentData = {
transcript_id: 'project_view',
project_id: currentProject.id,
segments: [],
entities: projectEntities,
full_text: '',
created_at: new Date().toISOString()
};
// 加载最新的转录
if (transcriptsRes.ok) {
const transcripts = await transcriptsRes.json();
if (transcripts.length > 0) {
currentTranscript = await getTranscript(transcripts[0].id);
currentData = {
transcript_id: currentTranscript.id,
project_id: currentProject.id,
segments: [{ speaker: '全文', text: currentTranscript.full_text }],
entities: projectEntities,
full_text: currentTranscript.full_text,
created_at: currentTranscript.created_at
};
renderTranscript();
}
}
renderGraph();
renderEntityList();
@@ -97,39 +186,80 @@ async function loadProjectData() {
}
}
// Phase 2: Transcript Edit Mode
window.toggleEditMode = function() {
editMode = !editMode;
const editBtn = document.getElementById('editBtn');
const saveBtn = document.getElementById('saveBtn');
const content = document.getElementById('transcriptContent');
if (editMode) {
editBtn.style.display = 'none';
saveBtn.style.display = 'inline-block';
content.contentEditable = 'true';
content.style.background = '#0f0f0f';
content.style.border = '1px solid #00d4ff';
content.focus();
} else {
editBtn.style.display = 'inline-block';
saveBtn.style.display = 'none';
content.contentEditable = 'false';
content.style.background = '';
content.style.border = '';
}
};
window.saveTranscript = async function() {
if (!currentTranscript) return;
const content = document.getElementById('transcriptContent');
const fullText = content.innerText;
try {
await updateTranscript(currentTranscript.id, fullText);
currentTranscript.full_text = fullText;
toggleEditMode();
alert('转录文本已保存');
} catch (err) {
console.error('Save failed:', err);
alert('保存失败: ' + err.message);
}
};
// Render transcript with entity highlighting
function renderTranscript() {
const container = document.getElementById('transcriptContent');
if (!container || !currentData || !currentData.segments) return;
if (!container || !currentData) return;
container.innerHTML = '';
currentData.segments.forEach((seg, idx) => {
const div = document.createElement('div');
div.className = 'segment';
div.dataset.index = idx;
// 高亮实体
let text = seg.text;
const entities = findEntitiesInText(seg.text);
// 按位置倒序替换,避免位置偏移
entities.sort((a, b) => b.start - a.start);
entities.forEach(ent => {
const before = text.slice(0, ent.start);
const name = text.slice(ent.start, ent.end);
const after = text.slice(ent.end);
text = before + `<span class="entity" data-id="${ent.id}" onclick="window.selectEntity('${ent.id}')">${name}</span>` + after;
});
div.innerHTML = `
<div class="speaker">${seg.speaker}</div>
<div class="segment-text">${text}</div>
`;
container.appendChild(div);
if (editMode) {
container.innerText = currentData.full_text || '';
return;
}
// 高亮实体
let text = currentData.full_text || '';
const entities = findEntitiesInText(text);
// 按位置倒序替换,避免位置偏移
entities.sort((a, b) => b.start - a.start);
entities.forEach(ent => {
const before = text.slice(0, ent.start);
const name = text.slice(ent.start, ent.end);
const after = text.slice(ent.end);
text = before + `<span class="entity" data-id="${ent.id}" onclick="window.selectEntity('${ent.id}')">${name}</span>` + after;
});
const div = document.createElement('div');
div.className = 'segment';
div.innerHTML = `
<div class="speaker">转录文本</div>
<div class="segment-text">${text}</div>
`;
container.appendChild(div);
}
// 在文本中查找实体位置
@@ -201,6 +331,7 @@ function renderGraph() {
// 使用数据库中的关系
const links = projectRelations.map(r => ({
id: r.id,
source: r.source_id,
target: r.target_id,
type: r.type
@@ -256,7 +387,11 @@ function renderGraph() {
.on('start', dragstarted)
.on('drag', dragged)
.on('end', dragended))
.on('click', (e, d) => window.selectEntity(d.id));
.on('click', (e, d) => window.selectEntity(d.id))
.on('contextmenu', (e, d) => {
e.preventDefault();
showContextMenu(e, d.id);
});
// 节点圆圈
node.append('circle')
@@ -332,9 +467,13 @@ function renderEntityList() {
div.className = 'entity-item';
div.dataset.id = ent.id;
div.onclick = () => window.selectEntity(ent.id);
div.oncontextmenu = (e) => {
e.preventDefault();
showContextMenu(e, ent.id);
};
div.innerHTML = `
<span class="entity-type-badge type-${ent.type.toLowerCase()}">${ent.type}</span>
<span class="entity-type-badge type-${ent.type}">${ent.type}</span>
<div>
<div style="font-weight:500;">${ent.name}</div>
<div style="font-size:0.8rem;color:#666;">${ent.definition || '暂无定义'}</div>
@@ -354,11 +493,9 @@ window.selectEntity = function(entityId) {
// 高亮文本中的实体
document.querySelectorAll('.entity').forEach(el => {
if (el.dataset.id === entityId) {
el.style.background = '#ff6b6b';
el.style.color = '#fff';
el.classList.add('selected');
} else {
el.style.background = '';
el.style.color = '';
el.classList.remove('selected');
}
});
@@ -371,17 +508,286 @@ window.selectEntity = function(entityId) {
// 高亮实体列表
document.querySelectorAll('.entity-item').forEach(el => {
if (el.dataset.id === entityId) {
el.style.background = '#2a2a2a';
el.style.borderLeft = '3px solid #ff6b6b';
el.classList.add('selected');
} else {
el.style.background = '';
el.style.borderLeft = '';
el.classList.remove('selected');
}
});
console.log('Selected:', entity.name, entity.definition);
};
// Phase 2: Context Menu
function initContextMenu() {
document.addEventListener('click', () => {
hideContextMenu();
});
}
function showContextMenu(e, entityId) {
contextMenuTarget = entityId;
const menu = document.getElementById('contextMenu');
menu.style.left = e.pageX + 'px';
menu.style.top = e.pageY + 'px';
menu.classList.add('show');
}
function hideContextMenu() {
const menu = document.getElementById('contextMenu');
menu.classList.remove('show');
contextMenuTarget = null;
}
// Phase 2: Entity Editor Modal
window.editEntity = function() {
hideContextMenu();
if (!contextMenuTarget && !selectedEntity) return;
const entityId = contextMenuTarget || selectedEntity;
const entity = projectEntities.find(e => e.id === entityId);
if (!entity) return;
document.getElementById('entityName').value = entity.name;
document.getElementById('entityType').value = entity.type;
document.getElementById('entityDefinition').value = entity.definition || '';
document.getElementById('entityAliases').value = (entity.aliases || []).join(', ');
// 显示关系编辑器
document.getElementById('relationEditor').style.display = 'block';
renderRelationList(entityId);
document.getElementById('entityModal').dataset.entityId = entityId;
document.getElementById('entityModal').classList.add('show');
};
function renderRelationList(entityId) {
const container = document.getElementById('relationList');
const entityRelations = projectRelations.filter(r =>
r.source_id === entityId || r.target_id === entityId
);
if (entityRelations.length === 0) {
container.innerHTML = '<p style="color:#666;font-size:0.8rem;">暂无关系</p>';
return;
}
container.innerHTML = entityRelations.map(r => {
const isSource = r.source_id === entityId;
const otherId = isSource ? r.target_id : r.source_id;
const other = projectEntities.find(e => e.id === otherId);
const otherName = other ? other.name : 'Unknown';
const arrow = isSource ? '→' : '←';
return `
<div class="relation-item">
<span>${arrow} ${otherName} (${r.type})</span>
<button onclick="deleteRelation('${r.id}')">删除</button>
</div>
`;
}).join('');
}
window.hideEntityModal = function() {
document.getElementById('entityModal').classList.remove('show');
};
window.saveEntity = async function() {
const entityId = document.getElementById('entityModal').dataset.entityId;
if (!entityId) return;
const data = {
name: document.getElementById('entityName').value,
type: document.getElementById('entityType').value,
definition: document.getElementById('entityDefinition').value,
aliases: document.getElementById('entityAliases').value.split(',').map(s => s.trim()).filter(s => s)
};
try {
await updateEntity(entityId, data);
await loadProjectData();
hideEntityModal();
} catch (err) {
console.error('Save failed:', err);
alert('保存失败: ' + err.message);
}
};
window.deleteEntity = async function() {
const entityId = document.getElementById('entityModal').dataset.entityId;
if (!entityId) return;
if (!confirm('确定要删除这个实体吗?相关的提及和关系也会被删除。')) return;
try {
await deleteEntityApi(entityId);
await loadProjectData();
hideEntityModal();
} catch (err) {
console.error('Delete failed:', err);
alert('删除失败: ' + err.message);
}
};
// Phase 2: Merge Modal
window.showMergeModal = function() {
hideContextMenu();
if (!contextMenuTarget && !selectedEntity) return;
const sourceId = contextMenuTarget || selectedEntity;
const source = projectEntities.find(e => e.id === sourceId);
if (!source) return;
document.getElementById('mergeSource').value = source.name;
document.getElementById('mergeModal').dataset.sourceId = sourceId;
// 填充目标实体选项(排除自己)
const select = document.getElementById('mergeTarget');
select.innerHTML = projectEntities
.filter(e => e.id !== sourceId)
.map(e => `<option value="${e.id}">${e.name} (${e.type})</option>`)
.join('');
document.getElementById('mergeModal').classList.add('show');
};
window.hideMergeModal = function() {
document.getElementById('mergeModal').classList.remove('show');
};
window.confirmMerge = async function() {
const sourceId = document.getElementById('mergeModal').dataset.sourceId;
const targetId = document.getElementById('mergeTarget').value;
if (!sourceId || !targetId) return;
try {
await mergeEntitiesApi(sourceId, targetId);
await loadProjectData();
hideMergeModal();
} catch (err) {
console.error('Merge failed:', err);
alert('合并失败: ' + err.message);
}
};
// Phase 2: Relation Modal
window.showAddRelation = function() {
const entityId = document.getElementById('entityModal').dataset.entityId;
if (!entityId) return;
const entity = projectEntities.find(e => e.id === entityId);
document.getElementById('relationModal').dataset.sourceId = entityId;
// 填充目标选项
const select = document.getElementById('relationTarget');
select.innerHTML = projectEntities
.filter(e => e.id !== entityId)
.map(e => `<option value="${e.id}">${e.name}</option>`)
.join('');
document.getElementById('relationModal').classList.add('show');
};
window.hideRelationModal = function() {
document.getElementById('relationModal').classList.remove('show');
};
window.saveRelation = async function() {
const sourceId = document.getElementById('relationModal').dataset.sourceId;
const targetId = document.getElementById('relationTarget').value;
const type = document.getElementById('relationType').value;
const evidence = document.getElementById('relationEvidence').value;
if (!sourceId || !targetId) return;
try {
await createRelationApi({
source_entity_id: sourceId,
target_entity_id: targetId,
relation_type: type,
evidence: evidence
});
await loadProjectData();
renderRelationList(sourceId);
hideRelationModal();
} catch (err) {
console.error('Create relation failed:', err);
alert('创建关系失败: ' + err.message);
}
};
window.deleteRelation = async function(relationId) {
if (!confirm('确定要删除这个关系吗?')) return;
try {
await deleteRelationApi(relationId);
await loadProjectData();
const entityId = document.getElementById('entityModal').dataset.entityId;
if (entityId) renderRelationList(entityId);
} catch (err) {
console.error('Delete relation failed:', err);
alert('删除关系失败: ' + err.message);
}
};
// Phase 2: Text Selection - Create Entity
function initTextSelection() {
document.addEventListener('selectionchange', () => {
const selection = window.getSelection();
const text = selection.toString().trim();
if (text.length > 0 && text.length < 50) {
showSelectionToolbar();
} else {
hideSelectionToolbar();
}
});
}
function showSelectionToolbar() {
document.getElementById('selectionToolbar').classList.add('show');
}
window.hideSelectionToolbar = function() {
document.getElementById('selectionToolbar').classList.remove('show');
window.getSelection().removeAllRanges();
};
window.createEntityFromSelection = async function() {
const selection = window.getSelection();
const text = selection.toString().trim();
if (!text) return;
// 获取选中文本在全文中的位置
const container = document.getElementById('transcriptContent');
const fullText = currentTranscript ? currentTranscript.full_text : '';
const startPos = fullText.indexOf(text);
try {
const result = await createEntityApi({
name: text,
type: 'OTHER',
definition: '',
transcript_id: currentTranscript ? currentTranscript.id : null,
start_pos: startPos >= 0 ? startPos : null,
end_pos: startPos >= 0 ? startPos + text.length : null
});
hideSelectionToolbar();
await loadProjectData();
if (!result.existed) {
alert(`已创建实体: ${text}`);
} else {
alert(`实体 "${text}" 已存在`);
}
} catch (err) {
console.error('Create entity failed:', err);
alert('创建实体失败: ' + err.message);
}
};
// Show/hide upload
window.showUpload = function() {
const el = document.getElementById('uploadOverlay');
@@ -420,14 +826,9 @@ function initUpload() {
// 更新当前数据
currentData = result;
// 重新加载项目数据(包含新实体和关系)
// 重新加载项目数据
await loadProjectData();
// 渲染转录文本
if (result.segments && result.segments.length > 0) {
renderTranscript();
}
if (overlay) overlay.classList.remove('show');
} catch (err) {