-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_ia_computer.js
More file actions
231 lines (206 loc) · 8.34 KB
/
20_ia_computer.js
File metadata and controls
231 lines (206 loc) · 8.34 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
// IA/HTML computation + request/response bridge for the popup.
(function installIAComputer() {
const NS = globalThis.__POSEYEDOM.content;
function getWindowOffset() {
try {
const cfg = NS.state && NS.state.config ? NS.state.config : null;
if (cfg && cfg.browserWindowOffset != null) return Math.max(0, Number(cfg.browserWindowOffset));
} catch (_) {}
return 91;
}
function parseISO(ts) {
const d = new Date(ts);
return Number.isNaN(d.getTime()) ? null : d;
}
function assignLabel(baseKey, currentPos, labelState) {
let info = labelState[baseKey];
if (!info) {
const baseLabel = `autolabel_${labelState._counter}`;
labelState._counter += 1;
info = { baseLabel, lastPos: null, nextSuffix: 1 };
labelState[baseKey] = info;
}
let label;
if (info.lastPos === currentPos) {
label = info.baseLabel;
} else {
if (info.lastPos === null) {
label = info.baseLabel;
} else {
label = `${info.baseLabel}_${info.nextSuffix}`;
info.nextSuffix += 1;
}
info.lastPos = currentPos;
}
return label;
}
function flushUnusedBaseLabels(activeRecords, labelState) {
const activeBases = new Set(Array.from(activeRecords.keys()).map((k) => k.split("::")[0]));
Object.keys(labelState).forEach((base) => {
if (base === "_counter") return;
if (!activeBases.has(base)) delete labelState[base];
});
}
function computeIAFromLogs(logs, opts = {}) {
const cfg = NS.state && NS.state.config ? NS.state.config : {};
const offsetMsInput = Number(opts.offsetMs || 0);
const windowOffset = Number.isFinite(opts.browserWindowOffset)
? Math.max(0, Number(opts.browserWindowOffset))
: getWindowOffset();
const ordered = [...(logs || [])].sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
if (ordered.length === 0) {
return { iasText: "# IA\tstart_time\tend_time\tshape\tID\tx\ty\tright\tbottom\tlabel\n", htmlMapping: {} };
}
const ipEntry = ordered.find((e) => e && e.coordinates && e.coordinates.message === "First 's' key press logged");
let baseEpochMs;
if (ipEntry) {
const ipTime = parseISO(ipEntry.coordinates.timestamp);
if (!ipTime) {
const firstTs = parseISO(ordered[0].timestamp);
if (!firstTs) throw new Error("No valid timestamps in logs.");
baseEpochMs = firstTs.getTime();
} else {
baseEpochMs = ipTime.getTime() - offsetMsInput;
}
} else {
const firstTs = parseISO(ordered[0].timestamp);
if (!firstTs) throw new Error("No valid timestamps in logs.");
baseEpochMs = firstTs.getTime();
}
const toRelativeMs = (ts) => {
const d = parseISO(ts);
if (!d) throw new Error(`Invalid log timestamp: ${ts}`);
return Math.max(0, Math.floor(d.getTime() - baseEpochMs));
};
const activeRecords = new Map(); // key -> rec
const labelState = { _counter: 1 };
const iaData = [];
const htmlMapping = {};
let nextId = 1;
let lastCoordIso = null;
for (const entry of ordered) {
const isCoordLog = entry && entry.coordinates && Array.isArray(entry.coordinates.coordinates);
if (!isCoordLog) continue;
const currentMs = toRelativeMs(entry.timestamp);
const coordsWrap = entry.coordinates.coordinates || [];
const coords = coordsWrap.filter((c) => c && c.width && c.height);
const seenKeys = new Set();
if (!coords || coords.length === 0) {
for (const [key, rec] of Array.from(activeRecords.entries())) {
rec.end = currentMs;
iaData.push(rec);
activeRecords.delete(key);
}
flushUnusedBaseLabels(activeRecords, labelState);
lastCoordIso = entry.timestamp;
continue;
}
if (coords.length > 1) {
const __OFF = windowOffset;
const sorted = [...coords].sort((a, b) => a.y + __OFF - (b.y + __OFF));
let mergedHtml = "";
const ys = [],
xs = [],
rights = [],
bottoms = [];
let lastY = null;
for (const c of sorted) {
const x = c.x;
const y = c.y + __OFF;
if (lastY !== null && y > lastY) mergedHtml += "\n";
mergedHtml += c.html;
lastY = y;
ys.push(y);
xs.push(x);
rights.push(x + (c.width || 0));
bottoms.push(y + (c.height || 0));
}
const baseKey = `multi|${mergedHtml}`;
const posKey = `ys|${ys.join(",")}`;
const fullKey = `${baseKey}::${posKey}`;
seenKeys.add(fullKey);
const label = assignLabel(baseKey, posKey, labelState);
if (!activeRecords.has(fullKey)) {
const hM = Number.isFinite(opts.errorMarginH)
? Math.max(0, Number(opts.errorMarginH))
: Math.max(0, Number(cfg.errorMarginH != null ? cfg.errorMarginH : 0));
const vM = Number.isFinite(opts.errorMarginV)
? Math.max(0, Number(opts.errorMarginV))
: Math.max(0, Number(cfg.errorMarginV != null ? cfg.errorMarginV : 0));
const x0 = Math.min(...xs) - hM;
const y0 = Math.min(...ys) - vM;
const r0 = Math.max(...rights) + hM;
const b0 = Math.max(...bottoms) + vM;
const rec = { start: currentMs, end: currentMs, id: nextId++, label, html: mergedHtml, x: x0, y: y0, right: r0, bottom: b0 };
activeRecords.set(fullKey, rec);
htmlMapping[label] = mergedHtml;
} else {
activeRecords.get(fullKey).end = currentMs;
}
} else {
const c = coords[0];
const x = c.x;
const y = c.y + windowOffset;
const mergedHtml = c.html;
const baseKey = `single|${mergedHtml}|wh|${c.width}x${c.height}`;
const posKey = `y|${y}`;
const fullKey = `${baseKey}::${posKey}`;
seenKeys.add(fullKey);
const label = assignLabel(baseKey, posKey, labelState);
if (!activeRecords.has(fullKey)) {
const hM = Number.isFinite(opts.errorMarginH)
? Math.max(0, Number(opts.errorMarginH))
: Math.max(0, Number(cfg.errorMarginH != null ? cfg.errorMarginH : 0));
const vM = Number.isFinite(opts.errorMarginV)
? Math.max(0, Number(opts.errorMarginV))
: Math.max(0, Number(cfg.errorMarginV != null ? cfg.errorMarginV : 0));
const xAdj = x - hM;
const yAdj = y - vM;
const rightAdj = x + (c.width || 0) + hM;
const bottomAdj = y + (c.height || 0) + vM;
const rec = { start: currentMs, end: currentMs, id: nextId++, label, html: mergedHtml, x: xAdj, y: yAdj, right: rightAdj, bottom: bottomAdj };
activeRecords.set(fullKey, rec);
htmlMapping[label] = mergedHtml;
} else {
activeRecords.get(fullKey).end = currentMs;
}
}
for (const [key, rec] of Array.from(activeRecords.entries())) {
if (!seenKeys.has(key)) {
rec.end = currentMs;
iaData.push(rec);
activeRecords.delete(key);
}
}
flushUnusedBaseLabels(activeRecords, labelState);
lastCoordIso = entry.timestamp;
}
const finalMs = lastCoordIso ? toRelativeMs(lastCoordIso) : 0;
for (const rec of activeRecords.values()) {
rec.end = finalMs;
iaData.push(rec);
}
let iasText = "# IA\tstart_time\tend_time\tshape\tID\tx\ty\tright\tbottom\tlabel\n";
for (const rec of iaData) {
iasText += `-${rec.start}\t-${rec.end}\tRECTANGLE\t${rec.id}\t${rec.x.toFixed(2)}\t${rec.y.toFixed(2)}\t${rec.right.toFixed(2)}\t${rec.bottom.toFixed(2)}\t${rec.label}\n`;
}
return { iasText, htmlMapping };
}
NS.iaComputer = { computeIAFromLogs };
try {
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message && message.type === "compute_ia_html_from_logs") {
try {
const { logs, offsetMs, errorMarginH, errorMarginV, browserWindowOffset } = message;
const out = computeIAFromLogs(Array.isArray(logs) ? logs : [], { offsetMs, errorMarginH, errorMarginV, browserWindowOffset });
sendResponse({ ok: true, ...out });
} catch (e) {
sendResponse({ ok: false, error: e && e.message ? e.message : String(e) });
}
return true;
}
});
} catch (err) {
console.error("Failed to attach compute_ia_html_from_logs listener:", err);
}
})();