@desert-ant-labs/gist 0.1.0

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/index.d.ts ADDED
@@ -0,0 +1,77 @@
1
+ /** A predicted topic and its probability. */
2
+ export interface Topic {
3
+ /** Taxonomy slug, e.g. `"technology"`. */
4
+ slug: string;
5
+ /** Human-readable name, e.g. `"Technology & Software"`. */
6
+ name: string;
7
+ /** Probability in `0..1`. */
8
+ score: number;
9
+ }
10
+
11
+ /** Options for `classify`. */
12
+ export interface ClassifyOptions {
13
+ /** Max topics to return. Default 3. */
14
+ topK?: number;
15
+ /** Override the tuned probability threshold. */
16
+ threshold?: number;
17
+ }
18
+
19
+ /** How the model is loaded. Bundled by default (offline); the repo/revision are pinned. */
20
+ export interface LoadOptions {
21
+ /** An explicit model directory (adopt files there, else download). Omit to use the bundled model. */
22
+ directory?: string;
23
+ /** Download progress in `[0, 1]`. */
24
+ onProgress?: (fraction: number) => void;
25
+ /** Bring-your-own LiteRT.js module (the `@litertjs/core` namespace). */
26
+ litert?: unknown;
27
+ /** URL/path to the LiteRT.js Wasm directory. */
28
+ litertWasmDir?: string;
29
+ /** LiteRT.js accelerator: `"wasm"` (default), `"webgpu"`, or `"webnn"`. */
30
+ accelerator?: "wasm" | "webgpu" | "webnn";
31
+ }
32
+
33
+ /**
34
+ * On-device multi-label content topic tagging (26 topics, 7 languages) with local
35
+ * WebAssembly and LiteRT.js inference. Create one with `await Gist.load()` and reuse it.
36
+ *
37
+ * ```ts
38
+ * const gist = await Gist.load();
39
+ * await gist.classify("How to start a podcast with your iPhone");
40
+ * await gist.scores("Why Billionaires Fear This Economist");
41
+ * ```
42
+ */
43
+ export declare class Gist {
44
+ static load(options?: LoadOptions): Promise<Gist>;
45
+ /** Ranked topics above the tuned threshold (the top topic is always returned). */
46
+ classify(text: string, options?: ClassifyOptions): Promise<Topic[]>;
47
+ /** The full 26-topic probability distribution (slug -> probability). */
48
+ scores(text: string): Promise<Record<string, number>>;
49
+ }
50
+
51
+ /** One post's topic scores (from `Gist.scores`), optionally timestamped. */
52
+ export interface PostTopics {
53
+ topics: Record<string, number>;
54
+ timestamp?: number | Date;
55
+ }
56
+
57
+ /** A channel-level topic in the ranked roll-up. */
58
+ export interface ChannelTopic {
59
+ slug: string;
60
+ /** Share of the channel's total topical weight, `0..1`. */
61
+ share: number;
62
+ /** Posts that meaningfully touch this topic. */
63
+ postCount: number;
64
+ }
65
+
66
+ /** Options for `channelTopics`. */
67
+ export interface RollupOptions {
68
+ topN?: number;
69
+ floor?: number;
70
+ minPosts?: number;
71
+ halfLifeDays?: number;
72
+ touch?: number;
73
+ now?: number;
74
+ }
75
+
76
+ /** Aggregate a channel's posts into a ranked list of channel-level topics. Pure, no model. */
77
+ export declare function channelTopics(posts: PostTopics[], options?: RollupOptions): ChannelTopic[];
package/index.js ADDED
@@ -0,0 +1,179 @@
1
+ // On-device content topic tagging for JavaScript. This file instantiates the
2
+ // WebAssembly Swift core, owns the LiteRT.js session, and exposes the typed API
3
+ // (a `Gist` class with an async `load` factory). Works in node and browsers via
4
+ // @litertjs/core (LiteRT.js): XNNPACK CPU ("wasm") by default.
5
+
6
+ const IS_NODE = typeof process !== "undefined" && !!process.versions?.node;
7
+
8
+ async function instantiateCore() {
9
+ globalThis.__GistHost ??= {};
10
+ const { instantiate } = await import("./dist/instantiate.js");
11
+ if (IS_NODE) {
12
+ // Give the Swift ModelStore node's fs as a platform seam (the download/
13
+ // verify/cache logic stays in Swift; here we only read bundled files).
14
+ const fsmod = await import("node:fs");
15
+ globalThis.__DalNodeFS = {
16
+ existsSync: fsmod.existsSync, statSync: fsmod.statSync,
17
+ readFileSync: (p) => new Uint8Array(fsmod.readFileSync(p)),
18
+ writeFileSync: fsmod.writeFileSync,
19
+ mkdirSync: fsmod.mkdirSync, renameSync: fsmod.renameSync, unlinkSync: fsmod.unlinkSync,
20
+ };
21
+ const { defaultNodeSetup } = await import("./dist/platforms/node.js");
22
+ await instantiate(await defaultNodeSetup({}));
23
+ } else {
24
+ const { init } = await import("./dist/index.js");
25
+ await init({});
26
+ }
27
+ return globalThis.__GistExports;
28
+ }
29
+ const core = await instantiateCore();
30
+
31
+ async function loadLiteRtModule(options) {
32
+ return options.litert ?? (await import("@litertjs/core"));
33
+ }
34
+
35
+ async function resolveWasmDir(options) {
36
+ if (options.litertWasmDir) return options.litertWasmDir;
37
+ if (IS_NODE) {
38
+ const { createRequire } = await import("node:module");
39
+ const { pathToFileURL } = await import("node:url");
40
+ const path = await import("node:path");
41
+ const fs = await import("node:fs");
42
+ const require = createRequire(import.meta.url);
43
+ let dir = path.dirname(require.resolve("@litertjs/core"));
44
+ for (let i = 0; i < 4 && !fs.existsSync(path.join(dir, "wasm")); i++) dir = path.dirname(dir);
45
+ return pathToFileURL(path.join(dir, "wasm") + "/").href;
46
+ }
47
+ return "https://cdn.jsdelivr.net/npm/@litertjs/core/wasm/";
48
+ }
49
+
50
+ // LiteRT.js loads its own Wasm runtime with a browser `importScripts`/`<script>`
51
+ // path; in node we provide a minimal shim so the emscripten loader (which wants
52
+ // `require`/`__dirname`) runs. No-op in the browser and if already present.
53
+ let nodeShimReady;
54
+ async function ensureNodeLiteRtShim() {
55
+ if (!IS_NODE || typeof globalThis.importScripts === "function") return;
56
+ nodeShimReady ??= (async () => {
57
+ const fs = await import("node:fs");
58
+ const path = await import("node:path");
59
+ const { fileURLToPath } = await import("node:url");
60
+ const { createRequire } = await import("node:module");
61
+ globalThis.self ??= globalThis;
62
+ globalThis.require ??= createRequire(import.meta.url);
63
+ globalThis.importScripts = (url) => {
64
+ const s = url.toString();
65
+ const p = s.startsWith("file:") ? fileURLToPath(s) : s;
66
+ globalThis.__dirname = path.dirname(p);
67
+ globalThis.__filename = p;
68
+ (0, eval)(fs.readFileSync(p, "utf8"));
69
+ };
70
+ })();
71
+ await nodeShimReady;
72
+ }
73
+
74
+ let liteRtReady;
75
+ async function ensureLiteRt(options, lrt) {
76
+ await ensureNodeLiteRtShim();
77
+ liteRtReady ??= lrt.loadLiteRt(await resolveWasmDir(options));
78
+ await liteRtReady;
79
+ }
80
+
81
+ // The model ships bundled in this package (`model/`), so the beta runs offline
82
+ // with no Hugging Face download. Callers may override with `options.directory`.
83
+ async function bundledModelDir() {
84
+ if (!IS_NODE) return "";
85
+ const path = await import("node:path");
86
+ const { fileURLToPath } = await import("node:url");
87
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), "model");
88
+ }
89
+
90
+ /**
91
+ * On-device multi-label content topic tagging. Create one with
92
+ * `await Gist.load()` and reuse it.
93
+ *
94
+ * ```js
95
+ * const gist = await Gist.load();
96
+ * await gist.classify("How to start a podcast with your iPhone");
97
+ * await gist.scores("Why Billionaires Fear This Economist"); // full distribution
98
+ * ```
99
+ */
100
+ export class Gist {
101
+ static async load(options = {}) {
102
+ const resolved = options;
103
+ const lrt = await loadLiteRtModule(resolved);
104
+ await ensureLiteRt(resolved, lrt);
105
+ const { loadAndCompile, Tensor } = lrt;
106
+ const accelerator = resolved.accelerator ?? "wasm";
107
+ let model;
108
+
109
+ const typedArray = (t) => {
110
+ const bytes = t.data.slice();
111
+ switch (t.type) {
112
+ case "int32": return new Int32Array(bytes.buffer);
113
+ case "float32": return new Float32Array(bytes.buffer);
114
+ case "uint8": return new Uint8Array(bytes.buffer);
115
+ default: throw new Error(`unsupported tensor type: ${t.type}`);
116
+ }
117
+ };
118
+ globalThis.__GistHost = {
119
+ createSession: async (modelSource) => {
120
+ let modelData = modelSource;
121
+ if (typeof modelSource === "string" && IS_NODE) {
122
+ const fs = await import("node:fs");
123
+ modelData = new Uint8Array(fs.readFileSync(modelSource));
124
+ }
125
+ model = await loadAndCompile(modelData, { accelerator });
126
+ },
127
+ run: async (inputs) => {
128
+ const feeds = {};
129
+ const made = [];
130
+ for (const [name, t] of Object.entries(inputs)) {
131
+ const tensor = new Tensor(typedArray(t), Array.from(t.dims));
132
+ feeds[name] = tensor;
133
+ made.push(tensor);
134
+ }
135
+ const results = await model.run(feeds);
136
+ const outputs = {};
137
+ const toDelete = [...made];
138
+ for (const [name, out] of Object.entries(results)) {
139
+ const host = accelerator === "wasm" ? out : await out.moveTo("wasm");
140
+ const arr = host.toTypedArray();
141
+ outputs[name] = {
142
+ data: new Uint8Array(arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength)),
143
+ dims: Array.from(host.type.layout.dimensions),
144
+ type: host.type.dtype,
145
+ };
146
+ toDelete.push(out);
147
+ if (host !== out) toDelete.push(host);
148
+ }
149
+ for (const t of toDelete) t.delete();
150
+ return outputs;
151
+ },
152
+ };
153
+
154
+ let cacheRoot = "";
155
+ if (IS_NODE) {
156
+ const os = await import("node:os");
157
+ const path = await import("node:path");
158
+ cacheRoot = path.join(os.homedir(), ".cache");
159
+ }
160
+ const directory = resolved.directory ?? (await bundledModelDir());
161
+ const onProgress = typeof resolved.onProgress === "function" ? resolved.onProgress : undefined;
162
+ await core.load(cacheRoot, directory, onProgress);
163
+ return new Gist();
164
+ }
165
+
166
+ /** Ranked topics for `text` above the tuned threshold (top topic always kept). */
167
+ async classify(text, options = {}) {
168
+ const arr = await core.classify(text, options.topK ?? 3, options.threshold);
169
+ return Array.from(arr).map((t) => ({ ...t }));
170
+ }
171
+
172
+ /** The full 26-topic probability distribution (slug -> probability). */
173
+ async scores(text) {
174
+ const obj = await core.scores(text);
175
+ return { ...obj };
176
+ }
177
+ }
178
+
179
+ export { channelTopics } from "./channel.js";
Binary file
@@ -0,0 +1,36 @@
1
+ {
2
+ "sem_model": "potion",
3
+ "slugs": [
4
+ "arts-culture",
5
+ "business",
6
+ "finance",
7
+ "career",
8
+ "technology",
9
+ "science",
10
+ "health-fitness",
11
+ "food-drink",
12
+ "travel",
13
+ "education",
14
+ "news-politics",
15
+ "society-culture",
16
+ "comedy",
17
+ "music",
18
+ "film-tv",
19
+ "gaming",
20
+ "sports",
21
+ "lifestyle-fashion",
22
+ "home-garden",
23
+ "parenting-family",
24
+ "relationships",
25
+ "self-improvement",
26
+ "spirituality-religion",
27
+ "history",
28
+ "true-crime",
29
+ "creator-economy"
30
+ ],
31
+ "dim": 8448,
32
+ "hidden": 384,
33
+ "ngram_dim": 8192,
34
+ "threshold": 0.35,
35
+ "precision_at_1": 0.826
36
+ }
Binary file
@@ -0,0 +1 @@
1
+ {"vocab_size": 76676, "dim": 256, "scale": 1.0, "normalize": true}
Binary file
@@ -0,0 +1,187 @@
1
+ {
2
+ "version": 1,
3
+ "topics": [
4
+ {
5
+ "slug": "arts-culture",
6
+ "name": "Arts & Culture",
7
+ "description": "Visual art, design, literature, theatre, and cultural criticism.",
8
+ "iab": "Arts, Entertainment",
9
+ "apple": "Arts"
10
+ },
11
+ {
12
+ "slug": "business",
13
+ "name": "Business & Entrepreneurship",
14
+ "description": "Starting and running companies, startups, strategy, and management.",
15
+ "iab": "Business",
16
+ "apple": "Business"
17
+ },
18
+ {
19
+ "slug": "finance",
20
+ "name": "Personal Finance & Investing",
21
+ "description": "Budgeting, saving, investing, markets, crypto, and money decisions.",
22
+ "iab": "Personal Finance",
23
+ "apple": "Business"
24
+ },
25
+ {
26
+ "slug": "career",
27
+ "name": "Careers & Productivity",
28
+ "description": "Jobs, hiring, workplace skills, remote work, and getting things done.",
29
+ "iab": "Careers",
30
+ "apple": "Business"
31
+ },
32
+ {
33
+ "slug": "technology",
34
+ "name": "Technology & Software",
35
+ "description": "Software, gadgets, AI, programming, cloud infrastructure, engineering, and the tech industry.",
36
+ "iab": "Technology & Computing",
37
+ "apple": "Technology"
38
+ },
39
+ {
40
+ "slug": "science",
41
+ "name": "Science",
42
+ "description": "Research, space, biology, physics, and how the world works.",
43
+ "iab": "Science",
44
+ "apple": "Science"
45
+ },
46
+ {
47
+ "slug": "health-fitness",
48
+ "name": "Health & Fitness",
49
+ "description": "Exercise, nutrition, mental health, medicine, and wellbeing.",
50
+ "iab": "Health",
51
+ "apple": "Health & Fitness"
52
+ },
53
+ {
54
+ "slug": "food-drink",
55
+ "name": "Food & Cooking",
56
+ "description": "Recipes, restaurants, cooking technique, coffee, and drinks.",
57
+ "iab": "Food & Drink",
58
+ "apple": "Leisure"
59
+ },
60
+ {
61
+ "slug": "travel",
62
+ "name": "Travel & Outdoors",
63
+ "description": "Destinations, trip planning, adventure, and life on the road.",
64
+ "iab": "Travel",
65
+ "apple": "Society & Culture"
66
+ },
67
+ {
68
+ "slug": "education",
69
+ "name": "Education & Learning",
70
+ "description": "Teaching, studying, courses, languages, and how to learn.",
71
+ "iab": "Education",
72
+ "apple": "Education"
73
+ },
74
+ {
75
+ "slug": "news-politics",
76
+ "name": "News & Politics",
77
+ "description": "Current events, policy, elections, and political commentary.",
78
+ "iab": "News & Politics",
79
+ "apple": "News"
80
+ },
81
+ {
82
+ "slug": "society-culture",
83
+ "name": "Society & Culture",
84
+ "description": "Social issues, identity, philosophy, and everyday culture.",
85
+ "iab": "Society",
86
+ "apple": "Society & Culture"
87
+ },
88
+ {
89
+ "slug": "comedy",
90
+ "name": "Comedy & Entertainment",
91
+ "description": "Humor, pop culture, celebrity, and light entertainment.",
92
+ "iab": "Pop Culture",
93
+ "apple": "Comedy"
94
+ },
95
+ {
96
+ "slug": "music",
97
+ "name": "Music",
98
+ "description": "Making music, artists, genres, gear, and the music industry.",
99
+ "iab": "Music & Audio",
100
+ "apple": "Music"
101
+ },
102
+ {
103
+ "slug": "film-tv",
104
+ "name": "Film & TV",
105
+ "description": "Movies, television, streaming, reviews, and filmmaking.",
106
+ "iab": "Movies",
107
+ "apple": "TV & Film"
108
+ },
109
+ {
110
+ "slug": "gaming",
111
+ "name": "Video Gaming",
112
+ "description": "Games, esports, game design, and gaming culture.",
113
+ "iab": "Video Gaming",
114
+ "apple": "Leisure"
115
+ },
116
+ {
117
+ "slug": "sports",
118
+ "name": "Sports",
119
+ "description": "Teams, athletes, matches, training, and sports analysis.",
120
+ "iab": "Sports",
121
+ "apple": "Sports"
122
+ },
123
+ {
124
+ "slug": "lifestyle-fashion",
125
+ "name": "Lifestyle & Fashion",
126
+ "description": "Style, beauty, trends, and everyday lifestyle content.",
127
+ "iab": "Style & Fashion",
128
+ "apple": "Society & Culture"
129
+ },
130
+ {
131
+ "slug": "home-garden",
132
+ "name": "Home, Garden & DIY",
133
+ "description": "Home improvement, interior decor, gardening, houseplants, and hands-on DIY projects.",
134
+ "iab": "Home & Garden",
135
+ "apple": "Leisure"
136
+ },
137
+ {
138
+ "slug": "parenting-family",
139
+ "name": "Family & Parenting",
140
+ "description": "Raising kids, family life, pregnancy, and parenting.",
141
+ "iab": "Family & Relationships",
142
+ "apple": "Kids & Family"
143
+ },
144
+ {
145
+ "slug": "relationships",
146
+ "name": "Relationships & Dating",
147
+ "description": "Dating, romance, friendship, and interpersonal advice.",
148
+ "iab": "Family & Relationships",
149
+ "apple": "Society & Culture"
150
+ },
151
+ {
152
+ "slug": "self-improvement",
153
+ "name": "Self-Improvement",
154
+ "description": "Motivation, habits, mindset, and personal growth.",
155
+ "iab": "Healthy Living",
156
+ "apple": "Education"
157
+ },
158
+ {
159
+ "slug": "spirituality-religion",
160
+ "name": "Religion & Spirituality",
161
+ "description": "Faith, meditation, mindfulness, and spiritual practice.",
162
+ "iab": "Religion & Spirituality",
163
+ "apple": "Religion & Spirituality"
164
+ },
165
+ {
166
+ "slug": "history",
167
+ "name": "History",
168
+ "description": "Historical events, figures, and how the past shaped now.",
169
+ "iab": "Society",
170
+ "apple": "History"
171
+ },
172
+ {
173
+ "slug": "true-crime",
174
+ "name": "True Crime",
175
+ "description": "Crimes, investigations, mysteries, and the justice system.",
176
+ "iab": "News & Politics",
177
+ "apple": "True Crime"
178
+ },
179
+ {
180
+ "slug": "creator-economy",
181
+ "name": "Creator Economy & Marketing",
182
+ "description": "Growing an audience, monetizing content, and online marketing.",
183
+ "iab": "Business & Finance",
184
+ "apple": "Business"
185
+ }
186
+ ]
187
+ }
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@desert-ant-labs/gist",
3
+ "version": "0.1.0",
4
+ "description": "On-device multi-label content topic tagging (26 topics, 7 languages) with channel roll-up, via WebAssembly + LiteRT.js.",
5
+ "type": "module",
6
+ "private": false,
7
+ "license": "SEE LICENSE IN LICENSE.md",
8
+ "main": "./index.js",
9
+ "types": "./index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./index.d.ts",
13
+ "default": "./index.js"
14
+ },
15
+ "./wasm": "./dist/GistWeb.wasm"
16
+ },
17
+ "files": [
18
+ "index.js",
19
+ "index.d.ts",
20
+ "channel.js",
21
+ "dist",
22
+ "model",
23
+ "LICENSE.md"
24
+ ],
25
+ "scripts": {
26
+ "test": "node --test test/gist.test.mjs"
27
+ },
28
+ "dependencies": {
29
+ "@bjorn3/browser_wasi_shim": "^0.3.0"
30
+ },
31
+ "peerDependencies": {
32
+ "@litertjs/core": ">=2.1.0"
33
+ },
34
+ "peerDependenciesMeta": {
35
+ "@litertjs/core": {
36
+ "optional": true
37
+ }
38
+ },
39
+ "devDependencies": {
40
+ "@litertjs/core": "^2.5.2"
41
+ }
42
+ }