"""Chinese annotation layer (zh-paraformer-ts v1). Replaces the CTC aligner of tiny_voca.annotate for the Chinese front end: per-character timestamps come from Paraformer-zh (the same ASR family used for CER screening), are mapped onto the reference characters with a sequence alignment, and are split into initial/final token durations. The output manifests have exactly the schema tiny_voca.data expects. python -m tiny_voca.zh_annotate --features ../features \ --output ../annotations --config zh_config.json \ --dataset-revision zh-pilot-v1 """ import argparse import difflib import hashlib import json from collections import Counter, defaultdict from pathlib import Path import numpy as np import torch from .config import Config from .journal import atomic_json from .text import (PHONE_SET, SYMBOL_TO_ID, VOWEL_SET, VOICELESS, frontend_fingerprint) from .zh_text import zh_items FPS = 24000 / 256 # acoustic frames per second (sample_rate / hop) FRICATIVES_ZH = frozenset(('f', 's', 'sh', 'x', 'h')) MIN_MATCH = 0.7 def load_rows(features, split, config): rows = [json.loads(line) for line in (features / (split + '.jsonl')).read_text(encoding='utf-8').split('\n') if line.strip()] for row in rows: if row['speaker'] not in config.speakers: raise ValueError(f"unknown speaker {row['speaker']!r}") return rows def char_spans(ref_chars, asr_tokens, asr_ts): """Map reference characters to (start_ms, end_ms) spans via ASR tokens. Returns (spans, matched_ratio); spans entries may be None when a char could not even be interpolated (no matched neighbour on one side).""" asr_chars, asr_char_ts = [], [] for tok, (s, e) in zip(asr_tokens, asr_ts): if not tok: continue step = (e - s) / len(tok) for k, ch in enumerate(tok): asr_chars.append(ch) asr_char_ts.append((s + k * step, s + (k + 1) * step)) matcher = difflib.SequenceMatcher(a=ref_chars, b=asr_chars, autojunk=False) spans = [None] * len(ref_chars) matched = 0 for tag, i1, i2, j1, j2 in matcher.get_opcodes(): if tag == 'equal': for k in range(i2 - i1): spans[i1 + k] = asr_char_ts[j1 + k] matched += 1 # interpolate unmatched chars between matched neighbours for i in range(len(ref_chars)): if spans[i] is not None: continue prev = next((spans[j] for j in range(i - 1, -1, -1) if spans[j]), None) nxt = next((spans[j] for j in range(i + 1, len(ref_chars)) if spans[j]), None) if prev and nxt: spans[i] = (prev[1], nxt[0]) elif prev: spans[i] = (prev[1], prev[1] + 80) elif nxt: spans[i] = (max(0, nxt[0] - 80), nxt[0]) ratio = matched / max(1, len(ref_chars)) return spans, ratio def build_durations(items, spans, total_frames): """items: zh_items output; spans: per ref-char (start_ms, end_ms) with erhua chars already merged into the previous char by the caller. Returns (symbols, stress, durations) including BOS/EOS.""" # token float spans in frames seq = [] # (symbol, stress, start_f, end_f, is_phone) cursor = 0.0 char_idx = -1 pending_gap = [] # punct/sp entries waiting for the next char start first_start = spans[0][0] / 1000 * FPS if spans else 0.0 seq.append(('', 0, 0.0, first_start, False)) for item in items: kind = item[0] if kind in ('punct', 'sp'): pending_gap.append(item) continue if kind == 'erhua': continue # span merged into previous char by caller char_idx += 1 s_ms, e_ms = spans[char_idx] s_f, e_f = s_ms / 1000 * FPS, e_ms / 1000 * FPS for gap in pending_gap: if gap[0] == 'punct': seq.append((gap[1], 0, cursor, s_f, False)) else: seq.append(('', 0, s_f, s_f, False)) pending_gap = [] toks = item[2] if len(toks) == 2: # initial + final cut = s_f + 0.35 * (e_f - s_f) seq.append((toks[0][0], toks[0][1], s_f, cut, True)) seq.append((toks[1][0], toks[1][1], cut, e_f, True)) else: seq.append((toks[0][0], toks[0][1], s_f, e_f, True)) cursor = e_f for gap in pending_gap: if gap[0] == 'punct': seq.append((gap[1], 0, cursor, float(total_frames), False)) else: seq.append(('', 0, float(total_frames), float(total_frames), False)) seq.append(('', 0, cursor, float(total_frames), False)) # integerize: floor, then hand out the remainder by largest fraction durations = [max(0, int(b - a)) for _, _, a, b, _ in seq] # use exact float lengths for the remainder distribution floats = [b - a for _, _, a, b, _ in seq] durations = [int(f) for f in floats] rest = total_frames - sum(durations) order = sorted(range(len(seq)), key=lambda i: -(floats[i] - durations[i])) i = 0 while rest > 0 and order: durations[order[i % len(order)]] += 1 rest -= 1 i += 1 while rest < 0: # over-allocated: take from the longest non-phone, then phone cand = max(range(len(seq)), key=lambda j: durations[j] if not seq[j][4] else -1) if durations[cand] == 0: cand = max(range(len(seq)), key=lambda j: durations[j]) durations[cand] -= 1 rest += 1 # every phone token needs >= 1 frame: steal from the longest token for j, (_, _, _, _, is_phone) in enumerate(seq): if is_phone and durations[j] < 1: donor = max(range(len(seq)), key=lambda k: durations[k]) if durations[donor] > 1: durations[donor] -= 1 durations[j] = 1 symbols = [s for s, _, _, _, _ in seq] stress = [t for _, t, _, _, _ in seq] return symbols, stress, durations def snap_boundaries(symbols, durations, voiced, reach=6): """Round-2 refinement: move vowel->voiceless and fricative->vowel boundaries to the nearest voicing flip in the recorded prosody track (within +/-reach frames), keeping durations valid (phones >= 1 frame, total unchanged). Returns the adjusted durations.""" durations = list(durations) ends = list(np.cumsum(durations)) active = [i for i, d in enumerate(durations) if d > 0] for a, b in zip(active[:-1], active[1:]): if symbols[a] in VOWEL_SET and symbols[b] in VOICELESS: before = True elif symbols[a] in FRICATIVES_ZH and symbols[b] in VOWEL_SET: before = False else: continue boundary = int(ends[a]) best = None for shift in range(-reach, reach + 1): f = boundary + shift if 0 < f < len(voiced) and bool(voiced[f - 1]) == before and bool(voiced[f]) != before: if best is None or abs(shift) < abs(best): best = shift if not best: continue # a keeps >=1 frame; b (a phone) keeps >=1 frame if durations[a] + best < 1 or durations[b] - best < 1: continue durations[a] += best durations[b] -= best ends[a] += best return durations def boundary_offsets(symbols, durations, voiced, reach=6): found = {'vowel_to_voiceless': [], 'fricative_to_vowel': []} ends = np.cumsum(durations) active = [i for i, d in enumerate(durations) if d > 0] for a, b in zip(active[:-1], active[1:]): if symbols[a] in VOWEL_SET and symbols[b] in VOICELESS: kind, before = 'vowel_to_voiceless', True elif symbols[a] in FRICATIVES_ZH and symbols[b] in VOWEL_SET: kind, before = 'fricative_to_vowel', False else: continue boundary = int(ends[a]) best = None for shift in range(-reach, reach + 1): f = boundary + shift if 0 < f < len(voiced) and bool(voiced[f - 1]) == before and bool(voiced[f]) != before: if best is None or abs(shift) < abs(best): best = shift found[kind].append(best) return found def summarize_offsets(values): hits = np.array([v for v in values if v is not None], dtype=np.float64) out = {'boundaries': len(values), 'flip_found': round(len(hits) / max(len(values), 1), 4)} if len(hits): out.update(mean_offset_frames=round(float(hits.mean()), 3), mean_abs_frames=round(float(np.abs(hits).mean()), 3), within_1_frame=round(float((np.abs(hits) <= 1).mean()), 4), within_2_frames=round(float((np.abs(hits) <= 2).mean()), 4)) return out def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--features', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--config', type=Path) parser.add_argument('--dataset-revision', required=True) parser.add_argument('--clips-dir', type=Path, required=True, help='Directory with _.wav files') parser.add_argument('--snap', action='store_true', help='Snap vowel/voiceless and fricative/vowel boundaries to the ' 'nearest voicing flip in the recorded prosody track (round 2).') parser.add_argument('--min-vowel-voiced', type=float, default=0.5, help='QC gate: minimum voiced fraction inside vowel spans. ' 'The zh pilot uses 0.30: pyin under-detects voicing for ' 'the low male voice (whole-clip voiced 0.34-0.43 on clean ' 'rows), so the English 0.5 default rejects good M rows.') args = parser.parse_args() config = Config.from_dict(json.loads(args.config.read_text())) if args.config else Config() from funasr import AutoModel asr = AutoModel(model='paraformer-zh', model_revision='v2.0.4', disable_update=True) identity = { 'annotation_version': 'zh-1', 'frontend': frontend_fingerprint(), 'aligner': {'model': 'paraformer-zh', 'revision': 'v2.0.4', 'method': 'char timestamps + difflib mapping + 0.35 initial split' + (' + voicing-flip boundary snap' if args.snap else '')}, 'dataset_revision': args.dataset_revision, 'min_vowel_voiced': args.min_vowel_voiced, 'boundary_snap': bool(args.snap), 'sources': {split: hashlib.sha256((args.features / (split + '.jsonl')).read_bytes()).hexdigest() for split in ('train', 'validation')}, } fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() args.output.mkdir(parents=True, exist_ok=True) probe = defaultdict(list) summary = {'aligner': identity['aligner'], 'splits': {}} for split in ('train', 'validation'): rows = load_rows(args.features, split, config) accepted, rejected = [], [] for row in rows: wav = args.clips_dir / f"{row['id']}_{row['speaker']}.wav" items = zh_items(row['text']) ref_chars, char_items = [], [] for item in items: if item[0] == 'char': ref_chars.append(item[1]) char_items.append(item) elif item[0] == 'erhua': ref_chars.append(item[1]) try: res = asr.generate(input=str(wav)) asr_tokens = res[0]['text'].split() asr_ts = res[0]['timestamp'] if len(asr_tokens) != len(asr_ts): raise ValueError('asr token/timestamp count mismatch') spans, ratio = char_spans(ref_chars, asr_tokens, asr_ts) if ratio < MIN_MATCH or any(s is None for s in spans): raise ValueError(f'low asr match {ratio:.2f}') # merge erhua spans into the previous char merged_spans, k = [], 0 for item in items: if item[0] == 'char': s, e = spans[k] k += 1 merged_spans.append([s, e]) elif item[0] == 'erhua': s, e = spans[k] k += 1 merged_spans[-1][1] = e symbols, stress, durations = build_durations( items, [tuple(s) for s in merged_spans], row['frames']) if sum(durations) != row['frames']: raise ValueError('duration sum mismatch') feat = torch.load(args.features / row['path'], map_location='cpu', weights_only=True) voiced = feat['prosody'][:, 1].numpy() > 0.5 if args.snap: durations = snap_boundaries(symbols, durations, voiced) if sum(durations) != row['frames']: raise ValueError('duration sum mismatch after snap') found = boundary_offsets(symbols, durations, voiced) for kind, vals in found.items(): probe[(row['speaker'], kind)].extend(vals) # qc ends = np.cumsum(durations) vowel_frames = sum(d for s, d in zip(symbols, durations) if s in VOWEL_SET) vowel_voiced = float(np.mean([ voiced[int(ends[i]) - durations[i]:int(ends[i])].mean() for i, s in enumerate(symbols) if s in VOWEL_SET and durations[i] > 0])) if vowel_frames else 0.0 phone_durs = [d for s, d in zip(symbols, durations) if s in PHONE_SET] qc = {'token_probability_mean': round(ratio, 4), 'weak_phone_fraction': round(1 - ratio, 4), 'max_phone_frames': max(phone_durs) if phone_durs else 0, 'vowel_voiced': round(vowel_voiced, 4), 'phones_per_second': round(len(phone_durs) / (row['frames'] / FPS), 2)} reasons = [] if any(s == '' for s in symbols): reasons.append('unknown_phoneme') if qc['max_phone_frames'] > 70: reasons.append('overlong_phone') if qc['vowel_voiced'] < args.min_vowel_voiced: reasons.append('vowels_not_voiced') if not 4.0 <= qc['phones_per_second'] <= 30.0: reasons.append('implausible_rate') entry = {'id': row['id'], 'split': split, 'speaker': row['speaker'], 'text': row['text'], 'text_hash': row['text_hash'], 'path': row['path'], 'frames': row['frames'], 'symbols': ' '.join(symbols), 'tokens': [SYMBOL_TO_ID[s] for s in symbols], 'stress': list(stress), 'durations': [int(d) for d in durations], 'unknown': [], 'qc': qc, 'provenance': {**row.get('provenance', {}), 'dataset_revision': args.dataset_revision}, 'acoustic': config.acoustic_fingerprint, 'frontend': frontend_fingerprint(), 'annotation': fingerprint} if reasons: rejected.append({'id': row['id'], 'speaker': row['speaker'], 'text': row['text'], 'reasons': reasons, 'qc': qc}) else: accepted.append(entry) except Exception as error: # per-row failure -> rejected, keep going rejected.append({'id': row['id'], 'speaker': row['speaker'], 'text': row['text'], 'reasons': [f'{type(error).__name__}: {error}']}) for name, payload in ((split + '.jsonl', accepted), (split + '.rejected.jsonl', rejected)): tmp = args.output / (name + '.tmp') tmp.write_text(''.join(json.dumps(r, ensure_ascii=False) + '\n' for r in payload), encoding='utf-8') tmp.replace(args.output / name) summary['splits'][split] = { 'accepted': len(accepted), 'rejected': len(rejected), 'accepted_hours': round(sum(r['frames'] for r in accepted) / FPS / 3600, 3), 'rejection_reasons': dict(Counter(x for r in rejected for x in r['reasons']))} print(json.dumps({split: summary['splits'][split]}, ensure_ascii=False), flush=True) summary['timing_probe'] = { voice: {kind: summarize_offsets(probe[(voice, kind)]) for kind in ('vowel_to_voiceless', 'fricative_to_vowel')} for voice in config.speakers} atomic_json(args.output / 'summary.json', summary) atomic_json(args.output / 'annotations.json', { 'identity': identity, 'fingerprint': fingerprint, 'complete': True, 'stage': 'zh-paraformer-ts', 'acoustic_root': str(args.features.resolve()), 'limits': {}, 'counts': {s: summary['splits'][s]['accepted'] for s in summary['splits']}}) print(json.dumps({'timing_probe': summary['timing_probe']}, ensure_ascii=False), flush=True) print('ZH_ANNOTATE_DONE', flush=True) if __name__ == '__main__': main()