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

@@ -4,11 +4,13 @@
## 当前阶段
Phase 1: 骨架与单体分析 (MVP) - **已完成 ✅**
Phase 2: 交互与纠错工作台 - **已完成 ✅**
## 已完成
### 后端 (backend/)
### Phase 1: 骨架与单体分析 (MVP) ✅
#### 后端 (backend/)
- ✅ FastAPI 项目框架搭建
- ✅ SQLite 数据库设计 (schema.sql)
- ✅ 数据库管理模块 (db_manager.py)
@@ -26,7 +28,7 @@ Phase 1: 骨架与单体分析 (MVP) - **已完成 ✅**
- ✅ entity_mentions 表数据写入
- ✅ entity_relations 表数据写入
### 前端 (frontend/)
#### 前端 (frontend/)
- ✅ 项目管理页面 (index.html)
- ✅ 知识工作台页面 (workbench.html)
- ✅ D3.js 知识图谱可视化
@@ -35,20 +37,34 @@ Phase 1: 骨架与单体分析 (MVP) - **已完成 ✅**
- ✅ 转录文本中实体高亮显示
- ✅ 图谱与文本联动(点击实体双向高亮)
### 基础设施
- ✅ Dockerfile
- ✅ docker-compose.yml
- ✅ Git 仓库初始化
### Phase 2: 交互与纠错工作台 ✅
## Phase 2 计划 (交互与纠错工作台) - **即将开始**
#### 后端 API 新增
- ✅ 实体编辑 API (PUT /api/v1/entities/{id})
- ✅ 实体删除 API (DELETE /api/v1/entities/{id})
- ✅ 实体合并 API (POST /api/v1/entities/{id}/merge)
- ✅ 手动创建实体 API (POST /api/v1/projects/{id}/entities)
- ✅ 关系创建 API (POST /api/v1/projects/{id}/relations)
- ✅ 关系删除 API (DELETE /api/v1/relations/{id})
- ✅ 转录编辑 API (PUT /api/v1/transcripts/{id})
- 实体定义编辑功能
- 实体合并功能
- 关系编辑功能(添加/删除
- 人工修正数据保存
- 文本编辑器增强(支持编辑转录文本
#### 前端交互功能
- 实体编辑器模态框(名称、类型、定义、别名)
- ✅ 右键菜单(编辑实体、合并实体、标记为实体
- ✅ 实体合并功能
- ✅ 关系管理(添加、删除
- ✅ 转录文本编辑模式
- ✅ 划词创建实体
- ✅ 文本与图谱双向联动
## Phase 3 计划 (记忆与生长)
#### 数据库更新
- ✅ update_entity() - 更新实体信息
- ✅ delete_entity() - 删除实体及关联数据
- ✅ delete_relation() - 删除关系
- ✅ update_relation() - 更新关系
- ✅ update_transcript() - 更新转录文本
## Phase 3 计划 (记忆与生长) - **即将开始**
- 多文件图谱融合
- 实体对齐算法优化

View File

@@ -291,6 +291,104 @@ class DatabaseManager:
conn.close()
return [dict(r) for r in rows]
def update_entity(self, entity_id: str, **kwargs) -> Entity:
"""更新实体信息"""
conn = self.get_conn()
# 构建更新字段
allowed_fields = ['name', 'type', 'definition', 'canonical_name']
updates = []
values = []
for field in allowed_fields:
if field in kwargs:
updates.append(f"{field} = ?")
values.append(kwargs[field])
# 处理别名
if 'aliases' in kwargs:
updates.append("aliases = ?")
values.append(json.dumps(kwargs['aliases']))
if not updates:
conn.close()
return self.get_entity(entity_id)
updates.append("updated_at = ?")
values.append(datetime.now().isoformat())
values.append(entity_id)
query = f"UPDATE entities SET {', '.join(updates)} WHERE id = ?"
conn.execute(query, values)
conn.commit()
conn.close()
return self.get_entity(entity_id)
def delete_entity(self, entity_id: str):
"""删除实体及其关联数据"""
conn = self.get_conn()
# 删除提及记录
conn.execute("DELETE FROM entity_mentions WHERE entity_id = ?", (entity_id,))
# 删除关系
conn.execute("DELETE FROM entity_relations WHERE source_entity_id = ? OR target_entity_id = ?",
(entity_id, entity_id))
# 删除实体
conn.execute("DELETE FROM entities WHERE id = ?", (entity_id,))
conn.commit()
conn.close()
def delete_relation(self, relation_id: str):
"""删除关系"""
conn = self.get_conn()
conn.execute("DELETE FROM entity_relations WHERE id = ?", (relation_id,))
conn.commit()
conn.close()
def update_relation(self, relation_id: str, **kwargs) -> dict:
"""更新关系"""
conn = self.get_conn()
allowed_fields = ['relation_type', 'evidence']
updates = []
values = []
for field in allowed_fields:
if field in kwargs:
updates.append(f"{field} = ?")
values.append(kwargs[field])
if updates:
query = f"UPDATE entity_relations SET {', '.join(updates)} WHERE id = ?"
values.append(relation_id)
conn.execute(query, values)
conn.commit()
row = conn.execute("SELECT * FROM entity_relations WHERE id = ?", (relation_id,)).fetchone()
conn.close()
return dict(row) if row else None
def update_transcript(self, transcript_id: str, full_text: str) -> dict:
"""更新转录文本"""
conn = self.get_conn()
now = datetime.now().isoformat()
conn.execute(
"UPDATE transcripts SET full_text = ?, updated_at = ? WHERE id = ?",
(full_text, now, transcript_id)
)
conn.commit()
row = conn.execute("SELECT * FROM transcripts WHERE id = ?", (transcript_id,)).fetchone()
conn.close()
return dict(row) if row else None
# Singleton instance
_db_manager = None

View File

@@ -71,10 +71,251 @@ class ProjectCreate(BaseModel):
name: str
description: str = ""
class EntityUpdate(BaseModel):
name: Optional[str] = None
type: Optional[str] = None
definition: Optional[str] = None
aliases: Optional[List[str]] = None
class RelationCreate(BaseModel):
source_entity_id: str
target_entity_id: str
relation_type: str
evidence: Optional[str] = ""
class TranscriptUpdate(BaseModel):
full_text: str
class EntityMergeRequest(BaseModel):
source_entity_id: str
target_entity_id: str
# API Keys
KIMI_API_KEY = os.getenv("KIMI_API_KEY", "")
KIMI_BASE_URL = "https://api.kimi.com/coding"
# Phase 2: Entity Edit API
@app.put("/api/v1/entities/{entity_id}")
async def update_entity(entity_id: str, update: EntityUpdate):
"""更新实体信息(名称、类型、定义、别名)"""
if not DB_AVAILABLE:
raise HTTPException(status_code=500, detail="Database not available")
db = get_db_manager()
entity = db.get_entity(entity_id)
if not entity:
raise HTTPException(status_code=404, detail="Entity not found")
# 更新字段
update_data = {k: v for k, v in update.dict().items() if v is not None}
updated = db.update_entity(entity_id, **update_data)
return {
"id": updated.id,
"name": updated.name,
"type": updated.type,
"definition": updated.definition,
"aliases": updated.aliases
}
@app.delete("/api/v1/entities/{entity_id}")
async def delete_entity(entity_id: str):
"""删除实体"""
if not DB_AVAILABLE:
raise HTTPException(status_code=500, detail="Database not available")
db = get_db_manager()
entity = db.get_entity(entity_id)
if not entity:
raise HTTPException(status_code=404, detail="Entity not found")
db.delete_entity(entity_id)
return {"success": True, "message": f"Entity {entity_id} deleted"}
@app.post("/api/v1/entities/{entity_id}/merge")
async def merge_entities_endpoint(entity_id: str, merge_req: EntityMergeRequest):
"""合并两个实体"""
if not DB_AVAILABLE:
raise HTTPException(status_code=500, detail="Database not available")
db = get_db_manager()
# 验证两个实体都存在
source = db.get_entity(merge_req.source_entity_id)
target = db.get_entity(merge_req.target_entity_id)
if not source or not target:
raise HTTPException(status_code=404, detail="Entity not found")
result = db.merge_entities(merge_req.target_entity_id, merge_req.source_entity_id)
return {
"success": True,
"merged_entity": {
"id": result.id,
"name": result.name,
"type": result.type,
"definition": result.definition,
"aliases": result.aliases
}
}
# Phase 2: Relation Edit API
@app.post("/api/v1/projects/{project_id}/relations")
async def create_relation_endpoint(project_id: str, relation: RelationCreate):
"""创建新的实体关系"""
if not DB_AVAILABLE:
raise HTTPException(status_code=500, detail="Database not available")
db = get_db_manager()
# 验证实体存在
source = db.get_entity(relation.source_entity_id)
target = db.get_entity(relation.target_entity_id)
if not source or not target:
raise HTTPException(status_code=404, detail="Source or target entity not found")
relation_id = db.create_relation(
project_id=project_id,
source_entity_id=relation.source_entity_id,
target_entity_id=relation.target_entity_id,
relation_type=relation.relation_type,
evidence=relation.evidence
)
return {
"id": relation_id,
"source_id": relation.source_entity_id,
"target_id": relation.target_entity_id,
"type": relation.relation_type,
"success": True
}
@app.delete("/api/v1/relations/{relation_id}")
async def delete_relation(relation_id: str):
"""删除关系"""
if not DB_AVAILABLE:
raise HTTPException(status_code=500, detail="Database not available")
db = get_db_manager()
db.delete_relation(relation_id)
return {"success": True, "message": f"Relation {relation_id} deleted"}
@app.put("/api/v1/relations/{relation_id}")
async def update_relation(relation_id: str, relation: RelationCreate):
"""更新关系"""
if not DB_AVAILABLE:
raise HTTPException(status_code=500, detail="Database not available")
db = get_db_manager()
updated = db.update_relation(
relation_id=relation_id,
relation_type=relation.relation_type,
evidence=relation.evidence
)
return {
"id": relation_id,
"type": updated["relation_type"],
"evidence": updated["evidence"],
"success": True
}
# Phase 2: Transcript Edit API
@app.get("/api/v1/transcripts/{transcript_id}")
async def get_transcript(transcript_id: str):
"""获取转录详情"""
if not DB_AVAILABLE:
raise HTTPException(status_code=500, detail="Database not available")
db = get_db_manager()
transcript = db.get_transcript(transcript_id)
if not transcript:
raise HTTPException(status_code=404, detail="Transcript not found")
return transcript
@app.put("/api/v1/transcripts/{transcript_id}")
async def update_transcript(transcript_id: str, update: TranscriptUpdate):
"""更新转录文本(人工修正)"""
if not DB_AVAILABLE:
raise HTTPException(status_code=500, detail="Database not available")
db = get_db_manager()
transcript = db.get_transcript(transcript_id)
if not transcript:
raise HTTPException(status_code=404, detail="Transcript not found")
updated = db.update_transcript(transcript_id, update.full_text)
return {
"id": transcript_id,
"full_text": updated["full_text"],
"updated_at": updated["updated_at"],
"success": True
}
# Phase 2: Manual Entity Creation
class ManualEntityCreate(BaseModel):
name: str
type: str = "OTHER"
definition: str = ""
transcript_id: Optional[str] = None
start_pos: Optional[int] = None
end_pos: Optional[int] = None
@app.post("/api/v1/projects/{project_id}/entities")
async def create_manual_entity(project_id: str, entity: ManualEntityCreate):
"""手动创建实体(划词新建)"""
if not DB_AVAILABLE:
raise HTTPException(status_code=500, detail="Database not available")
db = get_db_manager()
# 检查是否已存在
existing = db.get_entity_by_name(project_id, entity.name)
if existing:
return {
"id": existing.id,
"name": existing.name,
"type": existing.type,
"existed": True
}
entity_id = str(uuid.uuid4())[:8]
new_entity = db.create_entity(Entity(
id=entity_id,
project_id=project_id,
name=entity.name,
type=entity.type,
definition=entity.definition
))
# 如果有提及位置信息,保存提及
if entity.transcript_id and entity.start_pos is not None and entity.end_pos is not None:
transcript = db.get_transcript(entity.transcript_id)
if transcript:
text = transcript["full_text"]
mention = EntityMention(
id=str(uuid.uuid4())[:8],
entity_id=entity_id,
transcript_id=entity.transcript_id,
start_pos=entity.start_pos,
end_pos=entity.end_pos,
text_snippet=text[max(0, entity.start_pos-20):min(len(text), entity.end_pos+20)],
confidence=1.0
)
db.add_mention(mention)
return {
"id": new_entity.id,
"name": new_entity.name,
"type": new_entity.type,
"definition": new_entity.definition,
"success": True
}
def transcribe_audio(audio_data: bytes, filename: str) -> dict:
"""转录音频OSS上传 + 听悟转录"""
@@ -379,14 +620,31 @@ async def get_entity_mentions(entity_id: str):
} for m in mentions]
@app.post("/api/v1/entities/{entity_id}/merge")
async def merge_entities(entity_id: str, target_entity_id: str):
async def merge_entities_endpoint(entity_id: str, merge_req: EntityMergeRequest):
"""合并两个实体"""
if not DB_AVAILABLE:
raise HTTPException(status_code=500, detail="Database not available")
db = get_db_manager()
result = db.merge_entities(target_entity_id, entity_id)
return {"success": True, "merged_entity": {"id": result.id, "name": result.name}}
# 验证两个实体都存在
source = db.get_entity(merge_req.source_entity_id)
target = db.get_entity(merge_req.target_entity_id)
if not source or not target:
raise HTTPException(status_code=404, detail="Entity not found")
result = db.merge_entities(merge_req.target_entity_id, merge_req.source_entity_id)
return {
"success": True,
"merged_entity": {
"id": result.id,
"name": result.name,
"type": result.type,
"definition": result.definition,
"aliases": result.aliases
}
}
# Health check
@app.get("/health")

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;
if (editMode) {
container.innerText = currentData.full_text || '';
return;
}
// 高亮实体
let text = seg.text;
const entities = findEntitiesInText(seg.text);
// 高亮实体
let text = currentData.full_text || '';
const entities = findEntitiesInText(text);
// 按位置倒序替换,避免位置偏移
entities.sort((a, b) => b.start - a.start);
// 按位置倒序替换,避免位置偏移
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);
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) {

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>InsightFlow - 知识工作台</title>
<title>InsightFlow - 知识工作台 (Phase 2)</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
@@ -66,6 +66,23 @@
justify-content: space-between;
align-items: center;
}
.panel-actions {
display: flex;
gap: 8px;
}
.btn-icon {
background: transparent;
border: 1px solid #333;
color: #888;
padding: 4px 10px;
border-radius: 4px;
cursor: pointer;
font-size: 0.8rem;
}
.btn-icon:hover {
border-color: #00d4ff;
color: #00d4ff;
}
.transcript-content {
flex: 1;
padding: 20px;
@@ -92,6 +109,13 @@
}
.segment-text {
color: #e0e0e0;
outline: none;
}
.segment-text[contenteditable="true"] {
background: #1a1a1a;
padding: 8px;
border-radius: 4px;
border: 1px solid #00d4ff;
}
.entity {
background: rgba(123, 44, 191, 0.3);
@@ -99,10 +123,16 @@
padding: 0 4px;
border-radius: 3px;
cursor: pointer;
position: relative;
}
.entity:hover {
background: rgba(123, 44, 191, 0.5);
}
.entity.selected {
background: #ff6b6b;
border-color: #ff6b6b;
color: #fff;
}
.graph-panel {
width: 50%;
display: flex;
@@ -127,10 +157,15 @@
border-radius: 6px;
margin-bottom: 8px;
cursor: pointer;
transition: all 0.2s;
}
.entity-item:hover {
background: #222;
}
.entity-item.selected {
background: #2a2a2a;
border-left: 3px solid #ff6b6b;
}
.entity-type-badge {
padding: 2px 8px;
border-radius: 4px;
@@ -139,11 +174,11 @@
margin-right: 12px;
text-transform: uppercase;
}
.type-project { background: #7b2cbf; }
.type-tech { background: #00d4ff; color: #000; }
.type-person { background: #ff6b6b; }
.type-org { background: #4ecdc4; color: #000; }
.type-other { background: #666; }
.type-PROJECT { background: #7b2cbf; }
.type-TECH { background: #00d4ff; color: #000; }
.type-PERSON { background: #ff6b6b; }
.type-ORG { background: #4ecdc4; color: #000; }
.type-OTHER { background: #666; }
.upload-overlay {
position: fixed;
top: 0;
@@ -186,10 +221,158 @@
font-size: 0.85rem;
margin-top: 0;
}
.btn-danger {
background: #ff6b6b;
}
.btn-secondary {
background: #333;
}
.empty-state {
text-align: center;
padding: 60px 20px;
}
/* Phase 2: Entity Editor Modal */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.8);
display: none;
align-items: center;
justify-content: center;
z-index: 3000;
}
.modal-overlay.show {
display: flex;
}
.modal {
background: #1a1a1a;
border-radius: 12px;
padding: 24px;
width: 90%;
max-width: 500px;
max-height: 80vh;
overflow-y: auto;
}
.modal-header {
font-size: 1.2rem;
margin-bottom: 20px;
color: #fff;
}
.form-group {
margin-bottom: 16px;
}
.form-group label {
display: block;
margin-bottom: 6px;
color: #888;
font-size: 0.85rem;
}
.form-group input,
.form-group select,
.form-group textarea {
width: 100%;
padding: 10px 12px;
background: #0a0a0a;
border: 1px solid #333;
border-radius: 6px;
color: #e0e0e0;
font-size: 0.95rem;
}
.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
outline: none;
border-color: #00d4ff;
}
.form-group textarea {
min-height: 80px;
resize: vertical;
}
.modal-actions {
display: flex;
gap: 10px;
justify-content: flex-end;
margin-top: 20px;
}
/* Phase 2: Context Menu */
.context-menu {
position: absolute;
background: #1a1a1a;
border: 1px solid #333;
border-radius: 6px;
padding: 6px 0;
z-index: 4000;
display: none;
min-width: 160px;
}
.context-menu.show {
display: block;
}
.context-menu-item {
padding: 8px 16px;
cursor: pointer;
font-size: 0.9rem;
color: #e0e0e0;
}
.context-menu-item:hover {
background: #2a2a2a;
}
.context-menu-divider {
height: 1px;
background: #333;
margin: 6px 0;
}
/* Phase 2: Relation Editor */
.relation-editor {
margin-top: 16px;
padding-top: 16px;
border-top: 1px solid #333;
}
.relation-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px;
background: #0a0a0a;
border-radius: 4px;
margin-bottom: 8px;
font-size: 0.85rem;
}
.relation-item button {
background: transparent;
border: none;
color: #ff6b6b;
cursor: pointer;
font-size: 0.8rem;
}
/* Phase 2: Selection toolbar */
.selection-toolbar {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: #1a1a1a;
border: 1px solid #333;
border-radius: 8px;
padding: 10px 20px;
display: none;
gap: 10px;
z-index: 3500;
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
}
.selection-toolbar.show {
display: flex;
}
/* Graph node styles */
.node-circle {
cursor: pointer;
}
.node-label {
pointer-events: none;
}
</style>
</head>
<body>
@@ -205,7 +388,10 @@
<div class="editor-panel">
<div class="panel-header">
<span>📄 转录文本</span>
<span style="font-size:0.8rem;color:#666;">点击实体高亮</span>
<div class="panel-actions">
<button class="btn-icon" onclick="toggleEditMode()" id="editBtn">✏️ 编辑</button>
<button class="btn-icon" onclick="saveTranscript()" id="saveBtn" style="display:none;">💾 保存</button>
</div>
</div>
<div class="transcript-content" id="transcriptContent">
<div class="empty-state">
@@ -218,7 +404,7 @@
<div class="graph-panel">
<div class="panel-header">
<span>🔗 知识图谱</span>
<span style="font-size:0.8rem;color:#666;">拖拽节点查看关系</span>
<span style="font-size:0.8rem;color:#666;">右键节点编辑 | 拖拽建立关系</span>
</div>
<svg id="graph-svg"></svg>
<div class="entity-list" id="entityList">
@@ -228,6 +414,7 @@
</div>
</div>
<!-- Upload Modal -->
<div class="upload-overlay" id="uploadOverlay">
<div class="upload-box">
<h2 style="margin-bottom:10px;">上传音频分析</h2>
@@ -235,10 +422,113 @@
<input type="file" id="fileInput" accept="audio/*" hidden>
<button class="btn" onclick="document.getElementById('fileInput').click()">选择文件</button>
<br><br>
<button class="btn" style="background:#333;" onclick="hideUpload()">取消</button>
<button class="btn btn-secondary" onclick="hideUpload()">取消</button>
</div>
</div>
<!-- Entity Editor Modal -->
<div class="modal-overlay" id="entityModal">
<div class="modal">
<h3 class="modal-header">编辑实体</h3>
<div class="form-group">
<label>实体名称</label>
<input type="text" id="entityName" placeholder="实体名称">
</div>
<div class="form-group">
<label>实体类型</label>
<select id="entityType">
<option value="PROJECT">项目 (PROJECT)</option>
<option value="TECH">技术 (TECH)</option>
<option value="PERSON">人物 (PERSON)</option>
<option value="ORG">组织 (ORG)</option>
<option value="OTHER">其他 (OTHER)</option>
</select>
</div>
<div class="form-group">
<label>定义描述</label>
<textarea id="entityDefinition" placeholder="一句话描述这个实体..."></textarea>
</div>
<div class="form-group">
<label>别名 (用逗号分隔)</label>
<input type="text" id="entityAliases" placeholder="别名1, 别名2, 别名3">
</div>
<div class="relation-editor" id="relationEditor" style="display:none;">
<h4 style="color:#888;font-size:0.9rem;margin-bottom:12px;">实体关系</h4>
<div id="relationList"></div>
<button class="btn-icon" onclick="showAddRelation()" style="margin-top:8px;">+ 添加关系</button>
</div>
<div class="modal-actions">
<button class="btn btn-danger" onclick="deleteEntity()" id="deleteEntityBtn">删除</button>
<button class="btn btn-secondary" onclick="hideEntityModal()">取消</button>
<button class="btn" onclick="saveEntity()">保存</button>
</div>
</div>
</div>
<!-- Add Relation Modal -->
<div class="modal-overlay" id="relationModal">
<div class="modal">
<h3 class="modal-header">添加关系</h3>
<div class="form-group">
<label>目标实体</label>
<select id="relationTarget"></select>
</div>
<div class="form-group">
<label>关系类型</label>
<select id="relationType">
<option value="belongs_to">属于 (belongs_to)</option>
<option value="works_with">合作 (works_with)</option>
<option value="depends_on">依赖 (depends_on)</option>
<option value="mentions">提及 (mentions)</option>
<option value="related">相关 (related)</option>
</select>
</div>
<div class="form-group">
<label>关系证据/说明</label>
<textarea id="relationEvidence" placeholder="描述这个关系的依据..."></textarea>
</div>
<div class="modal-actions">
<button class="btn btn-secondary" onclick="hideRelationModal()">取消</button>
<button class="btn" onclick="saveRelation()">添加</button>
</div>
</div>
</div>
<!-- Merge Entities Modal -->
<div class="modal-overlay" id="mergeModal">
<div class="modal">
<h3 class="modal-header">合并实体</h3>
<p style="color:#888;margin-bottom:16px;font-size:0.9rem;">将选中的实体合并到目标实体中</p>
<div class="form-group">
<label>源实体</label>
<input type="text" id="mergeSource" disabled>
</div>
<div class="form-group">
<label>目标实体 (保留)</label>
<select id="mergeTarget"></select>
</div>
<div class="modal-actions">
<button class="btn btn-secondary" onclick="hideMergeModal()">取消</button>
<button class="btn" onclick="confirmMerge()">合并</button>
</div>
</div>
</div>
<!-- Context Menu -->
<div class="context-menu" id="contextMenu">
<div class="context-menu-item" onclick="editEntity()">✏️ 编辑实体</div>
<div class="context-menu-item" onclick="showMergeModal()">🔄 合并实体</div>
<div class="context-menu-divider"></div>
<div class="context-menu-item" onclick="createEntityFromSelection()"> 标记为实体</div>
</div>
<!-- Selection Toolbar -->
<div class="selection-toolbar" id="selectionToolbar">
<span style="color:#888;font-size:0.85rem;">选中文本:</span>
<button class="btn-icon" onclick="createEntityFromSelection()">标记为实体</button>
<button class="btn-icon" onclick="hideSelectionToolbar()">取消</button>
</div>
<script src="app.js"></script>
</body>
</html>