forked from ddupont808/GPT-4V-Act
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
308 lines (258 loc) · 8.93 KB
/
main.js
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
const { app, BrowserWindow, ipcMain, webContents } = require('electron')
const { promisify } = require('util');
const path = require('node:path')
const fs = require('fs/promises');
const sleep = promisify(setTimeout);
const OpenAIChatController = require('./chatgpt');
let win;
const controller = new OpenAIChatController();
const prompt = (task, info) => `task: ${task}
type ClickAction = { action: "click", element: number }
type TypeAction = { action: "type", element: number, text: string }
type ScrollAction = { action: "scroll", direction: "up" | "down" }
type RequestInfoFromUser = { action: "request-info", prompt: string }
type RememberInfoFromSite = { action: "remember-info", info: string }
type Done = { action: "done" }
## response format
{
briefExplanation: string,
nextAction: ClickAction | TypeAction | ScrollAction | RequestInfoFromUser | RememberInfoFromSite | Done
}
## response examples
{
"briefExplanation": "I'll type 'funny cat videos' into the search bar"
"nextAction": { "action": "type", "element": 11, "text": "funny cat videos" }
}
{
"briefExplanation": "Today's doodle looks interesting, I'll click it"
"nextAction": { "action": "click", "element": 9 }
}
{
"briefExplanation": "I have to login to create a post"
"nextAction": { "action": "request-info", "prompt": "What is your login information?" }
}
{
"briefExplanation": "Today's doodle is about Henrietta Lacks, I'll remember that for our blog post"
"nextAction": { "action": "remember-info", "info": "Today's doodle is about Henrietta Lacks" }
}
## stored info
${JSON.stringify(info)}
## instructions
# observe the screenshot, and think about the next action
# output your response in a json markdown code block
`;
function extractJsonFromMarkdown(mdString) {
const regex = /```json\s*([\s\S]+?)\s*```/; // This captures content between ```json and ```
const match = mdString.match(regex);
if (!match) return null; // No JSON block found
const jsonString = match[1].trim();
try {
return JSON.parse(jsonString);
} catch (err) {
console.error('Failed to parse JSON:', err);
return null; // Invalid JSON content
}
}
function createWindow() {
win = new BrowserWindow({
width: 1280,
height: 720,
titleBarStyle: 'hidden',
titleBarOverlay: {
color: '#18181b',
symbolColor: '#74b1be'
},
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
webviewTag: true,
contextIsolation: false
}
})
ipcMain.on('current-url', (event, url) => {
win.webContents.send('update-url', url);
});
win.loadFile('index.html')
}
app.whenReady().then(async () => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
});
let webview;
let labelData;
ipcMain.on('webview-ready', async (event, id) => {
webview = webContents.fromId(id);
console.log(`Acquired webviewId ${id}`);
});
ipcMain.on('label-data', (event, data) => {
labelData = JSON.parse(data);
});
async function screenshot() {
webview.send('observer', 'screenshot-start');
await sleep(100);
const image = await webview.capturePage();
webview.send('observer', 'screenshot-end');
await fs.writeFile('tmp/screenshot.png', image.toPNG());
await controller.uploadImage('tmp/screenshot.png');
}
async function exportLabel() {
webview.send('observer', 'screenshot-start');
await sleep(200);
const savedData = labelData;
webview.send('observer', 'screenshot-end');
await sleep(200);
const image = await webview.capturePage();
// Create unique filename
const timestamp = Date.now();
const screenshotFilename = `screenshot_${timestamp}.png`;
const {width, height} = image.getSize();
// Save the image with unique name
await fs.writeFile(`dataset/${screenshotFilename}`, image.toPNG());
let coco = JSON.parse(await fs.readFile('dataset/_annotations.coco.json'));
const image_id = Math.max(...coco.images.map(({ id }) => id), 0) + 1;
const annotations_id = Math.max(...coco.annotations.map(({ id }) => id), 0) + 1;
let annotations = savedData.reduce((all, { bboxs }, index) => {
let bbox_annotations = bboxs.map((bbox, bboxIndex) => {
return {
id: index + annotations_id + bboxIndex,
image_id,
category_id: 0,
bbox,
area: bbox[2] * bbox[3],
segmentation: [],
iscrowd: 0
}
});
return all.concat(bbox_annotations);
}, []);
coco.annotations = coco.annotations.concat(annotations);
// update coco image format for labeling
let cocoImageFormat = {
id: image_id,
width,
height,
file_name: screenshotFilename, // updated filename
license: 1,
date_captured: new Date()
};
coco.images.push(cocoImageFormat);
await fs.writeFile('dataset/_annotations.coco.json', JSON.stringify(coco, null, 2));
}
ipcMain.on('screenshot', async (event, id) => screenshot());
ipcMain.on('export', async (event, id) => exportLabel());
ipcMain.on('randomize', async (event, id) => {
function randomizeSize() {
const [minWidth, minHeight] = [1280, 720];
const [maxWidth, maxHeight] = [3440, 1440];
// Get the old window size and position
const [oldWidth, oldHeight] = win.getSize();
const [oldX, oldY] = win.getPosition();
// Generate new random size
const width = Math.floor(Math.random() * (maxWidth - minWidth + 1) + minWidth);
const height = Math.floor(Math.random() * (maxHeight - minHeight + 1) + minHeight);
// Compute new position to keep bottom-right corner in the same position
const x = oldX + (oldWidth - width);
const y = oldY + (oldHeight - height);
// Set new size and position
win.setSize(width, height, false);
win.setPosition(x, y, false);
}
const urls = JSON.parse(await fs.readFile('dataset/urls.json'));
for(let i = 0; i < 10; i++) {
webview.send('navigate-webview', 'loadURL', urls.shuffles[parseInt(Math.random() * urls.shuffles.length)]);
await sleep(5000);
for(let i = 0; i < 10; i++) {
randomizeSize();
await sleep(100);
webview.send('shuffle');
await sleep(1500);
await exportLabel();
}
}
for(let i = 0; i < 10; i++) {
webview.send('navigate-webview', 'loadURL', urls.random[parseInt(Math.random() * urls.random.length)]);
await sleep(5000);
for(let i = 0; i < 10; i++) {
randomizeSize();
await sleep(100);
webview.send('randomize');
await sleep(1500);
await exportLabel();
}
}
});
let currentTask;
ipcMain.on('send', async (event, text) => {
currentTask = text;
await screenshot();
await controller.typeIntoPrompt(prompt(text, []));
await controller.clickSendButton();
});
ipcMain.on('continue', async (event, text) => {
await screenshot();
await controller.typeIntoPrompt(prompt(currentTask, []));
await controller.clickSendButton();
});
let action = () => {};
ipcMain.on('execute', async (event, text) => {
action();
});
controller.on('end_turn', (content) => {
if (BrowserWindow.getAllWindows().length === 0) return;
const data = extractJsonFromMarkdown(content);
let msg = data === null ? content : data.briefExplanation;
win.webContents.send('end_turn', msg);
action = () => {
if(data != null) {
switch(data.nextAction.action) {
case "click":
console.log(`clicking ${JSON.stringify(labelData[data.nextAction.element])}`);
let { x, y } = labelData[data.nextAction.element];
webview.sendInputEvent({
type: 'mouseDown',
x, y,
clickCount: 1
});
webview.sendInputEvent({
type: 'mouseUp',
x, y,
clickCount: 1
});
break;
case "type": {
console.log(`typing ${data.nextAction.text} into ${JSON.stringify(labelData[data.nextAction.element])}`);
let { x, y } = labelData[data.nextAction.element];
webview.sendInputEvent({
type: 'mouseDown',
x, y,
clickCount: 1
});
webview.sendInputEvent({
type: 'mouseUp',
x, y,
clickCount: 1
});
for(let char of data.nextAction.text) {
webview.sendInputEvent({
type: 'char',
keyCode: char
});
}
break;
}
default:
console.log(`unknown action ${JSON.stringify(data.nextAction)}`);
break;
}
}
};
});
await controller.initialize();
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})