eths / source /frontend /src /lib /live /lookup.ts
Ethscriptions's picture
Update: ≤3s WeChat-compatible live photos, sets 3 & 4 (fill-in-the-blank), in-browser maker tool
0daf81d verified
Raw History Blame Contribute Delete
5.65 kB
// Word lookup without AI: IPA + part of speech from Wiktionary, human pronunciation recordings from Wikimedia Commons.
export interface WordInfo {
ipa: string
pos: string
}
export interface Recording {
title: string
label: string
url: string
page: string
}
const POS_MAP: [RegExp, string][] = [
[/^Noun$/i, 'n.'], [/^Verb$/i, 'v.'], [/^Adjective$/i, 'adj.'], [/^Adverb$/i, 'adv.'],
[/^(Phrase|Idiom|Proverb)$/i, 'phr.'], [/^Interjection$/i, 'int.'], [/^Preposition$/i, 'prep.'], [/^Pronoun$/i, 'pron.'],
]
/** Make Wiktionary's narrow IPA look like the learner-dictionary style most readers expect. */
export function simplifyIpa(s: string) {
return s
.replace(/ɹ/g, 'r').replace(/ɚ/g, 'ər').replace(/ɝ/g, 'ɜːr').replace(/ɫ/g, 'l').replace(/ɾ/g, 't')
.replace(/ɛ/g, 'e').replace(/ɐ/g, 'ʌ').replace(/[()]/g, '').replace(/\.(?=\S)/g, '')
}
export async function lookupWord(word: string): Promise<WordInfo> {
const w = word.trim()
const url = `https://en.wiktionary.org/w/api.php?action=parse&format=json&origin=*&redirects=1&prop=wikitext&page=${encodeURIComponent(w)}`
const r = await fetch(url)
if (!r.ok) throw new Error('词典查询失败')
const j = await r.json()
const text: string = j?.parse?.wikitext?.['*'] ?? ''
if (!text) throw new Error('词典里没有这个词')
const m = text.match(/==English==([\s\S]*?)(\n==[^=][^\n]*==\s*\n|$)/)
const en = m ? m[1] : text
// IPA: prefer lines marked US / GA
const lines = en.split('\n').filter((l) => l.includes('{{IPA|en|'))
const pick =
lines.find((l) => /(a=|\{\{a\|)[^}]*\b(GA|GenAm)\b/.test(l)) ??
lines.find((l) => /\bUS\b/.test(l) && !/Southern US/.test(l)) ??
lines[0] ??
''
const ipaM = pick.match(/\{\{IPA\|en\|([^}]*)\}\}/)
let ipa = ''
if (ipaM) {
const first = ipaM[1].split('|').find((p) => /^[/[]/.test(p.trim()))
if (first) ipa = simplifyIpa(first.trim().replace(/^\[/, '/').replace(/\]$/, '/'))
}
let pos = ''
for (const h of en.matchAll(/\n===+\s*([^=\n]+?)\s*===+/g)) {
const hit = POS_MAP.find(([re]) => re.test(h[1]))
if (hit) {
pos = hit[1]
break
}
}
// phrases ("traffic light") often have no IPA of their own: build it from the single words
if (!ipa && /\s/.test(w)) {
const parts: string[] = []
for (const token of w.split(/\s+/)) {
try {
const sub = await lookupWord(token)
if (!sub.ipa) return { ipa: '', pos }
parts.push(sub.ipa.replace(/^\/|\/$/g, ''))
} catch {
return { ipa: '', pos }
}
}
ipa = `/${parts.join(' ')}/`
}
return { ipa, pos }
}
const COMMONS = 'https://commons.wikimedia.org/w/api.php'
async function commons(params: Record<string, string>) {
const q = new URLSearchParams({ format: 'json', origin: '*', ...params })
const r = await fetch(`${COMMONS}?${q}`)
if (!r.ok) throw new Error('维基共享资源暂时无法访问')
return r.json()
}
function labelFor(title: string) {
const t = title.replace(/^File:/, '')
let m = t.match(/^En-(us|uk|au|ca|nz|ie)-/i)
if (m) return ({ us: '美式', uk: '英式', au: '澳式', ca: '加拿大', nz: '新西兰', ie: '爱尔兰' } as Record<string, string>)[m[1].toLowerCase()] + ' · Commons'
m = t.match(/^LL-Q1860 \(eng\)-([^-]+)-/)
if (m) return `LinguaLibre · ${m[1]}`
return t
}
/** Find human pronunciation recordings of an English word on Wikimedia Commons. */
export async function findRecordings(word: string): Promise<Recording[]> {
const w = word.trim()
const lower = w.toLowerCase()
const titles = new Set<string>()
for (const v of [w, lower, lower.replace(/ /g, '_')]) {
for (const acc of ['us', 'uk', 'au']) titles.add(`File:En-${acc}-${v}.ogg`)
}
const exact = await commons({ action: 'query', titles: [...titles].join('|') })
const found: string[] = Object.values(exact?.query?.pages ?? {})
.filter((p) => !('missing' in (p as object)))
.map((p) => (p as { title: string }).title)
try {
const s = await commons({ action: 'query', list: 'search', srnamespace: '6', srlimit: '12', srsearch: `intitle:"${w}" intitle:LL-Q1860` })
for (const hit of s?.query?.search ?? []) {
const t: string = hit.title
if (t.toLowerCase().endsWith(`-${lower}.wav`) && t.includes('(eng)')) found.push(t)
}
} catch {
/* search is optional */
}
const uniq = [...new Set(found)].slice(0, 8)
if (!uniq.length) return []
const info = await commons({ action: 'query', titles: uniq.join('|'), prop: 'imageinfo', iiprop: 'url' })
const out: Recording[] = []
for (const p of Object.values(info?.query?.pages ?? {}) as { title: string; imageinfo?: { url: string; descriptionurl: string }[] }[]) {
const ii = p.imageinfo?.[0]
if (!ii) continue
let url = ii.url.split('?')[0]
if (/\.(ogg|oga|opus)$/i.test(url)) {
const name = url.split('/').pop()!
url = url.replace('/wikipedia/commons/', '/wikipedia/commons/transcoded/') + `/${name}.mp3`
}
out.push({ title: p.title, label: labelFor(p.title), url, page: ii.descriptionurl })
}
out.sort((a, b) => (a.label.startsWith('美式') ? -1 : 0) - (b.label.startsWith('美式') ? -1 : 0))
return out
}
/** Fetch audio bytes; for Commons .ogg transcodes fall back to the original file if the mp3 is missing. */
export async function fetchAudio(url: string): Promise<ArrayBuffer> {
let r = await fetch(url)
if (!r.ok && url.includes('/transcoded/')) {
const orig = url.replace('/transcoded/', '/').replace(/\/[^/]+\.mp3$/, '')
r = await fetch(orig)
}
if (!r.ok) throw new Error('音频下载失败')
return r.arrayBuffer()
}