docs: restructure markdown docs and publish the bridge
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
"""Report desktop / window-station names and foreground window."""
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
|
||||
UOI_NAME = 2
|
||||
UOI_FLAGS = 1
|
||||
|
||||
|
||||
def obj_name(handle):
|
||||
need = wintypes.DWORD(0)
|
||||
user32.GetUserObjectInformationW(handle, UOI_NAME, None, 0, ctypes.byref(need))
|
||||
buf = ctypes.create_unicode_buffer(need.value)
|
||||
ok = user32.GetUserObjectInformationW(handle, UOI_NAME, buf, need.value, ctypes.byref(need))
|
||||
return buf.value if ok else f'<err {ctypes.get_last_error()}>'
|
||||
|
||||
|
||||
h = user32.GetThreadDesktop(kernel32.GetCurrentThreadId())
|
||||
print("thread desktop:", obj_name(h))
|
||||
ws = user32.GetProcessWindowStation()
|
||||
print("window station:", obj_name(ws))
|
||||
print("OpenInputDesktop:", user32.OpenInputDesktop(0, False, 0x0100))
|
||||
input_desk = user32.OpenInputDesktop(0, False, 0x0100)
|
||||
if input_desk:
|
||||
print("input desktop name:", obj_name(input_desk))
|
||||
print("GetForegroundWindow:", user32.GetForegroundWindow())
|
||||
print("GetActiveWindow:", user32.GetActiveWindow())
|
||||
print("GetDesktopWindow:", user32.GetDesktopWindow())
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Try forcing foreground via AttachThreadInput, then test SendInput."""
|
||||
import ctypes, sys, time
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
|
||||
user32.AttachThreadInput.argtypes = [wintypes.DWORD, wintypes.DWORD, wintypes.BOOL]
|
||||
user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
|
||||
user32.GetWindowThreadProcessId.restype = wintypes.DWORD
|
||||
kernel32.GetCurrentThreadId.restype = wintypes.DWORD
|
||||
|
||||
|
||||
def force_foreground(hwnd):
|
||||
tid_target = user32.GetWindowThreadProcessId(hwnd, None)
|
||||
tid_self = kernel32.GetCurrentThreadId()
|
||||
print('threads: target', tid_target, 'self', tid_self)
|
||||
attached = user32.AttachThreadInput(tid_self, tid_target, True)
|
||||
print('AttachThreadInput:', attached, 'err', ctypes.get_last_error())
|
||||
user32.ShowWindow(hwnd, 9) # SW_RESTORE
|
||||
user32.BringWindowToTop(hwnd)
|
||||
ok = user32.SetForegroundWindow(hwnd)
|
||||
print('SetForegroundWindow:', ok, 'err', ctypes.get_last_error())
|
||||
user32.SetFocus(hwnd)
|
||||
time.sleep(0.5)
|
||||
print('foreground now:', user32.GetForegroundWindow(), 'active:', user32.GetActiveWindow())
|
||||
print('AttachThreadInput(detach):', user32.AttachThreadInput(tid_self, tid_target, False))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
force_foreground(int(sys.argv[1]))
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Diagnose SendInput delivery."""
|
||||
import time, ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||
user32.SendInput.argtypes = [wintypes.UINT, ctypes.c_void_p, ctypes.c_int]
|
||||
user32.SendInput.restype = wintypes.UINT
|
||||
|
||||
ULONG_PTR = ctypes.c_size_t
|
||||
|
||||
|
||||
class KEYBDINPUT(ctypes.Structure):
|
||||
_fields_ = [("wVk", wintypes.WORD), ("wScan", wintypes.WORD), ("dwFlags", wintypes.DWORD),
|
||||
("time", wintypes.DWORD), ("dwExtraInfo", ULONG_PTR)]
|
||||
|
||||
|
||||
class MOUSEINPUT(ctypes.Structure):
|
||||
_fields_ = [("dx", wintypes.LONG), ("dy", wintypes.LONG), ("mouseData", wintypes.DWORD),
|
||||
("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), ("dwExtraInfo", ULONG_PTR)]
|
||||
|
||||
|
||||
class HARDWAREINPUT(ctypes.Structure):
|
||||
_fields_ = [("uMsg", wintypes.DWORD), ("wParamL", wintypes.WORD), ("wParamH", wintypes.WORD)]
|
||||
|
||||
|
||||
class _I(ctypes.Union):
|
||||
_fields_ = [("mi", MOUSEINPUT), ("ki", KEYBDINPUT), ("hi", HARDWAREINPUT)]
|
||||
|
||||
|
||||
class INPUT(ctypes.Structure):
|
||||
_fields_ = [("type", wintypes.DWORD), ("u", _I)]
|
||||
|
||||
|
||||
KEYEVENTF_UNICODE = 0x0004
|
||||
KEYEVENTF_KEYUP = 0x0002
|
||||
|
||||
|
||||
def type_text(text):
|
||||
evts = []
|
||||
for ch in text:
|
||||
for flag in (KEYEVENTF_UNICODE, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP):
|
||||
inp = INPUT()
|
||||
inp.type = 1
|
||||
inp.u.ki = KEYBDINPUT(wVk=0, wScan=ord(ch), dwFlags=flag, time=0, dwExtraInfo=0)
|
||||
evts.append(inp)
|
||||
arr = (INPUT * len(evts))(*evts)
|
||||
sent = user32.SendInput(len(evts), ctypes.cast(arr, ctypes.c_void_p), ctypes.sizeof(INPUT))
|
||||
err = ctypes.get_last_error()
|
||||
return sent, err
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
hwnd = int(sys.argv[1])
|
||||
print("sizeof(INPUT) =", ctypes.sizeof(INPUT))
|
||||
print("foreground before:", user32.GetForegroundWindow(), "target:", hwnd)
|
||||
user32.SetForegroundWindow(hwnd)
|
||||
time.sleep(0.5)
|
||||
fg = user32.GetForegroundWindow()
|
||||
print("foreground after:", fg)
|
||||
sent, err = type_text('hello')
|
||||
print("SendInput sent:", sent, "last_error:", err)
|
||||
# also try mouse move to see if input pipeline alive
|
||||
p = wintypes.POINT(100, 100)
|
||||
user32.SetCursorPos(100, 100)
|
||||
time.sleep(0.2)
|
||||
user32.GetCursorPos(ctypes.byref(p))
|
||||
print("cursor:", p.x, p.y)
|
||||
time.sleep(1)
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public class MMDevices
|
||||
{
|
||||
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
|
||||
private class MMDeviceEnumeratorComObject { }
|
||||
|
||||
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IMMDeviceEnumerator
|
||||
{
|
||||
int EnumAudioEndpoints(int dataFlow, int stateMask, out IMMDeviceCollection devices);
|
||||
int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device);
|
||||
int GetDevice(string id, out IMMDevice device);
|
||||
int RegisterEndpointNotificationCallback(IntPtr client);
|
||||
int UnregisterEndpointNotificationCallback(IntPtr client);
|
||||
}
|
||||
|
||||
[Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IMMDeviceCollection
|
||||
{
|
||||
int GetCount(out int count);
|
||||
int Item(int index, out IMMDevice device);
|
||||
}
|
||||
|
||||
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IMMDevice
|
||||
{
|
||||
int Activate(ref Guid iid, int clsCtx, IntPtr activationParams, out IntPtr iface);
|
||||
int OpenPropertyStore(int access, out IPropertyStore store);
|
||||
int GetId(out IntPtr id);
|
||||
int GetState(out int state);
|
||||
}
|
||||
|
||||
[Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IPropertyStore
|
||||
{
|
||||
int GetCount(out int count);
|
||||
int GetAt(int index, out PROPERTYKEY key);
|
||||
int GetValue(ref PROPERTYKEY key, out PROPVARIANT value);
|
||||
int SetValue(ref PROPERTYKEY key, ref PROPVARIANT value);
|
||||
int Commit();
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct PROPERTYKEY { public Guid fmtid; public int pid; }
|
||||
|
||||
[StructLayout(LayoutKind.Explicit)]
|
||||
private struct PROPVARIANT
|
||||
{
|
||||
[FieldOffset(0)] public short vt;
|
||||
[FieldOffset(8)] public IntPtr pointerValue;
|
||||
}
|
||||
|
||||
private static PROPERTYKEY PKEY_Device_FriendlyName = new PROPERTYKEY
|
||||
{
|
||||
fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"),
|
||||
pid = 14
|
||||
};
|
||||
|
||||
public static List<string> List(int dataFlow)
|
||||
{
|
||||
return ListWithMask(dataFlow, 1);
|
||||
}
|
||||
|
||||
public static List<string> ListAll(int dataFlow)
|
||||
{
|
||||
// 0x0F: active | disabled | notpresent | unplugged
|
||||
return ListWithMask(dataFlow, 0x0F);
|
||||
}
|
||||
|
||||
public static List<string> ListWithMask(int dataFlow, int mask)
|
||||
{
|
||||
var result = new List<string>();
|
||||
var enumerator = (IMMDeviceEnumerator)(new MMDeviceEnumeratorComObject());
|
||||
IMMDeviceCollection collection;
|
||||
if (enumerator.EnumAudioEndpoints(dataFlow, mask, out collection) != 0)
|
||||
{
|
||||
result.Add("ERROR: EnumAudioEndpoints failed");
|
||||
return result;
|
||||
}
|
||||
int count;
|
||||
collection.GetCount(out count);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
IMMDevice device;
|
||||
collection.Item(i, out device);
|
||||
IPropertyStore store;
|
||||
device.OpenPropertyStore(0, out store);
|
||||
PROPVARIANT value;
|
||||
store.GetValue(ref PKEY_Device_FriendlyName, out value);
|
||||
string name = Marshal.PtrToStringUni(value.pointerValue);
|
||||
int state;
|
||||
device.GetState(out state);
|
||||
result.Add(name + " | state=" + state);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Message-based input (PostMessage) — works without a foreground/input desktop."""
|
||||
import ctypes, time
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||
WM_CHAR = 0x0102
|
||||
WM_KEYDOWN = 0x0100
|
||||
WM_KEYUP = 0x0101
|
||||
WM_LBUTTONDOWN = 0x0201
|
||||
WM_LBUTTONUP = 0x0202
|
||||
WM_SETCURSOR = 0x0020
|
||||
|
||||
|
||||
def post_char(hwnd, ch):
|
||||
user32.PostMessageW(hwnd, WM_CHAR, ord(ch), 0x00000001)
|
||||
|
||||
|
||||
def post_text(hwnd, text):
|
||||
for ch in text:
|
||||
post_char(hwnd, ch)
|
||||
time.sleep(0.01)
|
||||
|
||||
|
||||
def post_key(hwnd, vk):
|
||||
user32.PostMessageW(hwnd, WM_KEYDOWN, vk, 0x00000001)
|
||||
user32.PostMessageW(hwnd, WM_KEYUP, vk, 0xC0000001)
|
||||
|
||||
|
||||
def post_click(hwnd, x, y):
|
||||
lparam = (y << 16) | (x & 0xFFFF)
|
||||
user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lparam)
|
||||
user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lparam)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Test message-based input against Notepad (WM_CHAR to edit control)."""
|
||||
import ctypes, sys, time
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||
WM_CHAR = 0x0102
|
||||
WM_KEYDOWN = 0x0100
|
||||
WM_KEYUP = 0x0101
|
||||
|
||||
|
||||
def find_child_edit(hwnd):
|
||||
found = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
def cb(h, lparam):
|
||||
cls = ctypes.create_unicode_buffer(64)
|
||||
user32.GetClassNameW(h, cls, 64)
|
||||
if cls.value == 'Edit':
|
||||
found.append(h)
|
||||
return False
|
||||
return True
|
||||
|
||||
user32.EnumChildWindows(hwnd, cb, 0)
|
||||
return found[0] if found else None
|
||||
|
||||
|
||||
def post_text(hwnd, text):
|
||||
ok = 0
|
||||
for ch in text:
|
||||
if user32.PostMessageW(hwnd, WM_CHAR, ord(ch), 0x00000001):
|
||||
ok += 1
|
||||
time.sleep(0.005)
|
||||
return ok
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
hwnd = int(sys.argv[1])
|
||||
edit = find_child_edit(hwnd)
|
||||
print('notepad:', hwnd, 'edit:', edit)
|
||||
if edit:
|
||||
print('posted chars:', post_text(edit, 'MSGOK'))
|
||||
time.sleep(0.5)
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env node
|
||||
// qq-notify.cjs —— 把小肥鱼(dsh-bili-whale)的推送转成 QQ 消息(默认发语音条)
|
||||
//
|
||||
// 用法: node qq-notify.cjs "消息正文"
|
||||
// 或 WHALE_NOTIFY_TEXT="消息正文" node qq-notify.cjs
|
||||
//
|
||||
// 它会被 dsh-bili-whale 的 notify.mjs 以 type=command 调起,正文作为最后一个参数传入。
|
||||
// 走 SnowLuma 的 OneBot HTTP 接口发私聊。token 每次从 SnowLuma 的账号配置里现读,
|
||||
// 换了 token 也不用改这里。
|
||||
//
|
||||
// 主动推送默认走语音:正文先交给自建 TTS 合成 wav,再以 record 段发出;
|
||||
// 合成失败 / 太长(>58s)/ QQ_NOTIFY_VOICE=0 时退回文字。
|
||||
//
|
||||
// 环境变量(都可选):
|
||||
// QQ_NOTIFY_CONFIG_DIR SnowLuma 配置目录,默认 C:\Users\GuoAn\Desktop\SnowLuma-v2.4.0-win-x64\config
|
||||
// QQ_NOTIFY_BASE OneBot HTTP 地址,默认 http://127.0.0.1:3000
|
||||
// QQ_NOTIFY_TARGET 收信人 QQ,默认 419177984
|
||||
// QQ_NOTIFY_TOKEN 手动指定 accessToken(跳过读配置)
|
||||
// QQ_NOTIFY_TTS TTS 服务地址,默认 http://192.168.1.17:8080;置空则不发语音
|
||||
// QQ_NOTIFY_VOICE 0 = 强制发文字;默认发语音
|
||||
|
||||
const fs = require('node:fs')
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
|
||||
const CONFIG_DIR = process.env.QQ_NOTIFY_CONFIG_DIR || 'C:\\Users\\GuoAn\\Desktop\\SnowLuma-v2.4.0-win-x64\\config'
|
||||
const BASE = (process.env.QQ_NOTIFY_BASE || 'http://127.0.0.1:3000').replace(/\/+$/, '')
|
||||
const TARGET = Number(process.env.QQ_NOTIFY_TARGET || 419177984)
|
||||
const TTS_BASE = (process.env.QQ_NOTIFY_TTS ?? 'http://192.168.1.17:8080').replace(/\/+$/, '')
|
||||
const VOICE_ON = process.env.QQ_NOTIFY_VOICE !== '0' && TTS_BASE !== ''
|
||||
const LOG = path.join(os.homedir(), '.dsh', 'bin', 'qq-notify.log')
|
||||
|
||||
/** 语音条上限 60s,留 2s 余量。 */
|
||||
const MAX_VOICE_SECONDS = 58
|
||||
|
||||
function log(line) {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(LOG), { recursive: true })
|
||||
fs.appendFileSync(LOG, `[${new Date().toISOString()}] ${line}\n`)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/** 从 SnowLuma 的 onebot_<uin>.json 里找出 HTTP 服务的 accessToken。 */
|
||||
function findToken() {
|
||||
if (process.env.QQ_NOTIFY_TOKEN) return process.env.QQ_NOTIFY_TOKEN
|
||||
let files = []
|
||||
try {
|
||||
files = fs.readdirSync(CONFIG_DIR).filter((f) => /^onebot_.*\.json$/.test(f))
|
||||
} catch (e) {
|
||||
throw new Error(`读不到 SnowLuma 配置目录:${CONFIG_DIR}(${e.message})`)
|
||||
}
|
||||
// 优先取最近写过的那个账号
|
||||
files.sort((a, b) => {
|
||||
try {
|
||||
return fs.statSync(path.join(CONFIG_DIR, b)).mtimeMs - fs.statSync(path.join(CONFIG_DIR, a)).mtimeMs
|
||||
} catch { return 0 }
|
||||
})
|
||||
for (const f of files) {
|
||||
try {
|
||||
const cfg = JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, f), 'utf8'))
|
||||
// SnowLuma 的账号级快照把网络配置放在 networks 下面
|
||||
const servers = cfg?.httpServers || cfg?.networks?.httpServers || cfg?.onebot?.httpServers || []
|
||||
for (const s of servers) {
|
||||
if (s && s.accessToken) return String(s.accessToken)
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
throw new Error('没在 SnowLuma 配置里找到 HTTP accessToken')
|
||||
}
|
||||
|
||||
/** 只留下能念出来的字:去代码块、行内码、链接、Markdown 符号、emoji。 */
|
||||
function speechText(text) {
|
||||
return String(text ?? '')
|
||||
.replace(/```[\s\S]*?```/g, ' ')
|
||||
.replace(/`([^`]*)`/g, '$1')
|
||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
|
||||
.replace(/https?:\/\/\S+/g, ' ')
|
||||
.replace(/[*_~#>|]+/g, ' ')
|
||||
.replace(/[\p{Extended_Pictographic}\u{FE0F}\u{200D}\u{20E3}]/gu, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
/** 读 wav 头的时长(秒);不是 wav 或读不出来时返回 0。 */
|
||||
function wavDurationSeconds(bytes) {
|
||||
if (!Buffer.isBuffer(bytes) || bytes.length < 44) return 0
|
||||
if (bytes.toString('ascii', 0, 4) !== 'RIFF' || bytes.toString('ascii', 8, 12) !== 'WAVE') return 0
|
||||
let offset = 12
|
||||
let byteRate = 0
|
||||
let dataSize = 0
|
||||
while (offset + 8 <= bytes.length) {
|
||||
const id = bytes.toString('ascii', offset, offset + 4)
|
||||
const size = bytes.readUInt32LE(offset + 4)
|
||||
const body = offset + 8
|
||||
if (id === 'fmt ' && body + 16 <= bytes.length) {
|
||||
byteRate = bytes.readUInt32LE(body + 8)
|
||||
} else if (id === 'data') {
|
||||
dataSize = size
|
||||
break
|
||||
}
|
||||
offset = body + size + (size % 2)
|
||||
}
|
||||
if (byteRate <= 0 || dataSize <= 0) return 0
|
||||
return dataSize / byteRate
|
||||
}
|
||||
|
||||
/** 合成语音;失败返回 null(调用方退回文字)。 */
|
||||
async function synthesize(text) {
|
||||
const spoken = speechText(text)
|
||||
if (!spoken) return null
|
||||
try {
|
||||
const res = await fetch(`${TTS_BASE}/api/tts`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ text: spoken }),
|
||||
signal: AbortSignal.timeout(120000),
|
||||
})
|
||||
if (!res.ok) {
|
||||
log(`TTS FAIL http=${res.status} ${(await res.text().catch(() => '')).slice(0, 200)}`)
|
||||
return null
|
||||
}
|
||||
const bytes = Buffer.from(await res.arrayBuffer())
|
||||
if (bytes.length < 100) {
|
||||
log('TTS FAIL empty audio')
|
||||
return null
|
||||
}
|
||||
const seconds = wavDurationSeconds(bytes)
|
||||
if (seconds > MAX_VOICE_SECONDS) {
|
||||
log(`TTS SKIP ${seconds.toFixed(1)}s > ${MAX_VOICE_SECONDS}s`)
|
||||
return null
|
||||
}
|
||||
log(`TTS OK ${bytes.length}B ${seconds.toFixed(1)}s`)
|
||||
return bytes
|
||||
} catch (e) {
|
||||
log('TTS ERR ' + (e && e.message ? e.message : String(e)))
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function send(token, message) {
|
||||
const res = await fetch(`${BASE}/send_private_msg`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ user_id: TARGET, message }),
|
||||
signal: AbortSignal.timeout(60000),
|
||||
})
|
||||
const raw = await res.text().catch(() => '')
|
||||
let data = null
|
||||
try { data = JSON.parse(raw) } catch {}
|
||||
return { ok: res.ok && !(data && data.retcode !== 0 && data.status !== 'ok'), raw, data, status: res.status }
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const text = (process.argv[2] ?? process.env.WHALE_NOTIFY_TEXT ?? '').trim()
|
||||
if (!text) {
|
||||
console.error('用法: node qq-notify.cjs "消息正文"')
|
||||
process.exit(2)
|
||||
}
|
||||
const token = findToken()
|
||||
const body = text.length > 3000 ? text.slice(0, 3000) + '\n…' : text
|
||||
|
||||
if (VOICE_ON) {
|
||||
const bytes = await synthesize(body)
|
||||
if (bytes) {
|
||||
const sent = await send(token, [{ type: 'record', data: { file: 'base64://' + bytes.toString('base64') } }])
|
||||
if (sent.ok) {
|
||||
log(`OK-voice ${JSON.stringify(sent.data?.data ?? null).slice(0, 200)}`)
|
||||
console.log('QQ 已送达(语音)✓', JSON.stringify(sent.data?.data ?? null))
|
||||
return
|
||||
}
|
||||
log(`VOICE SEND FAIL http=${sent.status} ${sent.raw.slice(0, 300)};改发文字`)
|
||||
}
|
||||
}
|
||||
|
||||
const sent = await send(token, body)
|
||||
if (!sent.ok) {
|
||||
log(`FAIL http=${sent.status} ${sent.raw.slice(0, 300)}`)
|
||||
console.error(`QQ 推送失败:HTTP ${sent.status} ${sent.raw.slice(0, 300)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
log(`OK ${JSON.stringify(sent.data?.data ?? null).slice(0, 200)}`)
|
||||
console.log('QQ 已送达 ✓', JSON.stringify(sent.data?.data ?? null))
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
log('ERR ' + (e && e.message ? e.message : String(e)))
|
||||
console.error('QQ 推送失败:' + (e && e.message ? e.message : String(e)))
|
||||
process.exit(1)
|
||||
})
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
"""Standalone STT entry point for dsh-onebot-qq.
|
||||
|
||||
Called by the plugin as its "custom" engine:
|
||||
|
||||
python stt.py --file <wav> --out <workdir>/out --model <model>
|
||||
|
||||
The plugin hands over a 16 kHz mono WAV (already converted with ffmpeg) and
|
||||
reads the first *.txt in the work dir, so this script writes <out>.txt.
|
||||
|
||||
Two backends:
|
||||
* SenseVoice (sherpa-onnx) — used when --model points at a *.onnx file.
|
||||
Fast on CPU and strong on short Chinese utterances.
|
||||
* faster-whisper — used when --model is a whisper size or a local
|
||||
CTranslate2 model directory.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
MODEL_ROOT = os.environ.get("STT_MODEL_ROOT") or str(Path.home() / ".dsh" / "stt-models")
|
||||
TAG_RE = re.compile(r"<\|[^|]*\|>")
|
||||
|
||||
|
||||
def log(msg: str) -> None:
|
||||
sys.stderr.write(f"[stt] {msg}\n")
|
||||
sys.stderr.flush()
|
||||
|
||||
|
||||
def read_wav(path: Path) -> tuple["object", int]:
|
||||
import numpy as np
|
||||
|
||||
with wave.open(str(path), "rb") as wf:
|
||||
channels = wf.getnchannels()
|
||||
rate = wf.getframerate()
|
||||
width = wf.getsampwidth()
|
||||
frames = wf.readframes(wf.getnframes())
|
||||
if width != 2:
|
||||
raise SystemExit(f"expected 16-bit PCM, got sample width {width}")
|
||||
samples = np.frombuffer(frames, dtype=np.int16).astype("float32") / 32768.0
|
||||
if channels > 1:
|
||||
samples = samples.reshape(-1, channels).mean(axis=1)
|
||||
return samples, rate
|
||||
|
||||
|
||||
def transcribe_sense_voice(wav: Path, model: Path, tokens: Path, language: str) -> str:
|
||||
import sherpa_onnx
|
||||
|
||||
if not tokens.is_file():
|
||||
raise SystemExit(f"missing sense-voice tokens file: {tokens}")
|
||||
recognizer = sherpa_onnx.OfflineRecognizer.from_sense_voice(
|
||||
model=str(model),
|
||||
tokens=str(tokens),
|
||||
num_threads=int(os.environ.get("STT_THREADS") or 1),
|
||||
use_itn=True,
|
||||
language=language or "zh",
|
||||
debug=False,
|
||||
)
|
||||
samples, rate = read_wav(wav)
|
||||
stream = recognizer.create_stream()
|
||||
stream.accept_waveform(rate, samples)
|
||||
recognizer.decode_stream(stream)
|
||||
return TAG_RE.sub("", stream.result.text or "").strip()
|
||||
|
||||
|
||||
def transcribe_whisper(wav: Path, model: str, language: str, prompt: str) -> str:
|
||||
# huggingface.co is unreachable here; hf-mirror serves the same repos.
|
||||
os.environ["HF_ENDPOINT"] = os.environ.get("STT_HF_ENDPOINT") or "https://hf-mirror.com"
|
||||
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
root = Path(model)
|
||||
asr = WhisperModel(
|
||||
str(root) if root.exists() else model,
|
||||
device="cpu",
|
||||
compute_type="int8",
|
||||
download_root=MODEL_ROOT,
|
||||
cpu_threads=int(os.environ.get("STT_THREADS") or 0),
|
||||
)
|
||||
segments, _info = asr.transcribe(
|
||||
str(wav),
|
||||
language=language or None,
|
||||
beam_size=1,
|
||||
vad_filter=True,
|
||||
condition_on_previous_text=False,
|
||||
initial_prompt=prompt or None,
|
||||
)
|
||||
return "".join(seg.text for seg in segments).strip()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--file", required=True)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--model", default="small")
|
||||
ap.add_argument("--tokens", default="")
|
||||
ap.add_argument("--lang", default="")
|
||||
ap.add_argument("--prompt", default="以下是普通话的句子,请用简体中文转写。")
|
||||
args = ap.parse_args()
|
||||
|
||||
wav = Path(args.file)
|
||||
if not wav.is_file():
|
||||
log(f"missing input: {wav}")
|
||||
return 2
|
||||
|
||||
started = time.time()
|
||||
if args.model.lower().endswith(".onnx"):
|
||||
tokens = Path(args.tokens) if args.tokens else Path(args.model).with_name("tokens.txt")
|
||||
text = transcribe_sense_voice(wav, Path(args.model), tokens, args.lang)
|
||||
backend = "sense-voice"
|
||||
else:
|
||||
text = transcribe_whisper(wav, args.model, args.lang, args.prompt)
|
||||
backend = "whisper"
|
||||
|
||||
out = Path(args.out + ".txt")
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(text, encoding="utf-8")
|
||||
log(f"ok backend={backend} chars={len(text)} elapsed={time.time() - started:.1f}s")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
set QT_ACCESSIBILITY=1
|
||||
start "" "C:\Program Files\Tencent\Weixin\Weixin.exe"
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Capture a window via PrintWindow (works without screen access)."""
|
||||
import sys, ctypes
|
||||
from ctypes import wintypes
|
||||
import win32gui, win32ui, win32con
|
||||
from PIL import Image
|
||||
|
||||
def capture(hwnd, out):
|
||||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||||
w, h = right - left, bottom - top
|
||||
hwnd_dc = win32gui.GetWindowDC(hwnd)
|
||||
mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
|
||||
save_dc = mfc_dc.CreateCompatibleDC()
|
||||
bmp = win32ui.CreateBitmap()
|
||||
bmp.CreateCompatibleBitmap(mfc_dc, w, h)
|
||||
save_dc.SelectObject(bmp)
|
||||
# PW_RENDERFULLCONTENT = 2
|
||||
ok = ctypes.windll.user32.PrintWindow(hwnd, save_dc.GetSafeHdc(), 2)
|
||||
info = bmp.GetInfo()
|
||||
bits = bmp.GetBitmapBits(True)
|
||||
img = Image.frombuffer('RGB', (info['bmWidth'], info['bmHeight']), bits, 'raw', 'BGRX', 0, 1)
|
||||
img.save(out)
|
||||
win32gui.DeleteObject(bmp.GetHandle())
|
||||
save_dc.DeleteDC()
|
||||
mfc_dc.DeleteDC()
|
||||
win32gui.ReleaseDC(hwnd, hwnd_dc)
|
||||
print('PrintWindow ok=', ok, 'size=', img.size, '->', out)
|
||||
|
||||
if __name__ == '__main__':
|
||||
capture(int(sys.argv[1]), sys.argv[2])
|
||||
@@ -0,0 +1,28 @@
|
||||
"""List child windows of a given HWND (all descendants)."""
|
||||
import sys
|
||||
import win32gui
|
||||
|
||||
def walk(hwnd, depth=0, max_depth=4, out=None):
|
||||
out = out if out is not None else []
|
||||
if depth > max_depth:
|
||||
return out
|
||||
kids = []
|
||||
def cb(h, _):
|
||||
kids.append(h)
|
||||
return True
|
||||
try:
|
||||
win32gui.EnumChildWindows(hwnd, cb, None)
|
||||
except Exception:
|
||||
pass
|
||||
for h in kids:
|
||||
rect = win32gui.GetWindowRect(h)
|
||||
out.append((depth, h, win32gui.GetClassName(h), win32gui.GetWindowText(h), rect,
|
||||
bool(win32gui.IsWindowVisible(h))))
|
||||
return out
|
||||
|
||||
if __name__ == '__main__':
|
||||
hwnd = int(sys.argv[1])
|
||||
rows = walk(hwnd)
|
||||
for depth, h, cls, title, rect, vis in rows[:80]:
|
||||
print(f"{' '*depth}{h} cls={cls!r} title={title!r} rect={rect} vis={vis}")
|
||||
print("total:", len(rows))
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Simulate dropping a file onto a window via WM_DROPFILES."""
|
||||
import ctypes
|
||||
import sys
|
||||
import time
|
||||
from ctypes import wintypes
|
||||
|
||||
import win32gui
|
||||
|
||||
user32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
user32.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, ctypes.c_size_t, ctypes.c_ssize_t]
|
||||
user32.PostMessageW.restype = wintypes.BOOL
|
||||
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
|
||||
|
||||
class DROPFILES(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("pFiles", wintypes.DWORD),
|
||||
("pt", wintypes.POINT),
|
||||
("fNC", wintypes.BOOL),
|
||||
("fWide", wintypes.BOOL),
|
||||
]
|
||||
|
||||
|
||||
def drop(hwnd, path, x, y):
|
||||
files = path.encode("utf-16-le") + b"\x00\x00\x00\x00"
|
||||
header = DROPFILES()
|
||||
header.pFiles = ctypes.sizeof(DROPFILES)
|
||||
header.pt = wintypes.POINT(x, y)
|
||||
header.fNC = False
|
||||
header.fWide = True
|
||||
payload = bytes(header) + files
|
||||
size = len(payload)
|
||||
kernel32.GlobalAlloc.argtypes = [wintypes.UINT, ctypes.c_size_t]
|
||||
kernel32.GlobalAlloc.restype = wintypes.HGLOBAL
|
||||
kernel32.GlobalLock.argtypes = [wintypes.HGLOBAL]
|
||||
kernel32.GlobalLock.restype = ctypes.c_void_p
|
||||
kernel32.GlobalUnlock.argtypes = [wintypes.HGLOBAL]
|
||||
kernel32.GlobalUnlock.restype = wintypes.BOOL
|
||||
hglobal = kernel32.GlobalAlloc(0x0042, size) # GMEM_MOVEABLE | GMEM_ZEROINIT
|
||||
ptr = kernel32.GlobalLock(hglobal)
|
||||
ctypes.memmove(ptr, payload, size)
|
||||
kernel32.GlobalUnlock(hglobal)
|
||||
user32.PostMessageW(hwnd, 0x0233, hglobal, 0) # WM_DROPFILES
|
||||
return hglobal
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
hwnd = int(sys.argv[1])
|
||||
path = sys.argv[2]
|
||||
x, y = (int(sys.argv[3]), int(sys.argv[4])) if len(sys.argv) > 4 else (400, 300)
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
h = drop(hwnd, path, x, y)
|
||||
time.sleep(2.0)
|
||||
print("dropped", path, "hglobal", h)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Input automation test: focus WeChat, Ctrl+F, type a query, screenshot the window."""
|
||||
import sys, time, ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.windll.user32
|
||||
ULONG_PTR = ctypes.POINTER(ctypes.c_ulong)
|
||||
|
||||
|
||||
class KEYBDINPUT(ctypes.Structure):
|
||||
_fields_ = [("wVk", wintypes.WORD), ("wScan", wintypes.WORD), ("dwFlags", wintypes.DWORD),
|
||||
("time", wintypes.DWORD), ("dwExtraInfo", ULONG_PTR)]
|
||||
|
||||
|
||||
class INPUT(ctypes.Structure):
|
||||
class _I(ctypes.Union):
|
||||
_fields_ = [("ki", KEYBDINPUT), ("padding", ctypes.c_byte * 32)]
|
||||
_anonymous_ = ("i",)
|
||||
_fields_ = [("type", wintypes.DWORD), ("i", _I)]
|
||||
|
||||
|
||||
KEYEVENTF_KEYUP = 0x0002
|
||||
KEYEVENTF_UNICODE = 0x0004
|
||||
VK_CONTROL = 0x11
|
||||
VK_F = 0x46
|
||||
VK_RETURN = 0x0D
|
||||
|
||||
|
||||
def send_inputs(*inputs):
|
||||
n = len(inputs)
|
||||
arr = (INPUT * n)(*inputs)
|
||||
user32.SendInput(n, arr, ctypes.sizeof(INPUT))
|
||||
|
||||
|
||||
def key_down(vk):
|
||||
i = INPUT(type=1)
|
||||
i.ki = KEYBDINPUT(wVk=vk, wScan=0, dwFlags=0, time=0, dwExtraInfo=None)
|
||||
return i
|
||||
|
||||
|
||||
def key_up(vk):
|
||||
i = INPUT(type=1)
|
||||
i.ki = KEYBDINPUT(wVk=vk, wScan=0, dwFlags=KEYEVENTF_KEYUP, time=0, dwExtraInfo=None)
|
||||
return i
|
||||
|
||||
|
||||
def type_text(text):
|
||||
for ch in text:
|
||||
for flag in (KEYEVENTF_UNICODE, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP):
|
||||
i = INPUT(type=1)
|
||||
i.ki = KEYBDINPUT(wVk=0, wScan=ord(ch), dwFlags=flag, time=0, dwExtraInfo=None)
|
||||
send_inputs(i)
|
||||
time.sleep(0.01)
|
||||
|
||||
|
||||
def ctrl_key(vk):
|
||||
send_inputs(key_down(VK_CONTROL), key_down(vk), key_up(vk), key_up(VK_CONTROL))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
hwnd = int(sys.argv[1])
|
||||
query = sys.argv[2] if len(sys.argv) > 2 else '文件传输助手'
|
||||
user32.ShowWindow(hwnd, 9)
|
||||
user32.SetForegroundWindow(hwnd)
|
||||
time.sleep(0.8)
|
||||
ctrl_key(VK_F)
|
||||
time.sleep(0.6)
|
||||
type_text(query)
|
||||
time.sleep(1.2)
|
||||
print('typed:', query)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Probe MSAA (IAccessible) tree of a window — some Qt/custom UIs expose this instead of UIA."""
|
||||
import sys, ctypes
|
||||
from ctypes import wintypes, POINTER, byref
|
||||
import comtypes
|
||||
from comtypes import GUID
|
||||
import comtypes.client
|
||||
from comtypes.automation import IDispatch
|
||||
|
||||
oleacc = ctypes.oledll.oleacc
|
||||
user32 = ctypes.windll.user32
|
||||
|
||||
OBJID_CLIENT = 0xFFFFFFFC
|
||||
IID_IAccessible = GUID("{618736E0-3C3D-11CF-810C-00AA00389B71}")
|
||||
|
||||
def main(hwnd):
|
||||
ptr = ctypes.POINTER(IDispatch)()
|
||||
hr = oleacc.AccessibleObjectFromWindow(wintypes.HWND(hwnd), wintypes.DWORD(OBJID_CLIENT),
|
||||
byref(IID_IAccessible), byref(ptr))
|
||||
print("hr:", hr, "ptr:", bool(ptr))
|
||||
if not ptr:
|
||||
return
|
||||
acc = ptr.QueryInterface(comtypes.gen.Accessibility.IAccessible) if False else ptr
|
||||
# via IDispatch, call properties through dispinterface is messy; use oleacc helpers on the pointer
|
||||
# Simpler: use accessible accChildCount through vtable is unavailable; try dynamic dispatch
|
||||
try:
|
||||
dispatch = ptr.QueryInterface(IDispatch)
|
||||
print("dispatch ok")
|
||||
except Exception as exc:
|
||||
print("dispatch fail", exc)
|
||||
# Use ctypes to call vtable method 7 (get_accChildCount is 4th method after IUnknown: 3 + 4?).
|
||||
# IAccessible vtable: IUnknown(0-2), get_accParent(3), get_accChildCount(4), get_accChild(5)...
|
||||
vtable = ctypes.cast(ptr, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
|
||||
fn_getcount = ctypes.WINFUNCTYPE(ctypes.HRESULT, ctypes.c_void_p, ctypes.POINTER(ctypes.c_long))(vtable[4])
|
||||
count = ctypes.c_long(-1)
|
||||
hr = fn_getcount(ptr, byref(count))
|
||||
print("accChildCount hr:", hr, "count:", count.value)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(int(sys.argv[1]))
|
||||
@@ -0,0 +1,54 @@
|
||||
"""OCR a PNG (optionally cropped/scaled) with Windows.Media.Ocr (zh-Hans-CN)."""
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from PIL import Image
|
||||
from winsdk.windows.graphics.imaging import BitmapDecoder
|
||||
from winsdk.windows.media.ocr import OcrEngine
|
||||
from winsdk.windows.globalization import Language
|
||||
from winsdk.windows.storage import StorageFile, FileAccessMode
|
||||
|
||||
CACHE = None
|
||||
|
||||
|
||||
async def ocr_png(path):
|
||||
file = await StorageFile.get_file_from_path_async(path)
|
||||
stream = await file.open_async(FileAccessMode.READ)
|
||||
decoder = await BitmapDecoder.create_async(stream)
|
||||
bitmap = await decoder.get_software_bitmap_async()
|
||||
engine = OcrEngine.try_create_from_language(Language('zh-Hans-CN'))
|
||||
result = await engine.recognize_async(bitmap)
|
||||
out = []
|
||||
for line in result.lines:
|
||||
words = list(line.words)
|
||||
if not words:
|
||||
continue
|
||||
x0 = min(w.bounding_rect.x for w in words)
|
||||
y0 = min(w.bounding_rect.y for w in words)
|
||||
x1 = max(w.bounding_rect.x + w.bounding_rect.width for w in words)
|
||||
y1 = max(w.bounding_rect.y + w.bounding_rect.height for w in words)
|
||||
out.append({'text': line.text, 'x': int(x0), 'y': int(y0), 'w': int(x1 - x0), 'h': int(y1 - y0)})
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
path = sys.argv[1]
|
||||
scale = float(sys.argv[2]) if len(sys.argv) > 2 else 1.0
|
||||
crop = None
|
||||
if len(sys.argv) > 6:
|
||||
crop = tuple(int(v) for v in sys.argv[3:7])
|
||||
img = Image.open(path).convert('RGB')
|
||||
if crop:
|
||||
img = img.crop(crop)
|
||||
if scale != 1.0:
|
||||
img = img.resize((int(img.width * scale), int(img.height * scale)), Image.LANCZOS)
|
||||
tmp = path + f'.ocr{scale}.png'
|
||||
img.save(tmp)
|
||||
lines = asyncio.run(ocr_png(tmp))
|
||||
for item in lines:
|
||||
print(f"[{item['x']},{item['y']} {item['w']}x{item['h']}] {item['text']}")
|
||||
print('lines:', len(lines))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""OCR helper with preprocessing for WeChat bubbles (Windows.Media.Ocr, zh-Hans)."""
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
from winsdk.windows.graphics.imaging import BitmapDecoder
|
||||
from winsdk.windows.media.ocr import OcrEngine
|
||||
from winsdk.windows.globalization import Language
|
||||
from winsdk.windows.storage import StorageFile, FileAccessMode
|
||||
|
||||
ENGINE = None
|
||||
|
||||
|
||||
def engine():
|
||||
global ENGINE
|
||||
if ENGINE is None:
|
||||
ENGINE = OcrEngine.try_create_from_language(Language('zh-Hans-CN'))
|
||||
return ENGINE
|
||||
|
||||
|
||||
async def ocr_png(path):
|
||||
file = await StorageFile.get_file_from_path_async(path)
|
||||
stream = await file.open_async(FileAccessMode.READ)
|
||||
decoder = await BitmapDecoder.create_async(stream)
|
||||
bitmap = await decoder.get_software_bitmap_async()
|
||||
result = await engine().recognize_async(bitmap)
|
||||
out = []
|
||||
for line in result.lines:
|
||||
words = list(line.words)
|
||||
if not words:
|
||||
continue
|
||||
x0 = min(w.bounding_rect.x for w in words)
|
||||
y0 = min(w.bounding_rect.y for w in words)
|
||||
x1 = max(w.bounding_rect.x + w.bounding_rect.width for w in words)
|
||||
y1 = max(w.bounding_rect.y + w.bounding_rect.height for w in words)
|
||||
out.append({'text': line.text, 'x': int(x0), 'y': int(y0), 'w': int(x1 - x0), 'h': int(y1 - y0)})
|
||||
return out
|
||||
|
||||
|
||||
def preprocess(img, scale=2.5, invert=False):
|
||||
img = img.convert('L')
|
||||
img = ImageOps.autocontrast(img, cutoff=1)
|
||||
# push mid-tones apart so bubble background becomes white and glyphs black
|
||||
lut = []
|
||||
for i in range(256):
|
||||
if i < 110:
|
||||
lut.append(0)
|
||||
elif i > 175:
|
||||
lut.append(255)
|
||||
else:
|
||||
lut.append(int((i - 110) * 255 / 65))
|
||||
img = img.point(lut)
|
||||
if invert:
|
||||
img = ImageOps.invert(img)
|
||||
if scale != 1.0:
|
||||
img = img.resize((int(img.width * scale), int(img.height * scale)), Image.LANCZOS)
|
||||
return img.convert('RGB')
|
||||
|
||||
|
||||
def main():
|
||||
path = sys.argv[1]
|
||||
scale = float(sys.argv[2]) if len(sys.argv) > 2 else 2.5
|
||||
crop = tuple(int(v) for v in sys.argv[3:7]) if len(sys.argv) > 6 else None
|
||||
img = Image.open(path).convert('RGB')
|
||||
if crop:
|
||||
img = img.crop(crop)
|
||||
for invert in (False, True):
|
||||
out = path + f'.{scale}.{"inv" if invert else "std"}.png'
|
||||
preprocess(img, scale, invert).save(out)
|
||||
lines = asyncio.run(ocr_png(out))
|
||||
print(f'--- invert={invert}')
|
||||
for item in lines:
|
||||
print(f"[{item['x']},{item['y']} {item['w']}x{item['h']}] {item['text']}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Message-injection helpers for WeChat: click / type / key by PostMessage."""
|
||||
import ctypes, sys, time
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||
WM_CHAR = 0x0102
|
||||
WM_KEYDOWN = 0x0100
|
||||
WM_KEYUP = 0x0101
|
||||
WM_LBUTTONDOWN = 0x0201
|
||||
WM_LBUTTONUP = 0x0202
|
||||
WM_MOUSEMOVE = 0x0200
|
||||
MK_LBUTTON = 0x0001
|
||||
|
||||
|
||||
def post_click(hwnd, x, y):
|
||||
lp = (y << 16) | (x & 0xFFFF)
|
||||
user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp)
|
||||
user32.PostMessageW(hwnd, WM_LBUTTONDOWN, MK_LBUTTON, lp)
|
||||
time.sleep(0.05)
|
||||
user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp)
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def post_text(hwnd, text):
|
||||
for ch in text:
|
||||
user32.PostMessageW(hwnd, WM_CHAR, ord(ch), 1)
|
||||
time.sleep(0.02)
|
||||
|
||||
|
||||
def post_key(hwnd, vk):
|
||||
user32.PostMessageW(hwnd, WM_KEYDOWN, vk, 1)
|
||||
user32.PostMessageW(hwnd, WM_KEYUP, vk, 0xC0000001)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
hwnd = int(sys.argv[1])
|
||||
cmd = sys.argv[2]
|
||||
if cmd == 'click':
|
||||
post_click(hwnd, int(sys.argv[3]), int(sys.argv[4]))
|
||||
print('clicked', sys.argv[3], sys.argv[4])
|
||||
elif cmd == 'text':
|
||||
post_text(hwnd, sys.argv[3])
|
||||
print('typed', sys.argv[3])
|
||||
elif cmd == 'key':
|
||||
post_key(hwnd, int(sys.argv[3], 0))
|
||||
print('key', sys.argv[3])
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Probe WeChat (Weixin 4.x) windows and their UI Automation tree."""
|
||||
import sys, ctypes, json
|
||||
import win32gui, win32process
|
||||
|
||||
def list_windows():
|
||||
out = []
|
||||
def cb(hwnd, _):
|
||||
if not win32gui.IsWindowVisible(hwnd):
|
||||
return True
|
||||
title = win32gui.GetWindowText(hwnd)
|
||||
cls = win32gui.GetClassName(hwnd)
|
||||
_, pid = win32process.GetWindowThreadProcessId(hwnd)
|
||||
try:
|
||||
import psutil
|
||||
name = psutil.Process(pid).name()
|
||||
except Exception:
|
||||
name = '?'
|
||||
out.append(dict(hwnd=hwnd, cls=cls, title=title, pid=pid, proc=name,
|
||||
rect=win32gui.GetWindowRect(hwnd)))
|
||||
return True
|
||||
win32gui.EnumWindows(cb, None)
|
||||
return out
|
||||
|
||||
def dump(ctrl, depth=0, max_depth=5, lines=None, max_lines=400):
|
||||
lines = lines if lines is not None else []
|
||||
if depth > max_depth or len(lines) > max_lines:
|
||||
return lines
|
||||
try:
|
||||
r = ctrl.BoundingRectangle
|
||||
rect = f"({r.left},{r.top},{r.right - r.left}x{r.bottom - r.top})"
|
||||
except Exception:
|
||||
rect = "?"
|
||||
child = ctrl.GetFirstChildControl()
|
||||
nchild = 0
|
||||
while child:
|
||||
nchild += 1
|
||||
child = child.GetNextSiblingControl()
|
||||
lines.append(" " * depth + f"[{ctrl.ControlTypeName}] name={ctrl.Name!r} aid={ctrl.AutomationId!r} cls={ctrl.ClassName!r} children={nchild} {rect}")
|
||||
child = ctrl.GetFirstChildControl()
|
||||
while child:
|
||||
dump(child, depth + 1, max_depth, lines, max_lines)
|
||||
child = child.GetNextSiblingControl()
|
||||
return lines
|
||||
|
||||
if __name__ == '__main__':
|
||||
mode = sys.argv[1] if len(sys.argv) > 1 else 'list'
|
||||
if mode == 'list':
|
||||
for w in list_windows():
|
||||
print(json.dumps(w, ensure_ascii=False))
|
||||
else:
|
||||
hwnd = int(sys.argv[2])
|
||||
depth = int(sys.argv[3]) if len(sys.argv) > 3 else 5
|
||||
out = sys.argv[4] if len(sys.argv) > 4 else None
|
||||
import uiautomation as auto
|
||||
ctrl = auto.ControlFromHandle(hwnd)
|
||||
lines = dump(ctrl, 0, depth)
|
||||
text = "\n".join(lines)
|
||||
if out:
|
||||
with open(out, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
print(f"wrote {len(lines)} lines to {out}")
|
||||
else:
|
||||
print(text)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Click a point in WeChat and grab any transient popup window that appears."""
|
||||
import ctypes
|
||||
import sys
|
||||
import time
|
||||
|
||||
import win32con
|
||||
import win32gui
|
||||
import win32process
|
||||
import win32ui
|
||||
from PIL import Image
|
||||
|
||||
H = 197792
|
||||
PID = 10800
|
||||
|
||||
|
||||
def click(px, py):
|
||||
left, top, _, _ = win32gui.GetWindowRect(H)
|
||||
cx, cy = win32gui.ClientToScreen(H, (0, 0))
|
||||
ox, oy = cx - left, cy - top
|
||||
x, y = px - ox, py - oy
|
||||
lp = (y << 16) | (x & 0xFFFF)
|
||||
u = ctypes.windll.user32
|
||||
u.PostMessageW(H, win32con.WM_MOUSEMOVE, 0, lp)
|
||||
time.sleep(0.04)
|
||||
u.PostMessageW(H, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lp)
|
||||
time.sleep(0.04)
|
||||
u.PostMessageW(H, win32con.WM_LBUTTONUP, 0, lp)
|
||||
|
||||
|
||||
def grab(hwnd, path):
|
||||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||||
w, h = right - left, bottom - top
|
||||
if w <= 0 or h <= 0:
|
||||
return False
|
||||
hwnd_dc = win32gui.GetWindowDC(hwnd)
|
||||
mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
|
||||
save_dc = mfc_dc.CreateCompatibleDC()
|
||||
bmp = win32ui.CreateBitmap()
|
||||
bmp.CreateCompatibleBitmap(mfc_dc, w, h)
|
||||
save_dc.SelectObject(bmp)
|
||||
ok = ctypes.windll.user32.PrintWindow(hwnd, save_dc.GetSafeHdc(), 2)
|
||||
info = bmp.GetInfo()
|
||||
img = Image.frombuffer('RGB', (info['bmWidth'], info['bmHeight']),
|
||||
bmp.GetBitmapBits(True), 'raw', 'BGRX', 0, 1)
|
||||
if ok:
|
||||
img.save(path)
|
||||
mfc_dc.DeleteDC()
|
||||
save_dc.DeleteDC()
|
||||
win32gui.ReleaseDC(hwnd, hwnd_dc)
|
||||
return bool(ok)
|
||||
|
||||
|
||||
def popups():
|
||||
found = []
|
||||
def cb(h, _):
|
||||
try:
|
||||
_, pid = win32process.GetWindowThreadProcessId(h)
|
||||
if pid == PID and win32gui.IsWindowVisible(h):
|
||||
cls = win32gui.GetClassName(h)
|
||||
if cls == 'Qt51514QWindowToolSaveBits':
|
||||
found.append(h)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
win32gui.EnumWindows(cb, None)
|
||||
return found
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
px, py = int(sys.argv[1]), int(sys.argv[2])
|
||||
click(px, py)
|
||||
for delay in (0.15, 0.3, 0.6):
|
||||
time.sleep(delay)
|
||||
hits = popups()
|
||||
print('delay', delay, 'popups', hits, [win32gui.GetWindowRect(h) for h in hits])
|
||||
for i, h in enumerate(hits):
|
||||
p = rf'C:\Users\GuoAn\AppData\Local\Temp\wx_popup_{i}.png'
|
||||
print('grab', h, grab(h, p), p)
|
||||
if hits:
|
||||
break
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Hold the WeChat voice button with real SendInput while capturing mid-hold."""
|
||||
import ctypes
|
||||
import sys
|
||||
import time
|
||||
from ctypes import wintypes
|
||||
|
||||
import win32gui
|
||||
import win32ui
|
||||
from PIL import Image
|
||||
|
||||
H = 197792
|
||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||
|
||||
|
||||
class MOUSEINPUT(ctypes.Structure):
|
||||
_fields_ = [('dx', wintypes.LONG), ('dy', wintypes.LONG), ('mouseData', wintypes.DWORD),
|
||||
('dwFlags', wintypes.DWORD), ('time', wintypes.DWORD),
|
||||
('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong))]
|
||||
|
||||
|
||||
class INPUT(ctypes.Structure):
|
||||
class _I(ctypes.Union):
|
||||
_fields_ = [('mi', MOUSEINPUT)]
|
||||
|
||||
_anonymous_ = ('i',)
|
||||
_fields_ = [('type', wintypes.DWORD), ('i', _I)]
|
||||
|
||||
|
||||
def mouse(flag):
|
||||
inp = INPUT()
|
||||
inp.type = 0
|
||||
inp.mi = MOUSEINPUT(0, 0, 0, flag, 0, None)
|
||||
return user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(INPUT))
|
||||
|
||||
|
||||
def grab(path):
|
||||
left, top, right, bottom = win32gui.GetWindowRect(H)
|
||||
w, h = right - left, bottom - top
|
||||
dc = win32gui.GetWindowDC(H)
|
||||
mfc = win32ui.CreateDCFromHandle(dc)
|
||||
mem = mfc.CreateCompatibleDC()
|
||||
bmp = win32ui.CreateBitmap()
|
||||
bmp.CreateCompatibleBitmap(mfc, w, h)
|
||||
mem.SelectObject(bmp)
|
||||
ok = ctypes.windll.user32.PrintWindow(H, mem.GetSafeHdc(), 2)
|
||||
info = bmp.GetInfo()
|
||||
img = Image.frombuffer('RGB', (info['bmWidth'], info['bmHeight']),
|
||||
bmp.GetBitmapBits(True), 'raw', 'BGRX', 0, 1)
|
||||
if ok:
|
||||
img.save(path)
|
||||
mfc.DeleteDC()
|
||||
mem.DeleteDC()
|
||||
win32gui.ReleaseDC(H, dc)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
px, py = int(sys.argv[1]), int(sys.argv[2])
|
||||
secs = float(sys.argv[3]) if len(sys.argv) > 3 else 3.0
|
||||
left, top, _, _ = win32gui.GetWindowRect(H)
|
||||
cx, cy = win32gui.ClientToScreen(H, (0, 0))
|
||||
ox, oy = cx - left, cy - top
|
||||
sx, sy = cx + (px - ox), cy + py
|
||||
print('screen', sx, sy)
|
||||
user32.SetCursorPos(sx, sy)
|
||||
time.sleep(0.3)
|
||||
print('down', mouse(0x0002))
|
||||
time.sleep(0.9)
|
||||
grab(r'C:\Users\GuoAn\AppData\Local\Temp\wx_hold_mid.png')
|
||||
print('mid captured')
|
||||
time.sleep(max(0.0, secs - 0.9))
|
||||
print('up', mouse(0x0004))
|
||||
time.sleep(1.2)
|
||||
grab(r'C:\Users\GuoAn\AppData\Local\Temp\wx_hold_end.png')
|
||||
print('end captured')
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Bring WeChat main window to front and dump its UIA tree."""
|
||||
import sys, time, ctypes
|
||||
import win32gui, uiautomation as auto
|
||||
|
||||
def find_main():
|
||||
hwnd = ctypes.windll.user32.FindWindowW('Qt51514QWindowIcon', None)
|
||||
if hwnd:
|
||||
return hwnd
|
||||
hits = []
|
||||
def cb(h, _):
|
||||
cls = win32gui.GetClassName(h)
|
||||
if cls in ('Qt51514QWindowIcon', 'WeChatMainWndForPC'):
|
||||
hits.append(h)
|
||||
return True
|
||||
win32gui.EnumWindows(cb, None)
|
||||
return hits[0] if hits else 0
|
||||
|
||||
def dump(ctrl, depth=0, max_depth=6, lines=None, max_lines=600):
|
||||
lines = lines if lines is not None else []
|
||||
if depth > max_depth or len(lines) > max_lines:
|
||||
return lines
|
||||
try:
|
||||
r = ctrl.BoundingRectangle
|
||||
rect = f"({r.left},{r.top},{r.right - r.left}x{r.bottom - r.top})"
|
||||
except Exception:
|
||||
rect = "?"
|
||||
kids = []
|
||||
try:
|
||||
child = ctrl.GetFirstChildControl()
|
||||
while child:
|
||||
kids.append(child)
|
||||
child = child.GetNextSiblingControl()
|
||||
except Exception:
|
||||
pass
|
||||
lines.append(" " * depth + f"[{ctrl.ControlTypeName}] name={ctrl.Name!r} aid={ctrl.AutomationId!r} cls={ctrl.ClassName!r} n={len(kids)} {rect}")
|
||||
for child in kids:
|
||||
dump(child, depth + 1, max_depth, lines, max_lines)
|
||||
return lines
|
||||
|
||||
if __name__ == '__main__':
|
||||
hwnd = find_main()
|
||||
print("hwnd:", hwnd)
|
||||
if hwnd:
|
||||
u = ctypes.windll.user32
|
||||
u.ShowWindow(hwnd, 9)
|
||||
u.SetForegroundWindow(hwnd)
|
||||
time.sleep(1.2)
|
||||
print("visible:", bool(u.IsWindowVisible(hwnd)), "rect:", win32gui.GetWindowRect(hwnd))
|
||||
ctrl = auto.ControlFromHandle(hwnd)
|
||||
lines = dump(ctrl, 0, int(sys.argv[1]) if len(sys.argv) > 1 else 6)
|
||||
out = sys.argv[2] if len(sys.argv) > 2 else r'C:\Users\GuoAn\AppData\Local\Temp\wx_tree.txt'
|
||||
with open(out, 'w', encoding='utf-8') as f:
|
||||
f.write("\n".join(lines))
|
||||
print(f"wrote {len(lines)} lines to {out}")
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Click a UIA element by name inside a window (fallback: PostMessage click at center)."""
|
||||
import sys, time
|
||||
import uiautomation as auto
|
||||
|
||||
|
||||
def main(hwnd, name):
|
||||
win = auto.ControlFromHandle(hwnd)
|
||||
if win is None:
|
||||
print('no window for hwnd', hwnd)
|
||||
return 1
|
||||
target = None
|
||||
for ctl in win.GetChildren():
|
||||
if name in (ctl.Name or ''):
|
||||
target = ctl
|
||||
break
|
||||
if target is None:
|
||||
# search deeper
|
||||
for ctl, depth in auto.WalkControl(win, maxDepth=6):
|
||||
if name in (ctl.Name or ''):
|
||||
target = ctl
|
||||
break
|
||||
if target is None:
|
||||
print('not found:', name)
|
||||
return 2
|
||||
rect = target.BoundingRectangle
|
||||
print('found:', target.ControlTypeName, repr(target.Name), rect)
|
||||
try:
|
||||
target.Click()
|
||||
print('clicked via UIA')
|
||||
except Exception as exc:
|
||||
print('uia click failed:', exc)
|
||||
return 3
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
hwnd = int(sys.argv[1])
|
||||
name = sys.argv[2]
|
||||
sys.exit(main(hwnd, name))
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Wait for WeChat main window (post-login) and dump its UIA tree."""
|
||||
import sys, time, ctypes, json
|
||||
import win32gui, win32process, psutil, uiautomation as auto
|
||||
|
||||
def weixin_pids():
|
||||
pids = set()
|
||||
for p in psutil.process_iter(['pid', 'name']):
|
||||
try:
|
||||
if p.info['name'] and p.info['name'].lower() == 'weixin.exe':
|
||||
pids.add(p.info['pid'])
|
||||
except Exception:
|
||||
pass
|
||||
return pids
|
||||
|
||||
def windows():
|
||||
rows = []
|
||||
def cb(h, _):
|
||||
_, pid = win32process.GetWindowThreadProcessId(h)
|
||||
if pid in weixin_pids():
|
||||
rect = win32gui.GetWindowRect(h)
|
||||
rows.append(dict(hwnd=h, pid=pid, cls=win32gui.GetClassName(h),
|
||||
title=win32gui.GetWindowText(h),
|
||||
w=rect[2] - rect[0], h=rect[3] - rect[1]))
|
||||
return True
|
||||
win32gui.EnumWindows(cb, None)
|
||||
return rows
|
||||
|
||||
def dump(ctrl, depth=0, max_depth=8, lines=None, max_lines=1500):
|
||||
lines = lines if lines is not None else []
|
||||
if depth > max_depth or len(lines) > max_lines:
|
||||
return lines
|
||||
try:
|
||||
r = ctrl.BoundingRectangle
|
||||
rect = f"({r.left},{r.top},{r.right - r.left}x{r.bottom - r.top})"
|
||||
except Exception:
|
||||
rect = "?"
|
||||
kids = []
|
||||
try:
|
||||
child = ctrl.GetFirstChildControl()
|
||||
while child:
|
||||
kids.append(child)
|
||||
child = child.GetNextSiblingControl()
|
||||
except Exception:
|
||||
pass
|
||||
lines.append(" " * depth + f"[{ctrl.ControlTypeName}] name={ctrl.Name!r} aid={ctrl.AutomationId!r} cls={ctrl.ClassName!r} n={len(kids)} {rect}")
|
||||
for child in kids:
|
||||
dump(child, depth + 1, max_depth, lines, max_lines)
|
||||
return lines
|
||||
|
||||
if __name__ == '__main__':
|
||||
deadline = time.time() + int(sys.argv[1] if len(sys.argv) > 1 else 600)
|
||||
out = sys.argv[2] if len(sys.argv) > 2 else r'C:\Users\GuoAn\AppData\Local\Temp\wx_main_tree.txt'
|
||||
target = None
|
||||
while time.time() < deadline:
|
||||
for w in windows():
|
||||
if w['w'] >= 600 and 'Login' not in w['cls']:
|
||||
target = w
|
||||
break
|
||||
if target:
|
||||
break
|
||||
time.sleep(5)
|
||||
if not target:
|
||||
print("TIMEOUT: main window not found")
|
||||
sys.exit(2)
|
||||
print("main window:", json.dumps(target, ensure_ascii=False))
|
||||
u = ctypes.windll.user32
|
||||
u.ShowWindow(target['hwnd'], 9)
|
||||
u.SetForegroundWindow(target['hwnd'])
|
||||
time.sleep(1.5)
|
||||
ctrl = auto.ControlFromHandle(target['hwnd'])
|
||||
lines = dump(ctrl)
|
||||
with open(out, 'w', encoding='utf-8') as f:
|
||||
f.write("\n".join(lines))
|
||||
print(f"wrote {len(lines)} lines to {out}")
|
||||
@@ -0,0 +1,26 @@
|
||||
"""List all windows (visible or not) belonging to Weixin processes."""
|
||||
import win32gui, win32process, psutil, json, sys
|
||||
|
||||
target_pids = {}
|
||||
for p in psutil.process_iter(['pid', 'name']):
|
||||
try:
|
||||
if p.info['name'] and p.info['name'].lower() in ('weixin.exe', 'wechat.exe'):
|
||||
target_pids[p.info['pid']] = p.info['name']
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
rows = []
|
||||
def cb(hwnd, _):
|
||||
_, pid = win32process.GetWindowThreadProcessId(hwnd)
|
||||
if pid in target_pids:
|
||||
rows.append(dict(hwnd=hwnd, pid=pid, cls=win32gui.GetClassName(hwnd),
|
||||
title=win32gui.GetWindowText(hwnd),
|
||||
visible=bool(win32gui.IsWindowVisible(hwnd)),
|
||||
iconic=bool(win32gui.IsIconic(hwnd)),
|
||||
rect=win32gui.GetWindowRect(hwnd)))
|
||||
return True
|
||||
|
||||
win32gui.EnumWindows(cb, None)
|
||||
print("pids:", target_pids)
|
||||
for r in rows:
|
||||
print(json.dumps(r, ensure_ascii=False))
|
||||
Reference in New Issue
Block a user