-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.ts
More file actions
319 lines (275 loc) · 8.84 KB
/
main.ts
File metadata and controls
319 lines (275 loc) · 8.84 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
import {
App,
FileSystemAdapter,
MarkdownView,
Notice,
Plugin,
PluginSettingTab,
Setting,
TFile,
} from "obsidian";
import { promptGPTChat } from "src/gpt";
import { ResultDialog } from "src/ui/result_dialog";
const defaultMaxTokens = 2000;
interface AiSummaryPluginSettings {
openAiApiKey: string;
baseUrl: string;
model: string;
maxTokens: number;
defaultPrompt: string;
}
const DEFAULT_SETTINGS: AiSummaryPluginSettings = {
openAiApiKey: "",
baseUrl: "https://api.openai.com/v1",
model: "gpt-3.5-turbo",
maxTokens: defaultMaxTokens,
defaultPrompt:
"Write me a 2-3 paragraph summary of this in the first person.",
};
export default class AiSummaryPlugin extends Plugin {
settings: AiSummaryPluginSettings;
async generateSummary(): Promise<string> {
const dialog = new ResultDialog(this.app);
dialog.open();
try {
const { vault } = this.app;
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
const file = markdownView?.file;
if (!file) {
dialog.addContent("[AI-SUMMARY] Error: No note is currently open.");
return "No note open.";
}
const content = await vault.cachedRead(file);
const frontMatter = this.extractFrontmatter(content);
const referencedNotes = await this.getReferencedContent(content, file);
if (!referencedNotes || referencedNotes.length === 0) {
dialog.addContent("[AI-SUMMARY] No referenced notes found.");
return "No referenced notes found.";
}
await promptGPTChat(
frontMatter["prompt"] ?? this.settings.defaultPrompt,
this.generateGPTPrompt(referencedNotes),
this.settings.openAiApiKey,
this.settings.baseUrl,
this.settings.model,
this.settings.maxTokens,
dialog
);
return "Summary written.";
} catch (error) {
console.error("[AI-SUMMARY] Error generating summary:", error);
dialog.addContent(`[AI-SUMMARY] Error: Failed to generate summary - ${error.message}`);
return "Failed to generate summary.";
}
}
async summarizeCurrentDocument(): Promise<string> {
const dialog = new ResultDialog(this.app);
dialog.open();
try {
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
const file = markdownView?.file;
if (!file) {
dialog.addContent("[AI-SUMMARY] Error: No note is currently open.");
return "No note open.";
}
const content = await this.app.vault.cachedRead(file);
const frontMatter = this.extractFrontmatter(content);
// Remove frontmatter from content for summarization
const contentWithoutFrontmatter = content.replace(/^---\n[\s\S]*?\n---\n/, '');
if (!contentWithoutFrontmatter.trim()) {
dialog.addContent("[AI-SUMMARY] The current document is empty.");
return "The current document is empty.";
}
await promptGPTChat(
frontMatter["prompt"] ?? this.settings.defaultPrompt,
contentWithoutFrontmatter,
this.settings.openAiApiKey,
this.settings.baseUrl,
this.settings.model,
this.settings.maxTokens,
dialog
);
return "Document summary generated.";
} catch (error) {
console.error("[AI-SUMMARY] Error generating document summary:", error);
dialog.addContent(`[AI-SUMMARY] Error: Failed to generate document summary - ${error.message}`);
return "Failed to generate document summary.";
}
}
hasOpenNote(): boolean {
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
return !!markdownView?.file;
}
generateGPTPrompt(notes: string[]): string {
let prompt = "";
for (const note of notes) {
prompt += note;
prompt += "----";
}
return prompt;
}
async getReferencedContent(
content: string,
currentFile: TFile
): Promise<string[] | undefined> {
const referencedNotes: string[] = [];
const lines = content.split("\n");
for (const line of lines) {
if (line.includes("[[") && line.includes("]]")) {
const links = this.extractTextBetweenBrackets(line);
for (const link of links) {
const noteLink = this.app.metadataCache.getFirstLinkpathDest(
link,
currentFile.path
);
referencedNotes.push(await this.readContents(noteLink));
}
}
}
return referencedNotes;
}
async readContents(note: TFile | null) {
if (note) {
return await this.app.vault.read(note);
}
return "";
}
extractTextBetweenBrackets(str: string): string[] {
const regex = /\[\[([\s\S]*?)\]\]/g;
const matches = [];
let match;
while ((match = regex.exec(str)) !== null) {
matches.push(match[1]);
}
return matches;
}
extractFrontmatter(md: string): Record<string, string> {
const frontmatterRegex = /^---\n([\s\S]*?)\n---\n/;
const match = md.match(frontmatterRegex);
const frontmatter: Record<string, string> = {};
if (match) {
const frontmatterString = match[1];
const frontmatterLines = frontmatterString.split("\n");
frontmatterLines.forEach((line) => {
const [key, value] = line.split(":").map((item) => item.trim());
frontmatter[key.toLowerCase()] = value;
});
}
return frontmatter;
}
async onload() {
await this.loadSettings();
this.addRibbonIcon("pencil", "Summarize referenced notes", async () => {
const resultSummary = await this.generateSummary();
new Notice(resultSummary);
});
this.addCommand({
id: "ai-summary",
name: "Summarize referenced notes",
checkCallback: (checking: boolean) => {
if (checking) {
return this.hasOpenNote();
}
(async () => {
new Notice(await this.generateSummary());
})();
},
});
this.addCommand({
id: "summarize-current-document",
name: "Summarize current document",
checkCallback: (checking: boolean) => {
if (checking) {
return this.hasOpenNote();
}
(async () => {
new Notice(await this.summarizeCurrentDocument());
})();
},
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new AiSummarySettingTab(this.app, this));
}
onunload() {}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class AiSummarySettingTab extends PluginSettingTab {
plugin: AiSummaryPlugin;
constructor(app: App, plugin: AiSummaryPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "Settings for the AI Summary Plugin." });
new Setting(containerEl)
.setName("OpenAI API Key")
.setDesc("OpenAI API Key")
.addText((text) =>
text
.setPlaceholder("API Key")
.setValue(this.plugin.settings.openAiApiKey)
.onChange(async (value) => {
this.plugin.settings.openAiApiKey = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Base URL")
.setDesc("Base URL for API requests")
.addText((text) =>
text
.setPlaceholder("https://api.openai.com/v1")
.setValue(this.plugin.settings.baseUrl)
.onChange(async (value) => {
this.plugin.settings.baseUrl = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Model")
.setDesc("Enter the model name")
.addText((text) =>
text
.setPlaceholder("gpt-3.5-turbo")
.setValue(this.plugin.settings.model)
.onChange(async (value) => {
this.plugin.settings.model = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Max tokens")
.setDesc("Max tokens")
.addText((text) =>
text
.setPlaceholder(defaultMaxTokens.toString())
.setValue(
this.plugin.settings.maxTokens?.toString() ||
defaultMaxTokens.toString()
)
.onChange(async (value) => {
this.plugin.settings.maxTokens = Number.parseInt(value);
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Default prompt")
.setDesc("Default system prompt")
.addTextArea((text) =>
text
.setPlaceholder("Prompt")
.setValue(this.plugin.settings.defaultPrompt)
.onChange(async (value) => {
this.plugin.settings.defaultPrompt = value;
await this.plugin.saveSettings();
})
);
}
}