-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
403 lines (354 loc) · 16 KB
/
Copy pathbackground.js
File metadata and controls
403 lines (354 loc) · 16 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
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
// Rate Limiting & Caching State
const CACHE_TTL = 1000 * 60 * 5; // 5 minutes cache
const analysisCache = new Map(); // Key: ImageHash, Value: { timestamp, data }
let lastCallTime = 0;
let latestCoordinates = null; // Store latest game coordinates
const MIN_INTERVAL = 2000; // 2 seconds between calls
// Listen for messages from content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "ANALYZE_SCREENSHOT") {
handleAnalysis(sender.tab.id, sendResponse);
return true; // Keep channel open for async response
}
if (message.type === "LOCATIONS_FOUND") {
if (message.payload && message.payload.length > 0) {
// Store the most relevant coordinate (usually the last one or first one, depending on game mode)
// For now, take the first valid one
latestCoordinates = message.payload[0];
console.log("Updated Ground Truth Coordinates:", latestCoordinates);
}
}
if (message.type === "CLEAR_LOCATIONS") {
latestCoordinates = null;
console.log("Cleared Ground Truth Coordinates.");
}
});
function hashCode(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
async function handleAnalysis(tabId, sendResponse) {
try {
// Rate Limiting Check
const now = Date.now();
if (now - lastCallTime < MIN_INTERVAL) {
sendResponse({ success: false, error: "Please wait a few seconds between analyses." });
return;
}
// 1. Capture Screenshot
const dataUrl = await chrome.tabs.captureVisibleTab(null, { format: "jpeg", quality: 80 });
// Caching Check
// Hashing the full base64 is heavy, maybe just take a substring or assume if user clicks button again in same location it might be same?
// But user might move. Let's hash the first 1000 + last 1000 chars of base64 for speed + some uniqueness
const hashInput = dataUrl.substring(0, 1000) + dataUrl.substring(dataUrl.length - 1000);
const imgHash = hashCode(hashInput);
if (analysisCache.has(imgHash)) {
const cached = analysisCache.get(imgHash);
if (now - cached.timestamp < CACHE_TTL) {
console.log("Returning cached analysis");
sendResponse({ success: true, data: cached.data, cached: true });
return;
} else {
analysisCache.delete(imgHash);
}
}
lastCallTime = now;
// 2. Get API Settings
const settings = await chrome.storage.local.get(['apiKey', 'apiProvider', 'modelName', 'coachLanguage']);
const apiKey = settings.apiKey;
const provider = settings.apiProvider || 'openai'; // default to openai
const modelName = settings.modelName; // Don't default here to avoid polluting other providers
const coachLanguage = settings.coachLanguage || 'English'; // Default language
if (!apiKey) {
sendResponse({ success: false, error: "No API Key configured. Please set it in the Extension Side Panel." });
return;
}
// 3. Call AI API
const analysisResult = await callAI(dataUrl, apiKey, provider, modelName, coachLanguage);
// Cache Result
const finalResult = censorResult(analysisResult);
analysisCache.set(imgHash, { timestamp: now, data: finalResult });
sendResponse({ success: true, data: finalResult });
} catch (e) {
console.error("Analysis failed:", e);
sendResponse({ success: false, error: e.message });
}
}
function censorResult(result) {
if (!result || !result.country) return result;
const country = result.country;
// Create a regex to match country name (case insensitive)
// Also try to match common variations if possible, but exact match is a good start
const countryRegex = new RegExp(`\\b${country}\\b`, 'gi');
// Helper to censor text
const censorText = (text) => {
if (!text) return text;
return text.replace(countryRegex, '[MYSTERIOUS COUNTRY]');
};
if (result.reasoning) {
result.reasoning = censorText(result.reasoning);
}
if (result.key_hint) {
result.key_hint = censorText(result.key_hint);
}
if (result.clues && Array.isArray(result.clues)) {
result.clues.forEach(clue => {
if (clue.description) {
clue.description = censorText(clue.description);
}
});
}
return result;
}
async function callAI(imageBase64, apiKey, provider, modelName, language) {
let promptContext = "";
if (latestCoordinates) {
promptContext = `
LOCATION DATA (GROUND TRUTH - USE FOR VERIFICATION BUT DO NOT REVEAL EXPLICITLY):
Coordinates: ${latestCoordinates.lat}, ${latestCoordinates.lng}
(Use these coordinates to be certain of the country, but pretend to deduce it only from the image in the reasoning).
`;
}
const prompt = `YOU ARE AN EXPERT GEOGUESSR COACH. YOUR GOAL IS TO TEACH, NOT JUST GIVE THE SOLUTION.
RESPONSE LANGUAGE: ${language} (All descriptive text must be in this language).
${promptContext}
Analyze this Google Street View image and identify the elements that allow determining the country.
FUNDAMENTAL COACHING INSTRUCTIONS (FOLLOW STRICTLY):
1. ABSOLUTE PROHIBITION TO NAME THE COUNTRY, CITY, OR COORDINATES in the "reasoning" or "clues" sections.
2. DO NOT USE NATIONAL ADJECTIVES (e.g., "Thai", "French", "Italian").
- INSTEAD OF: "Thai script" -> WRITE: "Script typical of Southeast Asia with many small circles"
- INSTEAD OF: "Italian flag" -> WRITE: "Tricolor flag green, white, and red"
- INSTEAD OF: "Typical of Chile" -> WRITE: "Typical of this Andean region"
3. Your goal is to DESCRIBE VISUAL CLUES, not give the solution. The user must make the mental connection.
4. Use location data (if available) ONLY to internally verify the correctness of your analysis.
5. If you reveal the country name in the descriptive text (reasoning/clues), YOU HAVE FAILED the task.
6. IMPORTANT: The "country" field in the JSON MUST BE FILLED with the correct country name. The prohibition applies only to descriptive text.
ELEMENTS TO LOOK FOR:
1. BOLLARDS: Describe shape, reflector colors, stripe patterns
2. ELECTRIC POLES: Material, shape, insulators
3. ROAD MARKINGS: Center line color, edges
4. SIGNAGE: Language, colors, sign shape
5. LANDSCAPE: Vegetation, climate, architecture
Respond in JSON format with this structure:
{
"country": "Country Name (MANDATORY - Write it here for the system, but it will be hidden from the user)",
"city": "Nearest City Name (or 'Unknown')",
"region": "Position in the country (North, South, East, West, Center, etc.)",
"key_hint": "The unique key hint that distinguishes this country from others (e.g., 'Yellow license plate front and back', 'Pole with black and yellow stripes'). WITHOUT naming the country.",
"reasoning": "Didactic explanation guiding the user towards the solution WITHOUT EVER mentioning the place name.",
"clues": [
{
"category": "CATEGORY",
"description": "Visual clue description (WITHOUT proper nation names)",
"confidence": "HIGH|MEDIUM|LOW"
}
]
}
DO NOT guess. Be precise.`;
// Remove data:image/jpeg;base64, prefix for API if needed, or keep it depending on provider
// OpenAI expects URL or base64.
if (provider === 'openai') {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: "gpt-4o", // or gpt-4-turbo
messages: [
{
role: "user",
content: [
{ type: "text", text: prompt },
{ type: "image_url", image_url: { url: imageBase64 } }
]
}
],
max_tokens: 500,
response_format: { type: "json_object" }
})
});
if (!response.ok) {
throw new Error(`OpenAI API Error: ${response.statusText}`);
}
const data = await response.json();
return JSON.parse(data.choices[0].message.content);
} else if (provider === 'anthropic') {
// Simple base64 extraction
const base64Data = imageBase64.split(',')[1];
const mediaType = imageBase64.split(';')[0].split(':')[1];
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
'content-type': 'application/json',
'anthropic-dangerous-direct-browser-access': 'true' // Required for browser extensions if calling directly
},
body: JSON.stringify({
model: "claude-3-5-sonnet-20240620",
max_tokens: 1024,
messages: [
{
role: "user",
content: [
{
type: "image",
source: {
type: "base64",
media_type: mediaType,
data: base64Data
}
},
{ type: "text", text: prompt + " Respond in JSON." }
]
}
]
})
});
if (!response.ok) {
const errText = await response.text();
throw new Error(`Anthropic API Error: ${errText}`);
}
const data = await response.json();
// Anthropic doesn't force JSON object as strictly as OpenAI, need to parse
const text = data.content[0].text;
// Find JSON in text
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (jsonMatch) {
return JSON.parse(jsonMatch[0]);
}
return { country: "Unknown", clues: [{ category: "Error", description: "Could not parse JSON response", confidence: "LOW" }] };
} else if (provider === 'gemini') {
const base64Data = imageBase64.split(',')[1];
// Using gemini-1.5-flash-latest to ensure availability
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
contents: [{
parts: [
{ text: prompt + " Respond in JSON." },
{
inline_data: {
mime_type: "image/jpeg",
data: base64Data
}
}
]
}],
generationConfig: {
response_mime_type: "application/json"
}
})
});
if (!response.ok) {
const errText = await response.text();
throw new Error(`Gemini API Error: ${errText}`);
}
const data = await response.json();
const text = data.candidates[0].content.parts[0].text;
try {
return JSON.parse(text);
} catch (e) {
// Fallback if raw text contains markdown json block
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (jsonMatch) return JSON.parse(jsonMatch[0]);
throw new Error("Could not parse Gemini JSON response");
}
} else if (provider === 'openrouter') {
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
'HTTP-Referer': 'https://github.com/geocoach-ai/extension', // Required by OpenRouter
'X-Title': 'GeoCoach Extension'
},
body: JSON.stringify({
model: modelName || 'google/gemini-2.0-flash-lite-preview-02-05:free', // Default fallback for OpenRouter
messages: [
{
role: "user",
content: [
{ type: "text", text: prompt },
{ type: "image_url", image_url: { url: imageBase64 } }
]
}
],
response_format: { type: "json_object" }
})
});
if (!response.ok) {
const errText = await response.text();
throw new Error(`OpenRouter API Error: ${errText}`);
}
const data = await response.json();
// OpenRouter returns standard OpenAI format
let content = data.choices[0].message.content;
try {
return JSON.parse(content);
} catch (e) {
// Fallback if raw text contains markdown json block
const jsonMatch = content.match(/\{[\s\S]*\}/);
if (jsonMatch) return JSON.parse(jsonMatch[0]);
throw new Error("Could not parse OpenRouter JSON response");
}
} else if (provider === 'groq') {
// Sanitize model name for Groq.
// Groq REQUIRES a vision model (e.g. llama-3.2-11b-vision-preview) to handle image arrays.
// If a text model is used, it throws "messages[0].content must be a string".
let targetModel = modelName || 'llama-3.2-11b-vision-preview';
// STRICT CHECK: If the model name does not contain "vision", force it to the default vision model.
// This prevents users from accidentally using text-only models (like llama3-8b-8192) which causes crashes.
// EXCEPTION: Llama 4 Preview models (Maverick/Scout) support vision but don't have "vision" in ID.
if (!targetModel.includes('vision') && !targetModel.includes('llama-4')) {
console.log("Detected non-vision model for Groq:", targetModel, "Forcing llama-3.2-11b-vision-preview");
targetModel = 'llama-3.2-11b-vision-preview';
}
const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: targetModel,
messages: [
{
role: "user",
content: [
{ type: "text", text: prompt },
{ type: "image_url", image_url: { url: imageBase64 } }
]
}
],
stream: false,
temperature: 0.1, // Low temperature for factual analysis
max_tokens: 512
})
});
if (!response.ok) {
const errText = await response.text();
throw new Error(`Groq API Error: ${errText}`);
}
const data = await response.json();
const content = data.choices[0].message.content;
try {
return JSON.parse(content);
} catch (e) {
const jsonMatch = content.match(/\{[\s\S]*\}/);
if (jsonMatch) return JSON.parse(jsonMatch[0]);
throw new Error("Could not parse Groq JSON response");
}
}
}