-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
379 lines (307 loc) · 10.4 KB
/
main.ts
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
import * as io from "io";
import * as clipboard from "clipboard-image";
import * as dotenv from "dotenv";
import cryptoJs from "crypto-js";
import pinyin from "pinyin";
import * as imgScr from "imgScript";
dotenv.config({ export: true });
const user32 = Deno.dlopen(
"user32.dll",
{
PeekMessageA: {
parameters: ["buffer", "usize", "u32", "u32", "u32"],
result: "i32",
nonblocking: false,
},
SetWindowsHookExA: {
parameters: ["i32", "function", "usize", "u32"],
result: "i32",
nonblocking: false,
},
CallNextHookEx: {
parameters: ["usize", "i32", "usize", "usize"],
result: "i32",
nonblocking: false,
},
SendInput: {
parameters: ["u32", "buffer", "i32"],
result: "i32",
nonblocking: false,
}
} as const,
);
let isPrtScPressed = false;
let isBusy = false;
const keyboardHook = new Deno.UnsafeCallback(
{ parameters: ["i32", "usize", "usize"], result: "usize" } as const,
(
nCode: number,
wParam: number | bigint,
lParam: number | bigint,
): number | bigint => {
const keyCode = (new Deno.UnsafePointerView(Deno.UnsafePointer.create(lParam)!)).getUint32();
const flags = (new Deno.UnsafePointerView(Deno.UnsafePointer.create(lParam)!)).getUint32(8);
if (nCode === 0 && (flags & 0x10) === 0) {
if (wParam === 257) {
if (keyCode === 0x2C) {
// NOTE: lParam 포인터의 데이터를 조작하여 alt키를 삽입할 수도 있을지는 모르겠으나
// 아직 deno에서 포인터를 통한 데이터 쓰기를 지원하지 않아 sendInput으로 대체
const input = new DataView(new Uint8Array(160).buffer);
input.setUint32(0, 1, true);
input.setUint16(8, 0x12, true);
input.setUint32(40 + 0, 1, true);
input.setUint16(40 + 8, 0x2C, true);
input.setUint32(80 + 0, 1, true);
input.setUint16(80 + 8, 0x2C, true);
input.setUint32(80 + 12, 2, true);
input.setUint32(120 + 0, 1, true);
input.setUint16(120 + 8, 0x12, true);
input.setUint32(120 + 12, 2, true);
user32.symbols.SendInput(4, new Uint8Array(input.buffer), 40);
isPrtScPressed = true;
return 1;
}
} else {
if (keyCode === 0x2C) {
return 1;
}
}
}
return user32.symbols.CallNextHookEx(0, nCode, wParam, lParam);
},
);
async function translate(text: string) {
const uuid = crypto.randomUUID();
const path = Deno.env.get("PAPAGO_API_URL");
const timestamp = new Date().valueOf().toString();
const papagoVersion = Deno.env.get("PAPAGO_VERSION")!;
const auth = cryptoJs.enc.Base64.stringify(
cryptoJs.HmacMD5(
`${uuid}\n${path}\n${timestamp}`,
papagoVersion,
),
);
const usp = new URLSearchParams();
usp.set("deviceId", uuid);
usp.set("locale", "en");
usp.set("dict", "true");
usp.set("dictDisplay", "30");
usp.set("honorific", "false");
usp.set("instant", "false");
usp.set("paging", "false");
usp.set("source", (Deno.env.get("SOURCE") === "en") ? "en" : "zh-CN");
usp.set("target", "ko");
usp.set("text", text);
const resp = await fetch(Deno.env.get("PAPAGO_API_URL")!, {
method: "post",
headers: new Headers({
"authorization": `PPG ${uuid}:${auth}`,
"timestamp": timestamp,
}),
body: usp,
});
console.log(Deno.env.get("PAPAGO_API_URL")!, resp.status);
return await resp.json();
}
async function makeMessage(txts: string[]) {
const joinedTxt = txts.join("\n\n");
let pnins: string[];
if (Deno.env.get("SOURCE")! === "ch") {
pnins = pinyin(joinedTxt).flat().join(" ").split("\n\n");
}
const translateResult = await translate(joinedTxt);
console.log("translateResult", translateResult);
const translatedTxts = translateResult.translatedText.split("\n\n");
let dict = "";
for (const item of (translateResult.dict?.items) ?? []) {
dict += `## ${item.entry.replace(/<.*?>/g, "")} ${(Deno.env.get("SOURCE")! === "ch") ? pinyin(item.entry.replace(/<.*?>/g, "")).flat().join(" ") : ""}\n`;
for (const pos of item.pos) {
for (const meaning of pos.meanings) {
dict += `1. ${meaning.meaning.replace(/<.*?>/g, "")}\n`
}
}
dict += "\n";
}
const output = [];
for (let i = 0; i < txts.length; i++) {
if (Deno.env.get("SOURCE")! === "ch") {
output.push(
[txts[i], pnins![i].trim(), translatedTxts[i]].join("\n"),
);
} else {
output.push(
[txts[i], translatedTxts[i]].join("\n"),
);
}
}
return output.join("\n\n") + "\n\n" + dict;
}
async function* infinity() {
while (true) {
yield;
await new Promise((ok) => setTimeout(ok, 0));
}
}
function isSourceLanguage(text: string) {
return (Deno.env.get("SOURCE")! === "en") ? (/[a-zA-Z]/g).test(text) : (/[\u4e00-\u9fa5]/g).test(text);
}
async function pollTgMessage() {
let offset = 0;
for await (const _ of infinity()) {
const resp = await fetch(
`${Deno.env.get("TELEGRAM_API_BASE_URL")}/bot${Deno.env.get(
"BOT_TOKEN",
)!}/getUpdates?offset=${offset}`,
{
method: "get",
},
);
console.log(`${Deno.env.get("TELEGRAM_API_BASE_URL")}/bot.../getUpdates?offset=${offset}`, resp.status);
const update = await resp.json();
for (const result of update.result) {
if (Deno.env.get("CHAT_ID")!) {
const message = await makeMessage([result.message.text]);
const resp = await fetch(
`${Deno.env.get("TELEGRAM_API_BASE_URL")}/bot${Deno.env.get(
"BOT_TOKEN",
)!}/sendMessage`,
{
method: "post",
headers: { "content-type": "application/json" },
body: JSON.stringify({
chat_id: Deno.env.get("CHAT_ID")!,
text: message,
}),
},
);
console.log(`${Deno.env.get("TELEGRAM_API_BASE_URL")}/bot.../sendMessage`, resp.status, await resp.json());
} else {
const resp = await fetch(
`${Deno.env.get("TELEGRAM_API_BASE_URL")}/bot${Deno.env.get(
"BOT_TOKEN",
)!}/sendMessage`,
{
method: "post",
headers: { "content-type": "application/json" },
body: JSON.stringify({
chat_id: result.message.chat.id,
text: result.message.chat.id,
}),
},
);
console.log(`${Deno.env.get("TELEGRAM_API_BASE_URL")}/bot.../sendMessage`, resp.status, await resp.json());
}
offset = result.update_id + 1;
}
await new Promise((ok) => {
setTimeout(ok, 500);
});
}
}
function setKeyboardHook() {
user32.symbols.SetWindowsHookExA(13, keyboardHook.pointer, 0, 0);
}
async function pumpWsMessage() {
const msg = new Uint8Array(48);
for await (const _ of infinity()) {
user32.symbols.PeekMessageA(msg, 0, 0, 0, 1);
if (isPrtScPressed) {
isPrtScPressed = false;
if (!isBusy) {
isBusy = true;
try {
await new Promise((ok) => setTimeout(ok, 500));
const bmpImg = await io.readAll(await clipboard.read());
const img = await imgScr.decode(bmpImg);
if (img.width > 1024) {
const ratio = 1024 / img.width;
img.resize(1024, Math.round(img.height * ratio));
}
const pngImg = await img.encode(1);
await (await Deno.open("output.png", { create: true, write: true, truncate: true })).write(pngImg);
let fd = new FormData();
fd.set(
"file",
new File([await Deno.readFile("output.png")], "output.png"),
);
let resp = await fetch(
`${Deno.env.get("API_BASE_URL")!}/infer/${Deno.env.get("SOURCE")!}`,
{
method: "post",
body: fd,
},
);
console.log(`${Deno.env.get("API_BASE_URL")!}/infer/${Deno.env.get("SOURCE")!}`, resp.status);
const detectionMap = new Map();
const detections = await resp.json();
for (const detection of detections[0]) {
const [leftUpper, , , leftBottom] = detection[0];
const [txt] = detection[1];
if (isSourceLanguage(txt)) {
let near = null;
for (const [candidateDetection] of detectionMap) {
const [x1, y1] = candidateDetection;
const [x2, y2] = leftUpper;
if ((x2 - x1) ** 2 <= parseInt(Deno.env.get("X_DELTA")!) && (y2 - y1) ** 2 <= parseInt(Deno.env.get("Y_DELTA")!)) {
near = candidateDetection;
break;
}
}
if (near) {
const oldTxt = detectionMap.get(near);
detectionMap.set(leftBottom, oldTxt + txt.trim());
detectionMap.delete(near);
} else {
detectionMap.set(leftBottom, txt.trim());
}
}
}
let message = "no detections.";
if (detectionMap.size > 0) {
const txts = [];
for (const [, txt] of detectionMap) {
txts.push(txt);
}
message = await makeMessage(txts);
}
fd = new FormData();
fd.set("chat_id", Deno.env.get("CHAT_ID")!);
fd.set(
"photo",
new File([await Deno.readFile("output.png")], "output.png"),
);
resp = await fetch(
`${Deno.env.get("TELEGRAM_API_BASE_URL")}/bot${Deno.env.get(
"BOT_TOKEN",
)!}/sendPhoto`,
{ method: "post", body: fd },
);
console.log(`${Deno.env.get("TELEGRAM_API_BASE_URL")}/bot.../sendPhoto`, resp.status, await resp.json());
resp = await fetch(
`${Deno.env.get("TELEGRAM_API_BASE_URL")}/bot${Deno.env.get(
"BOT_TOKEN",
)!}/sendMessage`,
{
method: "post",
headers: { "content-type": "application/json" },
body: JSON.stringify({
chat_id: Deno.env.get("CHAT_ID")!,
text: message,
}),
},
);
console.log(`${Deno.env.get("TELEGRAM_API_BASE_URL")}/bot.../sendMessage`, resp.status, await resp.json());
} catch (e) {
console.log(e);
} finally {
isBusy = false;
}
}
}
}
}
(function main() {
pollTgMessage();
setKeyboardHook();
pumpWsMessage();
})();