Files
music_quiz/apps/server/src/collector/other-names.ts

53 lines
2.5 KiB
TypeScript

/**
* An artist's name in the other script, for searching again: Melon writes "디제이디오씨" while YouTube Music knows
* "DJ DOC", so "디제이디오씨 Everybody" finds nothing. Names come from artist names already seen in saved YouTube Music
* results, kept when they sound the same (sound.ts); the most often seen first.
*/
import type { Database } from 'bun:sqlite';
import { artistParts, compareKey } from '@mq/shared';
import { hangulSkeletons, latinSkeletons, soundsLike } from './sound';
const onlyHangul = (s: string) => /\p{Script=Hangul}/u.test(s) && !/[A-Za-z]/.test(s);
const onlyLatin = (s: string) => /[A-Za-z]/.test(s) && !/\p{Script=Hangul}/u.test(s);
const skeletons = (name: string) => (onlyHangul(name) ? [...new Set([...hangulSkeletons(name, false), ...hangulSkeletons(name, true)])] : latinSkeletons(name));
export function otherScriptNames(db: Database): (artist: string, max?: number) => string[] {
const seen = new Map<string, Set<number>>();
const rows = db.query<{ song_id: number; channel: string }, []>("SELECT song_id, channel FROM youtube_candidates WHERE source = 'ytmusic' AND channel IS NOT NULL").all();
for (const r of rows) {
for (const p of artistParts(r.channel)) {
const name = p.trim();
if (!(onlyHangul(name) || onlyLatin(name)) || name.length > 40) continue;
let ids = seen.get(name);
if (!ids) seen.set(name, (ids = new Set()));
ids.add(r.song_id);
}
}
const index = new Map<string, string[]>();
for (const name of seen.keys())
for (const k of skeletons(name)) {
if (k.length < 2) continue;
const list = index.get(k);
if (list) list.push(name);
else index.set(k, [name]);
}
return (artist, max = 2) => {
const out = new Map<string, number>();
for (const part of artistParts(artist)) {
if (!onlyHangul(part) && !onlyLatin(part)) continue;
for (const k of skeletons(part))
for (const name of index.get(k) ?? []) {
if (compareKey(name) === compareKey(part) || !soundsLike(part, name)) continue;
out.set(name, Math.max(out.get(name) ?? 0, seen.get(name)!.size));
}
}
// one spelling per sound ("DJ DOC" and "DJ. DOC"): the most seen
const byKey = new Map<string, [string, number]>();
for (const [name, n] of out) {
const k = compareKey(name);
if ((byKey.get(k)?.[1] ?? -1) < n) byKey.set(k, [name, n]);
}
return [...byKey.values()].sort((a, b) => b[1] - a[1]).slice(0, max).map(([name]) => name);
};
}