Initial commit: Lumen Android puzzle notebook v1.7
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare immutable WAV masters and bundled FLACs; Android performs no speech synthesis."""
|
||||
import argparse, hashlib, importlib.metadata, json, subprocess
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import onnxruntime as ort
|
||||
import espeakng_loader
|
||||
from kokoro_onnx import Kokoro
|
||||
from kokoro_onnx.config import EspeakConfig
|
||||
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--model',type=Path,required=True)
|
||||
parser.add_argument('--voices',type=Path,required=True)
|
||||
parser.add_argument('--voice',default='bf_emma')
|
||||
parser.add_argument('--speed',type=float,default=.82)
|
||||
parser.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1])
|
||||
a=parser.parse_args()
|
||||
source=a.root/'assets/narration';raw=a.root/'app/src/main/res/raw'
|
||||
(source/'wav').mkdir(parents=True,exist_ok=True);raw.mkdir(parents=True,exist_ok=True)
|
||||
options=ort.SessionOptions();options.intra_op_num_threads=4;options.inter_op_num_threads=1
|
||||
session=ort.InferenceSession(str(a.model),sess_options=options,providers=['CPUExecutionProvider'])
|
||||
session.disable_fallback()
|
||||
config=EspeakConfig(lib_path=str(espeakng_loader.get_library_path()),data_path=str(espeakng_loader.get_data_path()))
|
||||
engine=Kokoro.from_session(session,str(a.voices),espeak_config=config)
|
||||
tracks={}
|
||||
for record in json.loads((source/'scripts.json').read_text()):
|
||||
paragraphs=[]
|
||||
for part in record['text'].split('\n\n'):
|
||||
if paragraphs and len(part)<45:paragraphs[-1]+='\n\n'+part
|
||||
elif paragraphs and len(paragraphs[-1])<45:paragraphs[-1]+='\n\n'+part
|
||||
else:paragraphs.append(part)
|
||||
rate=24000;pieces=[np.zeros(int(rate*.18),dtype=np.float32)];frames=len(pieces[0]);cues=[]
|
||||
for part in paragraphs:
|
||||
print(f"Rendering {record['pageId']} · {len(cues)+1}/{len(paragraphs)}",flush=True)
|
||||
samples,sample_rate=engine.create(part.replace('\n',' '),voice=a.voice,speed=a.speed,lang='en-gb',sentence_pause=.38,clause_pause=.14)
|
||||
assert sample_rate==rate
|
||||
samples=np.asarray(samples,dtype=np.float32).reshape(-1)
|
||||
assert len(samples)>rate*.3 and np.isfinite(samples).all()
|
||||
fade=min(240,len(samples)//4)
|
||||
samples[:fade]*=np.linspace(0,1,fade);samples[-fade:]*=np.linspace(1,0,fade)
|
||||
start=frames;pieces.append(samples);frames+=len(samples)
|
||||
cues.append({'startMs':round(start*1000/rate),'endMs':round(frames*1000/rate),'text':part})
|
||||
pause=np.zeros(int(rate*.60),dtype=np.float32);pieces.append(pause);frames+=len(pause)
|
||||
audio=np.concatenate(pieces);peak=float(np.max(np.abs(audio)));assert peak>.01
|
||||
audio*=.86/peak
|
||||
wav=source/'wav'/f"{record['resource']}.wav";flac=raw/f"{record['resource']}.flac"
|
||||
sf.write(wav,audio,rate,subtype='PCM_16')
|
||||
subprocess.run(['ffmpeg','-v','error','-y','-i',str(wav),'-c:a','flac','-compression_level','8',str(flac)],check=True)
|
||||
decoded,check_rate=sf.read(flac,dtype='int16');master,_=sf.read(wav,dtype='int16')
|
||||
assert check_rate==rate and np.array_equal(decoded,master)
|
||||
tracks[record['pageId']]={**record,'file':flac.name,'sampleRate':rate,'channels':1,'frames':len(audio),
|
||||
'durationMs':round(len(audio)*1000/rate),'textSha256':hashlib.sha256(record['text'].encode()).hexdigest(),
|
||||
'flacSha256':hashlib.sha256(flac.read_bytes()).hexdigest(),'cues':cues}
|
||||
print(f"Saved {wav.name}: {len(audio)/rate:.1f}s; lossless FLAC verified",flush=True)
|
||||
manifest={'voice':a.voice,'speed':a.speed,'language':'en-gb','method':'Synthetic narration rendered during development; bundled file playback only.',
|
||||
'modelSha256':hashlib.sha256(a.model.read_bytes()).hexdigest(),'voicesSha256':hashlib.sha256(a.voices.read_bytes()).hexdigest(),
|
||||
'packages':{p:importlib.metadata.version(p) for p in ['kokoro-onnx','onnxruntime','soundfile','espeakng-loader']},'tracks':tracks}
|
||||
(source/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n')
|
||||
(raw/'narration_manifest.json').write_text(json.dumps({'tracks':tracks},ensure_ascii=False,indent=2)+'\n')
|
||||
print('All five narration masters and runtime FLACs prepared.',flush=True)
|
||||
Reference in New Issue
Block a user