cortico-world-agent-speed 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +64 -0
- package/LICENSE +0 -14
- package/README.md +29 -11
- package/THIRD_PARTY_NOTICES.md +69 -0
- package/activity.d.ts +15 -0
- package/activity.js +88 -3
- package/describe.json +806 -0
- package/dist/webui.css +2 -0
- package/dist/webui.css.map +7 -0
- package/dist/webui.js +2 -0
- package/dist/webui.js.map +7 -0
- package/host/app-store.cjs +68 -0
- package/host/cursor.cjs +67 -0
- package/host/electron-main.cjs +666 -0
- package/host/input-shape.cjs +63 -0
- package/host/mouse-lease.cjs +77 -0
- package/host/overlay.cjs +139 -0
- package/host/portrait.cjs +52 -0
- package/host/preload.cjs +60 -14
- package/host/renderer-gone.cjs +24 -0
- package/host/windows.cjs +251 -0
- package/package.json +27 -7
- package/scripts/build-webui.mjs +40 -0
- package/scripts/speech-bank/build.py +166 -0
- package/scripts/speech-bank/dicts.py +76 -0
- package/src/ENV_PROMPT.en.md +51 -0
- package/src/ENV_PROMPT.md +51 -0
- package/src/asr/address.ts +25 -0
- package/src/asr/hotkey.ts +335 -0
- package/src/asr/result.ts +51 -0
- package/src/asr/segmenter.ts +269 -0
- package/src/asr/sherpa.ts +280 -0
- package/src/asr/simplify.ts +38 -0
- package/src/asr/system-recognizer.ts +292 -0
- package/src/asr/system-sapi.ps1 +173 -0
- package/src/asr/transcription-api.ts +176 -0
- package/src/chat.ts +212 -0
- package/src/config.ts +481 -0
- package/src/cua/ENV_PROMPT.en.md +29 -0
- package/src/cua/ENV_PROMPT.md +29 -0
- package/src/cua/config.ts +88 -0
- package/src/cua/cua.ts +712 -0
- package/src/cua/engine/darwin.ts +410 -0
- package/src/cua/engine/display.ts +55 -0
- package/src/cua/engine/fail.ts +15 -0
- package/src/cua/engine/foreground.ts +8 -0
- package/src/cua/engine/image.ts +57 -0
- package/src/cua/engine/keys.ts +70 -0
- package/src/cua/engine/linux-keys.ts +29 -0
- package/src/cua/engine/linux.ts +343 -0
- package/src/cua/engine/mac-keys.ts +57 -0
- package/src/cua/engine/user-activity.ts +54 -0
- package/src/cua/engine/wait-idle.ts +31 -0
- package/src/cua/engine/win32.ts +299 -0
- package/src/cua/engine-child.ts +274 -0
- package/src/cua/engine-ipc.ts +140 -0
- package/src/cua/i18n/de.ts +53 -0
- package/src/cua/i18n/en.ts +63 -0
- package/src/cua/i18n/es-419.ts +53 -0
- package/src/cua/i18n/fr.ts +53 -0
- package/src/cua/i18n/index.ts +26 -0
- package/src/cua/i18n/it.ts +53 -0
- package/src/cua/i18n/ja.ts +53 -0
- package/src/cua/i18n/ko.ts +53 -0
- package/src/cua/i18n/pt-BR.ts +53 -0
- package/src/cua/i18n/ru.ts +59 -0
- package/src/cua/i18n/zh-Hant.ts +53 -0
- package/src/cua/i18n/zh.ts +59 -0
- package/src/cua/model-text.ts +252 -0
- package/src/cua/terminal.ts +31 -0
- package/src/cua/tools.ts +153 -0
- package/src/definition.ts +146 -0
- package/src/host-reason.ts +32 -0
- package/src/i18n/de.ts +409 -0
- package/src/i18n/en.ts +443 -0
- package/src/i18n/es-419.ts +409 -0
- package/src/i18n/fr.ts +409 -0
- package/src/i18n/index.ts +56 -0
- package/src/i18n/it.ts +409 -0
- package/src/i18n/ja.ts +409 -0
- package/src/i18n/ko.ts +409 -0
- package/src/i18n/pt-BR.ts +409 -0
- package/src/i18n/ru.ts +415 -0
- package/src/i18n/zh-Hant.ts +409 -0
- package/src/i18n/zh.ts +440 -0
- package/src/index.ts +15 -0
- package/src/model-text.ts +344 -0
- package/src/moves.ts +101 -0
- package/src/pack-import.ts +361 -0
- package/src/packs.ts +449 -0
- package/src/runtime/download.ts +29 -0
- package/src/runtime/store.ts +293 -0
- package/src/script.ts +202 -0
- package/src/self.ts +247 -0
- package/src/server.ts +479 -0
- package/src/speech/data/CMUDICT-LICENSE +33 -0
- package/src/speech/data/IPADIC-COPYING +71 -0
- package/src/speech/data/UNICODE-LICENSE +39 -0
- package/src/speech/data/en.tsv.gz +0 -0
- package/src/speech/data/ja-ipadic.tsv.gz +0 -0
- package/src/speech/data/ja-unihan.tsv.gz +0 -0
- package/src/speech/data/zh.json +1 -0
- package/src/speech/index.ts +204 -0
- package/src/speech/ipa.ts +83 -0
- package/src/speech/japanese.ts +105 -0
- package/src/speech/jukujikun.ts +22 -0
- package/src/speech/korean.ts +35 -0
- package/src/speech/lang.ts +151 -0
- package/src/speech/rules.ts +72 -0
- package/src/speech/syllable.ts +76 -0
- package/src/status.ts +164 -0
- package/src/tools.ts +110 -0
- package/src/webui/api-rows.css +2 -0
- package/src/webui/api-rows.ts +44 -0
- package/src/webui/client.ts +451 -0
- package/src/webui/dress-dialog.css +14 -0
- package/src/webui/dress-dialog.ts +117 -0
- package/src/webui/dress-panel.ts +160 -0
- package/src/webui/key-capture.ts +60 -0
- package/src/webui/shared/modal.css +13 -0
- package/src/webui/shared/modal.ts +77 -0
- package/src/webui/shared/problem.css +15 -0
- package/src/webui/shared/problem.ts +217 -0
- package/src/webui/shared/strings.ts +5 -0
- package/src/webui/style.css +50 -0
- package/src/window-host.ts +116 -0
- package/src/world.ts +2926 -0
- package/web/activity-motion.js +117 -0
- package/web/appearance.js +60 -0
- package/web/body-host.js +257 -0
- package/web/coo/coo.js +384 -0
- package/web/coo/figure.js +15 -0
- package/web/coo/figure.json +1224 -0
- package/web/dist/dress-dialog.css +1 -0
- package/web/dist/dress-dialog.js +1 -0
- package/web/drag-row.js +49 -0
- package/web/drag.js +149 -0
- package/web/dress.css +170 -0
- package/web/dress.html +37 -0
- package/web/dress.js +786 -0
- package/web/figure-frame.html +16 -0
- package/web/figure-frame.js +128 -0
- package/web/frame-loop.js +55 -0
- package/web/hints.js +77 -0
- package/web/i18n/de.js +170 -0
- package/web/i18n/en.js +177 -0
- package/web/i18n/es-419.js +170 -0
- package/web/i18n/fr.js +170 -0
- package/web/i18n/it.js +170 -0
- package/web/i18n/ja.js +170 -0
- package/web/i18n/ko.js +170 -0
- package/web/i18n/pt-BR.js +170 -0
- package/web/i18n/ru.js +170 -0
- package/web/i18n/zh-Hant.js +170 -0
- package/web/i18n/zh.js +175 -0
- package/web/i18n.js +54 -0
- package/{renderer/vendor → web}/kit/body.js +31 -58
- package/web/looks.js +70 -0
- package/web/mic-worklet.js +36 -0
- package/web/mic.js +117 -0
- package/web/motion-frames.js +80 -0
- package/web/motion-level.js +40 -0
- package/web/new-year-2027.svg +238 -0
- package/web/overlay.html +16 -0
- package/web/overlay.js +100 -0
- package/web/pet-app.js +3000 -0
- package/web/pet.css +642 -0
- package/web/pet.html +21 -0
- package/web/scale-slider.js +259 -0
- package/web/show-hide.js +49 -0
- package/web/sound.js +245 -0
- package/web/speech/zh.json +1 -0
- package/web/speech/zh.ogg +0 -0
- package/web/speech.js +197 -0
- package/web/stage.js +160 -0
- package/web/swap-motion.js +119 -0
- package/web/ui.js +195 -0
- package/host/launch.js +0 -187
- package/host/library.cjs +0 -638
- package/host/main.cjs +0 -389
- package/index.js +0 -93
- package/renderer/index.html +0 -22
- package/renderer/pet-sandbox.html +0 -11
- package/renderer/pet.css +0 -38
- package/renderer/pet.js +0 -251
- package/renderer/vendor/activity-motion.js +0 -101
- package/renderer/vendor/figure-frame.js +0 -115
- package/renderer/vendor/pack.css +0 -2
- /package/{renderer/vendor → web}/kit/rig.js +0 -0
package/host/windows.cjs
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The other windows on the desktop, for a figure pack whose manifest `needs` `windows`.
|
|
3
|
+
*
|
|
4
|
+
* `createWindowSource({ screen }).list(own)` lists the visible top-level windows front first, as
|
|
5
|
+
* `{ id, x, y, w, h, active }` in Electron's screen DIPs, leaving out `own` (the pet window's native handle)
|
|
6
|
+
* and what is not an ordinary window on the current desktop. `id` is the window's native number as a string
|
|
7
|
+
* (HWND, CGWindowID, X11 window id); `active` marks the foreground window and is absent on macOS. Only that
|
|
8
|
+
* leaves this file: no title, class or program name. `ledgesFrom(rects, origin, view)` turns the list into the
|
|
9
|
+
* parts of each top edge no window in front of it hides, as `{ x0, x1, y }` in the pet window's page pixels;
|
|
10
|
+
* `windowsFrom(rects, origin, view)` gives the whole windows on the page, as `{ id, x0, y0, x1, y1, active }`.
|
|
11
|
+
*
|
|
12
|
+
* Each platform reads what the computer-use engine reads (src/cua/engine), here in the window process:
|
|
13
|
+
* - Windows: the z-order from GetTopWindow/GetWindow and the frame DWM draws, in physical pixels, each
|
|
14
|
+
* display at its own scale (`screen.screenToDipPoint` picks the display a corner is on; not `toDip`: on
|
|
15
|
+
* Windows Electron's `nativeOrigin` is a display's pixel origin divided by its scale, so a display off the
|
|
16
|
+
* origin at other than 100% would come out shifted); minimized, cloaked (another virtual desktop), tool
|
|
17
|
+
* and click-through windows and the shell's own are left out. The foreground window is GetForegroundWindow's.
|
|
18
|
+
* - macOS: CGWindowListCopyWindowInfo, front to back, layer 0 only (ordinary app windows; the pet
|
|
19
|
+
* window floats above it), reading `kCGWindowLayer`, `kCGWindowNumber` and `kCGWindowBounds` and
|
|
20
|
+
* never the window's name, which is what the Screen Recording permission guards. Bounds are points of
|
|
21
|
+
* the global display space, which is what Electron's DIPs are on macOS, so they need no conversion.
|
|
22
|
+
* - Linux: the window manager's `_NET_CLIENT_LIST_STACKING` over X11, in physical pixels of the whole
|
|
23
|
+
* X screen (one scale for all displays), with the frame the manager draws (`_NET_FRAME_EXTENTS`) put
|
|
24
|
+
* back and a client-side frame's shadow (`_GTK_FRAME_EXTENTS`) taken off; hidden windows, windows on
|
|
25
|
+
* another workspace, docks and the desktop are left out; the foreground window is `_NET_ACTIVE_WINDOW`.
|
|
26
|
+
* Under Wayland the app runs through XWayland and sees only the X11 programs' windows.
|
|
27
|
+
* Elsewhere, or where the native calls do not load, `list` answers null and nothing is read. koffi
|
|
28
|
+
* loads on the first `list`, so the window process reads nothing until a pack asks.
|
|
29
|
+
*/
|
|
30
|
+
const { toDip } = require('./cursor.cjs');
|
|
31
|
+
|
|
32
|
+
/** Most windows walked in z-order on one read. */
|
|
33
|
+
const WINDOWS_MAX = 512;
|
|
34
|
+
/** Most tops one read reports. */
|
|
35
|
+
const LEDGES_MAX = 64;
|
|
36
|
+
/** Most whole windows one read reports, the frontmost kept. */
|
|
37
|
+
const RECTS_MAX = 64;
|
|
38
|
+
|
|
39
|
+
/** Windows: `(own) => rects` in DIPs. */
|
|
40
|
+
function openWin32(koffi, screen) {
|
|
41
|
+
const GW_HWNDNEXT = 2, GWL_EXSTYLE = -20;
|
|
42
|
+
const WS_EX_TRANSPARENT = 0x00000020, WS_EX_TOOLWINDOW = 0x00000080;
|
|
43
|
+
const DWMWA_EXTENDED_FRAME_BOUNDS = 9, DWMWA_CLOAKED = 14;
|
|
44
|
+
// the desktop, its wallpaper host and the taskbars
|
|
45
|
+
const SHELL_CLASSES = new Set(['Progman', 'WorkerW', 'Shell_TrayWnd', 'Shell_SecondaryTrayWnd']);
|
|
46
|
+
const user32 = koffi.load('user32.dll'), dwmapi = koffi.load('dwmapi.dll');
|
|
47
|
+
const GetTopWindow = user32.func('intptr_t __stdcall GetTopWindow(intptr_t hwnd)');
|
|
48
|
+
const GetWindow = user32.func('intptr_t __stdcall GetWindow(intptr_t hwnd, uint32_t cmd)');
|
|
49
|
+
const IsWindowVisible = user32.func('int __stdcall IsWindowVisible(intptr_t hwnd)');
|
|
50
|
+
const IsIconic = user32.func('int __stdcall IsIconic(intptr_t hwnd)');
|
|
51
|
+
const GetWindowLongW = user32.func('int32_t __stdcall GetWindowLongW(intptr_t hwnd, int index)');
|
|
52
|
+
const GetClassNameW = user32.func('int __stdcall GetClassNameW(intptr_t hwnd, void *buf, int max)');
|
|
53
|
+
const GetWindowRect = user32.func('int __stdcall GetWindowRect(intptr_t hwnd, void *rect)');
|
|
54
|
+
const GetForegroundWindow = user32.func('intptr_t __stdcall GetForegroundWindow()');
|
|
55
|
+
const DwmGetWindowAttribute = dwmapi.func('int32_t __stdcall DwmGetWindowAttribute(intptr_t hwnd, uint32_t attr, void *value, uint32_t size)');
|
|
56
|
+
const dip = (x, y) => { const p = screen.screenToDipPoint({ x, y }); return { x: Math.floor(p.x), y: Math.floor(p.y) }; };
|
|
57
|
+
return (own) => {
|
|
58
|
+
const rect = Buffer.alloc(16), flag = Buffer.alloc(4), name = Buffer.alloc(128);
|
|
59
|
+
const out = [];
|
|
60
|
+
try {
|
|
61
|
+
const fg = GetForegroundWindow();
|
|
62
|
+
let h = GetTopWindow(0);
|
|
63
|
+
for (let i = 0; h && i < WINDOWS_MAX; i++, h = GetWindow(h, GW_HWNDNEXT)) {
|
|
64
|
+
if (BigInt(h) === own || !IsWindowVisible(h) || IsIconic(h)) continue;
|
|
65
|
+
if (GetWindowLongW(h, GWL_EXSTYLE) & (WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT)) continue;
|
|
66
|
+
if (DwmGetWindowAttribute(h, DWMWA_CLOAKED, flag, 4) === 0 && flag.readUInt32LE(0) !== 0) continue;
|
|
67
|
+
if (GetClassNameW(h, name, 64) > 0 && SHELL_CLASSES.has(name.toString('utf16le').split('\0')[0])) continue;
|
|
68
|
+
// the frame DWM draws, without the invisible resize borders GetWindowRect counts in
|
|
69
|
+
if (DwmGetWindowAttribute(h, DWMWA_EXTENDED_FRAME_BOUNDS, rect, 16) !== 0 && !GetWindowRect(h, rect)) continue;
|
|
70
|
+
const p = dip(rect.readInt32LE(0), rect.readInt32LE(4)), q = dip(rect.readInt32LE(8), rect.readInt32LE(12));
|
|
71
|
+
if (q.x > p.x && q.y > p.y) out.push({ id: String(h), x: p.x, y: p.y, w: q.x - p.x, h: q.y - p.y, active: h === fg });
|
|
72
|
+
}
|
|
73
|
+
} catch { /* a window closing mid-walk fails a call; what was read stands */ }
|
|
74
|
+
return out;
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** macOS: `() => rects` in points (DIPs); the pet window floats above layer 0, so it never shows in them. */
|
|
79
|
+
function openDarwin(koffi) {
|
|
80
|
+
const cg = koffi.load('/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics');
|
|
81
|
+
const cf = koffi.load('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation');
|
|
82
|
+
// a name of its own: koffi type names are per process
|
|
83
|
+
koffi.struct('PetWindowsCGRect', { x: 'double', y: 'double', width: 'double', height: 'double' });
|
|
84
|
+
const CGWindowListCopyWindowInfo = cg.func('void *CGWindowListCopyWindowInfo(uint32_t option, uint32_t relativeToWindow)');
|
|
85
|
+
const CGRectMakeWithDictionaryRepresentation = cg.func('bool CGRectMakeWithDictionaryRepresentation(void *dict, _Out_ PetWindowsCGRect *rect)');
|
|
86
|
+
const CFRelease = cf.func('void CFRelease(void *ref)');
|
|
87
|
+
const CFArrayGetCount = cf.func('long CFArrayGetCount(void *array)');
|
|
88
|
+
const CFArrayGetValueAtIndex = cf.func('void *CFArrayGetValueAtIndex(void *array, long index)');
|
|
89
|
+
const CFDictionaryGetValue = cf.func('void *CFDictionaryGetValue(void *dict, void *key)');
|
|
90
|
+
const CFStringCreateWithCString = cf.func('void *CFStringCreateWithCString(void *alloc, const char *s, uint32_t encoding)');
|
|
91
|
+
const CFNumberGetValue = cf.func('bool CFNumberGetValue(void *n, long type, _Out_ int64_t *value)');
|
|
92
|
+
// kCFStringEncodingUTF8; the keys live as long as the process
|
|
93
|
+
const LAYER = CFStringCreateWithCString(null, 'kCGWindowLayer', 0x08000100);
|
|
94
|
+
const BOUNDS = CFStringCreateWithCString(null, 'kCGWindowBounds', 0x08000100);
|
|
95
|
+
const NUMBER = CFStringCreateWithCString(null, 'kCGWindowNumber', 0x08000100);
|
|
96
|
+
// kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements; kCFNumberSInt64Type
|
|
97
|
+
const ON_SCREEN = 1 | 16, SINT64 = 4;
|
|
98
|
+
return () => {
|
|
99
|
+
const list = CGWindowListCopyWindowInfo(ON_SCREEN, 0);
|
|
100
|
+
if (!list) return [];
|
|
101
|
+
const out = [];
|
|
102
|
+
try {
|
|
103
|
+
const n = Math.min(WINDOWS_MAX, Number(CFArrayGetCount(list)));
|
|
104
|
+
for (let i = 0; i < n; i++) {
|
|
105
|
+
const w = CFArrayGetValueAtIndex(list, i);
|
|
106
|
+
const layer = CFDictionaryGetValue(w, LAYER), v = [0n];
|
|
107
|
+
if (!layer || !CFNumberGetValue(layer, SINT64, v) || Number(v[0]) !== 0) continue;
|
|
108
|
+
const bounds = CFDictionaryGetValue(w, BOUNDS);
|
|
109
|
+
const r = { x: 0, y: 0, width: 0, height: 0 };
|
|
110
|
+
if (!bounds || !CGRectMakeWithDictionaryRepresentation(bounds, r) || !(r.width > 0) || !(r.height > 0)) continue;
|
|
111
|
+
const number = CFDictionaryGetValue(w, NUMBER), id = [0n];
|
|
112
|
+
if (!number || !CFNumberGetValue(number, SINT64, id)) continue;
|
|
113
|
+
out.push({ id: String(id[0]), x: r.x, y: r.y, w: r.width, h: r.height });
|
|
114
|
+
}
|
|
115
|
+
} finally {
|
|
116
|
+
CFRelease(list);
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Linux (X11): `(own) => rects` in DIPs, or a throw when there is no X server to open. */
|
|
123
|
+
function openX11(koffi, screen) {
|
|
124
|
+
const x11 = koffi.load('libX11.so.6');
|
|
125
|
+
const XOpenDisplay = x11.func('void *XOpenDisplay(const char *name)');
|
|
126
|
+
const XDefaultRootWindow = x11.func('unsigned long XDefaultRootWindow(void *dpy)');
|
|
127
|
+
const XInternAtom = x11.func('unsigned long XInternAtom(void *dpy, const char *name, int onlyIfExists)');
|
|
128
|
+
const XGetWindowProperty = x11.func('int XGetWindowProperty(void *dpy, unsigned long w, unsigned long prop, long offset, long length, int del, unsigned long type, _Out_ unsigned long *actualType, _Out_ int *actualFormat, _Out_ unsigned long *nitems, _Out_ unsigned long *after, _Out_ void **data)');
|
|
129
|
+
const XFree = x11.func('int XFree(void *data)');
|
|
130
|
+
const XGetGeometry = x11.func('int XGetGeometry(void *dpy, unsigned long d, _Out_ unsigned long *root, _Out_ int *x, _Out_ int *y, _Out_ unsigned int *w, _Out_ unsigned int *h, _Out_ unsigned int *border, _Out_ unsigned int *depth)');
|
|
131
|
+
const XTranslateCoordinates = x11.func('int XTranslateCoordinates(void *dpy, unsigned long src, unsigned long dst, int x, int y, _Out_ int *dx, _Out_ int *dy, _Out_ unsigned long *child)');
|
|
132
|
+
const XSync = x11.func('int XSync(void *dpy, int discard)');
|
|
133
|
+
const XSetErrorHandler = x11.func('void *XSetErrorHandler(void *handler)');
|
|
134
|
+
const dpy = XOpenDisplay(null);
|
|
135
|
+
if (!dpy) throw new Error('no X display');
|
|
136
|
+
const root = XDefaultRootWindow(dpy);
|
|
137
|
+
// a window closing between being listed and being read raises BadWindow, and Xlib's default handler exits
|
|
138
|
+
// the process: the read runs under a handler that ignores errors, and the one before it comes back afterwards
|
|
139
|
+
const ignore = koffi.register(() => 0, koffi.pointer(koffi.proto('int PetWindowsXErrorHandler(void *dpy, void *event)')));
|
|
140
|
+
const atoms = new Map();
|
|
141
|
+
const atom = (name) => {
|
|
142
|
+
if (!atoms.has(name)) atoms.set(name, Number(XInternAtom(dpy, name, 0)));
|
|
143
|
+
return atoms.get(name);
|
|
144
|
+
};
|
|
145
|
+
/** A 32-bit window property as numbers, [] when absent. */
|
|
146
|
+
const prop = (w, name) => {
|
|
147
|
+
const type = [0], format = [0], n = [0], after = [0], data = [null];
|
|
148
|
+
if (XGetWindowProperty(dpy, w, atom(name), 0, 1024, 0, 0, type, format, n, after, data) !== 0 || !data[0]) return [];
|
|
149
|
+
try {
|
|
150
|
+
const count = Number(n[0]);
|
|
151
|
+
return format[0] === 32 && count ? Array.from(koffi.decode(data[0], koffi.array('unsigned long', count)), Number) : [];
|
|
152
|
+
} finally {
|
|
153
|
+
XFree(data[0]);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
const ALL_DESKTOPS = 0xffffffff;
|
|
157
|
+
return (own) => {
|
|
158
|
+
const displays = screen.getAllDisplays();
|
|
159
|
+
const previous = XSetErrorHandler(ignore);
|
|
160
|
+
const out = [];
|
|
161
|
+
try {
|
|
162
|
+
const stack = prop(root, '_NET_CLIENT_LIST_STACKING');
|
|
163
|
+
const current = prop(root, '_NET_CURRENT_DESKTOP')[0], active = prop(root, '_NET_ACTIVE_WINDOW')[0];
|
|
164
|
+
const hidden = atom('_NET_WM_STATE_HIDDEN'), skipTypes = [atom('_NET_WM_WINDOW_TYPE_DOCK'), atom('_NET_WM_WINDOW_TYPE_DESKTOP')];
|
|
165
|
+
// the stacking list runs bottom to top
|
|
166
|
+
for (const w of stack.reverse().slice(0, WINDOWS_MAX)) {
|
|
167
|
+
if (BigInt(w) === own || prop(w, '_NET_WM_STATE').includes(hidden)) continue;
|
|
168
|
+
const desk = prop(w, '_NET_WM_DESKTOP')[0];
|
|
169
|
+
if (desk !== undefined && current !== undefined && desk !== current && desk !== ALL_DESKTOPS) continue;
|
|
170
|
+
if (prop(w, '_NET_WM_WINDOW_TYPE').some((t) => skipTypes.includes(t))) continue;
|
|
171
|
+
const r = [0], gx = [0], gy = [0], gw = [0], gh = [0], b = [0], d = [0];
|
|
172
|
+
if (!XGetGeometry(dpy, w, r, gx, gy, gw, gh, b, d)) continue;
|
|
173
|
+
const ax = [0], ay = [0], child = [0];
|
|
174
|
+
if (!XTranslateCoordinates(dpy, w, root, 0, 0, ax, ay, child)) continue;
|
|
175
|
+
// [left, right, top, bottom]: the manager's frame outside the client, a client-side frame's shadow inside it
|
|
176
|
+
const [fl = 0, fr = 0, ft = 0, fb = 0] = prop(w, '_NET_FRAME_EXTENTS');
|
|
177
|
+
const [sl = 0, sr = 0, st = 0, sb = 0] = prop(w, '_GTK_FRAME_EXTENTS');
|
|
178
|
+
const x = ax[0] - fl + sl, y = ay[0] - ft + st, wd = gw[0] + fl + fr - sl - sr, ht = gh[0] + ft + fb - st - sb;
|
|
179
|
+
const p = toDip({ x, y }, displays), q = toDip({ x: x + wd, y: y + ht }, displays);
|
|
180
|
+
if (q.x > p.x && q.y > p.y) out.push({ id: String(w), x: p.x, y: p.y, w: q.x - p.x, h: q.y - p.y, active: w === active });
|
|
181
|
+
}
|
|
182
|
+
} finally {
|
|
183
|
+
// errors the server sends late arrive while ours is still the handler
|
|
184
|
+
XSync(dpy, 0);
|
|
185
|
+
XSetErrorHandler(previous);
|
|
186
|
+
}
|
|
187
|
+
return out;
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const OPENERS = { win32: openWin32, darwin: openDarwin, linux: openX11 };
|
|
192
|
+
|
|
193
|
+
function createWindowSource({ screen, platform = process.platform, loadKoffi = () => require('koffi') }) {
|
|
194
|
+
const opener = OPENERS[platform];
|
|
195
|
+
if (!opener) return { available: false, list: () => null };
|
|
196
|
+
let read;
|
|
197
|
+
/** The windows in front first, or null when the native calls will not load (no X server, say). */
|
|
198
|
+
const list = (own) => {
|
|
199
|
+
if (read === null) return null;
|
|
200
|
+
if (!read) {
|
|
201
|
+
try { read = opener(loadKoffi(), screen); } catch { read = null; return null; }
|
|
202
|
+
}
|
|
203
|
+
try { return read(own); } catch { return null; }
|
|
204
|
+
};
|
|
205
|
+
return { available: true, list };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** `[a, b]` less `[c, d]`. */
|
|
209
|
+
function cut([a, b], [c, d]) {
|
|
210
|
+
if (d <= a || c >= b) return [[a, b]];
|
|
211
|
+
const out = [];
|
|
212
|
+
if (c > a) out.push([a, c]);
|
|
213
|
+
if (d < b) out.push([d, b]);
|
|
214
|
+
return out;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The visible tops of `rects` (screen DIPs, front first) in page pixels of the pet window: `origin` is its top
|
|
219
|
+
* left on screen, `view` its `{ width, floor }` (the floor's height in the page). A top counts where it is on the
|
|
220
|
+
* page above the floor, and only the parts no window in front covers; tops come highest first.
|
|
221
|
+
*/
|
|
222
|
+
function ledgesFrom(rects, origin, view) {
|
|
223
|
+
const out = [], front = [];
|
|
224
|
+
for (const r of rects) {
|
|
225
|
+
const x0 = r.x - origin.x, x1 = x0 + r.w, y = r.y - origin.y;
|
|
226
|
+
let spans = [[Math.max(0, x0), Math.min(view.width, x1)]];
|
|
227
|
+
for (const a of front) if (y >= a.y && y < a.y + a.h) spans = spans.flatMap((s) => cut(s, [a.x0, a.x1]));
|
|
228
|
+
front.push({ x0, x1, y, h: r.h });
|
|
229
|
+
if (y <= 0 || y >= view.floor) continue;
|
|
230
|
+
for (const [a, b] of spans) if (b > a) out.push({ x0: a, x1: b, y });
|
|
231
|
+
}
|
|
232
|
+
return out.sort((a, b) => a.y - b.y || a.x0 - b.x0).slice(0, LEDGES_MAX);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* The windows of `rects` (screen DIPs, front first) that reach onto the page of the pet window above its floor,
|
|
237
|
+
* front first, as `{ id, x0, y0, x1, y1 }` in page pixels and whole (parts off the page and behind other windows
|
|
238
|
+
* included), with `active` where the platform reports it; `origin` and `view` as for `ledgesFrom`.
|
|
239
|
+
*/
|
|
240
|
+
function windowsFrom(rects, origin, view) {
|
|
241
|
+
const out = [];
|
|
242
|
+
for (const { id, x, y, w, h, active } of rects) {
|
|
243
|
+
const x0 = x - origin.x, y0 = y - origin.y, x1 = x0 + w, y1 = y0 + h;
|
|
244
|
+
if (x1 <= 0 || x0 >= view.width || y1 <= 0 || y0 >= view.floor) continue;
|
|
245
|
+
out.push(active === undefined ? { id, x0, y0, x1, y1 } : { id, x0, y0, x1, y1, active });
|
|
246
|
+
if (out.length === RECTS_MAX) break;
|
|
247
|
+
}
|
|
248
|
+
return out;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
module.exports = { createWindowSource, ledgesFrom, windowsFrom };
|
package/package.json
CHANGED
|
@@ -1,15 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cortico-world-agent-speed",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "
|
|
6
|
-
"main": "./index.
|
|
7
|
-
"exports": "./index.
|
|
8
|
-
"files": [
|
|
9
|
-
|
|
5
|
+
"description": "The Coopanion desktop pet with local Agent Speed activity animation",
|
|
6
|
+
"main": "./src/index.ts",
|
|
7
|
+
"exports": { ".": "./src/index.ts", "./web/*": "./web/*", "./host/*": "./host/*" },
|
|
8
|
+
"files": [
|
|
9
|
+
"activity.js", "activity.d.ts", "src/", "host/", "web/", "!web/whale/", "dist/",
|
|
10
|
+
"scripts/", "describe.json", "CHANGELOG.md", "THIRD_PARTY_NOTICES.md", "LICENSE-MIT"
|
|
11
|
+
],
|
|
12
|
+
"scripts": { "build": "node scripts/build-webui.mjs" },
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"fflate": "0.8.3",
|
|
15
|
+
"jpeg-js": "0.4.4",
|
|
16
|
+
"koffi": "3.3.1",
|
|
17
|
+
"opencc-js": "1.4.1",
|
|
18
|
+
"sherpa-onnx-node": "1.13.8",
|
|
19
|
+
"ws": "8.21.3"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": { "esbuild": "0.28.2" },
|
|
10
22
|
"keywords": ["cortico-world", "cortico", "agent-speed"],
|
|
11
23
|
"license": "AGPL-3.0-or-later",
|
|
12
24
|
"os": ["darwin", "win32"],
|
|
13
25
|
"engines": { "node": ">=22" },
|
|
14
|
-
"cortico": {
|
|
26
|
+
"cortico": {
|
|
27
|
+
"kind": "world",
|
|
28
|
+
"api": 6,
|
|
29
|
+
"displayName": "Agent Speed",
|
|
30
|
+
"webUiClient": "dist/webui.js",
|
|
31
|
+
"webUiStyle": "dist/webui.css",
|
|
32
|
+
"describe": "describe.json",
|
|
33
|
+
"tags": ["apps", "external-setup", "experimental"]
|
|
34
|
+
}
|
|
15
35
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 面板 bundle:`src/webui/client.ts` → `dist/webui.js` + `dist/webui.css`。
|
|
3
|
+
* 两个产物名写死在 package.json 的 `cortico.webUiClient` / `webUiStyle` 里,
|
|
4
|
+
* 服务端自己给它们分配 URL。
|
|
5
|
+
*
|
|
6
|
+
* 不给 `cortico/*` 配 alias 也不 external:浏览器侧只允许 `import type` 框架,
|
|
7
|
+
* 那些 import 编译期就被擦掉。构建若报 "Could not resolve cortico/…",说明有一处
|
|
8
|
+
* 运行时依赖漏网,去把它本地化,而不是在这里放行。
|
|
9
|
+
*/
|
|
10
|
+
import * as esbuild from 'esbuild';
|
|
11
|
+
import { mkdirSync, rmSync } from 'node:fs';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
|
|
14
|
+
const root = fileURLToPath(new URL('../', import.meta.url));
|
|
15
|
+
const outdir = `${root}dist`;
|
|
16
|
+
|
|
17
|
+
rmSync(outdir, { recursive: true, force: true });
|
|
18
|
+
mkdirSync(outdir, { recursive: true });
|
|
19
|
+
|
|
20
|
+
const result = await esbuild.build({
|
|
21
|
+
entryPoints: [{ in: `${root}src/webui/client.ts`, out: 'webui' }],
|
|
22
|
+
outdir,
|
|
23
|
+
bundle: true,
|
|
24
|
+
format: 'esm',
|
|
25
|
+
target: 'es2022',
|
|
26
|
+
platform: 'browser',
|
|
27
|
+
minify: true,
|
|
28
|
+
sourcemap: true,
|
|
29
|
+
metafile: true,
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
for (const [path, info] of Object.entries(result.metafile.outputs)) {
|
|
33
|
+
if (path.endsWith('.map')) continue;
|
|
34
|
+
console.log(`${path.replace(/\\/g, '/')} ${(info.bytes / 1024).toFixed(1)} KB`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
await esbuild.build({
|
|
38
|
+
entryPoints: [`${root}src/webui/dress-dialog.ts`],
|
|
39
|
+
outdir: `${root}web/dist`, bundle: true, format: 'esm', target: 'es2022', platform: 'browser', minify: true,
|
|
40
|
+
});
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Builds Coo's speech bank (web/speech/): one short, pitch-flat unit per toneless Mandarin syllable, and the
|
|
2
|
+
character table that maps Han characters to syllable and tone.
|
|
3
|
+
|
|
4
|
+
Each syllable is spoken alone by a TTS voice through a carrier character, cut to at most 20 ms of consonant before
|
|
5
|
+
the voicing and 160 ms of voicing, then set by Praat's PSOLA to one pitch (BANK_HZ, a 0.7-semitone fall over the
|
|
6
|
+
last quarter) and to a voiced length of UNIT_VOICED_S. Formants stay the speaker's; the page shifts the pitch by
|
|
7
|
+
playback rate only. The EQ follows Animal Crossing: New Horizons' Chinese dialogue as measured: the second and
|
|
8
|
+
third harmonics 11-13 and 16-20 dB under the fundamental, under 1.5% of the energy above 4 kHz.
|
|
9
|
+
|
|
10
|
+
Output: web/speech/zh.ogg (Opus, units back to back with PAD_S of silence between them), web/speech/zh.json
|
|
11
|
+
({hz, units: {syllable: [start s, length s]}}) and src/speech/data/zh.json ({"<syllable><tone>": "<characters>"},
|
|
12
|
+
the most common reading of every character in U+4E00-U+9FFF, tone 5 = neutral).
|
|
13
|
+
|
|
14
|
+
python build.py --tts edge # Edge's read-aloud service, no account: the bank shipped is built this way
|
|
15
|
+
python build.py --tts azure # Azure Speech: AZURE_SPEECH_KEY, AZURE_SPEECH_REGION
|
|
16
|
+
|
|
17
|
+
The voice is --voice, zh-CN-XiaoyiNeural by default.
|
|
18
|
+
|
|
19
|
+
Needs ffmpeg on PATH and: pip install praat-parselmouth pypinyin numpy scipy soundfile (edge: edge-tts).
|
|
20
|
+
Raw recordings are cached under .cache/ next to this file.
|
|
21
|
+
"""
|
|
22
|
+
import argparse, asyncio, hashlib, json, os, subprocess, sys, urllib.request
|
|
23
|
+
from xml.sax.saxutils import escape
|
|
24
|
+
import numpy as np
|
|
25
|
+
import parselmouth
|
|
26
|
+
from parselmouth.praat import call
|
|
27
|
+
from pypinyin import pinyin, Style
|
|
28
|
+
from scipy.signal import butter, sosfilt, lfilter
|
|
29
|
+
|
|
30
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
31
|
+
OUT = os.path.normpath(os.path.join(HERE, '..', '..', 'web', 'speech'))
|
|
32
|
+
TABLE = os.path.normpath(os.path.join(HERE, '..', '..', 'src', 'speech', 'data', 'zh.json'))
|
|
33
|
+
CACHE = os.path.join(HERE, '.cache')
|
|
34
|
+
SR = 48000
|
|
35
|
+
BANK_HZ = 364 # the 中 pitch (400 Hz) plays it at 1.1x
|
|
36
|
+
UNIT_VOICED_S = .094 # 85 ms at 1.1x
|
|
37
|
+
CONS_MAX_S = .02
|
|
38
|
+
VOICED_MAX_S = .16
|
|
39
|
+
PAD_S = .06
|
|
40
|
+
# interjection readings (嗯 n, 呣 m, 噷 hm ...) are read as the nearest syllable of the language
|
|
41
|
+
INTERJECTIONS = {'m': 'en', 'n': 'en', 'ng': 'en', 'hm': 'en', 'hng': 'en', 'ê': 'e', 'r': 'er'}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def han_readings():
|
|
45
|
+
"""Every character in U+4E00-U+9FFF with its most common reading, as (char, syllable, tone)."""
|
|
46
|
+
out = []
|
|
47
|
+
for cp in range(0x4E00, 0xA000):
|
|
48
|
+
ch = chr(cp)
|
|
49
|
+
r = pinyin(ch, style=Style.TONE3, neutral_tone_with_five=True, errors='ignore')
|
|
50
|
+
if not r or not r[0] or not r[0][0][-1:].isdigit(): continue
|
|
51
|
+
s = r[0][0]
|
|
52
|
+
syl = s[:-1].replace('ü', 'v')
|
|
53
|
+
out.append((ch, INTERJECTIONS.get(syl, syl), int(s[-1])))
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def carriers(readings):
|
|
58
|
+
"""One character per syllable that has a single reading: GB2312 level 1 first, then level 2, first tone first."""
|
|
59
|
+
gb = {}
|
|
60
|
+
for hi in range(0xB0, 0xF8):
|
|
61
|
+
for lo in range(0xA1, 0xFF):
|
|
62
|
+
try: gb[bytes([hi, lo]).decode('gb2312')] = 0 if hi < 0xD8 else 1
|
|
63
|
+
except UnicodeDecodeError: pass
|
|
64
|
+
best = {}
|
|
65
|
+
for ch, syl, tone in readings:
|
|
66
|
+
n = len(pinyin(ch, style=Style.NORMAL, heteronym=True)[0])
|
|
67
|
+
rank = (n > 1, gb.get(ch, 2), tone != 1, tone)
|
|
68
|
+
if syl not in best or rank < best[syl][0]: best[syl] = (rank, ch)
|
|
69
|
+
return {s: ch for s, (_, ch) in sorted(best.items())}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def decode(data):
|
|
73
|
+
p = subprocess.run(['ffmpeg', '-v', 'error', '-i', 'pipe:0', '-f', 'f32le', '-ac', '1', '-ar', str(SR), 'pipe:1'], input=data, capture_output=True, check=True)
|
|
74
|
+
return np.frombuffer(p.stdout, np.float32).astype(np.float64)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
async def record(text, args):
|
|
78
|
+
os.makedirs(CACHE, exist_ok=True)
|
|
79
|
+
key = os.path.join(CACHE, hashlib.md5(f'{args.tts}|{args.voice}|{text}'.encode()).hexdigest())
|
|
80
|
+
if not os.path.exists(key):
|
|
81
|
+
if args.tts == 'edge':
|
|
82
|
+
import edge_tts
|
|
83
|
+
buf = bytearray()
|
|
84
|
+
async for c in edge_tts.Communicate(text, args.voice).stream():
|
|
85
|
+
if c['type'] == 'audio': buf += c['data']
|
|
86
|
+
else:
|
|
87
|
+
ssml = f"<speak version='1.0' xml:lang='zh-CN'><voice name='{args.voice}'>{escape(text)}</voice></speak>"
|
|
88
|
+
req = urllib.request.Request(
|
|
89
|
+
f"https://{os.environ['AZURE_SPEECH_REGION']}.tts.speech.microsoft.com/cognitiveservices/v1", data=ssml.encode(),
|
|
90
|
+
headers={'Ocp-Apim-Subscription-Key': os.environ['AZURE_SPEECH_KEY'], 'Content-Type': 'application/ssml+xml',
|
|
91
|
+
'X-Microsoft-OutputFormat': 'riff-48khz-16bit-mono-pcm', 'User-Agent': 'coopanion-speech-bank'})
|
|
92
|
+
buf = urllib.request.urlopen(req, timeout=30).read()
|
|
93
|
+
if len(buf) < 1000: raise RuntimeError(f'no audio for {text!r}')
|
|
94
|
+
open(key, 'wb').write(buf)
|
|
95
|
+
return decode(open(key, 'rb').read())
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def cut(x):
|
|
99
|
+
"""<=20 ms of consonant before the voicing and <=160 ms of voicing."""
|
|
100
|
+
snd = parselmouth.Sound(x, SR)
|
|
101
|
+
p = snd.to_pitch_ac(time_step=.005, pitch_floor=120, pitch_ceiling=700)
|
|
102
|
+
f0, ts = p.selected_array['frequency'], p.xs()
|
|
103
|
+
v = np.nonzero(f0 > 0)[0]
|
|
104
|
+
loud = np.nonzero(np.abs(x) > np.abs(x).max() * .03)[0]
|
|
105
|
+
a = loud[0] / SR
|
|
106
|
+
v0, v1 = (ts[v[0]], ts[v[-1]]) if len(v) else (a, loud[-1] / SR)
|
|
107
|
+
s, e = max(a, v0 - CONS_MAX_S), min(v1, v0 + VOICED_MAX_S)
|
|
108
|
+
return x[int(s * SR):int(e * SR)]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def peak(x, f0, gain_db, q):
|
|
112
|
+
A = 10 ** (gain_db / 40); w = 2 * np.pi * f0 / SR; al = np.sin(w) / (2 * q); c = np.cos(w)
|
|
113
|
+
b = np.array([1 + al * A, -2 * c, 1 - al * A]); a = np.array([1 + al / A, -2 * c, 1 - al / A])
|
|
114
|
+
return lfilter(b / a[0], a / a[0], x)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
LOWPASS = butter(4, 4500, 'low', fs=SR, output='sos')
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def unit(seg):
|
|
121
|
+
snd = parselmouth.Sound(seg, SR); d = snd.duration
|
|
122
|
+
m = call(snd, 'To Manipulation', .005, 100, 800)
|
|
123
|
+
pt = call('Create PitchTier', 'p', 0, d)
|
|
124
|
+
call(pt, 'Add point', 0, BANK_HZ); call(pt, 'Add point', d * .75, BANK_HZ); call(pt, 'Add point', d, BANK_HZ * 2 ** (-.7 / 12))
|
|
125
|
+
call([pt, m], 'Replace pitch tier')
|
|
126
|
+
k = min(1., UNIT_VOICED_S / max(d - CONS_MAX_S, .02))
|
|
127
|
+
dt = call('Create DurationTier', 'd', 0, d)
|
|
128
|
+
for t, f in ((0, 1.), (CONS_MAX_S, 1.), (CONS_MAX_S + .005, k), (d, k)): call(dt, 'Add point', t, f)
|
|
129
|
+
call([dt, m], 'Replace duration tier')
|
|
130
|
+
y = call(m, 'Get resynthesis (overlap-add)').values[0]
|
|
131
|
+
nc = int(CONS_MAX_S * SR)
|
|
132
|
+
y[:nc] *= 10 ** (-5 / 20)
|
|
133
|
+
y = peak(peak(sosfilt(LOWPASS, y), 1050, -6, .9), 1900, 4, 1.2)
|
|
134
|
+
y = y / (np.sqrt(np.mean(y[nc:] ** 2)) + 1e-9) * .1
|
|
135
|
+
fi, fo = int(.008 * SR), int(.035 * SR)
|
|
136
|
+
y[:fi] *= np.linspace(0, 1, fi) ** 2; y[-fo:] *= np.cos(np.linspace(0, np.pi / 2, fo))
|
|
137
|
+
return y
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
async def main():
|
|
141
|
+
ap = argparse.ArgumentParser()
|
|
142
|
+
ap.add_argument('--tts', choices=['edge', 'azure'], default='edge')
|
|
143
|
+
ap.add_argument('--voice', default='zh-CN-XiaoyiNeural')
|
|
144
|
+
args = ap.parse_args()
|
|
145
|
+
readings = han_readings()
|
|
146
|
+
table = {}
|
|
147
|
+
for ch, syl, tone in readings: table[f'{syl}{tone}'] = table.get(f'{syl}{tone}', '') + ch
|
|
148
|
+
which = carriers(readings)
|
|
149
|
+
print(len(readings), 'characters,', len(which), 'syllables', file=sys.stderr)
|
|
150
|
+
pad = np.zeros(int(PAD_S * SR)); parts, units, t = [pad], {}, PAD_S
|
|
151
|
+
for i, (syl, ch) in enumerate(which.items()):
|
|
152
|
+
u = unit(cut(await record(ch, args)))
|
|
153
|
+
units[syl] = [round(t, 4), round(len(u) / SR, 4)]
|
|
154
|
+
parts += [u, pad]; t += len(u) / SR + PAD_S
|
|
155
|
+
if i % 50 == 0: print(i, syl, ch, file=sys.stderr)
|
|
156
|
+
audio = np.concatenate(parts)
|
|
157
|
+
audio = (audio / np.abs(audio).max() * .9).astype(np.float32)
|
|
158
|
+
os.makedirs(OUT, exist_ok=True)
|
|
159
|
+
subprocess.run(['ffmpeg', '-v', 'error', '-y', '-f', 'f32le', '-ar', str(SR), '-ac', '1', '-i', 'pipe:0', '-c:a', 'libopus', '-b:a', '48k',
|
|
160
|
+
os.path.join(OUT, 'zh.ogg')], input=audio.tobytes(), check=True)
|
|
161
|
+
json.dump({'hz': BANK_HZ, 'units': units}, open(os.path.join(OUT, 'zh.json'), 'w', encoding='utf-8'), separators=(',', ':'))
|
|
162
|
+
json.dump(dict(sorted(table.items())), open(TABLE, 'w', encoding='utf-8'), ensure_ascii=False, separators=(',', ':'))
|
|
163
|
+
print(f'{len(units)} units, {t:.1f} s of audio', file=sys.stderr)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Writes the pronunciation data src/speech reads, into src/speech/data/:
|
|
2
|
+
|
|
3
|
+
- en.tsv.gz: word, ARPAbet with stress digits; the first pronunciation of each word in the CMU Pronouncing Dictionary.
|
|
4
|
+
- ja-ipadic.tsv.gz: word, pronunciation in hiragana; every IPADIC entry with a kanji in it. Where one spelling has
|
|
5
|
+
several entries, a common word's comes before a name's (Noun.name/org/place/proper), then the lower cost.
|
|
6
|
+
IPADIC-COPYING is its license, converted to UTF-8.
|
|
7
|
+
- ja-unihan.tsv.gz: kanji, its on'yomi and kun'yomi in hiragana ("on,on|kun,kun"), from Unihan's kJapanese field.
|
|
8
|
+
|
|
9
|
+
pip install cmudict
|
|
10
|
+
python dicts.py <mecab-ipadic-2.7.0-20070801 folder> <Unihan.zip>
|
|
11
|
+
|
|
12
|
+
The IPADIC folder is the unpacked source release (its *.csv are EUC-JP); Unihan.zip is from
|
|
13
|
+
https://www.unicode.org/Public/UCD/latest/ucd/ (kJapanese needs Unicode 15.1 or later).
|
|
14
|
+
"""
|
|
15
|
+
import glob, gzip, io, os, re, sys, zipfile
|
|
16
|
+
import cmudict
|
|
17
|
+
|
|
18
|
+
OUT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'src', 'speech', 'data'))
|
|
19
|
+
KANJI = re.compile('[㐀-䶿一-鿿々]')
|
|
20
|
+
PROPER = {'Noun.name.csv', 'Noun.org.csv', 'Noun.place.csv', 'Noun.proper.csv'}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def hira(s):
|
|
24
|
+
return ''.join(chr(ord(c) - 0x60) if 0x30a1 <= ord(c) <= 0x30f6 else c for c in s)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def write(name, table):
|
|
28
|
+
with gzip.open(os.path.join(OUT, name), 'wt', encoding='utf-8', newline='\n', compresslevel=9) as f:
|
|
29
|
+
for w in sorted(table): f.write(f'{w}\t{table[w]}\n')
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def english():
|
|
33
|
+
en = {}
|
|
34
|
+
with open(os.path.join(os.path.dirname(cmudict.__file__), 'data', 'cmudict.dict'), encoding='utf-8') as f:
|
|
35
|
+
for line in f:
|
|
36
|
+
line = line.split('#')[0].strip()
|
|
37
|
+
if not line: continue
|
|
38
|
+
word, phones = line.split(' ', 1)
|
|
39
|
+
if '(' in word: continue # word(2), word(3): later pronunciations
|
|
40
|
+
en[word.lower()] = phones
|
|
41
|
+
write('en.tsv.gz', en)
|
|
42
|
+
return len(en)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def ipadic(folder):
|
|
46
|
+
best = {}
|
|
47
|
+
for f in sorted(glob.glob(os.path.join(folder, '*.csv'))):
|
|
48
|
+
proper = os.path.basename(f) in PROPER
|
|
49
|
+
for line in open(f, encoding='euc-jp', errors='replace'):
|
|
50
|
+
c = line.rstrip('\n').split(',')
|
|
51
|
+
if len(c) < 13 or not KANJI.search(c[0]): continue
|
|
52
|
+
said = c[12] if c[12] != '*' else c[11]
|
|
53
|
+
if not re.fullmatch('[ァ-ー]+', said): continue
|
|
54
|
+
rank = (proper, int(c[3]))
|
|
55
|
+
if c[0] not in best or rank < best[c[0]][0]: best[c[0]] = (rank, hira(said))
|
|
56
|
+
write('ja-ipadic.tsv.gz', {w: r for w, (_, r) in best.items()})
|
|
57
|
+
with open(os.path.join(folder, 'COPYING'), encoding='euc-jp', errors='replace') as f:
|
|
58
|
+
open(os.path.join(OUT, 'IPADIC-COPYING'), 'w', encoding='utf-8', newline='\n').write(f.read())
|
|
59
|
+
return len(best)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def unihan(zip_path):
|
|
63
|
+
table = {}
|
|
64
|
+
with zipfile.ZipFile(zip_path) as z, z.open('Unihan_Readings.txt') as f:
|
|
65
|
+
for line in io.TextIOWrapper(f, encoding='utf-8'):
|
|
66
|
+
if not line.startswith('U+'): continue
|
|
67
|
+
cp, field, value = line.rstrip('\n').split('\t')
|
|
68
|
+
if field != 'kJapanese': continue
|
|
69
|
+
on = [hira(v) for v in value.split() if re.fullmatch('[ァ-ー]+', v)]
|
|
70
|
+
kun = [v for v in value.split() if re.fullmatch('[ぁ-ゟー]+', v)]
|
|
71
|
+
table[chr(int(cp[2:], 16))] = ','.join(on) + '|' + ','.join(kun)
|
|
72
|
+
write('ja-unihan.tsv.gz', table)
|
|
73
|
+
return len(table)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
print(english(), 'English words,', ipadic(sys.argv[1]), 'IPADIC words,', unihan(sys.argv[2]), 'Unihan kanji')
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
## Desktop pet
|
|
2
|
+
|
|
3
|
+
You have a body on {{pet.user}}'s computer screen: {{pet.body}}. It stands on the bottom edge of the screen (the top of the taskbar or the Dock). {{pet.user}} can see it, but not the text of your messages; whatever you want them to see has to come out in a bubble through `speed_pet_say` or `speed_pet_ask`.{{pet.reply}}{{pet.chat}}
|
|
4
|
+
|
|
5
|
+
When it has no instruction, the body moves on its own (blinking, looking around, walking a little, sitting down for a nap); your instructions go first. {{pet.user}} can poke it, pet it, or pick it up and throw it, and the body has reflexes for these that play on the spot: a poke changes its face or makes it hop, petting makes it look pleased or shy, a poke while it sleeps startles it awake, and landing hard after a throw knocks it out for a few seconds.
|
|
6
|
+
|
|
7
|
+
### Talking: `speed_pet_say`
|
|
8
|
+
|
|
9
|
+
Put one or two sentences in a bubble. The text types out at about 20 characters a second (three or four words) and stays a few seconds after the typing ends, longer for a longer bubble. Several calls in a row queue up and show one after another.
|
|
10
|
+
|
|
11
|
+
The script can carry expression and motion markers, from the vocabulary of the current figure. When the figure changes, a `[figure]` event or the `speed_pet_set` receipt says which words no longer work and which are new; go by those:
|
|
12
|
+
|
|
13
|
+
| Marker | Effect |
|
|
14
|
+
|---|---|
|
|
15
|
+
| 【word, word】 | Play these first, then carry on in a new bubble |
|
|
16
|
+
| <word> | Play it when the typing reaches this point, in the same bubble |
|
|
17
|
+
|
|
18
|
+
{{pet.vocab}}
|
|
19
|
+
|
|
20
|
+
Example: `【happy】Nice work today!<wink>Fancy a break?`
|
|
21
|
+
|
|
22
|
+
### Asking: `speed_pet_ask`
|
|
23
|
+
|
|
24
|
+
One question with 1–3 options, plus by default a box for {{pet.user}} to write their own answer. Their choice comes back as an `[answer]` event; you are also told when they close the question without answering.
|
|
25
|
+
|
|
26
|
+
### Moving and acting
|
|
27
|
+
|
|
28
|
+
- `speed_pet_move_to`: walk somewhere on the screen the body is on, 0 leftmost, 1 rightmost; `cursor` is the horizontal position of the mouse pointer. Returns only on arrival or interruption.
|
|
29
|
+
- `speed_pet_act`: play a sequence of expressions or motions without speaking. Words the vocabulary marks as held until the next action stay on.
|
|
30
|
+
|
|
31
|
+
{{pet.moves}}
|
|
32
|
+
|
|
33
|
+
### Adjusting yourself: `speed_pet_set`, `speed_pet_quiet`
|
|
34
|
+
|
|
35
|
+
`speed_pet_set` changes your own looks and habits: figure and dress (Coo's colours and accessories are dress too), how much you walk about, how long you snore, sound effects, size, bubble size, text size, the night or day look, hover buttons, and what you call {{pet.user}}. By {{pet.user}}'s settings on the Habits page, some take effect at once and others are first asked of {{pet.user}} in a bubble, changing only if they agree, with the receipt coming after their answer. {{pet.self}} The values to choose from:
|
|
36
|
+
|
|
37
|
+
{{pet.dress}}
|
|
38
|
+
|
|
39
|
+
`speed_pet_quiet` is temporary: quiet for a while (sound effects off and standing still by default), restored on its own when the time is up, settings unchanged. When {{pet.user}} is busy, in a meeting, or it is late at night, use it rather than changing the settings.
|
|
40
|
+
|
|
41
|
+
### Events you receive
|
|
42
|
+
|
|
43
|
+
Each event starts with {{pet.user}}'s local time when it happened, like `[14:32]`; the first event of a run and the first after the date changes also carry the date and weekday, like `[10-05 Sun 23:40]`.
|
|
44
|
+
|
|
45
|
+
- `[voice] {{pet.user}}: …`: speech the microphone heard and transcribed (voice input is {{pet.voice}}). The transcript can contain misheard words. Speech through the talk key interrupts the current model call or interruptible tool on delivery and skips unstarted tools in that round; receipts report actions already taken. Speech heard while always listening does not interrupt.
|
|
46
|
+
- `[typed] {{pet.user}}: …`: text typed after double-clicking the pet or through a hover button; images pasted into the box follow the text.
|
|
47
|
+
- `[answer] …`: an answer to `speed_pet_ask`.
|
|
48
|
+
- `[touch] …`: pokes, petting, being picked up and thrown, and being knocked out by a landing. "Poked you awake" and "knocked out" in an event are reflexes the body already played on the spot; they are over by the time the event reaches you, so there is no need to act them out again. Some touches do not wake you on their own and come with the next batch of events, possibly a while later.
|
|
49
|
+
- `[figure] …`: {{pet.user}} changed your figure or dress, or the figure could not be shown and you are back to Coo; any change to the vocabulary or to the figure's own targets is spelled out with it.
|
|
50
|
+
|
|
51
|
+
{{pet.cua}}
|