-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
205 lines (166 loc) · 4.92 KB
/
Copy pathbackground.js
File metadata and controls
205 lines (166 loc) · 4.92 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
const DEFAULT_MODEL = "gemini-2.5-flash";
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
handleMessage(message)
.then((data) => sendResponse({ ok: true, data }))
.catch((error) => sendResponse({ ok: false, error: error.message || String(error) }));
return true;
});
async function handleMessage(message) {
if (!message || !message.type) {
throw new Error("Invalid message.");
}
if (message.type === "capture-screen") {
return captureScreen();
}
if (message.type === "analyze-visible-page") {
return analyzeVisiblePage();
}
if (message.type === "analyze-image") {
return analyzeImage(message.payload);
}
throw new Error(`Unknown action: ${message.type}`);
}
async function captureScreen() {
const { tab, screenshotUrl } = await captureActiveTabScreenshot();
const payload = {
screenshotUrl,
sourceTitle: tab.title || "Captured page",
sourceUrl: tab.url || "",
mode: "crop"
};
await sendCropOverlayMessage(tab.id, payload);
return { tabId: tab.id };
}
async function analyzeVisiblePage() {
const { tab, screenshotUrl } = await captureActiveTabScreenshot();
const payload = {
screenshotUrl,
sourceTitle: tab.title || "Captured page",
sourceUrl: tab.url || "",
mode: "visible-page"
};
await sendCropOverlayMessage(tab.id, payload);
return { tabId: tab.id };
}
async function captureActiveTabScreenshot() {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const tab = tabs[0];
if (!tab || tab.id == null || tab.windowId == null) {
throw new Error("No active tab found.");
}
if (tab.url && /^(chrome|edge|brave|about):\/\//i.test(tab.url)) {
throw new Error("Chrome does not allow screenshots on internal browser pages.");
}
const screenshotUrl = await chrome.tabs.captureVisibleTab(tab.windowId, {
format: "png"
});
return { tab, screenshotUrl };
}
async function sendCropOverlayMessage(tabId, payload) {
try {
await chrome.tabs.sendMessage(tabId, {
type: "open-crop-overlay",
payload
});
return;
} catch (_error) {
await chrome.scripting.executeScript({
target: { tabId },
files: ["content-crop.js"]
});
await chrome.tabs.sendMessage(tabId, {
type: "open-crop-overlay",
payload
});
}
}
async function analyzeImage(payload) {
const { imageDataUrl, apiKey, prompt, model } = payload || {};
if (!imageDataUrl) {
throw new Error("No cropped image was provided.");
}
if (!apiKey) {
throw new Error("Gemini API key is required.");
}
const image = parseDataUrl(imageDataUrl);
const geminiModel = normalizeModel(model);
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:generateContent`, {
method: "POST",
headers: {
"x-goog-api-key": apiKey,
"Content-Type": "application/json"
},
body: JSON.stringify({
contents: [
{
parts: [
{
inline_data: {
mime_type: image.mimeType,
data: image.base64
}
},
{
text: prompt || defaultPrompt()
}
]
}
],
generationConfig: {
maxOutputTokens: 1200
}
})
});
const result = await response.json().catch(() => ({}));
if (!response.ok) {
const detail = result.error && result.error.message ? result.error.message : response.statusText;
throw new Error(`Gemini request failed: ${detail}`);
}
const answer = extractResponseText(result);
if (!answer) {
throw new Error("Gemini returned an empty answer.");
}
const stored = {
answer,
model: geminiModel,
createdAt: new Date().toISOString()
};
await chrome.storage.local.set({ latestAnswer: stored });
return stored;
}
function defaultPrompt() {
return [
"Baca soal pada gambar dan jawab hanya jawaban akhirnya saja.",
"Jangan pakai pembuka, ucapan terima kasih, analisis, langkah-langkah, markdown, atau penjelasan.",
"Kalau soal pilihan ganda, jawab format: A. isi jawaban.",
"Kalau soal isian/hitungan, jawab hasil akhirnya saja."
].join(" ");
}
function extractResponseText(result) {
const chunks = [];
for (const candidate of result.candidates || []) {
const parts = candidate.content && Array.isArray(candidate.content.parts)
? candidate.content.parts
: [];
for (const part of parts) {
if (typeof part.text === "string") {
chunks.push(part.text);
}
}
}
return chunks.join("\n").trim();
}
function parseDataUrl(dataUrl) {
const match = /^data:([^;,]+);base64,(.+)$/s.exec(dataUrl);
if (!match) {
throw new Error("Invalid cropped image format.");
}
return {
mimeType: match[1],
base64: match[2]
};
}
function normalizeModel(model) {
const value = (model || DEFAULT_MODEL).trim();
return value.replace(/^models\//, "") || DEFAULT_MODEL;
}