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:
Hadrian Burkhardt
2026-11-05 14:29:50 +01:00
parent d45cd0698a
commit 0718e3f252
149 changed files with 16875 additions and 393 deletions
+41
View File
@@ -0,0 +1,41 @@
"""Offline drama helpers. Stage directions remain metadata, never spoken text."""
import numpy as np
def validate_segments(record, cast):
segments = record['segments']
if not segments or ''.join(s['text'] for s in segments) != record['text']:
raise ValueError(f"Segments must preserve the exact prose: {record['pageId']}")
for segment in segments:
if not segment['text'].strip() or segment['speaker'] not in cast:
raise ValueError(f"Missing text or cast member: {segment}")
if not 0.5 <= segment.get('speed', cast[segment['speaker']]['speed']) <= 1.5:
raise ValueError('Delivery speed must be between 0.5 and 1.5')
if not 0 <= segment.get('pauseMs', 600) <= 5000:
raise ValueError('Pause must be between 0 and 5000 ms')
if segment.get('afterEffect') not in (None, 'door-knock', 'chair-shift', 'paper'):
raise ValueError('Unknown sound effect')
if segment.get('perspective', 'near') not in ('near', 'behind-door'):
raise ValueError('Unknown voice perspective')
def effect(name, rate=24000):
"""Original, deliberately soft Foley approximations, deterministic and offline."""
rng = np.random.default_rng(1031)
duration = {'door-knock': 1.0, 'chair-shift': .8, 'paper': .7}[name]
t = np.arange(round(rate * duration)) / rate
noise = rng.normal(size=len(t))
if name == 'door-knock':
result = np.zeros(len(t))
for onset in (.12, .40):
dt = np.maximum(t - onset, 0)
envelope = (t >= onset) * (1 - np.exp(-dt * 1000)) * np.exp(-dt * 35)
result += envelope * (np.sin(2 * np.pi * 175 * dt) + .4 * np.sin(2 * np.pi * 320 * dt) + .08 * noise)
elif name == 'chair-shift':
filtered = np.convolve(noise, np.ones(12) / 12, mode='same')
result = (filtered + .12 * np.sin(2 * np.pi * (180 * t + 22 * t * t))) * np.sin(np.pi * t / duration) ** 2
else:
filtered = noise - np.convolve(noise, np.ones(7) / 7, mode='same')
result = filtered * np.sin(np.pi * t / duration) ** 2 * (.65 + .35 * np.sin(2 * np.pi * 7 * t))
result *= .16 / np.max(np.abs(result))
return result.astype(np.float32)
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Validate a narrated story package, using standard Python plus ffmpeg."""
import argparse
import hashlib
import json
import struct
import subprocess
import wave
from pathlib import Path
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('package', type=Path)
a = parser.parse_args()
repo = Path(__file__).resolve().parents[1]
package = a.package.resolve()
read = lambda path: json.loads(path.read_text())
sha = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
campaign = read(package / 'campaign.json')
notebook = read(package / 'notebook.json')['pages']
scripts = {s['pageId']: s for s in read(package / 'narration/scripts.json')}
manifest = read(package / 'narration/manifest.json')
tracks = read(package / 'audio/narration_manifest.json')['tracks']
assert tracks == manifest['tracks'], 'Runtime/provenance manifests differ'
assert len({p['id'] for p in notebook}) == len(notebook), 'Duplicate page IDs'
prose = {p['id'] for p in notebook if p['type'] != 'puzzle'}
assert set(scripts) == prose == set(tracks), 'Every prose page must have exactly one recording'
images = {package / 'artwork/cover-v1.png'}
for level in campaign['levels']:
images.add(repo / level['illustrationAsset'])
for path in images:
data = path.read_bytes()
assert data[:8] == b'\x89PNG\r\n\x1a\n', path
w, h, depth, colour = struct.unpack('>IIBB', data[16:26])
assert min(w, h) >= 512 and depth == 8 and colour == 6, f'Expected large RGBA PNG: {path}'
for page in notebook:
if page['type'] == 'puzzle':
assert page['id'] not in tracks, 'Puzzle instructions should not autoplay'
continue
index = page.get('campaignIndex')
source = page.get('textSource')
text = campaign['levels'][index][source] if source in ('before', 'after') else page['text']
text = '\n\n'.join(s for s in [text, page.get('continuation', '')] if s)
script, track = scripts[page['id']], tracks[page['id']]
assert text == script['text'] == track['text'], f'Stale script: {page["id"]}'
assert hashlib.sha256(text.encode()).hexdigest() == track['textSha256']
assert track.get('cueJoin','\n\n').join(c['text'] for c in track['cues']) == text, f'Incomplete cues: {page["id"]}'
if script.get('segments'):
cast = read(package / 'narration/cast.json')
assert track['segments'] == script['segments'], 'Stale performance directions'
assert ''.join(s['text'] for s in script['segments']) == text
assert len(script['segments']) == len(track['cues'])
for segment, cue in zip(script['segments'], track['cues']):
assert segment['speaker'] == cue['speaker']
assert cast[segment['speaker']]['voice'] == cue['voice']
for event in track['events']:
assert 0 <= event['startMs'] < event['endMs'] <= track['durationMs']
assert all(event['endMs'] <= c['startMs'] or event['startMs'] >= c['endMs'] for c in track['cues']), 'Foley must leave the spoken words clear'
wav = repo / track['asset']
master = package / 'narration/wav' / track['file']
flac = package / 'narration/flac' / track['flacFile']
assert sha(wav) == sha(master) == track['wavSha256'], wav
assert sha(flac) == track['flacSha256'], flac
with wave.open(str(wav), 'rb') as audio:
assert (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) == (1, 2, 24000)
assert audio.getnframes() == track['frames']
pcm = audio.readframes(audio.getnframes())
samples = memoryview(pcm).cast('h')
peak = max(abs(v) for v in samples)
assert 1000 < peak < 32000, f'Silent/clipped recording: {wav}'
assert abs(track['durationMs'] - round(track['frames'] / 24)) <= 1
last = 0
for cue in track['cues']:
assert last <= cue['startMs'] < cue['endMs'] <= track['durationMs']
last = cue['endMs']
decoded = subprocess.check_output(['ffmpeg', '-v', 'error', '-i', str(flac), '-f', 's16le', '-acodec', 'pcm_s16le', '-'])
assert decoded == pcm, f'Lossless master mismatch: {flac}'
print(f'PASS {page["id"]}: script, cues, PCM and lossless archive ({track["durationMs"]/1000:.1f}s)')
minutes = sum(t['durationMs'] for t in tracks.values()) / 60000
if (package / 'audio/atmosphere.json').exists():
atmosphere = read(package / 'audio/atmosphere.json')
provenance = read(package / 'audio/atmosphere_provenance.json')['tracks']
for page_id, scene in atmosphere['pages'].items():
assert page_id in {p['id'] for p in notebook}
assert scene in atmosphere['scenes']
for name, scene in atmosphere['scenes'].items():
path = repo / scene['asset']
assert sha(path) == provenance[name]['wavSha256']
with wave.open(str(path), 'rb') as audio:
assert (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) == (1, 2, 24000)
pcm = memoryview(audio.readframes(audio.getnframes())).cast('h')
assert abs(pcm[-1] - pcm[0]) <= 1, 'Loop has a discontinuity'
assert 1000 < max(abs(v) for v in pcm) < 24000
print(f'PASS atmosphere: {name}, bundled PCM and seamless loop')
print(f'PASS package: {len(campaign["levels"])} puzzles, {len(notebook)} leaves, {len(images)} illustrations, {len(tracks)} recordings, {minutes:.1f} minutes')
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""Original wind, kitchen and haunted-house textures for The Midnight Invitation."""
import hashlib
import json
from pathlib import Path
import numpy as np
import soundfile as sf
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'assets/stories/midnight-invitation/audio'
RATE, SECONDS = 24000, 36
N = RATE * SECONDS
T = np.arange(N) / RATE
F = np.fft.rfftfreq(N, 1 / RATE)
tracks = {}
for name, seed in [('threshold', 103101), ('kitchen', 103102), ('hall', 103103)]:
rng = np.random.default_rng(seed)
def noise(low, high):
spectrum = np.fft.rfft(rng.normal(size=N))
spectrum *= (1 - np.exp(-(F / low) ** 4)) * np.exp(-(F / high) ** 2)
signal = np.fft.irfft(spectrum, n=N)
return signal / np.sqrt(np.mean(signal ** 2))
def swell(cycles, phase=0):
return .65 + .35 * np.sin(2 * np.pi * cycles * T / SECONDS + phase)
if name == 'threshold':
# Gentle air around a sheltered porch; leaves move in longer gusts.
sound = .75 * noise(75, 950) * swell(2, .3)
sound += .20 * noise(800, 3300) * swell(5, 1.2) ** 3
elif name == 'hall':
# Sheltered air and distant timber strain, with no voices or clock ticks.
sound = .50 * noise(45, 420) * swell(2, .7)
sound += .09 * noise(300, 1600) * swell(5, 1.4) ** 3
for onset in [6.2, 18.7, 29.1]:
distance = (T - onset + SECONDS / 2) % SECONDS - SECONDS / 2
envelope = np.exp(-(distance / .55) ** 2)
sound += .035 * np.sin(2 * np.pi * (190 * T + .12 * np.sin(2 * np.pi * T))) * envelope
else:
# Low stove draft and irregular, small embers, without a musical bed.
sound = .22 * noise(65, 650) * swell(2, 1.1)
sound += .07 * noise(500, 2200)
embers = noise(800, 4200)
for onset in rng.uniform(1, SECONDS - 1, 48):
dt = T - onset
envelope = np.where(dt >= 0, np.exp(-np.maximum(dt, 0) * 35), 0)
sound += rng.uniform(.13, .42) * embers * envelope
sound -= np.mean(sound)
ramp = np.linspace(0, 1, RATE // 20)
sound[-len(ramp):] -= (sound[-1] - sound[0]) * ramp * ramp * (3 - 2 * ramp)
sound *= .10 / np.sqrt(np.mean(sound ** 2))
sound *= min(1, .65 / np.max(np.abs(sound)))
path = OUT / f'ambience_{name}.wav'
sf.write(path, sound, RATE, subtype='PCM_16')
pcm, rate = sf.read(path)
assert abs(pcm[-1] - pcm[0]) <= 1 / 32768
tracks[name] = {'asset':path.relative_to(ROOT).as_posix(), 'sampleRate':RATE,
'channels':1, 'durationMs':SECONDS*1000, 'seed':seed,
'wavSha256':hashlib.sha256(path.read_bytes()).hexdigest(),
'peak':float(np.max(np.abs(pcm))), 'rms':float(np.sqrt(np.mean(pcm**2)))}
print(f'{name}: {SECONDS}s, peak {tracks[name]["peak"]:.3f}, seamless PCM loop')
(OUT/'atmosphere_provenance.json').write_text(json.dumps({
'method':'Original procedural textures, rendered offline; no third-party recordings or runtime synthesis.',
'generator':'scripts/render_drama_atmosphere.py', 'tracks':tracks,
},indent=2)+'\n')
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env python3
"""Export the pilot readings plus their quiet atmosphere for listening outside Lumen."""
import json
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
PACKAGE = ROOT / 'assets/stories/midnight-invitation'
OUT = ROOT / 'artifacts/audio-pilot'
OUT.mkdir(parents=True, exist_ok=True)
tracks = json.loads((PACKAGE/'audio/narration_manifest.json').read_text())['tracks']
for page, scene, name in [
('midnight.feather.memory', 'threshold', '01-at-the-door'),
('midnight.candle.entry', 'kitchen', '02-in-the-kitchen'),
]:
track = tracks[page]
# Same speech-time atmosphere gain as the app's default .7 volume setting.
duration = track['durationMs'] / 1000
subprocess.run(['ffmpeg','-v','error','-y','-i',str(ROOT/track['asset']),
'-stream_loop','-1','-i',str(PACKAGE/f'audio/ambience_{scene}.wav'),
'-filter_complex',f'[1:a]volume=0.07,afade=t=in:d=0.5,afade=t=out:st={duration-.8}:d=0.8[bed];[0:a][bed]amix=inputs=2:duration=first:normalize=0[out]',
'-map','[out]','-c:a','pcm_s16le',str(OUT/f'{name}.wav')],check=True)
print(OUT/f'{name}.wav')
+48 -9
View File
@@ -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')