#!/usr/bin/env python3
"""Re-runs the check behind /blog/pinyin-is-not-pronunciation.

Lab: voice onset time of the six Mandarin unaspirated/aspirated pairs (b/p, d/t, g/k, z/c,
zh/ch, j/q) in the audio-cmn syllable recordings, the public CC BY-SA 4.0 corpus Tingyin's free
single-syllable clips are taken from. Each pair is compared on matched syllables: the same final
in the same tone, so the vowel and the pitch are held constant and only the initial differs.

Pages: every outside page the post cites is fetched again and its supporting sentence looked up.

  python3 check.py            measure and compare with dataset.json
  python3 check.py --recheck  pages, plus the lab if it finishes within 60 s
  python3 check.py --write    measure and write dataset.json and dataset.csv

Exit 0 when every quote is present and every median is within TOL_MS of the dataset, 1 otherwise.
"""
import argparse
import csv
import html
import io
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
import wave
from concurrent.futures import ThreadPoolExecutor

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET = os.path.join(HERE, 'dataset.json')
CSV = os.path.join(HERE, 'dataset.csv')
CORPUS = 'https://raw.githubusercontent.com/hugolpz/audio-cmn/master/64k/syllabs/'
UA = 'Mozilla/5.0'
SR = 16000
TOL_MS = 10
LAB_BUDGET_S = 60.0

PAIRS = [
    ('b', 'p', ['a', 'ai', 'an', 'ang', 'ao', 'ei', 'en', 'eng', 'i', 'u']),
    ('d', 't', ['a', 'ai', 'an', 'ang', 'ao', 'e', 'eng', 'i', 'ou', 'u']),
    ('g', 'k', ['a', 'ai', 'an', 'ang', 'ao', 'e', 'en', 'eng', 'ou', 'u']),
    ('z', 'c', ['a', 'ai', 'an', 'ang', 'ao', 'e', 'en', 'i', 'ou', 'u']),
    ('zh', 'ch', ['a', 'ai', 'an', 'ang', 'ao', 'e', 'en', 'i', 'ou', 'u']),
    ('j', 'q', ['i', 'ia', 'ian', 'iang', 'iao', 'ie', 'in', 'ing', 'iu', 'iong']),
]

PAGES = [
    {'party': 'Pleco', 'claim': 'recordings from two native speakers for 34,000 Mandarin words',
     'url': 'https://www.pleco.com/',
     'quote': 'Audio Recordings from two different native speakers for 34,000 Mandarin words, '
              'with speech synthesizer (for sentences) and Cantonese support as well.'},
    {'party': 'italki', 'claim': 'Chinese tutors on italki average $10 to $40 an hour',
     'url': 'https://www.italki.com/en/teachers/chinese',
     'quote': 'On average, the cost can range from $10 to $40 per hour.'},
    {'party': 'HelloChinese', 'claim': 'HelloChinese uses speech recognition on pronunciation',
     'url': 'https://www.hellochinese.cc/',
     'quote': 'Speech Recognition Nail your pronunciation and make speaking Chinese effortless.'},
    {'party': 'Wikipedia: Pinyin', 'claim': 'pinyin was developed in the 1950s by Chinese linguists',
     'url': 'https://en.wikipedia.org/wiki/Pinyin',
     'quote': 'Hanyu Pinyin was developed in the 1950s by a group of Chinese linguists'},
    {'party': 'Wikipedia: Voiceless alveolar affricate', 'claim': 'Czech spells [ts] with c',
     'url': 'https://en.wikipedia.org/wiki/Voiceless_alveolar_affricate',
     'quote': "'what' See Czech phonology"},
    {'party': 'Wikipedia: Voiceless alveolar affricate', 'claim': 'Hungarian spells [ts] with c',
     'url': 'https://en.wikipedia.org/wiki/Voiceless_alveolar_affricate',
     'quote': "'kitten' See Hungarian phonology"},
    {'party': 'Wikipedia: Voiceless alveolar affricate', 'claim': 'Polish spells [ts] with c',
     'url': 'https://en.wikipedia.org/wiki/Voiceless_alveolar_affricate',
     'quote': "'what' See Polish phonology"},
    {'party': 'Tingyin', 'claim': 'web prices $2.49 weekly, $5.99 monthly, $15.99 once',
     'url': 'https://api.tingyin.app/subscriptions/plans',
     'quote': '"currency":"usd","options":[{"id":"weekly","kind":"recurring","web":2.49,'
              '"store":2.99},{"id":"monthly","kind":"recurring","web":5.99,"store":6.99},'
              '{"id":"lifetime","kind":"one_time","web":15.99,"store":19.99}]'},
]


def fetch(url, timeout=40):
    req = urllib.request.Request(url, headers={'User-Agent': UA})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return r.read()


def normalise(text):
    text = re.sub(r'<script.*?</script>|<style.*?</style>', ' ', text, flags=re.S | re.I)
    text = re.sub(r'<[^>]+>', ' ', text)
    text = html.unescape(text)
    for a, b in (('’', "'"), ('‘', "'"), ('“', '"'), ('”', '"'),
                 ('–', '-'), ('—', '-'), (' ', ' ')):
        text = text.replace(a, b)
    return re.sub(r'\s+', ' ', text).strip()


def decode(path):
    p = subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-ac', '1', '-ar', str(SR),
                        '-f', 'wav', '-'], capture_output=True, check=True)
    w = wave.open(io.BytesIO(p.stdout))
    return np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16).astype(np.float64) / 32768.0


def measure(x):
    """Voice onset time in ms, or None when no clear voicing onset is found."""
    win, hop = int(0.025 * SR), int(0.002 * SR)
    n = 1 + (len(x) - win) // hop
    idx = np.arange(win)[None, :] + hop * np.arange(n)[:, None]
    fr = x[idx]
    fr = fr - fr.mean(axis=1, keepdims=True)
    rms = np.sqrt((fr ** 2).mean(axis=1))
    nfft = 1024
    power = np.abs(np.fft.rfft(fr * np.hanning(win)[None, :], n=nfft, axis=1)) ** 2
    freqs = np.fft.rfftfreq(nfft, 1 / SR)
    energy = power.sum(axis=1) + 1e-12
    lowfrac = power[:, (freqs >= 80) & (freqs <= 1100)].sum(axis=1) / energy
    ac = np.fft.irfft(power, n=nfft, axis=1)
    ac = ac / (ac[:, :1] + 1e-12)
    per = ac[:, int(SR / 400):int(SR / 90)].max(axis=1)

    peak = rms.max()
    noise = np.percentile(rms[:max(5, int(0.15 * SR / hop))], 50)
    thr = max(4 * noise, 0.05 * peak)
    onset = None
    for i in range(n - 3):
        if rms[i] > thr and rms[i + 1] > thr and rms[i + 2] > thr:
            onset = i
            break
    if onset is None:
        return None
    for i in range(onset, n - 4):
        if all(per[i + k] > 0.5 and lowfrac[i + k] > 0.5 for k in range(4)):
            return (i - onset) * hop / SR * 1000
    return None


def candidates():
    for u, a, finals in PAIRS:
        for final in finals:
            for tone in (1, 2, 3, 4):
                yield '%s/%s' % (u, a), final, tone, u + final + str(tone), a + final + str(tone)


def download(names, tmp):
    def grab(name):
        try:
            data = fetch(CORPUS + 'cmn-%s.mp3' % name)
        except urllib.error.HTTPError as exc:
            if exc.code == 404:
                return name, None
            raise
        path = os.path.join(tmp, name + '.mp3')
        with open(path, 'wb') as fh:
            fh.write(data)
        return name, path

    with ThreadPoolExecutor(16) as pool:
        return dict(pool.map(grab, sorted(set(names))))


def lab(deadline=None):
    """Returns the matched items with their measured VOT, one per pair, final and tone."""
    tmp = tempfile.mkdtemp(prefix='pinyin-vot-')
    try:
        cands = list(candidates())
        started = time.monotonic()
        files = download([c[3] for c in cands] + [c[4] for c in cands], tmp)
        print('lab: %d syllables requested, %d exist in the corpus, %.1fs' % (
            len(files), sum(1 for p in files.values() if p), time.monotonic() - started))
        vot = {}
        for name, path in files.items():
            if deadline is not None and time.monotonic() > deadline:
                raise TimeoutError('lab over budget')
            if path:
                vot[name] = measure(decode(path))
    finally:
        shutil.rmtree(tmp, ignore_errors=True)

    items = []
    for pair, final, tone, u, a in cands:
        if vot.get(u) is None or vot.get(a) is None:
            continue
        items.append({'pair': pair, 'final': final, 'tone': tone,
                      'unaspirated': u, 'aspirated': a,
                      'unaspirated_ms': round(vot[u], 1), 'aspirated_ms': round(vot[a], 1),
                      'unaspirated_url': CORPUS + 'cmn-%s.mp3' % u,
                      'aspirated_url': CORPUS + 'cmn-%s.mp3' % a})
    return items


def summarise(items):
    rows = []
    for u, a, _ in PAIRS:
        pair = '%s/%s' % (u, a)
        sel = [i for i in items if i['pair'] == pair]
        us = [i['unaspirated_ms'] for i in sel]
        asp = [i['aspirated_ms'] for i in sel]
        longer = sum(1 for i in sel if i['aspirated_ms'] > i['unaspirated_ms'])
        um = int(round(float(np.median(us))))
        am = int(round(float(np.median(asp))))
        rows.append({'pair': pair, 'unaspirated': u, 'aspirated': a, 'matched_syllables': len(sel),
                     'unaspirated_median_ms': um, 'aspirated_median_ms': am, 'gap_ms': am - um,
                     'unaspirated_max_ms': int(round(max(us))), 'aspirated_min_ms': int(round(min(asp))),
                     'aspirated_longer': longer})
    return rows


def line(r):
    return ('%s n=%d %s median %d ms (max %d), %s median %d ms (min %d), gap %d ms, '
            'aspirated longer in %d of %d') % (
        r['pair'], r['matched_syllables'], r['unaspirated'], r['unaspirated_median_ms'],
        r['unaspirated_max_ms'], r['aspirated'], r['aspirated_median_ms'], r['aspirated_min_ms'],
        r['gap_ms'], r['aspirated_longer'], r['matched_syllables'])


def pages(rows):
    ok = True
    cache = {}
    out = []
    for row in rows:
        url = row['url']
        if url not in cache:
            try:
                cache[url] = normalise(fetch(url).decode('utf-8', 'replace'))
            except Exception as exc:  # a page that moved or refuses is a failed check, not a crash
                cache[url] = None
                print('FAIL %s: %s' % (url, exc))
        text = cache[url]
        present = text is not None and normalise(row['quote']) in text
        print('%s %s  %r' % ('ok  ' if present else 'FAIL', row['party'], row['quote'][:70]))
        out.append(dict(row, present=present))
        ok = ok and present
    return ok, out


def write(rows, items, page_rows):
    tools = {'python': platform.python_version(), 'numpy': np.__version__,
             'ffmpeg': subprocess.run(['ffmpeg', '-version'], capture_output=True,
                                      text=True).stdout.split()[2]}
    results = [dict(r, kind='pair', value='%d ms vs %d ms, gap %d ms' % (
        r['unaspirated_median_ms'], r['aspirated_median_ms'], r['gap_ms']),
        quote=line(r), url=CORPUS) for r in rows]
    results += [{'kind': 'page', 'party': p['party'], 'claim': p['claim'], 'value': p['claim'],
                 'quote': p['quote'], 'url': p['url'], 'present': p['present']} for p in page_rows]
    dataset = {
        'slug': 'pinyin-is-not-pronunciation',
        'method': 'lab',
        'checkedAt': time.strftime('%Y-%m-%d'),
        'tools': tools,
        'what': ('Voice onset time of the six unaspirated/aspirated pairs in the audio-cmn '
                 'syllable recordings (one speaker, CC BY-SA 4.0), the corpus Tingyin\'s free '
                 'single-syllable clips come from. Each pair is compared on matched syllables, '
                 'the same final in the same tone. VOT runs from the first frame whose energy '
                 'passes max(4x the leading noise floor, 5% of the clip peak) to the first of four '
                 'frames that are periodic (normalised autocorrelation >= 0.5 at a lag for '
                 '90-400 Hz) with energy below 1.1 kHz dominant; 25 ms Hann window, 2 ms hop.'),
        'inputs': items,
        'results': results,
        'notes': [
            'Matched set: for each pair, 10 finals x 4 tones were requested; a syllable that does '
            'not exist in Mandarin or in the corpus, or whose voicing onset the script could not '
            'find, drops the whole matched pair.',
            'For z/c, zh/ch and j/q the interval includes the frication of the affricate, so it is '
            'not comparable with laboratory VOT norms for plain stops.',
            'All recordings are by one speaker, so the numbers describe that speaker, not '
            'Mandarin speakers in general.',
            'In %d of %d matched syllables the aspirated member did not measure longer (listed in '
            'inputs). Frame-by-frame inspection of pai1 and pa1 on 2026-10-26 found little or no '
            'high-frequency noise before voicing, so in those two recordings the aspiration itself '
            'is short; the other cases were not inspected by hand.' % (
                sum(1 for i in items if i['aspirated_ms'] <= i['unaspirated_ms']), len(items)),
            'Shipped Tingyin clips are byte-identical copies of this corpus (sha256 of l1-ba-1.mp3 '
            'equals cmn-ba1.mp3: 7130b5ca...8637).',
            'Not checked: whether Pleco has a recording for each syllable the post names; its page '
            'gives a count of recorded words, not a per-entry guarantee.',
            'Not checked: whether HelloChinese\'s speech recognition scores tones or initials; only '
            'its own feature line was read.',
            'Not checked: store prices of Tingyin (the post quotes web prices only).',
        ],
    }
    with open(DATASET, 'w', encoding='utf-8') as fh:
        json.dump(dataset, fh, ensure_ascii=False, indent=1)
        fh.write('\n')
    with open(CSV, 'w', newline='', encoding='utf-8') as fh:
        cols = ['pair', 'unaspirated', 'aspirated', 'matched_syllables', 'unaspirated_median_ms',
                'aspirated_median_ms', 'gap_ms', 'unaspirated_max_ms', 'aspirated_min_ms',
                'aspirated_longer']
        w = csv.DictWriter(fh, fieldnames=cols, lineterminator='\n')
        w.writeheader()
        for r in rows:
            w.writerow({c: r[c] for c in cols})


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--recheck', action='store_true')
    ap.add_argument('--write', action='store_true')
    args = ap.parse_args()

    ok, page_rows = pages(PAGES)
    deadline = time.monotonic() + LAB_BUDGET_S if args.recheck else None
    try:
        items = lab(deadline)
    except TimeoutError:
        print('lab: skipped, over the %d s budget of --recheck' % LAB_BUDGET_S)
        items = None
    if items is not None:
        rows = summarise(items)
        if args.write:
            write(rows, items, page_rows)
            for r in rows:
                print('     ' + line(r))
            print('wrote', DATASET, CSV)
        else:
            stored = {r['pair']: r for r in json.load(open(DATASET, encoding='utf-8'))['results']
                      if r['kind'] == 'pair'}
            for r in rows:
                s = stored.get(r['pair'])
                good = (s is not None
                        and abs(r['unaspirated_median_ms'] - s['unaspirated_median_ms']) <= TOL_MS
                        and abs(r['aspirated_median_ms'] - s['aspirated_median_ms']) <= TOL_MS
                        and r['aspirated_longer'] == s['aspirated_longer'])
                print('%s %s' % ('ok  ' if good else 'FAIL', line(r)))
                ok = ok and good
    print('RESULT:', 'all checks hold' if ok else 'FAILED')
    return 0 if ok else 1


if __name__ == '__main__':
    sys.exit(main())
