-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
480 lines (420 loc) · 19.7 KB
/
Copy pathmain.js
File metadata and controls
480 lines (420 loc) · 19.7 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
const { Plugin, PluginSettingTab, Setting, Notice } = require('obsidian');
// ── 时间戳正则 ─────────────────────────────────────────────
// 冒号格式: 0:00, 12:34, 1:23:45, 0:099秒, 0:1212秒, 1:2345秒
// 中文格式: 分9秒, 分20秒, 分08秒, 分 5 秒(空格), 1分9秒, 12分30秒
// 分钟标记: 分钟
const TIMESTAMP_RE = /\d+:(?:\d{2}:\d{2}|\d{2}(?:\d{1,2})?(?:\.\d+)?秒?|\d{2})|分钟|\d*分\s*\d+\s*秒/;
const STAMP_ONLY_LINE = /^\s*(?:\d+:(?:\d{2}:\d{2}|\d{2}(?:\d{1,2})?(?:\.\d+)?秒?|\d{2})|分钟|\d*分\s*\d+\s*秒)\s*$/gm;
const STAMP_PREFIX = /^\s*(?:\d+:(?:\d{2}:\d{2}|\d{2}(?:\d{1,2})?(?:\.\d+)?秒?|\d{2})|分钟|\d*分\s*\d+\s*秒)\s*/gm;
const STAMP_GLOBAL = /\d+:(?:\d{2}:\d{2}|\d{2}(?:\d{1,2})?(?:\.\d+)?秒?|\d{2})|分钟|\d*分\s*\d+\s*秒/g;
// ── API 配置 ───────────────────────────────────────────────
const API_ENDPOINTS = {
deepseek: 'https://api.deepseek.com/v1/chat/completions',
openai: 'https://api.openai.com/v1/chat/completions',
chatgpt: null, // 尚未接入
gemini: null, // 尚未接入
};
const PROVIDER_MODELS = {
deepseek: ['deepseek-chat', 'deepseek-reasoner'],
openai: ['gpt-4o-mini', 'gpt-4o', 'gpt-4.1'],
chatgpt: ['gpt-4o-mini', 'gpt-4o', 'gpt-4.1'],
gemini: ['gemini-2.5-flash', 'gemini-2.5-pro'],
};
const PROVIDER_LABELS = {
deepseek: 'DeepSeek(默认)',
openai: 'OpenAI',
chatgpt: 'ChatGPT(尚未接入)',
gemini: 'Gemini(尚未接入)',
};
// 已接入可用的厂商
const ACTIVE_PROVIDERS = ['deepseek', 'openai'];
const DEFAULT_SYSTEM_PROMPT = [
'你是一位专业的中文编辑。请将以下转录文稿优化为一篇流畅、可阅读的文章。',
'',
'要求:',
'1. 保留所有原始内容和信息,不要删除、省略任何实质内容',
'2. 修正口语化表达,转为自然流畅的书面语',
'3. 优化段落结构和逻辑顺序,使文章层次分明',
'4. 修正语法错误、重复和不流畅的表达',
'5. 保持原文的语气和风格',
'6. 适当添加段落间过渡,使阅读更顺畅',
'7. 输出优化后的文章正文,根据发问者和访问者的语气,恰当添加对应的说明、注释或标记',
'',
'访谈类文稿特别处理:',
'- 识别发问者(主持人/采访者)和受访者(嘉宾/回答者)的发言',
'- 在发问者的文字前标注【问】',
'- 在受访者的文字前标注【答】',
'- 如果无法明确区分,可根据上下文语气判断:提问、引导性语言标注【问】;陈述、解释、回答性语言标注【答】',
].join('\n');
// ── 核心清理函数 ────────────────────────────────────────────
function removeTimestamps(text) {
let result = text;
result = result.replace(STAMP_ONLY_LINE, '');
result = result.replace(STAMP_PREFIX, '');
result = result.replace(STAMP_GLOBAL, '');
result = result.replace(/\n{3,}/g, '\n\n');
return result.trim();
}
function hasTimestamps(text) {
return TIMESTAMP_RE.test(text);
}
function countTimestamps(text) {
// 统计全文有多少处时间戳匹配(仅诊断用)
const m = text.match(new RegExp(TIMESTAMP_RE.source, 'g'));
return m ? m.length : 0;
}
// ── API 调用 ────────────────────────────────────────────────
async function callAI(text, settings) {
const provider = settings.apiProvider || 'deepseek';
const endpoint = API_ENDPOINTS[provider];
const apiKey = provider === 'deepseek'
? settings.deepseekApiKey
: settings.openaiApiKey;
if (!apiKey) {
throw new Error(`未配置 ${provider === 'deepseek' ? 'DeepSeek' : 'OpenAI'} API Key,请在设置中填写`);
}
const model = provider === 'deepseek'
? (settings.deepseekModel || 'deepseek-chat')
: (settings.openaiModel || 'gpt-4o-mini');
const systemPrompt = settings.customPrompt || DEFAULT_SYSTEM_PROMPT;
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: text },
],
temperature: 0.7,
}),
});
if (!response.ok) {
const errorText = await response.text();
let errorMsg;
try {
const err = JSON.parse(errorText);
errorMsg = err.error?.message || errorText;
} catch {
errorMsg = errorText;
}
throw new Error(`API 错误 (${response.status}): ${errorMsg}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
// ── 插件主类 ────────────────────────────────────────────────
class TimestampCleanerPlugin extends Plugin {
async onload() {
await this.loadSettings();
// ---- 命令: 清理时间戳 ----
this.addCommand({
id: 'clean-timestamps',
name: '清理时间戳 (选区或全文)',
editorCallback: (editor) => {
const selection = editor.getSelection();
if (selection) {
const cleaned = removeTimestamps(selection, this.settings);
editor.replaceSelection(cleaned);
new Notice('已清理选区中的时间戳');
} else {
const fullText = editor.getValue();
if (!hasTimestamps(fullText)) {
new Notice('未检测到时间戳');
return;
}
const cleaned = removeTimestamps(fullText, this.settings);
editor.setValue(cleaned);
new Notice('已清理全文时间戳');
}
}
});
// ---- 命令: 粘贴并清理 ----
this.addCommand({
id: 'paste-cleaned',
name: '粘贴并清理时间戳',
editorCallback: async (editor) => {
try {
const raw = await navigator.clipboard.readText();
if (!raw) {
new Notice('剪贴板为空');
return;
}
const hasTs = hasTimestamps(raw);
console.log('[ACA] 剪贴板长度:', raw.length, '含时间戳:', hasTs);
console.log('[ACA] 原文前200字:', raw.substring(0, 200));
if (!hasTs) {
editor.replaceSelection(raw);
new Notice(`已粘贴(未检测到时间戳,共 ${raw.length} 字符)`);
return;
}
const cleaned = removeTimestamps(raw);
console.log('[ACA] 清理后前200字:', cleaned.substring(0, 200));
editor.replaceSelection(cleaned);
new Notice(`已粘贴并清理 ${raw.length - cleaned.length} 字符时间戳`);
} catch (e) {
console.error('[ACA] 错误:', e);
new Notice('无法读取剪贴板');
}
}
});
// ---- 命令: AI 优化 ----
this.addCommand({
id: 'ai-refine',
name: 'AI 优化文稿 (选区或全文)',
editorCallback: async (editor) => {
const provider = this.settings.apiProvider || 'deepseek';
// 未接入的厂商
if (!ACTIVE_PROVIDERS.includes(provider)) {
const label = PROVIDER_LABELS[provider] || provider;
new Notice(`${label},请先切换到 DeepSeek 使用`, 6000);
return;
}
const apiKey = provider === 'deepseek'
? this.settings.deepseekApiKey
: this.settings.openaiApiKey;
if (!apiKey) {
new Notice(`请先在设置中配置 ${provider === 'deepseek' ? 'DeepSeek' : 'OpenAI'} API Key`, 8000);
return;
}
const selection = editor.getSelection();
const text = selection || editor.getValue();
if (!text.trim()) {
new Notice('文档为空');
return;
}
const model = provider === 'deepseek'
? (this.settings.deepseekModel || 'deepseek-chat')
: (this.settings.openaiModel || 'gpt-4o-mini');
const notice = new Notice(`正在调用 ${model} 优化文稿...`, 0);
try {
const refined = await callAI(text, this.settings);
notice.hide();
if (selection) {
editor.replaceSelection(refined);
} else {
editor.setValue(refined);
}
new Notice('AI 优化完成');
} catch (e) {
notice.hide();
new Notice(`优化失败: ${e.message}`, 8000);
console.error('[ACA] AI error:', e);
}
}
});
// ---- 自动清理粘贴(原生 DOM 捕获阶段拦截,早于 CodeMirror)----
const pasteCapture = (event) => {
try {
if (!this.settings.autoCleanOnPaste) return;
const target = event.target;
if (!target || typeof target.closest !== 'function') return;
if (!target.closest('.cm-editor') && !target.closest('.cm-content')) return;
const raw = event.clipboardData?.getData('text/plain');
if (!raw || !hasTimestamps(raw)) return;
event.preventDefault();
event.stopPropagation();
const cleaned = removeTimestamps(raw);
const remainStamps = countTimestamps(cleaned);
const totalLines = raw.split('\n').length;
const totalStamps = countTimestamps(raw);
// 收集未被清理的"疑似时间戳"样本
const broadRe = /\S*\d\S*[秒分时]\S*|\d+:\d+\S*/g;
const leftover = new Set();
let bm;
while ((bm = broadRe.exec(cleaned)) !== null) {
leftover.add(bm[0]);
if (leftover.size >= 8) break;
}
console.log('[TC] 行:', totalLines, '→', cleaned.split('\n').length,
'| 时间戳:', totalStamps, '→ 剩余:', remainStamps,
'| 字符:', raw.length, '→', cleaned.length);
console.log('[TC] 未清理样本:', [...leftover].join(' ||| '));
const msg = `已清理 ${totalStamps} 个,剩余 ${remainStamps} 个`;
if (leftover.size > 0) {
const samples = [...leftover].slice(0, 4).join(' ');
new Notice(msg + ' | 样本: ' + samples, 8000);
} else {
new Notice(msg, 3000);
}
const editor = this.app.workspace.activeEditor?.editor;
if (editor) {
editor.replaceSelection(cleaned);
}
} catch (e) {
console.error('[ACA] pasteCapture error:', e);
}
};
document.addEventListener('paste', pasteCapture, true);
this.register(() => document.removeEventListener('paste', pasteCapture, true));
console.log('[ACA] 插件加载完成');
// ---- 设置页 ----
this.addSettingTab(new TimestampCleanerSettingTab(this.app, this));
}
async loadSettings() {
const defaults = {
// 清理
autoCleanOnPaste: false,
preserveSectionHeaders: true,
// AI
apiProvider: 'deepseek',
deepseekApiKey: '',
openaiApiKey: '',
deepseekModel: 'deepseek-chat',
openaiModel: 'gpt-4o-mini',
customPrompt: '',
};
this.settings = Object.assign({}, defaults, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
// ── 设置面板 ────────────────────────────────────────────────
class TimestampCleanerSettingTab extends PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
// ========== 第一部分:时间戳清理 ==========
containerEl.createEl('h2', { text: '时间戳清理' });
new Setting(containerEl)
.setName('粘贴时自动清理时间戳')
.setDesc('开启后,每次粘贴带时间戳的文本时会自动去除时间戳。')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.autoCleanOnPaste)
.onChange(async (value) => {
this.plugin.settings.autoCleanOnPaste = value;
await this.plugin.saveSettings();
new Notice('设置已保存,即时生效');
}));
// ========== 第二部分:AI 优化 ==========
containerEl.createEl('h2', { text: 'AI 文稿优化' });
containerEl.createEl('p', {
text: '将清理后的转录文稿优化为流畅可读的文章。保留全部内容,不改写、不删减。',
cls: 'setting-item-description',
});
// API 厂商下拉
new Setting(containerEl)
.setName('API 厂商')
.setDesc('选择 AI 厂商。ChatGPT 和 Gemini 尚未接入,界面预留。')
.addDropdown(dropdown => {
dropdown.addOption('deepseek', 'DeepSeek(默认)');
dropdown.addOption('openai', 'OpenAI');
dropdown.addOption('chatgpt', 'ChatGPT(尚未接入)');
dropdown.addOption('gemini', 'Gemini(尚未接入)');
dropdown
.setValue(this.plugin.settings.apiProvider)
.onChange(async (value) => {
this.plugin.settings.apiProvider = value;
await this.plugin.saveSettings();
this.display();
});
});
const provider = this.plugin.settings.apiProvider || 'deepseek';
const isActive = ACTIVE_PROVIDERS.includes(provider);
// 未接入的厂商 — 显示占位提示
if (!isActive) {
const label = PROVIDER_LABELS[provider] || provider;
containerEl.createEl('div', {
cls: 'setting-item-description',
text: `⚠ ${label},API 接口尚未接入。请切换至 DeepSeek 使用。`,
}).style.cssText = 'padding:16px;color:var(--text-muted);font-style:italic;';
// 占位:禁用的 API Key 输入框
new Setting(containerEl)
.setName('API Key')
.setDesc('尚未接入,暂不可用')
.addText(text => {
text.setPlaceholder('尚未接入...')
.setDisabled(true);
text.inputEl.style.width = '300px';
});
// 占位:禁用的模型下拉
new Setting(containerEl)
.setName('模型')
.setDesc('尚未接入,暂不可用')
.addDropdown(dropdown => {
(PROVIDER_MODELS[provider] || []).forEach(m => dropdown.addOption(m, m));
dropdown.setDisabled(true);
});
}
// DeepSeek 设置
if (provider === 'deepseek') {
new Setting(containerEl)
.setName('DeepSeek API Key')
.setDesc('在 platform.deepseek.com 获取')
.addText(text => {
text.setPlaceholder('sk-...')
.setValue(this.plugin.settings.deepseekApiKey)
.onChange(async (value) => {
this.plugin.settings.deepseekApiKey = value;
await this.plugin.saveSettings();
});
text.inputEl.type = 'password';
text.inputEl.style.width = '300px';
});
new Setting(containerEl)
.setName('模型')
.setDesc('deepseek-chat (V3, 快且便宜) / deepseek-reasoner (R1, 深度推理)')
.addDropdown(dropdown => {
PROVIDER_MODELS.deepseek.forEach(m => dropdown.addOption(m, m));
dropdown
.setValue(this.plugin.settings.deepseekModel)
.onChange(async (value) => {
this.plugin.settings.deepseekModel = value;
await this.plugin.saveSettings();
});
});
}
// OpenAI 设置
if (provider === 'openai') {
new Setting(containerEl)
.setName('OpenAI API Key')
.setDesc('在 platform.openai.com 获取')
.addText(text => {
text.setPlaceholder('sk-...')
.setValue(this.plugin.settings.openaiApiKey)
.onChange(async (value) => {
this.plugin.settings.openaiApiKey = value;
await this.plugin.saveSettings();
});
text.inputEl.type = 'password';
text.inputEl.style.width = '300px';
});
new Setting(containerEl)
.setName('模型')
.setDesc('gpt-4o-mini (快且便宜) / gpt-4o (更强) / gpt-4.1 (最新)')
.addDropdown(dropdown => {
PROVIDER_MODELS.openai.forEach(m => dropdown.addOption(m, m));
dropdown
.setValue(this.plugin.settings.openaiModel)
.onChange(async (value) => {
this.plugin.settings.openaiModel = value;
await this.plugin.saveSettings();
});
});
}
// 自定义 Prompt(两个厂商通用)
containerEl.createEl('h3', { text: '高级' });
new Setting(containerEl)
.setName('自定义系统提示词')
.setDesc('留空则使用默认提示词。自定义时仍请强调"保留全部内容、不删减"。')
.addTextArea(text => {
text.setPlaceholder(DEFAULT_SYSTEM_PROMPT)
.setValue(this.plugin.settings.customPrompt)
.onChange(async (value) => {
this.plugin.settings.customPrompt = value;
await this.plugin.saveSettings();
});
text.inputEl.rows = 6;
text.inputEl.style.width = '100%';
});
}
}
module.exports = TimestampCleanerPlugin;