Text-to-Speech
English
German
voice-acting
qwen3
moss-audio-tokenizer-v2
audio-generation
File size: 10,322 Bytes
88faa07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python3
"""Conservative packed disposition of S3 transcript suspects after full ASR.

This is an automated repair, not ground-truth transcription.  It favors
excluding an uncertain short target over teaching a full-scene transcript to
a clipped target.  Original TAR/Parquet assets are immutable.  Every suspect
must have an ASR hypothesis and one explicit disposition; the 128+ sample QA
is a structural/audio-ASR consistency check, not a claim of human listening.
"""
from __future__ import annotations

from collections import Counter, defaultdict
from datetime import datetime, timezone
from difflib import SequenceMatcher
import hashlib
import json
import math
import os
from pathlib import Path
import re

import pyarrow as pa
import pyarrow.parquet as pq

from audit_target_text import AUDIT, PARENTHETICAL
from build_worklist import EXPECTED_ELIGIBLE, OUT, SHARDS, sha
from text_resolution import RESOLUTION_DIR

ASR = AUDIT.parent / 'target_asr_v1'
TOKEN = re.compile(r"[^\W_]+(?:['’\-][^\W_]+)*", re.UNICODE)
BAD_SINGLE = {'a', 'i', 'o', 'uh', 'um', 'mmm', 'hmm', 'ah', 'oh', 'the'}


def lexical(text: str) -> list[str]:
    return [word.casefold() for word in TOKEN.findall(PARENTHETICAL.sub(' ', text or ''))]


def repeated_run(words: list[str]) -> int:
    best = run = 0
    prior = None
    for word in words:
        run = run + 1 if word == prior else 1
        best = max(best, run)
        prior = word
    return best


def classify(row: dict) -> tuple[str, str, str, float]:
    source_text = str(row['source_text'] or '').strip()
    asr_text = ' '.join(str(row['asr_text'] or '').strip().split())
    old, new = lexical(source_text), lexical(asr_text)
    duration = float(row['duration_s'])
    rate_cap = max(4, math.ceil(duration * 6.5))
    if re.search(r'\b(?:GENERAL|SCRIPT|CAPTION|TRANSCRIPT):|\[pause\s', asr_text, re.I):
        return 'exclude', '', 'asr_reserved_prompt_marker', 0.
    if len(new) > rate_cap or repeated_run(new) >= 6 or len(asr_text) > 2048:
        return 'exclude', '', 'implausible_asr', 0.
    if not new:
        return 'exclude', '', 'empty_asr', 0.
    # A few original metadata strings contain thousands of hallucinated
    # repeated words.  Bound the quadratic alignment work; the full old
    # length is still used by the keep/no-keep decision below.
    old_head = old[:max(256, len(new) * 4)]
    matcher = SequenceMatcher(None, old_head, new, autojunk=False)
    common = sum(block.size for block in matcher.get_matching_blocks())
    support = common / len(new)
    agreement = matcher.ratio()
    aligned = int(row['aligned_word_count'])
    # A matching transcript is a false-positive rate/alignment flag.  An
    # aligned original with small ASR differences can preserve proper nouns.
    if (agreement >= .88 and len(old) <= rate_cap) or (
            aligned >= .8 * len(old) and agreement >= .80 and len(old) <= rate_cap):
        return 'verified_keep', '', 'asr_agrees_with_source', support
    if len(new) == 1:
        if len(old) <= 2 and new[0] == old[0] and new[0] not in BAD_SINGLE:
            return 'verified_keep', '', 'single_word_agreement', support
        return 'exclude', '', 'short_asr_not_safe', support
    # Full-scene text clipped to a sentence typically has source-prefix
    # support near 1 even if the global source-vs-ASR WER is very large.
    # Without substantial support, the ASR itself may be a hallucination.
    if support >= .68 and common >= 2 and asr_text:
        return 'relabel', asr_text, 'supported_clip_asr', support
    return 'exclude', '', 'asr_source_conflict', support


def main():
    asr_manifest_path = ASR / 'MANIFEST.json'
    audit_report_path = AUDIT / 'REPORT.json'
    asr_spec = json.loads(asr_manifest_path.read_text())
    audit_spec = json.loads(audit_report_path.read_text())
    assert asr_spec['status'] == 'COMPLETE_HYPOTHESES_NOT_APPROVED_LABELS'
    assert asr_spec['asr_include_unaligned'] is True, 'Every suspect needs a disposition'
    assert asr_spec['source_audit_sha256'] == sha(audit_report_path)
    assert audit_spec['rows'] == EXPECTED_ELIGIBLE
    assert not RESOLUTION_DIR.exists(), 'Do not overwrite an existing resolution'

    expected = set()
    for shard in range(SHARDS):
        part = AUDIT / f'suspect-{shard:03d}.parquet'
        for batch in pq.ParquetFile(part).iter_batches(columns=['uid'], batch_size=8192):
            for uid in batch.column(0).to_pylist():
                assert uid not in expected, uid
                expected.add(uid)
    assert len(expected) == sum(x['any_suspect'] for x in audit_spec['by_source'].values())
    assert len(expected) == asr_spec['rows']

    RESOLUTION_DIR.mkdir(parents=True)
    changes_path = RESOLUTION_DIR / 'changes.parquet'
    changes_partial = changes_path.with_suffix('.parquet.partial')
    schema = pa.schema([
        ('uid', pa.string()), ('action', pa.string()), ('text', pa.string()),
        ('source', pa.string()), ('reason', pa.string()), ('asr_support', pa.float32()),
        ('duration_s', pa.float32()), ('source_text', pa.string()), ('asr_text', pa.string()),
        ('record_locator_json', pa.string()), ('target_locator_json', pa.string())])
    writer = pq.ParquetWriter(changes_partial, schema, compression='zstd')
    observed = set()
    counts = Counter()
    by_source = defaultdict(Counter)
    excluded_hours = 0.
    qa_candidates = defaultdict(list)
    try:
        for part_spec in asr_spec['parts']:
            path = Path(part_spec['path'])
            assert sha(path) == part_spec['sha256']
            for batch in pq.ParquetFile(path).iter_batches(batch_size=4096):
                output = []
                for row in batch.to_pylist():
                    uid = row['uid']
                    assert uid in expected and uid not in observed, uid
                    observed.add(uid)
                    # The full ASR pass must retain these audit fields.  This
                    # prevents silently applying a repair to another target.
                    assert int(row['text_word_count']) == len(lexical(row['source_text']))
                    action, text, reason, support = classify(row)
                    counts[action] += 1
                    by_source[row['source']][action] += 1
                    if action == 'exclude':
                        excluded_hours += float(row['duration_s']) / 3600
                    decision = {'uid': uid, 'action': action, 'text': text,
                                'source': row['source'], 'reason': reason,
                                'asr_support': support,
                                'duration_s': float(row['duration_s']),
                                'source_text': row['source_text'],
                                'asr_text': row['asr_text'],
                                'record_locator_json': row['record_locator_json'],
                                'target_locator_json': row['target_locator_json']}
                    output.append(decision)
                    bucket = (row['source'], action)
                    digest = int.from_bytes(hashlib.blake2b(uid.encode(), digest_size=8).digest(), 'big')
                    qa_candidates[bucket].append((digest, decision))
                    if len(qa_candidates[bucket]) > 16:
                        qa_candidates[bucket].sort(key=lambda x: x[0])
                        del qa_candidates[bucket][16:]
                if output:
                    writer.write_table(pa.Table.from_pylist(output, schema=schema), row_group_size=4096)
    finally:
        writer.close()
    assert observed == expected, {'missing': len(expected-observed), 'extra': len(observed-expected)}
    assert pq.read_metadata(changes_partial).num_rows == len(expected)
    os.replace(changes_partial, changes_path)

    samples = []
    for bucket in sorted(qa_candidates):
        samples.extend(row for _, row in sorted(qa_candidates[bucket], key=lambda x: x[0])[:16])
    # All six source families should contribute across all observed actions;
    # up to 288 records are retained in one packed JSON QA artifact.
    assert len(samples) >= 128, len(samples)
    qa = {'status': 'PASS', 'kind': 'automated_structural_asr_consistency_not_human_listening',
          'sampled_rows': len(samples), 'action_rows': dict(counts),
          'samples': samples,
          'checks': ['every audited UID has exactly one ASR-backed disposition',
                     'all relabel texts have >=2 lexical words and >=0.68 ordered support',
                     'no implausible ASR word rate or repeated-run relabel accepted',
                     'source worklist and audit SHA-256 pinned']}
    qa_path = RESOLUTION_DIR / 'QA_SAMPLES.json'
    qa_path.write_text(json.dumps(qa, ensure_ascii=False, indent=2) + '\n')
    spec = {'status': 'PENDING_RENDER_QA', 'version': 'hvs-s3-target-text-v1',
            'created_utc': datetime.now(timezone.utc).isoformat(),
            'source_worklist_sha256': sha(OUT / 'MANIFEST.json'),
            'audit_report_sha256': sha(audit_report_path),
            'asr_manifest_sha256': sha(asr_manifest_path),
            'changes_file': changes_path.name, 'changes_sha256': sha(changes_path),
            'changed_rows': len(expected), 'action_rows': dict(counts),
            'accepted_rows': EXPECTED_ELIGIBLE - counts['exclude'],
            'excluded_rows': counts['exclude'],
            'excluded_target_hours': round(excluded_hours, 3),
            'unresolved_impossible_rows': 0,
            'by_source': {k: dict(v) for k, v in by_source.items()},
            'qa_status': qa['status'], 'qa_file': qa_path.name,
            'qa_sha256': sha(qa_path),
            'important_caveat': 'Automated ASR supports conservative clipping decisions; it is not a human-verified transcript of every sample.'}
    manifest_path = RESOLUTION_DIR / 'MANIFEST.json'
    temp = manifest_path.with_suffix('.json.partial')
    temp.write_text(json.dumps(spec, ensure_ascii=False, indent=2) + '\n')
    os.replace(temp, manifest_path)
    print(json.dumps({'status': spec['status'], 'suspects': len(expected),
                      'actions': dict(counts), 'excluded_hours': spec['excluded_target_hours'],
                      'qa_samples': len(samples)}), flush=True)


if __name__ == '__main__':
    main()