Open Lumen on a responsive bookshelf and land pending story work
- Start the app on a shelf of every installed book instead of the last book's home. Cards show the cover, translated metadata, available languages, restored patterns and either "Continue reading" or a way in. - Keep each book's saved route: the shelf is never written to flutter_screen, so choosing a book resumes its own leaf. - Lay the shelf out responsively: dense single-column cards on phones, a two-column grid from 720 logical pixels, a centred 860 px column on tablets and a chevron that exists in the bundled handwriting font. - Keep Settings reachable from the shelf and let the home page's story library button open the shelf instead of a dialog. - Add tool/shelf_screenshots_test.dart, which renders the shelf at phone and tablet metrics, checks that every card and Settings stay reachable without overflow, and writes artifacts/library/shelf-*.png. - Commit the pending Midnight Invitation package (campaign, notebook, narration and artwork), cast drama and ambience tooling, region selection, phone/tablet integration coverage and related docs. flutter analyze is clean and all 74 widget/domain tests pass.
This commit is contained in:
@@ -8,17 +8,31 @@ import onnxruntime as ort
|
||||
import espeakng_loader
|
||||
from kokoro_onnx import Kokoro
|
||||
from kokoro_onnx.config import EspeakConfig
|
||||
from audio_drama import validate_segments, effect
|
||||
|
||||
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('--page', action='append', default=[], help='Render only these page IDs; preserve other takes')
|
||||
parser.add_argument('--speaker', help='Render only this speaker, preserving all other recordings')
|
||||
parser.add_argument('--append-continuations', action='store_true', help='Preserve existing takes and append the new narrator passages')
|
||||
parser.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1])
|
||||
parser.add_argument('--story-root',type=Path,help='Render an independent story package with narration/scripts.json and audio/ assets')
|
||||
a=parser.parse_args()
|
||||
source=a.root/'assets/narration';raw=a.root/'assets/audio'
|
||||
source=(a.story_root/'narration') if a.story_root else a.root/'assets/narration'
|
||||
raw=(a.story_root/'audio') if a.story_root else a.root/'assets/audio'
|
||||
(source/'flac').mkdir(parents=True,exist_ok=True) if a.story_root else None
|
||||
records=json.loads((source/'scripts.json').read_text())
|
||||
cast=json.loads((source/'cast.json').read_text()) if (source/'cast.json').exists() else {}
|
||||
if a.page and not set(a.page) <= {r['pageId'] for r in records}:
|
||||
parser.error('Unknown page ID')
|
||||
for record in records:
|
||||
if record.get('segments'):
|
||||
validate_segments(record,cast)
|
||||
if a.append_continuations:
|
||||
parser.error('Segmented drama cannot append legacy continuations')
|
||||
(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'])
|
||||
@@ -26,8 +40,9 @@ 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)
|
||||
previous=json.loads((source/'manifest.json').read_text()) if (source/'manifest.json').exists() else {}
|
||||
tracks=dict(previous.get('tracks',{})) if a.speaker or a.append_continuations else {}
|
||||
for record in json.loads((source/'scripts.json').read_text()):
|
||||
tracks=dict(previous.get('tracks',{})) if a.speaker or a.page or a.append_continuations else {}
|
||||
for record in records:
|
||||
if a.page and record['pageId'] not in a.page: continue
|
||||
if a.speaker and record.get('speaker')!=a.speaker: continue
|
||||
old=tracks.get(record['pageId'])
|
||||
if a.append_continuations:
|
||||
@@ -41,7 +56,7 @@ for record in json.loads((source/'scripts.json').read_text()):
|
||||
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=[]
|
||||
rate=24000;pieces=[np.zeros(int(rate*.18),dtype=np.float32)];frames=len(pieces[0]);cues=[];events=[]
|
||||
if a.append_continuations:
|
||||
original,_=sf.read(source/'wav'/old['file'],dtype='int16')
|
||||
master,master_rate=sf.read(source/'wav'/old['file'],dtype='float32')
|
||||
@@ -51,11 +66,17 @@ for record in json.loads((source/'scripts.json').read_text()):
|
||||
sections=[(part,'Narrator' if a.append_continuations else record['speaker']) for part in paragraphs]
|
||||
if not a.append_continuations and record.get('continuation'):
|
||||
sections.extend((part,'Narrator') for part in record['continuation'].split('\n\n'))
|
||||
if record.get('segments'):
|
||||
sections=[(s['text'],s['speaker']) for s in record['segments']]
|
||||
for number,(part,speaker) in enumerate(sections,1):
|
||||
print(f"Rendering {record['pageId']} · {number}/{len(sections)}",flush=True)
|
||||
voice='bm_george' if speaker=='Narrator' else record.get('voice',a.voice)
|
||||
speed=.88 if speaker=='Narrator' else record.get('speed',a.speed)
|
||||
samples,sample_rate=engine.create(part.replace('\n',' '),voice=voice,speed=speed,lang='en-gb',sentence_pause=.38,clause_pause=.14)
|
||||
direction=record['segments'][number-1] if record.get('segments') else {}
|
||||
if direction:
|
||||
voice=cast[speaker]['voice']
|
||||
speed=direction.get('speed',cast[speaker]['speed'])
|
||||
samples,sample_rate=engine.create(part.strip().replace('\n',' '),voice=voice,speed=speed,lang=cast.get(speaker,{}).get('language','en-gb'),sentence_pause=direction.get('sentencePause',.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()
|
||||
@@ -63,12 +84,24 @@ for record in json.loads((source/'scripts.json').read_text()):
|
||||
samples[:fade]*=np.linspace(0,1,fade);samples[-fade:]*=np.linspace(1,0,fade)
|
||||
peak=float(np.max(np.abs(samples)));assert peak>.01
|
||||
samples*=.86/peak
|
||||
if direction.get('perspective')=='behind-door':
|
||||
# A restrained low-pass suggests a closed door; no pitch shifting.
|
||||
samples=np.convolve(samples,np.ones(9)/9,mode='same').astype(np.float32)*.86
|
||||
start=frames;pieces.append(samples);frames+=len(samples)
|
||||
cues.append({'startMs':round(start*1000/rate),'endMs':round(frames*1000/rate),'text':part,'speaker':speaker})
|
||||
pause=np.zeros(int(rate*.60),dtype=np.float32);pieces.append(pause);frames+=len(pause)
|
||||
cues.append({'startMs':round(start*1000/rate),'endMs':round(frames*1000/rate),'text':part,'speaker':speaker,'voice':voice,'speed':speed})
|
||||
pause=np.zeros(round(rate*direction.get('pauseMs',600)/1000),dtype=np.float32)
|
||||
if direction.get('afterEffect'):
|
||||
sound=effect(direction['afterEffect'],rate)
|
||||
lead=round(rate*.16)
|
||||
if len(pause)<lead+len(sound):
|
||||
pause=np.pad(pause,(0,lead+len(sound)-len(pause)))
|
||||
pause[lead:lead+len(sound)]+=sound
|
||||
events.append({'effect':direction['afterEffect'],'startMs':round((frames+lead)*1000/rate),'endMs':round((frames+lead+len(sound))*1000/rate)})
|
||||
pieces.append(pause);frames+=len(pause)
|
||||
audio=np.concatenate(pieces);peak=float(np.max(np.abs(audio)));assert peak>.01
|
||||
assert peak<1
|
||||
wav=source/'wav'/f"{record['resource']}.wav";flac=raw/f"{record['resource']}.flac"
|
||||
wav=source/'wav'/f"{record['resource']}.wav"
|
||||
flac=(source/'flac' if a.story_root else raw)/f"{record['resource']}.flac"
|
||||
sf.write(wav,audio,rate,subtype='PCM_16')
|
||||
shutil.copyfile(wav,raw/wav.name)
|
||||
subprocess.run(['ffmpeg','-v','error','-y','-i',str(wav),'-c:a','flac','-compression_level','8',str(flac)],check=True)
|
||||
@@ -77,6 +110,12 @@ for record in json.loads((source/'scripts.json').read_text()):
|
||||
tracks[record['pageId']]={**record,'file':wav.name,'flacFile':flac.name,'wavSha256':hashlib.sha256(wav.read_bytes()).hexdigest(),'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}
|
||||
if record.get('segments'):
|
||||
tracks[record['pageId']]['events']=events
|
||||
tracks[record['pageId']]['cueJoin']=''
|
||||
tracks[record['pageId']]['production']=record.get('production','drama-pilot-v1')
|
||||
if a.story_root:
|
||||
tracks[record['pageId']]['asset']=(raw/wav.name).resolve().relative_to(a.root.resolve()).as_posix()
|
||||
if a.append_continuations:
|
||||
output,_=sf.read(wav,dtype='int16')
|
||||
assert np.array_equal(output[:len(original)],original),'Original take changed while appending'
|
||||
@@ -84,7 +123,7 @@ for record in json.loads((source/'scripts.json').read_text()):
|
||||
tracks[record['pageId']]['originalPcmSha256']=hashlib.sha256(original.tobytes()).hexdigest()
|
||||
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.',
|
||||
'speakers':{'Mara':{'voice':'bf_emma','speed':.82},'Narrator':{'voice':'bm_george','speed':.88}},
|
||||
'speakers':{'Mara':{'voice':'bf_emma','speed':.82},'Narrator':{'voice':'bm_george','speed':.88},**cast},
|
||||
'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')
|
||||
|
||||
Reference in New Issue
Block a user