@kecan0406/aninames 0.1.0 → 0.3.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/README.md CHANGED
@@ -56,7 +56,7 @@ Built sizes: `core.sqlite` 610 MB, `kowiki.sqlite` 25 MB, `unlicensed.sqlite` 83
56
56
  | `<layer>/<table>/<hash>.json.gz` | about 32 KB of JSON rows sorted by key (16 KB for `entity`), named by the first 48 bits of the SHA-256 of the file |
57
57
  | `NOTICE.md`, `index.html` | each layer's sources and terms |
58
58
 
59
- The key tables are `flat` (folded names), `latin` (romaji keys), `sound` (sound keys across kana, Hangul and romaji), `part` (name tokens) and `initial` (Korean initials); their rows are `[key, entity number, name weight, flags, popularity, standing, bonus]`. `entity` rows, keyed by entity number (which follows the entity ids' order), carry the id, names, Danbooru tags, works and family of one entity in that layer. Layers stay in separate files; the only values a file carries from other layers are derived numbers and flags (popularity, family standing, adult, which layers know the entity).
59
+ The key tables are `flat` (folded names), `latin` (romaji keys), `sound` (sound keys across kana, Hangul and romaji), `part` (name tokens) and `initial` (Korean initials); their rows are `[key, entity number, name weight, flags, popularity, standing, bonus]`. `tag` holds the same rows for Danbooru tags, keyed by the tag folded like a name without its qualifier and weighted by the tag's posts. `home` holds them for the copyright tag each character comes from, weighted by the character's own posts; a `core` row whose character the `unlicensed` layer gives another home carries flag 64, which a client that reads `unlicensed` skips. `entity` rows, keyed by entity number (which follows the entity ids' order), carry the id, names, Danbooru tags, works, family, the ids other databases give one entity in that layer (TMDB's `tmdb:tv/…` and `tmdb:movie/…`, IGDB's `igdb:…` and Steam's `steam:…` among them, read from Wikidata) and a character's home tag. Layers stay in separate files; the only values a file carries from other layers are derived numbers and flags (popularity, family standing, adult, which layers know the entity).
60
60
 
61
61
  On the 10-04 build: 19,167 files, 149 MB gzip'd, a manifest of 236 KB gzip'd. `mise run compare` searches the probe sample (4,370 queries) both ways: the files find the entity first 87% of the time, SQLite 86% (FTS substring search is not in the files; typo search reads the rows around the query's position instead). A cold query needs a median of 2 rounds (p90 3), 31 files (p90 78) and 287 KB (p90 584 KB).
62
62
 
@@ -71,7 +71,7 @@ const [first] = await names.search('봇치', { limit: 10, signal })
71
71
  const works = await names.lookup(first?.works ?? [])
72
72
  ```
73
73
 
74
- `search` returns `Found` cards (`id`, `kind`, `label`, `names`, `danbooru` tags with the most posts first, `works`, `score`, `adult`); `search(query, { kind, limit, adult: false })` narrows it, and `lookup(ids)` returns the cards of given ids in one round. `cachedSource` keeps the files it fetched forever (their names are hashes of their contents), revalidates the manifest with its ETag or Last-Modified once a day (`maxAge`), answers from the cache when offline, refetches the manifest when the site has moved on to a new build, and deletes files a new manifest no longer names. `fileSource(dir)` reads a local `dist/site`.
74
+ `search` returns `Found` cards (`id`, `kind`, `label`, `names` with their `lang` and `kind`, `danbooru` tags with the most posts first, `works`, `refs`, `home`, the copyright tag a character comes from, `score`, `adult`); `search(query, { kind, limit, adult: false })` narrows it, `lookup(ids)` returns the cards of given ids in one round, and `tagged(tag, { kind, adult })` the cards of the entities that carry a Danbooru tag, most posts first, whatever its case, punctuation or qualifier (`soul-eater`, `soul_eater` and `soul_eater_(series)` find the same works); `prefix: true` also finds the tags that start with it. `cast(tag, { adult, prefix, limit })` returns the characters whose home is that tag, most posts first. `cachedSource` keeps the files it fetched forever (their names are hashes of their contents), revalidates the manifest with its ETag or Last-Modified once a day (`maxAge`), answers from the cache when offline, refetches the manifest when the site has moved on to a new build, and deletes files a new manifest no longer names. `fileSource(dir)` reads a local `dist/site`.
75
75
 
76
76
  ## Development
77
77
 
@@ -19,6 +19,7 @@ export declare class View {
19
19
  constructor(manifest: Manifest, layers: Layer[], loaded: Loaded);
20
20
  private rows;
21
21
  keys(table: KeyTable, range: Range): KeyRow[];
22
+ tagged(key: string, prefix: boolean, table?: 'tag' | 'home'): KeyRow[];
22
23
  private keysIn;
23
24
  around(table: KeyTable, key: string, radius: number): KeyRow[];
24
25
  entity(eid: number, mask?: number): EntityRow[];
@@ -1,4 +1,4 @@
1
- import { chunkPath, present } from "./format.js";
1
+ import { chunkPath, present, } from "./format.js";
2
2
  import { compare } from "./order.js";
3
3
  function last(count, below) {
4
4
  let lo = 0;
@@ -37,10 +37,13 @@ export class View {
37
37
  return rows;
38
38
  }
39
39
  keys(table, range) {
40
- return this.layers.flatMap((layer) => this.keysIn(layer, table, range));
40
+ return this.layers.flatMap((layer) => this.keysIn(layer, table, this.manifest.layers.get(layer)?.keys[table], range));
41
41
  }
42
- keysIn(layer, table, range) {
43
- const spans = this.manifest.layers.get(layer)?.keys[table];
42
+ tagged(key, prefix, table = 'tag') {
43
+ const range = { low: key, high: prefix ? `${key}\u{10FFFF}` : key };
44
+ return this.layers.flatMap((layer) => this.keysIn(layer, table, this.manifest.layers.get(layer)?.[table], range));
45
+ }
46
+ keysIn(layer, table, spans, range) {
44
47
  if (!spans)
45
48
  return [];
46
49
  const { low, high, open = false, limit = Number.POSITIVE_INFINITY, spans: most = Number.POSITIVE_INFINITY } = range;
@@ -2,12 +2,14 @@ import { type Kind, type Layer, type NameKind } from '../model.ts';
2
2
  export declare const FORMAT = 1;
3
3
  export declare const KEY_TABLES: readonly ["flat", "latin", "sound", "part", "initial"];
4
4
  export type KeyTable = (typeof KEY_TABLES)[number];
5
- export type Table = KeyTable | 'entity';
5
+ export declare const TABLES: readonly ["flat", "latin", "sound", "part", "initial", "tag", "home", "entity"];
6
+ export type Table = (typeof TABLES)[number];
6
7
  export declare const NAME_KINDS: readonly NameKind[];
7
8
  export declare const TRUSTED: readonly string[];
8
9
  export declare const CHARACTER = 1;
9
10
  export declare const MAIN = 2;
10
11
  export declare const ADULT = 4;
12
+ export declare const SHADOWED = 64;
11
13
  export declare function present(layer: Layer): number;
12
14
  export declare const HASH_LENGTH = 12;
13
15
  export declare function chunkPath(layer: Layer, table: Table, hash: string): string;
@@ -33,6 +35,8 @@ export interface EntitySpans extends Spans {
33
35
  }
34
36
  export interface LayerSpans {
35
37
  keys: Record<KeyTable, Spans>;
38
+ tag: Spans | undefined;
39
+ home: Spans | undefined;
36
40
  entity: EntitySpans;
37
41
  }
38
42
  export interface Manifest {
@@ -70,5 +74,7 @@ export interface EntityRow {
70
74
  standing: number;
71
75
  extra: number;
72
76
  adult: boolean;
77
+ refs: string[];
78
+ home: string | null;
73
79
  }
74
80
  export declare function readRows(table: Table, value: unknown): KeyRow[] | EntityRow[] | undefined;
@@ -3,6 +3,7 @@ import { flat } from "../text.js";
3
3
  import { compare } from "./order.js";
4
4
  export const FORMAT = 1;
5
5
  export const KEY_TABLES = ['flat', 'latin', 'sound', 'part', 'initial'];
6
+ export const TABLES = [...KEY_TABLES, 'tag', 'home', 'entity'];
6
7
  export const NAME_KINDS = [
7
8
  'main',
8
9
  'official',
@@ -17,6 +18,7 @@ export const TRUSTED = ['wikidata', 'aod', 'anidb', 'vndb'];
17
18
  export const CHARACTER = 1;
18
19
  export const MAIN = 2;
19
20
  export const ADULT = 4;
21
+ export const SHADOWED = 64;
20
22
  export function present(layer) {
21
23
  return 8 << LAYERS.indexOf(layer);
22
24
  }
@@ -25,7 +27,7 @@ export const HASH_LENGTH = 12;
25
27
  export function chunkPath(layer, table, hash) {
26
28
  return `${layer}/${table}/${hash}.json.gz`;
27
29
  }
28
- const PATH = new RegExp(`^(${LAYERS.join('|')})/(${[...KEY_TABLES, 'entity'].join('|')})/([0-9a-f]{12})\\.json\\.gz$`);
30
+ const PATH = new RegExp(`^(${LAYERS.join('|')})/(${TABLES.join('|')})/([0-9a-f]{12})\\.json\\.gz$`);
29
31
  export function parsePath(path) {
30
32
  const match = PATH.exec(path);
31
33
  return match ? { layer: match[1], table: match[2], hash: match[3] } : undefined;
@@ -95,6 +97,10 @@ function unpack(value, where, numbered) {
95
97
  }
96
98
  return out;
97
99
  }
100
+ function spansOf(value, where) {
101
+ const { bounds, files } = unpack(value, where, false);
102
+ return { bounds, files };
103
+ }
98
104
  export function readManifest(text) {
99
105
  let value;
100
106
  try {
@@ -119,11 +125,11 @@ export function readManifest(text) {
119
125
  if (!isObject(tables))
120
126
  throw bad(`layer ${layer} is malformed`);
121
127
  const keys = {};
122
- for (const table of KEY_TABLES) {
123
- const { bounds, files } = unpack(tables[table], `${layer}/${table}`, false);
124
- keys[table] = { bounds, files };
125
- }
126
- layers.set(layer, { keys, entity: unpack(tables.entity, `${layer}/entity`, true) });
128
+ for (const table of KEY_TABLES)
129
+ keys[table] = spansOf(tables[table], `${layer}/${table}`);
130
+ const tag = tables.tag === undefined ? undefined : spansOf(tables.tag, `${layer}/tag`);
131
+ const home = tables.home === undefined ? undefined : spansOf(tables.home, `${layer}/home`);
132
+ layers.set(layer, { keys, tag, home, entity: unpack(tables.entity, `${layer}/entity`, true) });
127
133
  }
128
134
  if (!layers.has('core'))
129
135
  throw bad('it has no core layer');
@@ -135,6 +141,10 @@ export function manifestPaths(manifest) {
135
141
  for (const table of KEY_TABLES)
136
142
  for (const hash of spans.keys[table].files)
137
143
  paths.add(chunkPath(layer, table, hash));
144
+ for (const hash of spans.tag?.files ?? [])
145
+ paths.add(chunkPath(layer, 'tag', hash));
146
+ for (const hash of spans.home?.files ?? [])
147
+ paths.add(chunkPath(layer, 'home', hash));
138
148
  for (const hash of spans.entity.files)
139
149
  paths.add(chunkPath(layer, 'entity', hash));
140
150
  }
@@ -181,10 +191,11 @@ const tagOf = (value) => Array.isArray(value) && typeof value[0] === 'string' &&
181
191
  : undefined;
182
192
  const workOf = (value) => Array.isArray(value) && isCount(value[0]) && typeof value[1] === 'string' ? [value[0], value[1]] : undefined;
183
193
  const eidOf = (value) => (isCount(value) ? value : undefined);
194
+ const refOf = (value) => typeof value === 'string' && value.indexOf(':') > 0 ? value : undefined;
184
195
  function entityRow(value) {
185
196
  if (!Array.isArray(value) || value.length < 10)
186
197
  return undefined;
187
- const [eid, id, rawNames, rawTags, rawWorks, rawReach, rank, standing, extra, adult] = value;
198
+ const [eid, id, rawNames, rawTags, rawWorks, rawReach, rank, standing, extra, adult, rawRefs = [], home = null] = value;
188
199
  if (!isCount(eid) || typeof id !== 'string')
189
200
  return undefined;
190
201
  const kind = id.startsWith('w/') ? 'work' : id.startsWith('c/') ? 'character' : undefined;
@@ -194,9 +205,10 @@ function entityRow(value) {
194
205
  const danbooru = list(rawTags, tagOf);
195
206
  const works = list(rawWorks, workOf);
196
207
  const reach = list(rawReach, eidOf);
197
- if (!names || !danbooru || !works || !reach)
208
+ const refs = list(rawRefs, refOf);
209
+ if (!names || !danbooru || !works || !reach || !refs || (home !== null && typeof home !== 'string'))
198
210
  return undefined;
199
- return { eid, id, kind, names, danbooru, works, reach, rank, standing, extra, adult: adult === 1 };
211
+ return { eid, id, kind, names, danbooru, works, reach, rank, standing, extra, adult: adult === 1, refs, home };
200
212
  }
201
213
  export function readRows(table, value) {
202
214
  if (!Array.isArray(value))
@@ -1,4 +1,4 @@
1
- import { type Kind, type Layer } from '../model.ts';
1
+ import { type Kind, type Layer, type NameKind } from '../model.ts';
2
2
  import { type Rows } from './chunks.ts';
3
3
  import { type Source } from './source.ts';
4
4
  export interface Found {
@@ -8,9 +8,12 @@ export interface Found {
8
8
  names: {
9
9
  text: string;
10
10
  lang: string | null;
11
+ kind: NameKind;
11
12
  }[];
12
13
  danbooru: string[];
13
14
  works: string[];
15
+ refs: string[];
16
+ home: string | null;
14
17
  score: number;
15
18
  adult: boolean;
16
19
  }
@@ -34,4 +37,16 @@ export declare class Names {
34
37
  signal?: AbortSignal;
35
38
  }): Promise<Found[]>;
36
39
  lookup(ids: string[], signal?: AbortSignal): Promise<Found[]>;
40
+ tagged(tag: string, options?: {
41
+ kind?: Kind;
42
+ adult?: boolean;
43
+ prefix?: boolean;
44
+ signal?: AbortSignal;
45
+ }): Promise<Found[]>;
46
+ cast(tag: string, options?: {
47
+ adult?: boolean;
48
+ prefix?: boolean;
49
+ limit?: number;
50
+ signal?: AbortSignal;
51
+ }): Promise<Found[]>;
37
52
  }
@@ -1,8 +1,9 @@
1
1
  import { gunzipSync } from 'node:zlib';
2
2
  import { LAYERS } from "../model.js";
3
+ import { flat, qualifiers } from "../text.js";
3
4
  import { View } from "./chunks.js";
4
5
  import { search } from "./engine.js";
5
- import { parsePath, readManifest, readRows } from "./format.js";
6
+ import { ADULT, CHARACTER, MAIN, NAME_KINDS, parsePath, readManifest, readRows, SHADOWED, } from "./format.js";
6
7
  import { Missing } from "./source.js";
7
8
  const KEEP = 256;
8
9
  const PARALLEL = 16;
@@ -50,14 +51,21 @@ function label(id, rows) {
50
51
  }
51
52
  function card(rows, score, adult) {
52
53
  const head = rows[0];
53
- const seen = new Set();
54
+ const seen = new Map();
54
55
  const names = [];
55
56
  for (const name of rows.flatMap((row) => row.names)) {
57
+ if (!SHOWN.has(name.kind))
58
+ continue;
56
59
  const key = `${name.lang ?? ''}\u0000${name.text}`;
57
- if (!SHOWN.has(name.kind) || seen.has(key))
60
+ const known = seen.get(key);
61
+ if (known) {
62
+ if (NAME_KINDS.indexOf(name.kind) < NAME_KINDS.indexOf(known.kind))
63
+ known.kind = name.kind;
58
64
  continue;
59
- seen.add(key);
60
- names.push({ text: name.text, lang: name.lang });
65
+ }
66
+ const shown = { text: name.text, lang: name.lang, kind: name.kind };
67
+ seen.set(key, shown);
68
+ names.push(shown);
61
69
  }
62
70
  const posts = new Map();
63
71
  for (const [tag, count] of rows.flatMap((row) => row.danbooru)) {
@@ -69,7 +77,9 @@ function card(rows, score, adult) {
69
77
  .sort((a, b) => (b.count ?? -1) - (a.count ?? -1) || a.at - b.at)
70
78
  .map((entry) => entry.tag);
71
79
  const works = head.kind === 'character' ? [...new Set(rows.flatMap((row) => row.works.map(([, id]) => id)))] : [];
72
- return { id: head.id, kind: head.kind, label: label(head.id, rows), names, danbooru, works, score, adult };
80
+ const refs = [...new Set(rows.flatMap((row) => row.refs))].sort();
81
+ const home = rows.findLast((row) => row.home !== null)?.home ?? null;
82
+ return { id: head.id, kind: head.kind, label: label(head.id, rows), names, danbooru, works, refs, home, score, adult };
73
83
  }
74
84
  export class Names {
75
85
  #source;
@@ -110,6 +120,45 @@ export class Names {
110
120
  return view.wanted.size > 0 ? undefined : out;
111
121
  });
112
122
  }
123
+ tagged(tag, options = {}) {
124
+ return this.#tagged('tag', tag, options);
125
+ }
126
+ cast(tag, options = {}) {
127
+ return this.#tagged('home', tag, options);
128
+ }
129
+ #tagged(table, tag, options) {
130
+ const { kind, adult = true, prefix = false, limit = Number.POSITIVE_INFINITY, signal } = options;
131
+ const key = flat(qualifiers(tag).base);
132
+ return this.#run(signal, (view) => {
133
+ if (!key)
134
+ return [];
135
+ const covered = view.layers.includes('unlicensed');
136
+ const best = new Map();
137
+ for (const [, eid, posts, flags, , standing] of view.tagged(key, prefix, table)) {
138
+ if (kind && (flags & CHARACTER ? 'character' : 'work') !== kind)
139
+ continue;
140
+ if (!adult && flags & ADULT)
141
+ continue;
142
+ if (covered && flags & SHADOWED)
143
+ continue;
144
+ const known = best.get(eid);
145
+ const mask = flags & ~(CHARACTER | MAIN | ADULT | SHADOWED);
146
+ if (!known || posts > known.posts)
147
+ best.set(eid, { posts, mask: mask | (known?.mask ?? 0), flags, standing });
148
+ else
149
+ known.mask |= mask;
150
+ }
151
+ const order = [...best]
152
+ .sort(([a, x], [b, y]) => y.posts - x.posts || y.standing - x.standing || a - b)
153
+ .slice(0, limit);
154
+ view.labels = true;
155
+ const out = order.flatMap(([eid, hit]) => {
156
+ const rows = view.entity(eid, hit.mask);
157
+ return rows.length > 0 ? [card(rows, 0, (hit.flags & ADULT) !== 0)] : [];
158
+ });
159
+ return view.wanted.size > 0 ? undefined : out;
160
+ });
161
+ }
113
162
  #open() {
114
163
  if (this.#state)
115
164
  return this.#state;
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { USER_AGENT } from "../model.js";
5
- import { KEY_TABLES, manifestPaths, parsePath, readManifest } from "./format.js";
5
+ import { manifestPaths, parsePath, readManifest, TABLES } from "./format.js";
6
6
  export class Missing extends Error {
7
7
  }
8
8
  const revalidators = new WeakMap();
@@ -96,7 +96,7 @@ async function put(path, data) {
96
96
  async function prune(dir, text) {
97
97
  const named = manifestPaths(readManifest(text));
98
98
  for (const layer of await readdir(dir).catch(() => [])) {
99
- for (const table of [...KEY_TABLES, 'entity']) {
99
+ for (const table of TABLES) {
100
100
  const folder = join(dir, layer, table);
101
101
  for (const file of await readdir(folder).catch(() => [])) {
102
102
  const path = `${layer}/${table}/${file}`;
package/lib/model.d.ts CHANGED
@@ -3,7 +3,7 @@ export type Layer = 'core' | 'kowiki' | 'unlicensed';
3
3
  export declare const LAYERS: readonly Layer[];
4
4
  export declare const USER_AGENT = "aninames/0.1 (+https://github.com/kecan0406/aninames)";
5
5
  export type NameKind = 'main' | 'official' | 'synonym' | 'short' | 'reading' | 'redirect' | 'section' | 'generated';
6
- export type Namespace = 'wikidata' | 'mal' | 'anilist' | 'anidb' | 'kitsu' | 'ann' | 'animeplanet' | 'anisearch' | 'livechart' | 'simkl' | 'animecountdown' | 'vndb' | 'bangumi' | 'danbooru' | 'kowiki' | 'anissia';
6
+ export type Namespace = 'wikidata' | 'mal' | 'anilist' | 'anidb' | 'kitsu' | 'ann' | 'animeplanet' | 'anisearch' | 'livechart' | 'simkl' | 'animecountdown' | 'tmdb' | 'igdb' | 'steam' | 'vndb' | 'bangumi' | 'danbooru' | 'kowiki' | 'anissia';
7
7
  export type Ref = `${Namespace}:${string}`;
8
8
  export interface Name {
9
9
  text: string;
@@ -14,10 +14,13 @@ export interface Entry {
14
14
  id: Ref;
15
15
  kind?: Kind;
16
16
  attach?: boolean;
17
+ family?: boolean;
17
18
  refs?: Ref[];
18
19
  names: Name[];
19
20
  works?: Ref[];
21
+ series?: Ref[];
20
22
  related?: Ref[];
23
+ near?: Ref[];
21
24
  link?: string[];
22
25
  rank?: number;
23
26
  adult?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kecan0406/aninames",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Multilingual alias index for anime titles and characters",
6
6
  "license": "MIT",