-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
198 lines (177 loc) · 5.75 KB
/
utils.ts
File metadata and controls
198 lines (177 loc) · 5.75 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
import Anthropic from "@anthropic-ai/sdk";
import { type App, Notice, type TFile } from "obsidian";
import type { MetadataToolSettings } from "./settings";
export async function callClaude(
prompt: string,
settings: MetadataToolSettings,
): Promise<string> {
const notice = new Notice("Generating metadata...", 0);
// Safe in Obsidian's Electron renderer — no browser security concerns apply
const anthropic = new Anthropic({
apiKey: settings.anthropicApiKey,
dangerouslyAllowBrowser: true,
});
try {
const message = await anthropic.messages.create({
model: settings.anthropicModel,
max_tokens: 2048,
messages: [{ role: "user", content: prompt }],
});
notice.hide();
if (message.content.length > 0 && message.content[0].type === "text") {
return message.content[0].text;
}
throw new Error("No text content in response");
} catch (error) {
notice.hide();
if (error instanceof Anthropic.AuthenticationError) {
new Notice(
"Authentication failed. Please check your API key in Settings → Metadator",
8000,
);
} else if (error instanceof Anthropic.RateLimitError) {
new Notice(
"Rate limit exceeded. Please wait a moment and try again.",
8000,
);
} else if (error instanceof Anthropic.InternalServerError) {
new Notice(
"API is currently overloaded. Please try again in a moment.",
8000,
);
} else if (error instanceof Anthropic.APIError) {
new Notice(`API error: ${error.message}`, 8000);
} else {
new Notice("An unknown API error occurred", 8000);
}
console.error("Claude API error:", error);
throw error;
}
}
export function splitIntoTokens(str: string): string[] {
const regex = /[\u4e00-\u9fa5]|[a-zA-Z0-9]+|[.,!?;,。!?;#]|[\n]/g;
const tokens = str.match(regex);
return tokens || [];
}
export function joinTokens(tokens: string[]): string {
let result = "";
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (token === "\n") {
result += token;
} else if (/[\u4e00-\u9fa5]|[.,!?;,。!?;#]/.test(token)) {
result += token;
} else {
const prevToken = i > 0 ? tokens[i - 1] : undefined;
const needsSpace = i > 0 && prevToken !== "\n";
result += (needsSpace ? " " : "") + token;
}
}
return result.trim();
}
export function truncateHeadOnly(tokens: string[], limit: number): string {
const truncated = tokens.slice(0, limit);
const suffix = truncated.length < tokens.length ? "..." : "";
return `${joinTokens(truncated)}${suffix}`;
}
export function truncateHeadTail(tokens: string[], limit: number): string {
if (limit >= tokens.length) {
return joinTokens(tokens);
}
const left = Math.max(1, Math.floor(limit * 0.8));
const right = Math.max(0, limit - left);
const leftTokens = tokens.slice(0, left);
if (right <= 0) {
return joinTokens(leftTokens);
}
const rightTokens = tokens.slice(-right);
return `${joinTokens(leftTokens)}\n...\n${joinTokens(rightTokens)}`;
}
export function truncateHeading(
contentStr: string,
tokens: string[],
limit: number,
): string {
let lines = contentStr.split("\n");
lines = lines.filter((line) => line.trim() !== "");
const newLines: string[] = [];
let captureNextParagraph = false;
for (const line of lines) {
if (line.startsWith("#")) {
newLines.push(line);
captureNextParagraph = true;
} else if (captureNextParagraph && line.trim() !== "") {
const lineTokens = splitIntoTokens(line);
const truncated = lineTokens.slice(0, 30);
const suffix = truncated.length < lineTokens.length ? "..." : "";
newLines.push(`${joinTokens(truncated)}${suffix}`);
captureNextParagraph = false;
}
}
let result = newLines.join("\n");
const totalTokens = splitIntoTokens(result);
if (totalTokens.length > limit) {
result = joinTokens(totalTokens.slice(0, limit));
} else {
const remainingTokens = limit - totalTokens.length;
const headTokens = tokens.slice(0, remainingTokens);
if (headTokens.length > 0) {
const suffix = headTokens.length < tokens.length ? "..." : "";
const head = `${joinTokens(headTokens)}${suffix}`;
result = `Outline: \n${result}\n\nBody: ${head}`;
} else {
result = `Outline: \n${result}`;
}
}
return result;
}
export async function getContent(
app: App,
file: TFile,
limit: number = 1000,
method: "head_only" | "head_tail" | "heading" = "head_only",
): Promise<string> {
let contentStr = await app.vault.read(file);
if (contentStr.length === 0) {
return "";
}
if (limit <= 0) {
return contentStr;
}
const tokens = splitIntoTokens(contentStr);
if (tokens.length > limit) {
if (method === "head_tail") {
contentStr = truncateHeadTail(tokens, limit);
} else if (method === "head_only") {
contentStr = truncateHeadOnly(tokens, limit);
} else if (method === "heading") {
contentStr = truncateHeading(contentStr, tokens, limit);
}
}
return contentStr;
}
export async function updateFrontMatter(
file: TFile,
app: App,
key: string,
value: string | boolean | string[],
method: "append" | "update" | "keep",
): Promise<void> {
await app.fileManager.processFrontMatter(file, (frontmatter) => {
if (method === "append") {
if (Array.isArray(value)) {
const existing = frontmatter[key];
const base = Array.isArray(existing)
? existing
: existing != null
? [String(existing)]
: [];
frontmatter[key] = Array.from(new Set(base.concat(value)));
}
} else if (method === "update") {
frontmatter[key] = value;
} else if (frontmatter[key] === undefined) {
frontmatter[key] = value;
}
});
}