Files

107 lines
5.0 KiB
Python

"""Prepare private Anna clips locally; only aggregate metadata goes to stdout."""
from pathlib import Path
import hashlib
import json
import os
import re
import subprocess
import time
import wave
import numpy as np
ROOT = Path('/data/athena-piper-test-20261027')
DATA = ROOT / 'anna-data'
AUDIO = DATA / 'wav'
AUDIO.mkdir(parents=True, exist_ok=True, mode=0o700)
os.umask(0o077)
CLI = Path('/opt/athena-deck-dev/runtime/state/parakeet-runtime/v0.6.1/runtime/parakeet-v0.6.1-bin-linux-cpu-x64/parakeet-cli')
MODEL = Path('/opt/athena-deck-dev/runtime/state/parakeet-runtime/v0.6.1/redux-packed.gguf')
source = ROOT / 'anna-input.wav'
with wave.open(str(source), 'rb') as wav:
rate = wav.getframerate()
assert wav.getnchannels() == 1 and wav.getsampwidth() == 2
pcm = np.frombuffer(wav.readframes(wav.getnframes()), dtype='<i2')
hop = rate // 100
frames = pcm[:len(pcm)//hop*hop].reshape(-1, hop).astype(np.float32)
rms = np.sqrt(np.mean(frames * frames, axis=1))
del frames
threshold = min(350, max(65, float(np.percentile(rms, 8)) * 1.5))
silent = rms < threshold
edges = np.diff(np.r_[False, silent, False].astype(np.int8))
pauses = [((a+b)/2)*hop for a,b in zip(np.where(edges == 1)[0], np.where(edges == -1)[0])
if b-a >= 18]
cuts = [0]
forced = set()
while len(pcm)-cuts[-1] > 16*rate:
start = cuts[-1]
choices = [int(p) for p in pauses if start+5*rate <= p <= start+14*rate]
if choices:
cuts.append(choices[-1])
else:
choices = [int(p) for p in pauses if start+4*rate <= p <= start+19*rate]
if choices:
cuts.append(choices[0])
else:
lo = (start+10*rate)//hop
hi = min(len(rms), (start+16*rate)//hop)
cut = int((lo+np.argmin(rms[lo:hi]))*hop)
cuts.append(cut); forced.add(cut)
cuts.append(len(pcm))
rows = []
accepted = []
started = time.monotonic()
for i,(a,b) in enumerate(zip(cuts, cuts[1:]), 1):
row = {'id':f'anna-{i:03}', 'source_start':a/rate, 'source_end':b/rate,
'forced_boundary':a in forced or b in forced}
lo,hi=a//hop,min(len(rms),(b+hop-1)//hop)
voiced=np.where(rms[lo:hi]>=threshold)[0]
if not len(voiced):
row['rejected']='silence'; rows.append(row); continue
aa=max(a,(lo+int(voiced[0]))*hop-int(.12*rate))
bb=min(b,(lo+int(voiced[-1])+1)*hop+int(.15*rate))
path=AUDIO/(row['id']+'.wav')
with wave.open(str(path),'wb') as wav:
wav.setnchannels(1);wav.setsampwidth(2);wav.setframerate(rate)
wav.writeframes(pcm[aa:bb].tobytes())
row['duration_seconds']=(bb-aa)/rate
result=subprocess.run([str(CLI),'transcribe','--model',str(MODEL),
'--input',str(path),'--lang','de','--threads','2','--timestamps','--json'],
capture_output=True,text=True,timeout=45)
if result.returncode:
row['rejected']='stt_failed'
else:
stt=json.loads(result.stdout)
text=' '.join(stt.get('text','').replace('|',' ').split())
conf=[w['conf'] for w in stt.get('words',[]) if isinstance(w.get('conf'),(int,float))]
row.update(text=text,mean_word_confidence=float(np.mean(conf)) if conf else None,
words=len(stt.get('words',[])))
(DATA/(row['id']+'.stt.json')).write_text(json.dumps(stt,ensure_ascii=False))
reason=('forced_boundary' if row['forced_boundary'] else
'short_or_empty' if len(text)<12 or row['duration_seconds']<1 else
'low_stt_confidence' if conf and np.mean(conf)<.9 else
'unexpected_script' if re.search('[\u3400-\u9fff]',text) else None)
if reason: row['rejected']=reason
else:
row['split']='heldout' if i%10==0 else 'train'
accepted.append(row)
rows.append(row)
(DATA/'segments.private.json').write_text(json.dumps(rows,ensure_ascii=False,indent=2))
(ROOT/'data-progress.json').write_text(json.dumps({'phase':'preparing',
'processed':i,'total':len(cuts)-1,'accepted':len(accepted),
'elapsed_seconds':time.monotonic()-started}))
for split in ('train','heldout'):
(DATA/f'{split}.csv').write_text(''.join(f'{r["id"]}.wav|{r["text"]}\n'
for r in accepted if r['split']==split))
summary={'phase':'complete','source_seconds':len(pcm)/rate,'source_sample_rate':rate,
'source_sha256':hashlib.file_digest(source.open('rb'),'sha256').hexdigest(),
'segments_total':len(rows),'segments_accepted':len(accepted),
'segments_rejected':len(rows)-len(accepted),
'train_segments':sum(r['split']=='train' for r in accepted),
'heldout_segments':sum(r['split']=='heldout' for r in accepted),
'accepted_audio_seconds':sum(r['duration_seconds'] for r in accepted),
'silence_threshold_pcm16':threshold,'elapsed_seconds':time.monotonic()-started,
'transcript_status':'Local ASR-generated; not manually verified ground truth',
'private_outputs':'Audio and transcripts stay under the own private Athena test root'}
(ROOT/'data-progress.json').write_text(json.dumps(summary,indent=2))
print(json.dumps(summary),flush=True)