File size: 5,646 Bytes
0daf81d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// 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()
}