-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1461 lines (1387 loc) · 67.8 KB
/
Copy pathscript.js
File metadata and controls
1461 lines (1387 loc) · 67.8 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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name AIMY Extension
// @namespace http://tampermonkey.net/
// @version 3.32
// @description PanoID → backend predict; per-pano dedupe + retry; smart map picker; shows current model epoch fetched from /api/v1/info.
// @author billy
// @match https://www.geoguessr.com/*
// @grant GM_xmlhttpRequest
// @grant GM.xmlHttpRequest
// @grant unsafeWindow
// @run-at document-start
// @require https://unpkg.com/leaflet@1.9.4/dist/leaflet.js
// @connect streetviewpixels-pa.googleapis.com
// @connect cbk0.google.com
// @connect 192.168.0.12
// @connect 127.0.0.1
// @connect localhost
// ==/UserScript==
(function() {
'use strict';
// Your geoai-serve instance (host:port). Everything else is derived from it.
const SERVER = 'http://192.168.0.12:6301';
const PREDICT_URL = SERVER + '/api/v1/predict';
const PREDICT_STREAM_URL = SERVER + '/api/v1/predict_stream';
const EXPLAIN_URL = SERVER + '/api/v1/explain';
// Runtime toggleable via the in-overlay switch. Persisted to
// localStorage. Initial defaults if nothing saved: auto-submit ON,
// overlay expanded.
let _autoSubmit = (() => {
try { const v = localStorage.getItem('aimy-autoguess'); return v === null ? true : v === '1'; }
catch (e) { return true; }
})();
let _collapsed = (() => {
try { return localStorage.getItem('aimy-collapsed') === '1'; }
catch (e) { return false; }
})();
// Prediction mode, sent as `cascade` on every predict POST. Two modes:
// 'fast' (Stage 1 = ProtoNet-select) and 'refined' (+ Stage 2 OCR/VLM).
let _cascade = (() => {
// Only two modes now: 'fast' (Stage 1 = ProtoNet-select) and 'refined'
// (+ Stage 2). Migrate any legacy value (plain/country_only/joint/fancy)
// to 'fast' — they all collapse to the same Stage-1 path server-side.
try {
const v = localStorage.getItem('aimy-cascade');
return v === 'refined' ? 'refined' : 'fast';
} catch (e) { return 'fast'; }
})();
const DEBUG_NET = false; // true → log every Geoguessr-internal fetch/XHR with body+response
const ZOOM = 3; // 8x4 = 32 tiles, ~4096x2048 stitched
const TILE_SIZE = 512;
// unsafeWindow gives us the page's REAL window — bypassing Tampermonkey's
// sandbox proxy. Needed to access google.maps and patch the actual fetch
// the page uses (Geoguessr's CSP blocks inline <script> injection).
const W = (typeof unsafeWindow !== 'undefined') ? unsafeWindow : window;
// Patch google.maps.Map in PAGE context to capture each Map instance.
// Polling lost the race on slow loads. Instead: hook the moment google
// gets assigned to window, then the moment .maps gets assigned to that,
// then wrap .Map. This catches the API load before any Map is created.
function wrapMapClass(MapCls) {
if (!MapCls || MapCls.__aimy_patched) return MapCls;
function Wrapped(...args) {
const map = new MapCls(...args);
(W.__aimy_maps = W.__aimy_maps || []).push(map);
return map;
}
Wrapped.prototype = MapCls.prototype;
Object.assign(Wrapped, MapCls);
Wrapped.__aimy_patched = true;
return Wrapped;
}
(function setupMapsHook() {
// Attempt 1: if Maps already loaded, patch in place.
try {
if (W.google && W.google.maps && W.google.maps.Map) {
W.google.maps.Map = wrapMapClass(W.google.maps.Map);
console.log('[aimy] Map class patched in place');
}
} catch (e) {}
// Attempt 2: property setter on google → maps → Map.
try {
if (!Object.getOwnPropertyDescriptor(W, 'google') ||
Object.getOwnPropertyDescriptor(W, 'google').configurable) {
let _google = W.google;
Object.defineProperty(W, 'google', {
configurable: true,
get() { return _google; },
set(v) {
_google = v;
if (!v || v.__aimy_hooked) return;
v.__aimy_hooked = true;
let _maps = v.maps;
if (_maps && _maps.Map && !_maps.Map.__aimy_patched) {
_maps.Map = wrapMapClass(_maps.Map);
}
try {
Object.defineProperty(v, 'maps', {
configurable: true,
get() { return _maps; },
set(m) {
_maps = m;
if (m && m.Map && !m.Map.__aimy_patched) {
let _MapClass = wrapMapClass(m.Map);
try {
Object.defineProperty(m, 'Map', {
configurable: true,
get() { return _MapClass; },
set(c) { _MapClass = wrapMapClass(c); }
});
} catch (e2) {}
console.log('[aimy] Map patched via property hook');
}
}
});
} catch (e2) {}
}
});
}
} catch (e) { /* property already non-configurable */ }
// Attempt 3: keep polling forever in case 1 & 2 missed. Cheap.
// Also patches the Map.prototype methods so any USE of an existing
// Map (created before our script ran, or via a constructor-bypass)
// captures the instance into __aimy_maps. This is the strongest of
// the four because it doesn't depend on catching the constructor.
const pollInt = setInterval(() => {
try {
if (W.google && W.google.maps && W.google.maps.Map &&
!W.google.maps.Map.__aimy_patched) {
W.google.maps.Map = wrapMapClass(W.google.maps.Map);
console.log('[aimy] Map class patched via poll');
}
hookMapPrototype();
hookStreetViewPanoramaPrototype();
} catch (e) {}
}, 250);
setTimeout(() => clearInterval(pollInt), 60_000);
})();
// Patch instance methods so the instance gets tracked the moment it's
// used — independent of how it was constructed. Geoguessr's guess map
// calls setCenter / panTo / addListener routinely, so this catches it
// even if every constructor-level hook missed.
function hookMapPrototype() {
if (!W.google || !W.google.maps || !W.google.maps.Map) return;
const proto = W.google.maps.Map.prototype;
if (proto.__aimy_proto_hooked) return;
proto.__aimy_proto_hooked = true;
// Methods that prove a Map instance is in active use (track-or-skip).
const methods = ['setCenter', 'panTo', 'setZoom', 'fitBounds'];
for (const m of methods) {
const orig = proto[m];
if (typeof orig !== 'function') continue;
proto[m] = function(...args) {
if (!this.__aimy_tracked) {
this.__aimy_tracked = true;
(W.__aimy_maps = W.__aimy_maps || []).push(this);
console.log(`[aimy] Map tracked via .${m}() prototype hook`);
}
return orig.apply(this, args);
};
}
// addListener is special — we ALSO note when 'click' is registered.
// The interactive guess map registers 'click' fresh each round; the
// read-only results-display map does not. Picking the map with the
// most recent 'click' listener ensures we trigger placePin on the
// right instance.
const origAddListener = proto.addListener;
if (typeof origAddListener === 'function') {
proto.addListener = function(eventName) {
if (!this.__aimy_tracked) {
this.__aimy_tracked = true;
(W.__aimy_maps = W.__aimy_maps || []).push(this);
console.log('[aimy] Map tracked via .addListener() prototype hook');
}
if (eventName === 'click') {
this.__aimy_click_listener_at = Date.now();
}
return origAddListener.apply(this, arguments);
};
}
}
// Hook StreetViewPanorama.prototype.setPano so we catch pano-change events
// when Geoguessr re-uses the same widget across duels rounds (the metadata
// RPC only fires on the first pano; subsequent rounds just call setPano on
// the existing panorama instance).
function hookStreetViewPanoramaPrototype() {
if (!W.google || !W.google.maps || !W.google.maps.StreetViewPanorama) return;
const proto = W.google.maps.StreetViewPanorama.prototype;
if (proto.__aimy_sv_hooked) return;
proto.__aimy_sv_hooked = true;
const origSetPano = proto.setPano;
if (typeof origSetPano === 'function') {
proto.setPano = function(panoID) {
// Remember the most-recent panorama instance so we can later
// query its `getPano()` to find the *currently visible* pano
// (used to identify the round-start pano after the gate
// clears, since by then no fresh setPano typically fires).
_activePanorama = this;
if (typeof panoID === 'string' && panoID.length > 5) {
onPanoIDDetected(panoID).catch(e =>
console.warn('[aimy] onPanoIDDetected (setPano) threw:', e));
}
return origSetPano.apply(this, arguments);
};
console.log('[aimy] StreetViewPanorama.setPano hooked');
}
}
// Most-recent StreetViewPanorama instance, captured by the setPano
// prototype hook. Used to ask "what pano is the user currently looking
// at?" — the canonical signal for which pano to predict on, regardless
// of whether a fresh setPano event has fired recently.
let _activePanorama = null;
function getCurrentPanoFromPanorama() {
if (!_activePanorama) return null;
try {
const p = _activePanorama.getPano && _activePanorama.getPano();
return (typeof p === 'string' && p.length > 5) ? p : null;
} catch (e) { return null; }
}
// Last-resort fallback: walk the DOM for existing Map instances stored on
// `.gm-style` parent divs as `__gm` (Google's internal property). Used when
// none of the constructor patches caught the Map.
function findMapInDom() {
const stylis = document.querySelectorAll('.gm-style');
const isMap = (v) => v && typeof v === 'object' &&
typeof v.panTo === 'function' &&
typeof v.setCenter === 'function' &&
typeof v.getCenter === 'function';
for (const el of stylis) {
let node = el;
for (let d = 0; d < 6 && node; d++) {
for (const k of Object.getOwnPropertyNames(node)) {
const v = node[k];
if (isMap(v)) return v;
if (v && typeof v === 'object' && isMap(v.map)) return v.map;
if (v && typeof v === 'object' && isMap(v.gm_map)) return v.gm_map;
}
node = node.parentElement;
}
}
return null;
}
// ── Network sniffer (DEBUG_NET) ────────────────────────────────────
// Patch via unsafeWindow so we hook the page's REAL fetch/XHR (CSP
// blocks inline-script injection, so we can't run code in page context
// any other way). Logs Geoguessr-internal calls only.
if (DEBUG_NET) {
const isInteresting = (u) =>
/geoguessr\.com\/api/.test(u) ||
/game-server\.geoguessr\.com/.test(u);
const origFetch = W.fetch.bind(W);
W.fetch = async function(input, init) {
const url = typeof input === 'string' ? input : (input && input.url) || '';
const method = (init && init.method) || (input && input.method) || 'GET';
if (isInteresting(url)) {
let body = init && init.body;
if (body && typeof body !== 'string') body = '[non-string body]';
console.log('%c[net] ' + method + ' ' + url, 'color:#9cf',
body ? 'body=' + String(body).slice(0, 400) : '');
}
const resp = await origFetch.apply(W, arguments);
if (isInteresting(url)) {
resp.clone().text()
.then(t => console.log('%c[net] <- ' + resp.status + ' ' + url, 'color:#9c9', t.slice(0, 600)))
.catch(() => {});
}
return resp;
};
const origOpen = W.XMLHttpRequest.prototype.open;
const origSend = W.XMLHttpRequest.prototype.send;
W.XMLHttpRequest.prototype.open = function(method, url) {
this.__aimy_m = method;
this.__aimy_u = url;
return origOpen.apply(this, arguments);
};
W.XMLHttpRequest.prototype.send = function(body) {
const url = this.__aimy_u || '';
if (isInteresting(url)) {
console.log('%c[net-xhr] ' + this.__aimy_m + ' ' + url, 'color:#fc9',
body ? 'body=' + String(body).slice(0, 400) : '');
this.addEventListener('load', () => {
console.log('%c[net-xhr] <- ' + this.status + ' ' + url, 'color:#9c9',
(this.responseText || '').slice(0, 600));
});
}
return origSend.apply(this, arguments);
};
console.log('[aimy] DEBUG_NET hooks installed via unsafeWindow');
}
let globalPanoID = undefined;
let roundNumber = 1;
// Dedupe predict + autoGuess by panoID. Geoguessr re-fires the metadata
// RPC for the same pano during the results screen of duels (and similar
// mid-round scenarios), which without dedupe spawns repeated predict +
// autoGuess attempts. Bounded set; keeps last 50 panoIDs to avoid leaks.
const _predictedPanoIDs = new Set();
const MAX_TRACKED_PANOS = 100;
let _currentAutoGuessPano = null; // tracks the active retry's pano for abort-on-new-round
// Cross-mode round-detection: ALL the gate/state-machine logic was ripped
// out (it kept breaking across game modes). Replaced with a simpler
// per-pano flow inside onPanoIDDetected:
// 1. Wait for the guess button to appear (= "live round").
// 2. Verify the panorama is STILL on this pano (via getPano()) — if
// it's moved on, this pano-id event is stale, abandon.
// 3. Predict + autoGuess.
// Each pano-id event runs independently. Intermediate walk panos
// naturally fall out because by the time the button reappears, the
// panorama has moved past them.
const PANO_BUTTON_WAIT_MS = 90_000; // max wait for button per pano
function isNewGame() { return roundNumber === 1; }
function getGameID() { return window.location.pathname.split('/')[2]; }
async function wait(ms) { return new Promise(r => setTimeout(r, ms)); }
// Team-duels uses gs2.geoguessr.com/{sessionId-32hex}/{roundId-24hex}/guess
// and the page only knows those IDs from a separate state-fetch call.
// Hook fetch/XHR via unsafeWindow to capture the latest pair so submitGuess
// can construct the URL when it's time to guess.
const _teamDuelsCtx = { sessionId: null, roundId: null };
(function hookTeamDuelsIds() {
const re = /gs2\.geoguessr\.com\/([a-f0-9]{32})\/([a-f0-9]{24})\b/;
const stash = (url) => {
const m = re.exec(url || '');
if (m) {
_teamDuelsCtx.sessionId = m[1];
_teamDuelsCtx.roundId = m[2];
}
};
try {
const origFetch = W.fetch.bind(W);
W.fetch = function(input, init) {
stash(typeof input === 'string' ? input : (input && input.url));
return origFetch.apply(W, arguments);
};
const origOpen = W.XMLHttpRequest.prototype.open;
W.XMLHttpRequest.prototype.open = function(method, url) {
stash(url);
return origOpen.apply(this, arguments);
};
} catch (e) {
console.warn('[aimy] failed to hook team-duels ID sniffer:', e);
}
})();
let _map = null, _finalMarker = null;
// Inline map is hidden by default and created lazily on first reveal.
let _mapOn = (() => {
try { return localStorage.getItem('aimy-map-on') === '1'; }
catch (e) { return false; }
})();
let _lastLat = null, _lastLng = null;
const PIN_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="34" viewBox="0 0 24 34">' +
'<path d="M12 0C5.4 0 0 5.4 0 12c0 9 12 22 12 22s12-13 12-22c0-6.6-5.4-12-12-12z" ' +
'fill="#ef4444" stroke="#fff" stroke-width="1.6"/>' +
'<circle cx="12" cy="12" r="4" fill="#fff"/>' +
'</svg>';
function ensureLeafletCSS() {
if (document.getElementById('aimy-leaflet-css')) return;
const link = document.createElement('link');
link.id = 'aimy-leaflet-css';
link.rel = 'stylesheet';
link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
document.head.appendChild(link);
}
function injectStyles() {
if (document.getElementById('aimy-styles')) return;
const s = document.createElement('style');
s.id = 'aimy-styles';
s.textContent = `
#aimy-overlay {
position: fixed; top: 14px; right: 14px; z-index: 999999;
width: 268px;
background: rgba(22,24,30,0.94);
-webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px);
color: #e8eaed; border-radius: 12px;
box-shadow: 0 10px 34px rgba(0,0,0,0.5),
0 0 0 1px rgba(255,255,255,0.06);
font-family: 'Neue Helvetica','Helvetica Neue',-apple-system,
BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif;
font-size: 12px; line-height: 1.4;
overflow: hidden; user-select: none;
-webkit-font-smoothing: antialiased;
}
#aimy-header {
display: flex; align-items: center; justify-content: space-between;
height: 34px; padding: 0 7px 0 11px; cursor: grab;
border-bottom: 1px solid rgba(255,255,255,0.06);
}
#aimy-header:active { cursor: grabbing; }
/* Empty flexible drag region on the header's left side. */
#aimy-grip { flex: 1; align-self: stretch; }
.aimy-hcontrols { display: flex; align-items: center; gap: 8px; }
#aimy-cascade {
background: rgba(255,255,255,0.07); color: #d6d9df;
border: 1px solid rgba(255,255,255,0.12); border-radius: 6px;
font: 600 10.5px/1 inherit; padding: 3px 5px;
outline: none; cursor: pointer;
}
#aimy-cascade option { background: #1c1e24; color: #e8eaed; }
.aimy-switch {
display: inline-flex; align-items: center; gap: 6px; cursor: pointer;
font-size: 10.5px; font-weight: 600;
color: rgba(232,234,237,0.55); transition: color 140ms;
}
.aimy-switch:hover { color: rgba(232,234,237,0.85); }
.aimy-switch .aimy-dot {
width: 22px; height: 13px; border-radius: 999px;
background: rgba(255,255,255,0.12); position: relative;
transition: background 180ms cubic-bezier(.16,1,.3,1);
}
.aimy-switch .aimy-dot::after {
content: ""; position: absolute; top: 2px; left: 2px;
width: 9px; height: 9px; border-radius: 50%; background: #cfd2d8;
transition: transform 180ms cubic-bezier(.16,1,.3,1), background 180ms;
}
.aimy-switch.on { color: #e8eaed; }
.aimy-switch.on .aimy-dot { background: #6cbe3f; }
.aimy-switch.on .aimy-dot::after { transform: translateX(9px); background: #fff; }
#aimy-collapse {
width: 22px; height: 22px; display: flex; align-items: center;
justify-content: center; color: rgba(232,234,237,0.5);
cursor: pointer; border-radius: 6px;
transition: background 120ms, color 120ms,
transform 220ms cubic-bezier(.16,1,.3,1);
}
#aimy-collapse:hover { background: rgba(255,255,255,0.06); color: #e8eaed; }
#aimy-collapse svg { width: 12px; height: 12px; }
#aimy-body { padding: 11px 13px 12px; user-select: text; }
.aimy-place {
font-size: 13px; font-weight: 600; color: #f1f3f6; line-height: 1.35;
}
.aimy-coords {
font-family: ui-monospace,'SF Mono',Menlo,monospace;
font-size: 11px; color: #7f8794; margin-top: 4px;
font-feature-settings: "tnum"; letter-spacing: -0.01em;
}
.aimy-fallback {
display: inline-block; margin-left: 6px; padding: 1px 6px;
background: rgba(245,158,11,0.14); color: #f6b73c;
border-radius: 5px; font-size: 9.5px; font-weight: 600;
vertical-align: middle;
}
.aimy-s2-badge {
display: inline-block; margin-left: 6px; padding: 1px 6px;
background: rgba(108,190,63,0.16); color: #8fd25e;
border-radius: 5px; font-size: 9.5px; font-weight: 700;
vertical-align: middle; text-transform: uppercase; letter-spacing: 0.04em;
}
.aimy-s2-status {
margin-top: 8px; padding: 5px 8px;
background: rgba(108,190,63,0.09); border-radius: 6px;
font-size: 10.5px; color: #8fd25e;
font-family: ui-monospace,'SF Mono',Menlo,monospace;
animation: aimy-s2-pulse 1.4s ease-in-out infinite;
}
@keyframes aimy-s2-pulse { 0%,100% { opacity: .85; } 50% { opacity: .45; } }
.aimy-s2-explain {
margin-top: 8px; padding: 6px 8px;
background: rgba(108,190,63,0.06);
border-left: 2px solid rgba(108,190,63,0.4); border-radius: 4px;
font-size: 10.5px; color: #9aa3b3; line-height: 1.4; font-style: italic;
}
.aimy-btnrow { display: flex; gap: 7px; margin-top: 11px; }
#aimy-maptoggle, #aimy-explain {
appearance: none; flex: 1;
background: rgba(255,255,255,0.05); color: #aeb4c0;
border: 1px solid rgba(255,255,255,0.08); border-radius: 7px;
font: 600 10.5px/1 inherit; padding: 7px; cursor: pointer;
letter-spacing: 0.04em; text-transform: uppercase;
transition: background 120ms, color 120ms;
}
#aimy-maptoggle:hover, #aimy-explain:hover {
background: rgba(255,255,255,0.09); color: #e8eaed;
}
#aimy-explain { color: #8fd25e; border-color: rgba(108,190,63,0.25); }
#aimy-explain:hover { background: rgba(108,190,63,0.12); color: #a7e072; }
#aimy-explain.busy { opacity: 0.6; cursor: wait; }
/* Fullscreen heatmap viewer */
#aimy-lightbox {
position: fixed; inset: 0; z-index: 2147483000;
display: none; align-items: center; justify-content: center;
flex-direction: column; gap: 14px;
background: rgba(6,7,10,0.86); -webkit-backdrop-filter: blur(3px);
backdrop-filter: blur(3px); cursor: zoom-out;
}
#aimy-lightbox.on { display: flex; }
#aimy-lightbox img {
max-width: 96vw; max-height: 78vh; border-radius: 8px;
box-shadow: 0 12px 50px rgba(0,0,0,0.7);
image-rendering: auto;
}
#aimy-lightbox .aimy-lb-cap {
color: #cfd3da; font: 600 12px/1.4 'Helvetica Neue',system-ui,sans-serif;
letter-spacing: 0.02em; text-align: center; max-width: 90vw;
}
#aimy-lightbox .aimy-lb-cap b { color: #8fd25e; }
#aimy-lightbox .aimy-lb-spin {
color: #8fd25e; font: 600 13px/1 system-ui,sans-serif;
animation: aimy-s2-pulse 1.2s ease-in-out infinite;
}
#aimy-map {
margin-top: 9px; height: 168px; border-radius: 8px;
overflow: hidden; background: #0d0f14; display: none;
}
#aimy-overlay.map-on #aimy-map { display: block; }
/* ─── Collapsed state: shrink to a small round launcher ─────── */
#aimy-fab {
display: none;
width: 44px; height: 44px; border-radius: 50%;
align-items: center; justify-content: center;
cursor: pointer; color: #6cbe3f;
background: rgba(22,24,30,0.96);
box-shadow: 0 6px 20px rgba(0,0,0,0.5),
0 0 0 1px rgba(108,190,63,0.45) inset;
transition: transform 140ms cubic-bezier(.16,1,.3,1), color 140ms;
}
#aimy-fab:hover { transform: scale(1.06); color: #8fd25e; }
#aimy-fab:active { cursor: grabbing; }
#aimy-fab svg { width: 20px; height: 20px; }
/* When collapsed, the card chrome vanishes and only the circle
remains — the overlay itself becomes transparent and auto-sized
so it's just the 44px launcher. */
#aimy-overlay.aimy-collapsed {
width: auto; background: transparent; overflow: visible;
box-shadow: none; -webkit-backdrop-filter: none; backdrop-filter: none;
}
#aimy-overlay.aimy-collapsed #aimy-header,
#aimy-overlay.aimy-collapsed #aimy-body { display: none; }
#aimy-overlay.aimy-collapsed #aimy-fab { display: flex; }
`;
document.head.appendChild(s);
}
function makeDraggable(handles, target) {
// One-time cleanup of a stale key from an older resizable build —
// a leftover inline width/height would pin the overlay's size and
// stop it shrinking to the collapsed circle.
try { localStorage.removeItem('aimy-overlay-size'); } catch (e) {}
// Restore last position from localStorage (per-domain).
try {
const saved = JSON.parse(localStorage.getItem('aimy-overlay-pos') || 'null');
if (saved && typeof saved.x === 'number' && typeof saved.y === 'number') {
target.style.left = `${saved.x}px`;
target.style.top = `${saved.y}px`;
target.style.right = 'auto';
}
} catch (e) {}
let dx = 0, dy = 0, dragging = false, moved = false, activeHandle = null;
for (const handle of [].concat(handles)) {
handle.addEventListener('mousedown', (e) => {
if (e.target.closest('#aimy-collapse')) return;
if (e.target.closest('.aimy-switch')) return;
dragging = true; moved = false; activeHandle = handle;
const r = target.getBoundingClientRect();
dx = e.clientX - r.left;
dy = e.clientY - r.top;
e.preventDefault();
});
}
document.addEventListener('mousemove', (e) => {
if (!dragging) return;
moved = true;
const x = Math.max(0, Math.min(window.innerWidth - target.offsetWidth, e.clientX - dx));
const y = Math.max(0, Math.min(window.innerHeight - target.offsetHeight, e.clientY - dy));
target.style.left = `${x}px`;
target.style.top = `${y}px`;
target.style.right = 'auto';
});
document.addEventListener('mouseup', () => {
if (!dragging) return;
dragging = false;
// Flag a real drag on the launcher so its click handler doesn't
// also expand the card after a reposition.
if (moved && activeHandle && activeHandle.id === 'aimy-fab') {
activeHandle.dataset.dragged = '1';
}
activeHandle = null;
if (!moved) return;
try {
const r = target.getBoundingClientRect();
localStorage.setItem('aimy-overlay-pos', JSON.stringify({ x: r.left, y: r.top }));
} catch (e) {}
});
}
function ensureOverlay() {
let el = document.getElementById('aimy-overlay');
if (el) return el;
ensureLeafletCSS();
injectStyles();
el = document.createElement('div');
el.id = 'aimy-overlay';
el.innerHTML = `
<div id="aimy-header">
<span id="aimy-grip" title="drag"></span>
<div class="aimy-hcontrols">
<select id="aimy-cascade" title="prediction mode">
<option value="fast">Stage 1</option>
<option value="refined">+ Stage 2</option>
</select>
<span class="aimy-switch" id="aimy-auto" title="toggle auto-guess">
<span>Auto</span><span class="aimy-dot"></span>
</span>
<span id="aimy-collapse" title="collapse / expand">
<svg viewBox="0 0 14 14" fill="none">
<path d="M3 5l4 4 4-4" stroke="currentColor" stroke-width="1.8"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</span>
</div>
</div>
<div id="aimy-body">
<div class="aimy-place" id="aimy-place">—</div>
<div class="aimy-coords" id="aimy-coords"></div>
<div class="aimy-s2-status" id="aimy-s2-status" style="display:none;"></div>
<div class="aimy-s2-explain" id="aimy-s2-explain" style="display:none;"></div>
<div class="aimy-btnrow">
<button id="aimy-maptoggle">show map</button>
<button id="aimy-explain" title="show what the model looked at">explain</button>
</div>
<div id="aimy-map"></div>
</div>
<div id="aimy-fab" title="open AIMY">
<svg viewBox="0 0 24 24" fill="none">
<path d="M12 2C8.1 2 5 5.1 5 9c0 5.2 7 13 7 13s7-7.8 7-13c0-3.9-3.1-7-7-7z"
fill="currentColor" stroke="rgba(0,0,0,0.35)" stroke-width="1"/>
<circle cx="12" cy="9" r="2.6" fill="#15171e"/>
</svg>
</div>
`;
document.body.appendChild(el);
if (_collapsed) el.classList.add('aimy-collapsed');
if (_mapOn) el.classList.add('map-on');
const setCollapsed = (v) => {
_collapsed = v;
el.classList.toggle('aimy-collapsed', _collapsed);
try { localStorage.setItem('aimy-collapsed', _collapsed ? '1' : '0'); } catch (e2) {}
if (!_collapsed && _mapOn && _map) setTimeout(() => _map.invalidateSize(), 60);
};
const collapseBtn = document.getElementById('aimy-collapse');
collapseBtn.onclick = (e) => { e.stopPropagation(); setCollapsed(true); };
// The collapsed launcher: a click re-opens the card. A drag (handled
// by makeDraggable below) repositions it without triggering expand.
const fab = document.getElementById('aimy-fab');
fab.onclick = (e) => {
e.stopPropagation();
if (fab.dataset.dragged === '1') { fab.dataset.dragged = ''; return; }
setCollapsed(false);
};
const autoBtn = document.getElementById('aimy-auto');
const syncAutoBtn = () => autoBtn.classList.toggle('on', _autoSubmit);
syncAutoBtn();
autoBtn.onclick = (e) => {
e.stopPropagation();
_autoSubmit = !_autoSubmit;
try { localStorage.setItem('aimy-autoguess', _autoSubmit ? '1' : '0'); } catch (e2) {}
syncAutoBtn();
console.log(`[aimy] autoguess ${_autoSubmit ? 'ENABLED' : 'DISABLED'}`);
};
const cascadeSel = document.getElementById('aimy-cascade');
if (cascadeSel) {
cascadeSel.value = _cascade;
cascadeSel.onmousedown = (e) => e.stopPropagation();
cascadeSel.onclick = (e) => e.stopPropagation();
cascadeSel.onchange = (e) => {
e.stopPropagation();
_cascade = cascadeSel.value;
try { localStorage.setItem('aimy-cascade', _cascade); } catch (e2) {}
console.log(`[aimy] mode → ${_cascade}`);
};
}
// Inline map toggle — created lazily on first show (Leaflet needs a
// sized, visible container), centered on the latest prediction.
const mapToggle = document.getElementById('aimy-maptoggle');
const syncMapToggle = () => { mapToggle.textContent = _mapOn ? 'hide map' : 'show map'; };
syncMapToggle();
mapToggle.onclick = (e) => {
e.stopPropagation();
_mapOn = !_mapOn;
el.classList.toggle('map-on', _mapOn);
try { localStorage.setItem('aimy-map-on', _mapOn ? '1' : '0'); } catch (e2) {}
syncMapToggle();
if (_mapOn) ensureMap();
};
// Explain: ask the server for the occlusion heatmap of the current
// pano and show it in a fullscreen viewer.
const explainBtn = document.getElementById('aimy-explain');
explainBtn.onclick = async (e) => {
e.stopPropagation();
const pid = globalPanoID;
if (!pid) { openLightbox(null, 'no pano detected yet — load a round first'); return; }
if (explainBtn.classList.contains('busy')) return;
explainBtn.classList.add('busy');
openLightbox(null, 'reading the pano…');
try {
const { blob, headers } = await gmPostBlob(EXPLAIN_URL, { panoID: pid });
const sim = (headers.match(/x-explain-sim:\s*([\d.]+)/i) || [])[1];
const url = URL.createObjectURL(blob);
openLightbox(url, sim
? `prototype match <b>${sim}</b> — brighter red = the model relied on it more`
: 'brighter red = the model relied on that region more');
} catch (err) {
openLightbox(null, 'explain failed: ' + (err.message || err));
} finally {
explainBtn.classList.remove('busy');
}
};
makeDraggable([document.getElementById('aimy-header'), fab], el);
return el;
}
// Lazily build the inline Leaflet map (only when revealed — Leaflet needs
// a sized, visible container) and point it at the latest prediction.
function ensureMap() {
if (typeof L === 'undefined') return;
if (_lastLat == null || _lastLng == null) return;
if (!_map) {
_map = L.map('aimy-map', {
zoomControl: true, attributionControl: false,
}).setView([_lastLat, _lastLng], 6);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
}).addTo(_map);
}
if (_finalMarker) _finalMarker.setLatLng([_lastLat, _lastLng]);
else {
const icon = L.divIcon({
className: '', html: PIN_SVG,
iconSize: [24, 34], iconAnchor: [12, 34],
});
_finalMarker = L.marker([_lastLat, _lastLng], { icon }).addTo(_map);
}
_map.setView([_lastLat, _lastLng], 6);
setTimeout(() => _map && _map.invalidateSize(), 50);
}
// ─── Fullscreen heatmap viewer (the /explain overlay) ────────────────
let _lbUrl = null;
function ensureLightbox() {
let lb = document.getElementById('aimy-lightbox');
if (lb) return lb;
lb = document.createElement('div');
lb.id = 'aimy-lightbox';
lb.innerHTML =
'<div class="aimy-lb-spin">reading…</div>' +
'<img alt="model attention" style="display:none;">' +
'<div class="aimy-lb-cap"></div>';
lb.onclick = () => closeLightbox();
document.body.appendChild(lb);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') closeLightbox();
});
return lb;
}
function openLightbox(url, captionHTML) {
const lb = ensureLightbox();
const img = lb.querySelector('img');
const spin = lb.querySelector('.aimy-lb-spin');
const cap = lb.querySelector('.aimy-lb-cap');
if (_lbUrl) { URL.revokeObjectURL(_lbUrl); _lbUrl = null; }
if (url) {
_lbUrl = url;
img.src = url; img.style.display = '';
spin.style.display = 'none';
} else {
img.removeAttribute('src'); img.style.display = 'none';
spin.style.display = '';
}
cap.innerHTML = captionHTML || '';
lb.classList.add('on');
}
function closeLightbox() {
const lb = document.getElementById('aimy-lightbox');
if (lb) lb.classList.remove('on');
if (_lbUrl) { URL.revokeObjectURL(_lbUrl); _lbUrl = null; }
}
function showPrediction(data, round, panoID) {
ensureOverlay();
const lat = data.lat ?? data.final_lat;
const lng = data.lng ?? data.final_lng;
if (typeof lat !== 'number' || typeof lng !== 'number') return;
_lastLat = lat; _lastLng = lng;
// Coords + reverse-geocoded name.
document.getElementById('aimy-coords').textContent =
`${lat.toFixed(5)}, ${lng.toFixed(5)}`;
const placeBits = [data.admin2, data.admin1, data.country].filter(Boolean);
const fb = data.fallback_used
? ` <span class="aimy-fallback">L9 fallback</span>` : '';
// Stage 2 precision badge: only when refined cascade actually used the refinement.
let s2Badge = '';
if (data.stage2_used) {
s2Badge = ` <span class="aimy-s2-badge" title="Stage 2 refined ` +
`(${(data.stage2_precision || 'city')})">S2·${data.stage2_precision || 'city'}</span>`;
}
// ProtoNet-selector badge: shows it picked this L9 cell by image-feature
// match (over the top-K candidates) and how confident the match was.
let pnBadge = '';
if (data.protonet_select && data.protonet_select.selected) {
const sim = (data.protonet_select.top_sim ?? 0).toFixed(2);
const k = data.protonet_select.select_k ?? '';
pnBadge = ` <span class="aimy-s2-badge" title="ProtoNet selected this L9 cell ` +
`by image similarity over top-${k} candidates">PN·${sim}</span>`;
}
document.getElementById('aimy-place').innerHTML =
(placeBits.length ? placeBits.join(', ') : '—') + fb + s2Badge + pnBadge;
// Stage 2 explanation panel: visible when Stage 2 actually
// refined the prediction. When Stage 2 defers to Stage 1, that
// usually means Stage 1's cell-head guess is already as specific
// as the image evidence supports — so we hide the panel rather
// than display a confusing "no refinement" message.
const expEl = document.getElementById('aimy-s2-explain');
if (expEl) {
if (data.stage2_used && data.stage2_explanation) {
expEl.textContent = data.stage2_explanation;
expEl.style.display = '';
} else if (data.stage2_error) {
// Real error path: show it (helps debugging).
expEl.textContent = 'Stage 2 error: ' + data.stage2_error;
expEl.style.display = '';
} else {
expEl.style.display = 'none';
}
}
// Update the inline map only when it's currently revealed.
if (_mapOn) ensureMap();
// writeText returns a Promise; sync try/catch misses the rejection
// that fires when the document isn't focused. Swallow via .catch.
try {
const p = navigator.clipboard && navigator.clipboard.writeText(
`${lat.toFixed(5)}, ${lng.toFixed(5)}`);
if (p && typeof p.catch === 'function') p.catch(() => {});
} catch (e) {}
}
// Drive the official UI flow: trigger a click on the guess Map at the
// predicted lat/lng (Geoguessr's React listener catches it, drops the
// pin, enables the Guess button), then click the Guess button. Same
// code path as a manual guess, so React state updates on its own — no
// reload needed.
// Single funnel for "we just saw a fresh pano". Called from both the
// XHR/metadata RPC hook AND StreetViewPanorama.setPano. Dedupe handles
// duplicate fires from either source.
// Polls the DOM for the live-guess button to appear. Returns when the
// button is visible+enabled, OR after maxMs elapses (returning false).
// The button is GG's authoritative signal that "you can submit a guess
// right now" — i.e. we're in a live round, not the result screen or
// an inter-round animation.
async function waitForGuessButton(maxMs) {
const t0 = Date.now();
while (Date.now() - t0 < maxMs) {
if (findGuessButton()) return true;
await wait(300);
}
return false;
}
async function onPanoIDDetected(panoID) {
if (typeof panoID !== 'string' || !panoID) return;
if (_predictedPanoIDs.has(panoID)) return;
_predictedPanoIDs.add(panoID);
if (_predictedPanoIDs.size > MAX_TRACKED_PANOS) {
const arr = Array.from(_predictedPanoIDs);
_predictedPanoIDs.clear();
arr.slice(-50).forEach(id => _predictedPanoIDs.add(id));
}
globalPanoID = panoID;
console.log(`[aimy] pano detected: ${panoID.slice(0,8)}…`);
// Wait for the guess button to appear. Multiple parallel calls (one
// per pano during a duels walk) all wait here simultaneously — only
// the one whose pano matches the panorama's current state when the
// button reappears will actually proceed.
const buttonAppeared = await waitForGuessButton(PANO_BUTTON_WAIT_MS);
if (!buttonAppeared) {
console.log(`[aimy] no guess button for ${panoID.slice(0,8)}… within `
+ `${PANO_BUTTON_WAIT_MS/1000}s — abandoning`);
return;
}
// Check the panorama is STILL showing this pano. If it's moved on
// (a later setPano fired and the panorama is parked elsewhere),
// this call is stale — abandon to avoid predicting on the wrong
// location. The panorama's current pano is the canonical "what the
// user sees right now".
const currentPano = getCurrentPanoFromPanorama();
if (currentPano && currentPano !== panoID) {
console.log(`[aimy] panorama moved (${panoID.slice(0,8)}… → `
+ `${currentPano.slice(0,8)}…) — abandoning stale`);
return;
}
try {
const data = await getCoordinates(panoID);
console.log(`prediction: ${data.lat}, ${data.lng}`,
data.country ? `(${data.country})` : '');
showPrediction(data, roundNumber, panoID);
if (_autoSubmit) {
autoGuessWithRetry(data.lat, data.lng, panoID).catch(e =>
console.warn('[aimy] autoGuess threw:', e));
}
} catch (e) {
console.warn('predict failed:', e.message || e);
}
roundNumber++;
}
// Retry wrapper: try autoGuess up to N times (because the Guess button
// can take a moment to appear after the round starts). Aborts if a newer
// panoID begins its own retry loop, so we don't double-fire on a stale pano.
async function autoGuessWithRetry(lat, lng, panoID, maxAttempts = 6, intervalMs = 3000) {
_currentAutoGuessPano = panoID;
for (let i = 0; i < maxAttempts; i++) {
if (_currentAutoGuessPano !== panoID) return false; // newer pano took over
const ok = await autoGuess(lat, lng, /*quiet=*/i > 0);
if (ok) return true;
await wait(intervalMs);
}
if (_currentAutoGuessPano === panoID) {
console.log(`[aimy] gave up auto-guessing for ${panoID} after ${maxAttempts} tries`);
}
return false;
}
function isMapVisible(m) {
try {
const d = m.getDiv();
return !!(d && d.offsetParent !== null);
} catch (e) { return true; }
}
function pickGuessMap() {
const maps = W.__aimy_maps || [];
// Prefer the map whose 'click' listener was registered most recently —
// that's the live guess map for the current round. Read-only results
// maps don't register 'click'.
let pick = null, bestT = 0;
for (const m of maps) {
const t = m.__aimy_click_listener_at || 0;
if (t > bestT && isMapVisible(m)) { bestT = t; pick = m; }
}
if (pick) return pick;
// Fallback: last-registered visible map
for (let i = maps.length - 1; i >= 0; i--) {
if (isMapVisible(maps[i])) return maps[i];
}
if (maps.length) return maps[maps.length - 1];
return findMapInDom();
}
async function autoGuess(lat, lng, quiet = false) {
if (!W.google || !W.google.maps) {
if (!quiet) console.warn('[aimy] google.maps not yet loaded — skipping autoguess');
return false;
}
const map = pickGuessMap();
if (!map) {
if (!quiet) console.warn('[aimy] no Map captured AND DOM fallback found nothing — manual guess required');
return false;
}
try {
const latLng = new W.google.maps.LatLng(lat, lng);